]> git.vpit.fr Git - perl/modules/re-engine-Hooks.git/blob - src/5015007/regcomp.c
Hook convertion of branches into tries
[perl/modules/re-engine-Hooks.git] / src / 5015007 / 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 "re_defs.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
90 #ifdef op
91 #undef op
92 #endif /* op */
93
94 #ifdef MSDOS
95 #  if defined(BUGGY_MSC6)
96  /* MSC 6.00A breaks on op/regexp.t test 85 unless we turn this off */
97 #    pragma optimize("a",off)
98  /* But MSC 6.00A is happy with 'w', for aliases only across function calls*/
99 #    pragma optimize("w",on )
100 #  endif /* BUGGY_MSC6 */
101 #endif /* MSDOS */
102
103 #ifndef STATIC
104 #define STATIC  static
105 #endif
106
107 typedef struct RExC_state_t {
108     U32         flags;                  /* are we folding, multilining? */
109     char        *precomp;               /* uncompiled string. */
110     REGEXP      *rx_sv;                 /* The SV that is the regexp. */
111     regexp      *rx;                    /* perl core regexp structure */
112     regexp_internal     *rxi;           /* internal data for regexp object pprivate field */        
113     char        *start;                 /* Start of input for compile */
114     char        *end;                   /* End of input for compile */
115     char        *parse;                 /* Input-scan pointer. */
116     I32         whilem_seen;            /* number of WHILEM in this expr */
117     regnode     *emit_start;            /* Start of emitted-code area */
118     regnode     *emit_bound;            /* First regnode outside of the allocated space */
119     regnode     *emit;                  /* Code-emit pointer; &regdummy = don't = compiling */
120     I32         naughty;                /* How bad is this pattern? */
121     I32         sawback;                /* Did we see \1, ...? */
122     U32         seen;
123     I32         size;                   /* Code size. */
124     I32         npar;                   /* Capture buffer count, (OPEN). */
125     I32         cpar;                   /* Capture buffer count, (CLOSE). */
126     I32         nestroot;               /* root parens we are in - used by accept */
127     I32         extralen;
128     I32         seen_zerolen;
129     I32         seen_evals;
130     regnode     **open_parens;          /* pointers to open parens */
131     regnode     **close_parens;         /* pointers to close parens */
132     regnode     *opend;                 /* END node in program */
133     I32         utf8;           /* whether the pattern is utf8 or not */
134     I32         orig_utf8;      /* whether the pattern was originally in utf8 */
135                                 /* XXX use this for future optimisation of case
136                                  * where pattern must be upgraded to utf8. */
137     I32         uni_semantics;  /* If a d charset modifier should use unicode
138                                    rules, even if the pattern is not in
139                                    utf8 */
140     HV          *paren_names;           /* Paren names */
141     
142     regnode     **recurse;              /* Recurse regops */
143     I32         recurse_count;          /* Number of recurse regops */
144     I32         in_lookbehind;
145     I32         contains_locale;
146     I32         override_recoding;
147 #if ADD_TO_REGEXEC
148     char        *starttry;              /* -Dr: where regtry was called. */
149 #define RExC_starttry   (pRExC_state->starttry)
150 #endif
151 #ifdef DEBUGGING
152     const char  *lastparse;
153     I32         lastnum;
154     AV          *paren_name_list;       /* idx -> name */
155 #define RExC_lastparse  (pRExC_state->lastparse)
156 #define RExC_lastnum    (pRExC_state->lastnum)
157 #define RExC_paren_name_list    (pRExC_state->paren_name_list)
158 #endif
159 } RExC_state_t;
160
161 #define RExC_flags      (pRExC_state->flags)
162 #define RExC_precomp    (pRExC_state->precomp)
163 #define RExC_rx_sv      (pRExC_state->rx_sv)
164 #define RExC_rx         (pRExC_state->rx)
165 #define RExC_rxi        (pRExC_state->rxi)
166 #define RExC_start      (pRExC_state->start)
167 #define RExC_end        (pRExC_state->end)
168 #define RExC_parse      (pRExC_state->parse)
169 #define RExC_whilem_seen        (pRExC_state->whilem_seen)
170 #ifdef RE_TRACK_PATTERN_OFFSETS
171 #define RExC_offsets    (pRExC_state->rxi->u.offsets) /* I am not like the others */
172 #endif
173 #define RExC_emit       (pRExC_state->emit)
174 #define RExC_emit_start (pRExC_state->emit_start)
175 #define RExC_emit_bound (pRExC_state->emit_bound)
176 #define RExC_naughty    (pRExC_state->naughty)
177 #define RExC_sawback    (pRExC_state->sawback)
178 #define RExC_seen       (pRExC_state->seen)
179 #define RExC_size       (pRExC_state->size)
180 #define RExC_npar       (pRExC_state->npar)
181 #define RExC_nestroot   (pRExC_state->nestroot)
182 #define RExC_extralen   (pRExC_state->extralen)
183 #define RExC_seen_zerolen       (pRExC_state->seen_zerolen)
184 #define RExC_seen_evals (pRExC_state->seen_evals)
185 #define RExC_utf8       (pRExC_state->utf8)
186 #define RExC_uni_semantics      (pRExC_state->uni_semantics)
187 #define RExC_orig_utf8  (pRExC_state->orig_utf8)
188 #define RExC_open_parens        (pRExC_state->open_parens)
189 #define RExC_close_parens       (pRExC_state->close_parens)
190 #define RExC_opend      (pRExC_state->opend)
191 #define RExC_paren_names        (pRExC_state->paren_names)
192 #define RExC_recurse    (pRExC_state->recurse)
193 #define RExC_recurse_count      (pRExC_state->recurse_count)
194 #define RExC_in_lookbehind      (pRExC_state->in_lookbehind)
195 #define RExC_contains_locale    (pRExC_state->contains_locale)
196 #define RExC_override_recoding  (pRExC_state->override_recoding)
197
198
199 #define ISMULT1(c)      ((c) == '*' || (c) == '+' || (c) == '?')
200 #define ISMULT2(s)      ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
201         ((*s) == '{' && regcurly(s)))
202
203 #ifdef SPSTART
204 #undef SPSTART          /* dratted cpp namespace... */
205 #endif
206 /*
207  * Flags to be passed up and down.
208  */
209 #define WORST           0       /* Worst case. */
210 #define HASWIDTH        0x01    /* Known to match non-null strings. */
211
212 /* Simple enough to be STAR/PLUS operand, in an EXACT node must be a single
213  * character, and if utf8, must be invariant.  Note that this is not the same thing as REGNODE_SIMPLE */
214 #define SIMPLE          0x02
215 #define SPSTART         0x04    /* Starts with * or +. */
216 #define TRYAGAIN        0x08    /* Weeded out a declaration. */
217 #define POSTPONED       0x10    /* (?1),(?&name), (??{...}) or similar */
218
219 #define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
220
221 /* whether trie related optimizations are enabled */
222 #if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
223 #define TRIE_STUDY_OPT
224 #define FULL_TRIE_STUDY
225 #define TRIE_STCLASS
226 #endif
227
228
229
230 #define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3]
231 #define PBITVAL(paren) (1 << ((paren) & 7))
232 #define PAREN_TEST(u8str,paren) ( PBYTE(u8str,paren) & PBITVAL(paren))
233 #define PAREN_SET(u8str,paren) PBYTE(u8str,paren) |= PBITVAL(paren)
234 #define PAREN_UNSET(u8str,paren) PBYTE(u8str,paren) &= (~PBITVAL(paren))
235
236 /* If not already in utf8, do a longjmp back to the beginning */
237 #define UTF8_LONGJMP 42 /* Choose a value not likely to ever conflict */
238 #define REQUIRE_UTF8    STMT_START {                                       \
239                                      if (! UTF) JMPENV_JUMP(UTF8_LONGJMP); \
240                         } STMT_END
241
242 /* About scan_data_t.
243
244   During optimisation we recurse through the regexp program performing
245   various inplace (keyhole style) optimisations. In addition study_chunk
246   and scan_commit populate this data structure with information about
247   what strings MUST appear in the pattern. We look for the longest 
248   string that must appear at a fixed location, and we look for the
249   longest string that may appear at a floating location. So for instance
250   in the pattern:
251   
252     /FOO[xX]A.*B[xX]BAR/
253     
254   Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
255   strings (because they follow a .* construct). study_chunk will identify
256   both FOO and BAR as being the longest fixed and floating strings respectively.
257   
258   The strings can be composites, for instance
259   
260      /(f)(o)(o)/
261      
262   will result in a composite fixed substring 'foo'.
263   
264   For each string some basic information is maintained:
265   
266   - offset or min_offset
267     This is the position the string must appear at, or not before.
268     It also implicitly (when combined with minlenp) tells us how many
269     characters must match before the string we are searching for.
270     Likewise when combined with minlenp and the length of the string it
271     tells us how many characters must appear after the string we have 
272     found.
273   
274   - max_offset
275     Only used for floating strings. This is the rightmost point that
276     the string can appear at. If set to I32 max it indicates that the
277     string can occur infinitely far to the right.
278   
279   - minlenp
280     A pointer to the minimum length of the pattern that the string 
281     was found inside. This is important as in the case of positive 
282     lookahead or positive lookbehind we can have multiple patterns 
283     involved. Consider
284     
285     /(?=FOO).*F/
286     
287     The minimum length of the pattern overall is 3, the minimum length
288     of the lookahead part is 3, but the minimum length of the part that
289     will actually match is 1. So 'FOO's minimum length is 3, but the 
290     minimum length for the F is 1. This is important as the minimum length
291     is used to determine offsets in front of and behind the string being 
292     looked for.  Since strings can be composites this is the length of the
293     pattern at the time it was committed with a scan_commit. Note that
294     the length is calculated by study_chunk, so that the minimum lengths
295     are not known until the full pattern has been compiled, thus the 
296     pointer to the value.
297   
298   - lookbehind
299   
300     In the case of lookbehind the string being searched for can be
301     offset past the start point of the final matching string. 
302     If this value was just blithely removed from the min_offset it would
303     invalidate some of the calculations for how many chars must match
304     before or after (as they are derived from min_offset and minlen and
305     the length of the string being searched for). 
306     When the final pattern is compiled and the data is moved from the
307     scan_data_t structure into the regexp structure the information
308     about lookbehind is factored in, with the information that would 
309     have been lost precalculated in the end_shift field for the 
310     associated string.
311
312   The fields pos_min and pos_delta are used to store the minimum offset
313   and the delta to the maximum offset at the current point in the pattern.    
314
315 */
316
317 typedef struct scan_data_t {
318     /*I32 len_min;      unused */
319     /*I32 len_delta;    unused */
320     I32 pos_min;
321     I32 pos_delta;
322     SV *last_found;
323     I32 last_end;           /* min value, <0 unless valid. */
324     I32 last_start_min;
325     I32 last_start_max;
326     SV **longest;           /* Either &l_fixed, or &l_float. */
327     SV *longest_fixed;      /* longest fixed string found in pattern */
328     I32 offset_fixed;       /* offset where it starts */
329     I32 *minlen_fixed;      /* pointer to the minlen relevant to the string */
330     I32 lookbehind_fixed;   /* is the position of the string modfied by LB */
331     SV *longest_float;      /* longest floating string found in pattern */
332     I32 offset_float_min;   /* earliest point in string it can appear */
333     I32 offset_float_max;   /* latest point in string it can appear */
334     I32 *minlen_float;      /* pointer to the minlen relevant to the string */
335     I32 lookbehind_float;   /* is the position of the string modified by LB */
336     I32 flags;
337     I32 whilem_c;
338     I32 *last_closep;
339     struct regnode_charclass_class *start_class;
340 } scan_data_t;
341
342 /*
343  * Forward declarations for pregcomp()'s friends.
344  */
345
346 static const scan_data_t zero_scan_data =
347   { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0};
348
349 #define SF_BEFORE_EOL           (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
350 #define SF_BEFORE_SEOL          0x0001
351 #define SF_BEFORE_MEOL          0x0002
352 #define SF_FIX_BEFORE_EOL       (SF_FIX_BEFORE_SEOL|SF_FIX_BEFORE_MEOL)
353 #define SF_FL_BEFORE_EOL        (SF_FL_BEFORE_SEOL|SF_FL_BEFORE_MEOL)
354
355 #ifdef NO_UNARY_PLUS
356 #  define SF_FIX_SHIFT_EOL      (0+2)
357 #  define SF_FL_SHIFT_EOL               (0+4)
358 #else
359 #  define SF_FIX_SHIFT_EOL      (+2)
360 #  define SF_FL_SHIFT_EOL               (+4)
361 #endif
362
363 #define SF_FIX_BEFORE_SEOL      (SF_BEFORE_SEOL << SF_FIX_SHIFT_EOL)
364 #define SF_FIX_BEFORE_MEOL      (SF_BEFORE_MEOL << SF_FIX_SHIFT_EOL)
365
366 #define SF_FL_BEFORE_SEOL       (SF_BEFORE_SEOL << SF_FL_SHIFT_EOL)
367 #define SF_FL_BEFORE_MEOL       (SF_BEFORE_MEOL << SF_FL_SHIFT_EOL) /* 0x20 */
368 #define SF_IS_INF               0x0040
369 #define SF_HAS_PAR              0x0080
370 #define SF_IN_PAR               0x0100
371 #define SF_HAS_EVAL             0x0200
372 #define SCF_DO_SUBSTR           0x0400
373 #define SCF_DO_STCLASS_AND      0x0800
374 #define SCF_DO_STCLASS_OR       0x1000
375 #define SCF_DO_STCLASS          (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
376 #define SCF_WHILEM_VISITED_POS  0x2000
377
378 #define SCF_TRIE_RESTUDY        0x4000 /* Do restudy? */
379 #define SCF_SEEN_ACCEPT         0x8000 
380
381 #define UTF cBOOL(RExC_utf8)
382 #define LOC (get_regex_charset(RExC_flags) == REGEX_LOCALE_CHARSET)
383 #define UNI_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_UNICODE_CHARSET)
384 #define DEPENDS_SEMANTICS (get_regex_charset(RExC_flags) == REGEX_DEPENDS_CHARSET)
385 #define AT_LEAST_UNI_SEMANTICS (get_regex_charset(RExC_flags) >= REGEX_UNICODE_CHARSET)
386 #define ASCII_RESTRICTED (get_regex_charset(RExC_flags) == REGEX_ASCII_RESTRICTED_CHARSET)
387 #define MORE_ASCII_RESTRICTED (get_regex_charset(RExC_flags) == REGEX_ASCII_MORE_RESTRICTED_CHARSET)
388 #define AT_LEAST_ASCII_RESTRICTED (get_regex_charset(RExC_flags) >= REGEX_ASCII_RESTRICTED_CHARSET)
389
390 #define FOLD cBOOL(RExC_flags & RXf_PMf_FOLD)
391
392 #define OOB_UNICODE             12345678
393 #define OOB_NAMEDCLASS          -1
394
395 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
396 #define CHR_DIST(a,b) (UTF ? utf8_distance(a,b) : a - b)
397
398
399 /* length of regex to show in messages that don't mark a position within */
400 #define RegexLengthToShowInErrorMessages 127
401
402 /*
403  * If MARKER[12] are adjusted, be sure to adjust the constants at the top
404  * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
405  * op/pragma/warn/regcomp.
406  */
407 #define MARKER1 "<-- HERE"    /* marker as it appears in the description */
408 #define MARKER2 " <-- HERE "  /* marker as it appears within the regex */
409
410 #define REPORT_LOCATION " in regex; marked by " MARKER1 " in m/%.*s" MARKER2 "%s/"
411
412 /*
413  * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
414  * arg. Show regex, up to a maximum length. If it's too long, chop and add
415  * "...".
416  */
417 #define _FAIL(code) STMT_START {                                        \
418     const char *ellipses = "";                                          \
419     IV len = RExC_end - RExC_precomp;                                   \
420                                                                         \
421     if (!SIZE_ONLY)                                                     \
422         SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx_sv);                   \
423     if (len > RegexLengthToShowInErrorMessages) {                       \
424         /* chop 10 shorter than the max, to ensure meaning of "..." */  \
425         len = RegexLengthToShowInErrorMessages - 10;                    \
426         ellipses = "...";                                               \
427     }                                                                   \
428     code;                                                               \
429 } STMT_END
430
431 #define FAIL(msg) _FAIL(                            \
432     Perl_croak(aTHX_ "%s in regex m/%.*s%s/",       \
433             msg, (int)len, RExC_precomp, ellipses))
434
435 #define FAIL2(msg,arg) _FAIL(                       \
436     Perl_croak(aTHX_ msg " in regex m/%.*s%s/",     \
437             arg, (int)len, RExC_precomp, ellipses))
438
439 /*
440  * Simple_vFAIL -- like FAIL, but marks the current location in the scan
441  */
442 #define Simple_vFAIL(m) STMT_START {                                    \
443     const IV offset = RExC_parse - RExC_precomp;                        \
444     Perl_croak(aTHX_ "%s" REPORT_LOCATION,                              \
445             m, (int)offset, RExC_precomp, RExC_precomp + offset);       \
446 } STMT_END
447
448 /*
449  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
450  */
451 #define vFAIL(m) STMT_START {                           \
452     if (!SIZE_ONLY)                                     \
453         SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx_sv);   \
454     Simple_vFAIL(m);                                    \
455 } STMT_END
456
457 /*
458  * Like Simple_vFAIL(), but accepts two arguments.
459  */
460 #define Simple_vFAIL2(m,a1) STMT_START {                        \
461     const IV offset = RExC_parse - RExC_precomp;                        \
462     S_re_croak2(aTHX_ m, REPORT_LOCATION, a1,                   \
463             (int)offset, RExC_precomp, RExC_precomp + offset);  \
464 } STMT_END
465
466 /*
467  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
468  */
469 #define vFAIL2(m,a1) STMT_START {                       \
470     if (!SIZE_ONLY)                                     \
471         SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx_sv);   \
472     Simple_vFAIL2(m, a1);                               \
473 } STMT_END
474
475
476 /*
477  * Like Simple_vFAIL(), but accepts three arguments.
478  */
479 #define Simple_vFAIL3(m, a1, a2) STMT_START {                   \
480     const IV offset = RExC_parse - RExC_precomp;                \
481     S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2,               \
482             (int)offset, RExC_precomp, RExC_precomp + offset);  \
483 } STMT_END
484
485 /*
486  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
487  */
488 #define vFAIL3(m,a1,a2) STMT_START {                    \
489     if (!SIZE_ONLY)                                     \
490         SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx_sv);   \
491     Simple_vFAIL3(m, a1, a2);                           \
492 } STMT_END
493
494 /*
495  * Like Simple_vFAIL(), but accepts four arguments.
496  */
497 #define Simple_vFAIL4(m, a1, a2, a3) STMT_START {               \
498     const IV offset = RExC_parse - RExC_precomp;                \
499     S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, a3,           \
500             (int)offset, RExC_precomp, RExC_precomp + offset);  \
501 } STMT_END
502
503 #define ckWARNreg(loc,m) STMT_START {                                   \
504     const IV offset = loc - RExC_precomp;                               \
505     Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION,      \
506             (int)offset, RExC_precomp, RExC_precomp + offset);          \
507 } STMT_END
508
509 #define ckWARNregdep(loc,m) STMT_START {                                \
510     const IV offset = loc - RExC_precomp;                               \
511     Perl_ck_warner_d(aTHX_ packWARN2(WARN_DEPRECATED, WARN_REGEXP),     \
512             m REPORT_LOCATION,                                          \
513             (int)offset, RExC_precomp, RExC_precomp + offset);          \
514 } STMT_END
515
516 #define ckWARN2regdep(loc,m, a1) STMT_START {                           \
517     const IV offset = loc - RExC_precomp;                               \
518     Perl_ck_warner_d(aTHX_ packWARN2(WARN_DEPRECATED, WARN_REGEXP),     \
519             m REPORT_LOCATION,                                          \
520             a1, (int)offset, RExC_precomp, RExC_precomp + offset);      \
521 } STMT_END
522
523 #define ckWARN2reg(loc, m, a1) STMT_START {                             \
524     const IV offset = loc - RExC_precomp;                               \
525     Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION,      \
526             a1, (int)offset, RExC_precomp, RExC_precomp + offset);      \
527 } STMT_END
528
529 #define vWARN3(loc, m, a1, a2) STMT_START {                             \
530     const IV offset = loc - RExC_precomp;                               \
531     Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION,         \
532             a1, a2, (int)offset, RExC_precomp, RExC_precomp + offset);  \
533 } STMT_END
534
535 #define ckWARN3reg(loc, m, a1, a2) STMT_START {                         \
536     const IV offset = loc - RExC_precomp;                               \
537     Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION,      \
538             a1, a2, (int)offset, RExC_precomp, RExC_precomp + offset);  \
539 } STMT_END
540
541 #define vWARN4(loc, m, a1, a2, a3) STMT_START {                         \
542     const IV offset = loc - RExC_precomp;                               \
543     Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION,         \
544             a1, a2, a3, (int)offset, RExC_precomp, RExC_precomp + offset); \
545 } STMT_END
546
547 #define ckWARN4reg(loc, m, a1, a2, a3) STMT_START {                     \
548     const IV offset = loc - RExC_precomp;                               \
549     Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION,      \
550             a1, a2, a3, (int)offset, RExC_precomp, RExC_precomp + offset); \
551 } STMT_END
552
553 #define vWARN5(loc, m, a1, a2, a3, a4) STMT_START {                     \
554     const IV offset = loc - RExC_precomp;                               \
555     Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION,         \
556             a1, a2, a3, a4, (int)offset, RExC_precomp, RExC_precomp + offset); \
557 } STMT_END
558
559
560 /* Allow for side effects in s */
561 #define REGC(c,s) STMT_START {                  \
562     if (!SIZE_ONLY) *(s) = (c); else (void)(s); \
563 } STMT_END
564
565 /* Macros for recording node offsets.   20001227 mjd@plover.com 
566  * Nodes are numbered 1, 2, 3, 4.  Node #n's position is recorded in
567  * element 2*n-1 of the array.  Element #2n holds the byte length node #n.
568  * Element 0 holds the number n.
569  * Position is 1 indexed.
570  */
571 #ifndef RE_TRACK_PATTERN_OFFSETS
572 #define Set_Node_Offset_To_R(node,byte)
573 #define Set_Node_Offset(node,byte)
574 #define Set_Cur_Node_Offset
575 #define Set_Node_Length_To_R(node,len)
576 #define Set_Node_Length(node,len)
577 #define Set_Node_Cur_Length(node)
578 #define Node_Offset(n) 
579 #define Node_Length(n) 
580 #define Set_Node_Offset_Length(node,offset,len)
581 #define ProgLen(ri) ri->u.proglen
582 #define SetProgLen(ri,x) ri->u.proglen = x
583 #else
584 #define ProgLen(ri) ri->u.offsets[0]
585 #define SetProgLen(ri,x) ri->u.offsets[0] = x
586 #define Set_Node_Offset_To_R(node,byte) STMT_START {                    \
587     if (! SIZE_ONLY) {                                                  \
588         MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n",         \
589                     __LINE__, (int)(node), (int)(byte)));               \
590         if((node) < 0) {                                                \
591             Perl_croak(aTHX_ "value of node is %d in Offset macro", (int)(node)); \
592         } else {                                                        \
593             RExC_offsets[2*(node)-1] = (byte);                          \
594         }                                                               \
595     }                                                                   \
596 } STMT_END
597
598 #define Set_Node_Offset(node,byte) \
599     Set_Node_Offset_To_R((node)-RExC_emit_start, (byte)-RExC_start)
600 #define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
601
602 #define Set_Node_Length_To_R(node,len) STMT_START {                     \
603     if (! SIZE_ONLY) {                                                  \
604         MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n",           \
605                 __LINE__, (int)(node), (int)(len)));                    \
606         if((node) < 0) {                                                \
607             Perl_croak(aTHX_ "value of node is %d in Length macro", (int)(node)); \
608         } else {                                                        \
609             RExC_offsets[2*(node)] = (len);                             \
610         }                                                               \
611     }                                                                   \
612 } STMT_END
613
614 #define Set_Node_Length(node,len) \
615     Set_Node_Length_To_R((node)-RExC_emit_start, len)
616 #define Set_Cur_Node_Length(len) Set_Node_Length(RExC_emit, len)
617 #define Set_Node_Cur_Length(node) \
618     Set_Node_Length(node, RExC_parse - parse_start)
619
620 /* Get offsets and lengths */
621 #define Node_Offset(n) (RExC_offsets[2*((n)-RExC_emit_start)-1])
622 #define Node_Length(n) (RExC_offsets[2*((n)-RExC_emit_start)])
623
624 #define Set_Node_Offset_Length(node,offset,len) STMT_START {    \
625     Set_Node_Offset_To_R((node)-RExC_emit_start, (offset));     \
626     Set_Node_Length_To_R((node)-RExC_emit_start, (len));        \
627 } STMT_END
628 #endif
629
630 #if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
631 #define EXPERIMENTAL_INPLACESCAN
632 #endif /*PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS*/
633
634 #define DEBUG_STUDYDATA(str,data,depth)                              \
635 DEBUG_OPTIMISE_MORE_r(if(data){                                      \
636     PerlIO_printf(Perl_debug_log,                                    \
637         "%*s" str "Pos:%"IVdf"/%"IVdf                                \
638         " Flags: 0x%"UVXf" Whilem_c: %"IVdf" Lcp: %"IVdf" %s",       \
639         (int)(depth)*2, "",                                          \
640         (IV)((data)->pos_min),                                       \
641         (IV)((data)->pos_delta),                                     \
642         (UV)((data)->flags),                                         \
643         (IV)((data)->whilem_c),                                      \
644         (IV)((data)->last_closep ? *((data)->last_closep) : -1),     \
645         is_inf ? "INF " : ""                                         \
646     );                                                               \
647     if ((data)->last_found)                                          \
648         PerlIO_printf(Perl_debug_log,                                \
649             "Last:'%s' %"IVdf":%"IVdf"/%"IVdf" %sFixed:'%s' @ %"IVdf \
650             " %sFloat: '%s' @ %"IVdf"/%"IVdf"",                      \
651             SvPVX_const((data)->last_found),                         \
652             (IV)((data)->last_end),                                  \
653             (IV)((data)->last_start_min),                            \
654             (IV)((data)->last_start_max),                            \
655             ((data)->longest &&                                      \
656              (data)->longest==&((data)->longest_fixed)) ? "*" : "",  \
657             SvPVX_const((data)->longest_fixed),                      \
658             (IV)((data)->offset_fixed),                              \
659             ((data)->longest &&                                      \
660              (data)->longest==&((data)->longest_float)) ? "*" : "",  \
661             SvPVX_const((data)->longest_float),                      \
662             (IV)((data)->offset_float_min),                          \
663             (IV)((data)->offset_float_max)                           \
664         );                                                           \
665     PerlIO_printf(Perl_debug_log,"\n");                              \
666 });
667
668 static void clear_re(pTHX_ void *r);
669
670 /* Mark that we cannot extend a found fixed substring at this point.
671    Update the longest found anchored substring and the longest found
672    floating substrings if needed. */
673
674 STATIC void
675 S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data, I32 *minlenp, int is_inf)
676 {
677     const STRLEN l = CHR_SVLEN(data->last_found);
678     const STRLEN old_l = CHR_SVLEN(*data->longest);
679     GET_RE_DEBUG_FLAGS_DECL;
680
681     PERL_ARGS_ASSERT_SCAN_COMMIT;
682
683     if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
684         SvSetMagicSV(*data->longest, data->last_found);
685         if (*data->longest == data->longest_fixed) {
686             data->offset_fixed = l ? data->last_start_min : data->pos_min;
687             if (data->flags & SF_BEFORE_EOL)
688                 data->flags
689                     |= ((data->flags & SF_BEFORE_EOL) << SF_FIX_SHIFT_EOL);
690             else
691                 data->flags &= ~SF_FIX_BEFORE_EOL;
692             data->minlen_fixed=minlenp;
693             data->lookbehind_fixed=0;
694         }
695         else { /* *data->longest == data->longest_float */
696             data->offset_float_min = l ? data->last_start_min : data->pos_min;
697             data->offset_float_max = (l
698                                       ? data->last_start_max
699                                       : data->pos_min + data->pos_delta);
700             if (is_inf || (U32)data->offset_float_max > (U32)I32_MAX)
701                 data->offset_float_max = I32_MAX;
702             if (data->flags & SF_BEFORE_EOL)
703                 data->flags
704                     |= ((data->flags & SF_BEFORE_EOL) << SF_FL_SHIFT_EOL);
705             else
706                 data->flags &= ~SF_FL_BEFORE_EOL;
707             data->minlen_float=minlenp;
708             data->lookbehind_float=0;
709         }
710     }
711     SvCUR_set(data->last_found, 0);
712     {
713         SV * const sv = data->last_found;
714         if (SvUTF8(sv) && SvMAGICAL(sv)) {
715             MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
716             if (mg)
717                 mg->mg_len = 0;
718         }
719     }
720     data->last_end = -1;
721     data->flags &= ~SF_BEFORE_EOL;
722     DEBUG_STUDYDATA("commit: ",data,0);
723 }
724
725 /* Can match anything (initialization) */
726 STATIC void
727 S_cl_anything(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
728 {
729     PERL_ARGS_ASSERT_CL_ANYTHING;
730
731     ANYOF_BITMAP_SETALL(cl);
732     cl->flags = ANYOF_CLASS|ANYOF_EOS|ANYOF_UNICODE_ALL
733                 |ANYOF_LOC_NONBITMAP_FOLD|ANYOF_NON_UTF8_LATIN1_ALL;
734
735     /* If any portion of the regex is to operate under locale rules,
736      * initialization includes it.  The reason this isn't done for all regexes
737      * is that the optimizer was written under the assumption that locale was
738      * all-or-nothing.  Given the complexity and lack of documentation in the
739      * optimizer, and that there are inadequate test cases for locale, so many
740      * parts of it may not work properly, it is safest to avoid locale unless
741      * necessary. */
742     if (RExC_contains_locale) {
743         ANYOF_CLASS_SETALL(cl);     /* /l uses class */
744         cl->flags |= ANYOF_LOCALE;
745     }
746     else {
747         ANYOF_CLASS_ZERO(cl);       /* Only /l uses class now */
748     }
749 }
750
751 /* Can match anything (initialization) */
752 STATIC int
753 S_cl_is_anything(const struct regnode_charclass_class *cl)
754 {
755     int value;
756
757     PERL_ARGS_ASSERT_CL_IS_ANYTHING;
758
759     for (value = 0; value <= ANYOF_MAX; value += 2)
760         if (ANYOF_CLASS_TEST(cl, value) && ANYOF_CLASS_TEST(cl, value + 1))
761             return 1;
762     if (!(cl->flags & ANYOF_UNICODE_ALL))
763         return 0;
764     if (!ANYOF_BITMAP_TESTALLSET((const void*)cl))
765         return 0;
766     return 1;
767 }
768
769 /* Can match anything (initialization) */
770 STATIC void
771 S_cl_init(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
772 {
773     PERL_ARGS_ASSERT_CL_INIT;
774
775     Zero(cl, 1, struct regnode_charclass_class);
776     cl->type = ANYOF;
777     cl_anything(pRExC_state, cl);
778     ARG_SET(cl, ANYOF_NONBITMAP_EMPTY);
779 }
780
781 /* These two functions currently do the exact same thing */
782 #define cl_init_zero            S_cl_init
783
784 /* 'AND' a given class with another one.  Can create false positives.  'cl'
785  * should not be inverted.  'and_with->flags & ANYOF_CLASS' should be 0 if
786  * 'and_with' is a regnode_charclass instead of a regnode_charclass_class. */
787 STATIC void
788 S_cl_and(struct regnode_charclass_class *cl,
789         const struct regnode_charclass_class *and_with)
790 {
791     PERL_ARGS_ASSERT_CL_AND;
792
793     assert(and_with->type == ANYOF);
794
795     /* I (khw) am not sure all these restrictions are necessary XXX */
796     if (!(ANYOF_CLASS_TEST_ANY_SET(and_with))
797         && !(ANYOF_CLASS_TEST_ANY_SET(cl))
798         && (and_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
799         && !(and_with->flags & ANYOF_LOC_NONBITMAP_FOLD)
800         && !(cl->flags & ANYOF_LOC_NONBITMAP_FOLD)) {
801         int i;
802
803         if (and_with->flags & ANYOF_INVERT)
804             for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
805                 cl->bitmap[i] &= ~and_with->bitmap[i];
806         else
807             for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
808                 cl->bitmap[i] &= and_with->bitmap[i];
809     } /* XXXX: logic is complicated otherwise, leave it along for a moment. */
810
811     if (and_with->flags & ANYOF_INVERT) {
812
813         /* Here, the and'ed node is inverted.  Get the AND of the flags that
814          * aren't affected by the inversion.  Those that are affected are
815          * handled individually below */
816         U8 affected_flags = cl->flags & ~INVERSION_UNAFFECTED_FLAGS;
817         cl->flags &= (and_with->flags & INVERSION_UNAFFECTED_FLAGS);
818         cl->flags |= affected_flags;
819
820         /* We currently don't know how to deal with things that aren't in the
821          * bitmap, but we know that the intersection is no greater than what
822          * is already in cl, so let there be false positives that get sorted
823          * out after the synthetic start class succeeds, and the node is
824          * matched for real. */
825
826         /* The inversion of these two flags indicate that the resulting
827          * intersection doesn't have them */
828         if (and_with->flags & ANYOF_UNICODE_ALL) {
829             cl->flags &= ~ANYOF_UNICODE_ALL;
830         }
831         if (and_with->flags & ANYOF_NON_UTF8_LATIN1_ALL) {
832             cl->flags &= ~ANYOF_NON_UTF8_LATIN1_ALL;
833         }
834     }
835     else {   /* and'd node is not inverted */
836         U8 outside_bitmap_but_not_utf8; /* Temp variable */
837
838         if (! ANYOF_NONBITMAP(and_with)) {
839
840             /* Here 'and_with' doesn't match anything outside the bitmap
841              * (except possibly ANYOF_UNICODE_ALL), which means the
842              * intersection can't either, except for ANYOF_UNICODE_ALL, in
843              * which case we don't know what the intersection is, but it's no
844              * greater than what cl already has, so can just leave it alone,
845              * with possible false positives */
846             if (! (and_with->flags & ANYOF_UNICODE_ALL)) {
847                 ARG_SET(cl, ANYOF_NONBITMAP_EMPTY);
848                 cl->flags &= ~ANYOF_NONBITMAP_NON_UTF8;
849             }
850         }
851         else if (! ANYOF_NONBITMAP(cl)) {
852
853             /* Here, 'and_with' does match something outside the bitmap, and cl
854              * doesn't have a list of things to match outside the bitmap.  If
855              * cl can match all code points above 255, the intersection will
856              * be those above-255 code points that 'and_with' matches.  If cl
857              * can't match all Unicode code points, it means that it can't
858              * match anything outside the bitmap (since the 'if' that got us
859              * into this block tested for that), so we leave the bitmap empty.
860              */
861             if (cl->flags & ANYOF_UNICODE_ALL) {
862                 ARG_SET(cl, ARG(and_with));
863
864                 /* and_with's ARG may match things that don't require UTF8.
865                  * And now cl's will too, in spite of this being an 'and'.  See
866                  * the comments below about the kludge */
867                 cl->flags |= and_with->flags & ANYOF_NONBITMAP_NON_UTF8;
868             }
869         }
870         else {
871             /* Here, both 'and_with' and cl match something outside the
872              * bitmap.  Currently we do not do the intersection, so just match
873              * whatever cl had at the beginning.  */
874         }
875
876
877         /* Take the intersection of the two sets of flags.  However, the
878          * ANYOF_NONBITMAP_NON_UTF8 flag is treated as an 'or'.  This is a
879          * kludge around the fact that this flag is not treated like the others
880          * which are initialized in cl_anything().  The way the optimizer works
881          * is that the synthetic start class (SSC) is initialized to match
882          * anything, and then the first time a real node is encountered, its
883          * values are AND'd with the SSC's with the result being the values of
884          * the real node.  However, there are paths through the optimizer where
885          * the AND never gets called, so those initialized bits are set
886          * inappropriately, which is not usually a big deal, as they just cause
887          * false positives in the SSC, which will just mean a probably
888          * imperceptible slow down in execution.  However this bit has a
889          * higher false positive consequence in that it can cause utf8.pm,
890          * utf8_heavy.pl ... to be loaded when not necessary, which is a much
891          * bigger slowdown and also causes significant extra memory to be used.
892          * In order to prevent this, the code now takes a different tack.  The
893          * bit isn't set unless some part of the regular expression needs it,
894          * but once set it won't get cleared.  This means that these extra
895          * modules won't get loaded unless there was some path through the
896          * pattern that would have required them anyway, and  so any false
897          * positives that occur by not ANDing them out when they could be
898          * aren't as severe as they would be if we treated this bit like all
899          * the others */
900         outside_bitmap_but_not_utf8 = (cl->flags | and_with->flags)
901                                       & ANYOF_NONBITMAP_NON_UTF8;
902         cl->flags &= and_with->flags;
903         cl->flags |= outside_bitmap_but_not_utf8;
904     }
905 }
906
907 /* 'OR' a given class with another one.  Can create false positives.  'cl'
908  * should not be inverted.  'or_with->flags & ANYOF_CLASS' should be 0 if
909  * 'or_with' is a regnode_charclass instead of a regnode_charclass_class. */
910 STATIC void
911 S_cl_or(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl, const struct regnode_charclass_class *or_with)
912 {
913     PERL_ARGS_ASSERT_CL_OR;
914
915     if (or_with->flags & ANYOF_INVERT) {
916
917         /* Here, the or'd node is to be inverted.  This means we take the
918          * complement of everything not in the bitmap, but currently we don't
919          * know what that is, so give up and match anything */
920         if (ANYOF_NONBITMAP(or_with)) {
921             cl_anything(pRExC_state, cl);
922         }
923         /* We do not use
924          * (B1 | CL1) | (!B2 & !CL2) = (B1 | !B2 & !CL2) | (CL1 | (!B2 & !CL2))
925          *   <= (B1 | !B2) | (CL1 | !CL2)
926          * which is wasteful if CL2 is small, but we ignore CL2:
927          *   (B1 | CL1) | (!B2 & !CL2) <= (B1 | CL1) | !B2 = (B1 | !B2) | CL1
928          * XXXX Can we handle case-fold?  Unclear:
929          *   (OK1(i) | OK1(i')) | !(OK1(i) | OK1(i')) =
930          *   (OK1(i) | OK1(i')) | (!OK1(i) & !OK1(i'))
931          */
932         else if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
933              && !(or_with->flags & ANYOF_LOC_NONBITMAP_FOLD)
934              && !(cl->flags & ANYOF_LOC_NONBITMAP_FOLD) ) {
935             int i;
936
937             for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
938                 cl->bitmap[i] |= ~or_with->bitmap[i];
939         } /* XXXX: logic is complicated otherwise */
940         else {
941             cl_anything(pRExC_state, cl);
942         }
943
944         /* And, we can just take the union of the flags that aren't affected
945          * by the inversion */
946         cl->flags |= or_with->flags & INVERSION_UNAFFECTED_FLAGS;
947
948         /* For the remaining flags:
949             ANYOF_UNICODE_ALL and inverted means to not match anything above
950                     255, which means that the union with cl should just be
951                     what cl has in it, so can ignore this flag
952             ANYOF_NON_UTF8_LATIN1_ALL and inverted means if not utf8 and ord
953                     is 127-255 to match them, but then invert that, so the
954                     union with cl should just be what cl has in it, so can
955                     ignore this flag
956          */
957     } else {    /* 'or_with' is not inverted */
958         /* (B1 | CL1) | (B2 | CL2) = (B1 | B2) | (CL1 | CL2)) */
959         if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
960              && (!(or_with->flags & ANYOF_LOC_NONBITMAP_FOLD)
961                  || (cl->flags & ANYOF_LOC_NONBITMAP_FOLD)) ) {
962             int i;
963
964             /* OR char bitmap and class bitmap separately */
965             for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
966                 cl->bitmap[i] |= or_with->bitmap[i];
967             if (ANYOF_CLASS_TEST_ANY_SET(or_with)) {
968                 for (i = 0; i < ANYOF_CLASSBITMAP_SIZE; i++)
969                     cl->classflags[i] |= or_with->classflags[i];
970                 cl->flags |= ANYOF_CLASS;
971             }
972         }
973         else { /* XXXX: logic is complicated, leave it along for a moment. */
974             cl_anything(pRExC_state, cl);
975         }
976
977         if (ANYOF_NONBITMAP(or_with)) {
978
979             /* Use the added node's outside-the-bit-map match if there isn't a
980              * conflict.  If there is a conflict (both nodes match something
981              * outside the bitmap, but what they match outside is not the same
982              * pointer, and hence not easily compared until XXX we extend
983              * inversion lists this far), give up and allow the start class to
984              * match everything outside the bitmap.  If that stuff is all above
985              * 255, can just set UNICODE_ALL, otherwise caould be anything. */
986             if (! ANYOF_NONBITMAP(cl)) {
987                 ARG_SET(cl, ARG(or_with));
988             }
989             else if (ARG(cl) != ARG(or_with)) {
990
991                 if ((or_with->flags & ANYOF_NONBITMAP_NON_UTF8)) {
992                     cl_anything(pRExC_state, cl);
993                 }
994                 else {
995                     cl->flags |= ANYOF_UNICODE_ALL;
996                 }
997             }
998         }
999
1000         /* Take the union */
1001         cl->flags |= or_with->flags;
1002     }
1003 }
1004
1005 #define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
1006 #define TRIE_LIST_CUR(state)  ( TRIE_LIST_ITEM( state, 0 ).forid )
1007 #define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
1008 #define TRIE_LIST_USED(idx)  ( trie->states[state].trans.list ? (TRIE_LIST_CUR( idx ) - 1) : 0 )
1009
1010
1011 #ifdef DEBUGGING
1012 /*
1013    dump_trie(trie,widecharmap,revcharmap)
1014    dump_trie_interim_list(trie,widecharmap,revcharmap,next_alloc)
1015    dump_trie_interim_table(trie,widecharmap,revcharmap,next_alloc)
1016
1017    These routines dump out a trie in a somewhat readable format.
1018    The _interim_ variants are used for debugging the interim
1019    tables that are used to generate the final compressed
1020    representation which is what dump_trie expects.
1021
1022    Part of the reason for their existence is to provide a form
1023    of documentation as to how the different representations function.
1024
1025 */
1026
1027 /*
1028   Dumps the final compressed table form of the trie to Perl_debug_log.
1029   Used for debugging make_trie().
1030 */
1031
1032 STATIC void
1033 S_dump_trie(pTHX_ const struct _reg_trie_data *trie, HV *widecharmap,
1034             AV *revcharmap, U32 depth)
1035 {
1036     U32 state;
1037     SV *sv=sv_newmortal();
1038     int colwidth= widecharmap ? 6 : 4;
1039     U16 word;
1040     GET_RE_DEBUG_FLAGS_DECL;
1041
1042     PERL_ARGS_ASSERT_DUMP_TRIE;
1043
1044     PerlIO_printf( Perl_debug_log, "%*sChar : %-6s%-6s%-4s ",
1045         (int)depth * 2 + 2,"",
1046         "Match","Base","Ofs" );
1047
1048     for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
1049         SV ** const tmp = av_fetch( revcharmap, state, 0);
1050         if ( tmp ) {
1051             PerlIO_printf( Perl_debug_log, "%*s", 
1052                 colwidth,
1053                 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth, 
1054                             PL_colors[0], PL_colors[1],
1055                             (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
1056                             PERL_PV_ESCAPE_FIRSTCHAR 
1057                 ) 
1058             );
1059         }
1060     }
1061     PerlIO_printf( Perl_debug_log, "\n%*sState|-----------------------",
1062         (int)depth * 2 + 2,"");
1063
1064     for( state = 0 ; state < trie->uniquecharcount ; state++ )
1065         PerlIO_printf( Perl_debug_log, "%.*s", colwidth, "--------");
1066     PerlIO_printf( Perl_debug_log, "\n");
1067
1068     for( state = 1 ; state < trie->statecount ; state++ ) {
1069         const U32 base = trie->states[ state ].trans.base;
1070
1071         PerlIO_printf( Perl_debug_log, "%*s#%4"UVXf"|", (int)depth * 2 + 2,"", (UV)state);
1072
1073         if ( trie->states[ state ].wordnum ) {
1074             PerlIO_printf( Perl_debug_log, " W%4X", trie->states[ state ].wordnum );
1075         } else {
1076             PerlIO_printf( Perl_debug_log, "%6s", "" );
1077         }
1078
1079         PerlIO_printf( Perl_debug_log, " @%4"UVXf" ", (UV)base );
1080
1081         if ( base ) {
1082             U32 ofs = 0;
1083
1084             while( ( base + ofs  < trie->uniquecharcount ) ||
1085                    ( base + ofs - trie->uniquecharcount < trie->lasttrans
1086                      && trie->trans[ base + ofs - trie->uniquecharcount ].check != state))
1087                     ofs++;
1088
1089             PerlIO_printf( Perl_debug_log, "+%2"UVXf"[ ", (UV)ofs);
1090
1091             for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
1092                 if ( ( base + ofs >= trie->uniquecharcount ) &&
1093                      ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
1094                      trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
1095                 {
1096                    PerlIO_printf( Perl_debug_log, "%*"UVXf,
1097                     colwidth,
1098                     (UV)trie->trans[ base + ofs - trie->uniquecharcount ].next );
1099                 } else {
1100                     PerlIO_printf( Perl_debug_log, "%*s",colwidth,"   ." );
1101                 }
1102             }
1103
1104             PerlIO_printf( Perl_debug_log, "]");
1105
1106         }
1107         PerlIO_printf( Perl_debug_log, "\n" );
1108     }
1109     PerlIO_printf(Perl_debug_log, "%*sword_info N:(prev,len)=", (int)depth*2, "");
1110     for (word=1; word <= trie->wordcount; word++) {
1111         PerlIO_printf(Perl_debug_log, " %d:(%d,%d)",
1112             (int)word, (int)(trie->wordinfo[word].prev),
1113             (int)(trie->wordinfo[word].len));
1114     }
1115     PerlIO_printf(Perl_debug_log, "\n" );
1116 }    
1117 /*
1118   Dumps a fully constructed but uncompressed trie in list form.
1119   List tries normally only are used for construction when the number of 
1120   possible chars (trie->uniquecharcount) is very high.
1121   Used for debugging make_trie().
1122 */
1123 STATIC void
1124 S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie,
1125                          HV *widecharmap, AV *revcharmap, U32 next_alloc,
1126                          U32 depth)
1127 {
1128     U32 state;
1129     SV *sv=sv_newmortal();
1130     int colwidth= widecharmap ? 6 : 4;
1131     GET_RE_DEBUG_FLAGS_DECL;
1132
1133     PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_LIST;
1134
1135     /* print out the table precompression.  */
1136     PerlIO_printf( Perl_debug_log, "%*sState :Word | Transition Data\n%*s%s",
1137         (int)depth * 2 + 2,"", (int)depth * 2 + 2,"",
1138         "------:-----+-----------------\n" );
1139     
1140     for( state=1 ; state < next_alloc ; state ++ ) {
1141         U16 charid;
1142     
1143         PerlIO_printf( Perl_debug_log, "%*s %4"UVXf" :",
1144             (int)depth * 2 + 2,"", (UV)state  );
1145         if ( ! trie->states[ state ].wordnum ) {
1146             PerlIO_printf( Perl_debug_log, "%5s| ","");
1147         } else {
1148             PerlIO_printf( Perl_debug_log, "W%4x| ",
1149                 trie->states[ state ].wordnum
1150             );
1151         }
1152         for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
1153             SV ** const tmp = av_fetch( revcharmap, TRIE_LIST_ITEM(state,charid).forid, 0);
1154             if ( tmp ) {
1155                 PerlIO_printf( Perl_debug_log, "%*s:%3X=%4"UVXf" | ",
1156                     colwidth,
1157                     pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth, 
1158                             PL_colors[0], PL_colors[1],
1159                             (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
1160                             PERL_PV_ESCAPE_FIRSTCHAR 
1161                     ) ,
1162                     TRIE_LIST_ITEM(state,charid).forid,
1163                     (UV)TRIE_LIST_ITEM(state,charid).newstate
1164                 );
1165                 if (!(charid % 10)) 
1166                     PerlIO_printf(Perl_debug_log, "\n%*s| ",
1167                         (int)((depth * 2) + 14), "");
1168             }
1169         }
1170         PerlIO_printf( Perl_debug_log, "\n");
1171     }
1172 }    
1173
1174 /*
1175   Dumps a fully constructed but uncompressed trie in table form.
1176   This is the normal DFA style state transition table, with a few 
1177   twists to facilitate compression later. 
1178   Used for debugging make_trie().
1179 */
1180 STATIC void
1181 S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie,
1182                           HV *widecharmap, AV *revcharmap, U32 next_alloc,
1183                           U32 depth)
1184 {
1185     U32 state;
1186     U16 charid;
1187     SV *sv=sv_newmortal();
1188     int colwidth= widecharmap ? 6 : 4;
1189     GET_RE_DEBUG_FLAGS_DECL;
1190
1191     PERL_ARGS_ASSERT_DUMP_TRIE_INTERIM_TABLE;
1192     
1193     /*
1194        print out the table precompression so that we can do a visual check
1195        that they are identical.
1196      */
1197     
1198     PerlIO_printf( Perl_debug_log, "%*sChar : ",(int)depth * 2 + 2,"" );
1199
1200     for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
1201         SV ** const tmp = av_fetch( revcharmap, charid, 0);
1202         if ( tmp ) {
1203             PerlIO_printf( Perl_debug_log, "%*s", 
1204                 colwidth,
1205                 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth, 
1206                             PL_colors[0], PL_colors[1],
1207                             (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
1208                             PERL_PV_ESCAPE_FIRSTCHAR 
1209                 ) 
1210             );
1211         }
1212     }
1213
1214     PerlIO_printf( Perl_debug_log, "\n%*sState+-",(int)depth * 2 + 2,"" );
1215
1216     for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
1217         PerlIO_printf( Perl_debug_log, "%.*s", colwidth,"--------");
1218     }
1219
1220     PerlIO_printf( Perl_debug_log, "\n" );
1221
1222     for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
1223
1224         PerlIO_printf( Perl_debug_log, "%*s%4"UVXf" : ", 
1225             (int)depth * 2 + 2,"",
1226             (UV)TRIE_NODENUM( state ) );
1227
1228         for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
1229             UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
1230             if (v)
1231                 PerlIO_printf( Perl_debug_log, "%*"UVXf, colwidth, v );
1232             else
1233                 PerlIO_printf( Perl_debug_log, "%*s", colwidth, "." );
1234         }
1235         if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
1236             PerlIO_printf( Perl_debug_log, " (%4"UVXf")\n", (UV)trie->trans[ state ].check );
1237         } else {
1238             PerlIO_printf( Perl_debug_log, " (%4"UVXf") W%4X\n", (UV)trie->trans[ state ].check,
1239             trie->states[ TRIE_NODENUM( state ) ].wordnum );
1240         }
1241     }
1242 }
1243
1244 #endif
1245
1246
1247 /* make_trie(startbranch,first,last,tail,word_count,flags,depth)
1248   startbranch: the first branch in the whole branch sequence
1249   first      : start branch of sequence of branch-exact nodes.
1250                May be the same as startbranch
1251   last       : Thing following the last branch.
1252                May be the same as tail.
1253   tail       : item following the branch sequence
1254   count      : words in the sequence
1255   flags      : currently the OP() type we will be building one of /EXACT(|F|Fl)/
1256   depth      : indent depth
1257
1258 Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
1259
1260 A trie is an N'ary tree where the branches are determined by digital
1261 decomposition of the key. IE, at the root node you look up the 1st character and
1262 follow that branch repeat until you find the end of the branches. Nodes can be
1263 marked as "accepting" meaning they represent a complete word. Eg:
1264
1265   /he|she|his|hers/
1266
1267 would convert into the following structure. Numbers represent states, letters
1268 following numbers represent valid transitions on the letter from that state, if
1269 the number is in square brackets it represents an accepting state, otherwise it
1270 will be in parenthesis.
1271
1272       +-h->+-e->[3]-+-r->(8)-+-s->[9]
1273       |    |
1274       |   (2)
1275       |    |
1276      (1)   +-i->(6)-+-s->[7]
1277       |
1278       +-s->(3)-+-h->(4)-+-e->[5]
1279
1280       Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
1281
1282 This shows that when matching against the string 'hers' we will begin at state 1
1283 read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
1284 then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
1285 is also accepting. Thus we know that we can match both 'he' and 'hers' with a
1286 single traverse. We store a mapping from accepting to state to which word was
1287 matched, and then when we have multiple possibilities we try to complete the
1288 rest of the regex in the order in which they occured in the alternation.
1289
1290 The only prior NFA like behaviour that would be changed by the TRIE support is
1291 the silent ignoring of duplicate alternations which are of the form:
1292
1293  / (DUPE|DUPE) X? (?{ ... }) Y /x
1294
1295 Thus EVAL blocks following a trie may be called a different number of times with
1296 and without the optimisation. With the optimisations dupes will be silently
1297 ignored. This inconsistent behaviour of EVAL type nodes is well established as
1298 the following demonstrates:
1299
1300  'words'=~/(word|word|word)(?{ print $1 })[xyz]/
1301
1302 which prints out 'word' three times, but
1303
1304  'words'=~/(word|word|word)(?{ print $1 })S/
1305
1306 which doesnt print it out at all. This is due to other optimisations kicking in.
1307
1308 Example of what happens on a structural level:
1309
1310 The regexp /(ac|ad|ab)+/ will produce the following debug output:
1311
1312    1: CURLYM[1] {1,32767}(18)
1313    5:   BRANCH(8)
1314    6:     EXACT <ac>(16)
1315    8:   BRANCH(11)
1316    9:     EXACT <ad>(16)
1317   11:   BRANCH(14)
1318   12:     EXACT <ab>(16)
1319   16:   SUCCEED(0)
1320   17:   NOTHING(18)
1321   18: END(0)
1322
1323 This would be optimizable with startbranch=5, first=5, last=16, tail=16
1324 and should turn into:
1325
1326    1: CURLYM[1] {1,32767}(18)
1327    5:   TRIE(16)
1328         [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
1329           <ac>
1330           <ad>
1331           <ab>
1332   16:   SUCCEED(0)
1333   17:   NOTHING(18)
1334   18: END(0)
1335
1336 Cases where tail != last would be like /(?foo|bar)baz/:
1337
1338    1: BRANCH(4)
1339    2:   EXACT <foo>(8)
1340    4: BRANCH(7)
1341    5:   EXACT <bar>(8)
1342    7: TAIL(8)
1343    8: EXACT <baz>(10)
1344   10: END(0)
1345
1346 which would be optimizable with startbranch=1, first=1, last=7, tail=8
1347 and would end up looking like:
1348
1349     1: TRIE(8)
1350       [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
1351         <foo>
1352         <bar>
1353    7: TAIL(8)
1354    8: EXACT <baz>(10)
1355   10: END(0)
1356
1357     d = uvuni_to_utf8_flags(d, uv, 0);
1358
1359 is the recommended Unicode-aware way of saying
1360
1361     *(d++) = uv;
1362 */
1363
1364 #define TRIE_STORE_REVCHAR                                                 \
1365     STMT_START {                                                           \
1366         if (UTF) {                                                         \
1367             SV *zlopp = newSV(2);                                          \
1368             unsigned char *flrbbbbb = (unsigned char *) SvPVX(zlopp);      \
1369             unsigned const char *const kapow = uvuni_to_utf8(flrbbbbb, uvc & 0xFF); \
1370             SvCUR_set(zlopp, kapow - flrbbbbb);                            \
1371             SvPOK_on(zlopp);                                               \
1372             SvUTF8_on(zlopp);                                              \
1373             av_push(revcharmap, zlopp);                                    \
1374         } else {                                                           \
1375             char ooooff = (char)uvc;                                               \
1376             av_push(revcharmap, newSVpvn(&ooooff, 1));                     \
1377         }                                                                  \
1378         } STMT_END
1379
1380 #define TRIE_READ_CHAR STMT_START {                                           \
1381     wordlen++;                                                                \
1382     if ( UTF ) {                                                              \
1383         if ( folder ) {                                                       \
1384             if ( foldlen > 0 ) {                                              \
1385                uvc = utf8n_to_uvuni( scan, UTF8_MAXLEN, &len, uniflags );     \
1386                foldlen -= len;                                                \
1387                scan += len;                                                   \
1388                len = 0;                                                       \
1389             } else {                                                          \
1390                 len = UTF8SKIP(uc);\
1391                 uvc = to_utf8_fold( uc, foldbuf, &foldlen);                   \
1392                 foldlen -= UNISKIP( uvc );                                    \
1393                 scan = foldbuf + UNISKIP( uvc );                              \
1394             }                                                                 \
1395         } else {                                                              \
1396             uvc = utf8n_to_uvuni( (const U8*)uc, UTF8_MAXLEN, &len, uniflags);\
1397         }                                                                     \
1398     } else {                                                                  \
1399         uvc = (U32)*uc;                                                       \
1400         len = 1;                                                              \
1401     }                                                                         \
1402 } STMT_END
1403
1404
1405
1406 #define TRIE_LIST_PUSH(state,fid,ns) STMT_START {               \
1407     if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) {    \
1408         U32 ging = TRIE_LIST_LEN( state ) *= 2;                 \
1409         Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
1410     }                                                           \
1411     TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid;     \
1412     TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns;   \
1413     TRIE_LIST_CUR( state )++;                                   \
1414 } STMT_END
1415
1416 #define TRIE_LIST_NEW(state) STMT_START {                       \
1417     Newxz( trie->states[ state ].trans.list,               \
1418         4, reg_trie_trans_le );                                 \
1419      TRIE_LIST_CUR( state ) = 1;                                \
1420      TRIE_LIST_LEN( state ) = 4;                                \
1421 } STMT_END
1422
1423 #define TRIE_HANDLE_WORD(state) STMT_START {                    \
1424     U16 dupe= trie->states[ state ].wordnum;                    \
1425     regnode * const noper_next = regnext( noper );              \
1426                                                                 \
1427     DEBUG_r({                                                   \
1428         /* store the word for dumping */                        \
1429         SV* tmp;                                                \
1430         if (OP(noper) != NOTHING)                               \
1431             tmp = newSVpvn_utf8(STRING(noper), STR_LEN(noper), UTF);    \
1432         else                                                    \
1433             tmp = newSVpvn_utf8( "", 0, UTF );                  \
1434         av_push( trie_words, tmp );                             \
1435     });                                                         \
1436                                                                 \
1437     curword++;                                                  \
1438     trie->wordinfo[curword].prev   = 0;                         \
1439     trie->wordinfo[curword].len    = wordlen;                   \
1440     trie->wordinfo[curword].accept = state;                     \
1441                                                                 \
1442     if ( noper_next < tail ) {                                  \
1443         if (!trie->jump)                                        \
1444             trie->jump = (U16 *) PerlMemShared_calloc( word_count + 1, sizeof(U16) ); \
1445         trie->jump[curword] = (U16)(noper_next - convert);      \
1446         if (!jumper)                                            \
1447             jumper = noper_next;                                \
1448         if (!nextbranch)                                        \
1449             nextbranch= regnext(cur);                           \
1450     }                                                           \
1451                                                                 \
1452     if ( dupe ) {                                               \
1453         /* It's a dupe. Pre-insert into the wordinfo[].prev   */\
1454         /* chain, so that when the bits of chain are later    */\
1455         /* linked together, the dups appear in the chain      */\
1456         trie->wordinfo[curword].prev = trie->wordinfo[dupe].prev; \
1457         trie->wordinfo[dupe].prev = curword;                    \
1458     } else {                                                    \
1459         /* we haven't inserted this word yet.                */ \
1460         trie->states[ state ].wordnum = curword;                \
1461     }                                                           \
1462 } STMT_END
1463
1464
1465 #define TRIE_TRANS_STATE(state,base,ucharcount,charid,special)          \
1466      ( ( base + charid >=  ucharcount                                   \
1467          && base + charid < ubound                                      \
1468          && state == trie->trans[ base - ucharcount + charid ].check    \
1469          && trie->trans[ base - ucharcount + charid ].next )            \
1470            ? trie->trans[ base - ucharcount + charid ].next             \
1471            : ( state==1 ? special : 0 )                                 \
1472       )
1473
1474 #define MADE_TRIE       1
1475 #define MADE_JUMP_TRIE  2
1476 #define MADE_EXACT_TRIE 4
1477
1478 STATIC I32
1479 S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch, regnode *first, regnode *last, regnode *tail, U32 word_count, U32 flags, U32 depth)
1480 {
1481     dVAR;
1482     /* first pass, loop through and scan words */
1483     reg_trie_data *trie;
1484     HV *widecharmap = NULL;
1485     AV *revcharmap = newAV();
1486     regnode *cur;
1487     const U32 uniflags = UTF8_ALLOW_DEFAULT;
1488     STRLEN len = 0;
1489     UV uvc = 0;
1490     U16 curword = 0;
1491     U32 next_alloc = 0;
1492     regnode *jumper = NULL;
1493     regnode *nextbranch = NULL;
1494     regnode *convert = NULL;
1495     U32 *prev_states; /* temp array mapping each state to previous one */
1496     /* we just use folder as a flag in utf8 */
1497     const U8 * folder = NULL;
1498
1499 #ifdef DEBUGGING
1500     const U32 data_slot = add_data( pRExC_state, 4, "tuuu" );
1501     AV *trie_words = NULL;
1502     /* along with revcharmap, this only used during construction but both are
1503      * useful during debugging so we store them in the struct when debugging.
1504      */
1505 #else
1506     const U32 data_slot = add_data( pRExC_state, 2, "tu" );
1507     STRLEN trie_charcount=0;
1508 #endif
1509     SV *re_trie_maxbuff;
1510     GET_RE_DEBUG_FLAGS_DECL;
1511
1512     PERL_ARGS_ASSERT_MAKE_TRIE;
1513 #ifndef DEBUGGING
1514     PERL_UNUSED_ARG(depth);
1515 #endif
1516
1517     switch (flags) {
1518         case EXACT: break;
1519         case EXACTFA:
1520         case EXACTFU: folder = PL_fold_latin1; break;
1521         case EXACTF:  folder = PL_fold; break;
1522         case EXACTFL: folder = PL_fold_locale; break;
1523         default: Perl_croak( aTHX_ "panic! In trie construction, unknown node type %u", (unsigned) flags );
1524     }
1525
1526     trie = (reg_trie_data *) PerlMemShared_calloc( 1, sizeof(reg_trie_data) );
1527     trie->refcount = 1;
1528     trie->startstate = 1;
1529     trie->wordcount = word_count;
1530     RExC_rxi->data->data[ data_slot ] = (void*)trie;
1531     trie->charmap = (U16 *) PerlMemShared_calloc( 256, sizeof(U16) );
1532     if (!(UTF && folder))
1533         trie->bitmap = (char *) PerlMemShared_calloc( ANYOF_BITMAP_SIZE, 1 );
1534     trie->wordinfo = (reg_trie_wordinfo *) PerlMemShared_calloc(
1535                        trie->wordcount+1, sizeof(reg_trie_wordinfo));
1536
1537     DEBUG_r({
1538         trie_words = newAV();
1539     });
1540
1541     re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
1542     if (!SvIOK(re_trie_maxbuff)) {
1543         sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
1544     }
1545     DEBUG_OPTIMISE_r({
1546                 PerlIO_printf( Perl_debug_log,
1547                   "%*smake_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
1548                   (int)depth * 2 + 2, "", 
1549                   REG_NODE_NUM(startbranch),REG_NODE_NUM(first), 
1550                   REG_NODE_NUM(last), REG_NODE_NUM(tail),
1551                   (int)depth);
1552     });
1553    
1554    /* Find the node we are going to overwrite */
1555     if ( first == startbranch && OP( last ) != BRANCH ) {
1556         /* whole branch chain */
1557         convert = first;
1558     } else {
1559         /* branch sub-chain */
1560         convert = NEXTOPER( first );
1561     }
1562         
1563     /*  -- First loop and Setup --
1564
1565        We first traverse the branches and scan each word to determine if it
1566        contains widechars, and how many unique chars there are, this is
1567        important as we have to build a table with at least as many columns as we
1568        have unique chars.
1569
1570        We use an array of integers to represent the character codes 0..255
1571        (trie->charmap) and we use a an HV* to store Unicode characters. We use the
1572        native representation of the character value as the key and IV's for the
1573        coded index.
1574
1575        *TODO* If we keep track of how many times each character is used we can
1576        remap the columns so that the table compression later on is more
1577        efficient in terms of memory by ensuring the most common value is in the
1578        middle and the least common are on the outside.  IMO this would be better
1579        than a most to least common mapping as theres a decent chance the most
1580        common letter will share a node with the least common, meaning the node
1581        will not be compressible. With a middle is most common approach the worst
1582        case is when we have the least common nodes twice.
1583
1584      */
1585
1586     for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1587         regnode * const noper = NEXTOPER( cur );
1588         const U8 *uc = (U8*)STRING( noper );
1589         const U8 * const e  = uc + STR_LEN( noper );
1590         STRLEN foldlen = 0;
1591         U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1592         const U8 *scan = (U8*)NULL;
1593         U32 wordlen      = 0;         /* required init */
1594         STRLEN chars = 0;
1595         bool set_bit = trie->bitmap ? 1 : 0; /*store the first char in the bitmap?*/
1596
1597         if (OP(noper) == NOTHING) {
1598             trie->minlen= 0;
1599             continue;
1600         }
1601         if ( set_bit ) /* bitmap only alloced when !(UTF&&Folding) */
1602             TRIE_BITMAP_SET(trie,*uc); /* store the raw first byte
1603                                           regardless of encoding */
1604
1605         for ( ; uc < e ; uc += len ) {
1606             TRIE_CHARCOUNT(trie)++;
1607             TRIE_READ_CHAR;
1608             chars++;
1609             if ( uvc < 256 ) {
1610                 if ( !trie->charmap[ uvc ] ) {
1611                     trie->charmap[ uvc ]=( ++trie->uniquecharcount );
1612                     if ( folder )
1613                         trie->charmap[ folder[ uvc ] ] = trie->charmap[ uvc ];
1614                     TRIE_STORE_REVCHAR;
1615                 }
1616                 if ( set_bit ) {
1617                     /* store the codepoint in the bitmap, and its folded
1618                      * equivalent. */
1619                     TRIE_BITMAP_SET(trie,uvc);
1620
1621                     /* store the folded codepoint */
1622                     if ( folder ) TRIE_BITMAP_SET(trie,folder[ uvc ]);
1623
1624                     if ( !UTF ) {
1625                         /* store first byte of utf8 representation of
1626                            variant codepoints */
1627                         if (! UNI_IS_INVARIANT(uvc)) {
1628                             TRIE_BITMAP_SET(trie, UTF8_TWO_BYTE_HI(uvc));
1629                         }
1630                     }
1631                     set_bit = 0; /* We've done our bit :-) */
1632                 }
1633             } else {
1634                 SV** svpp;
1635                 if ( !widecharmap )
1636                     widecharmap = newHV();
1637
1638                 svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 1 );
1639
1640                 if ( !svpp )
1641                     Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%"UVXf, uvc );
1642
1643                 if ( !SvTRUE( *svpp ) ) {
1644                     sv_setiv( *svpp, ++trie->uniquecharcount );
1645                     TRIE_STORE_REVCHAR;
1646                 }
1647             }
1648         }
1649         if( cur == first ) {
1650             trie->minlen=chars;
1651             trie->maxlen=chars;
1652         } else if (chars < trie->minlen) {
1653             trie->minlen=chars;
1654         } else if (chars > trie->maxlen) {
1655             trie->maxlen=chars;
1656         }
1657
1658     } /* end first pass */
1659     DEBUG_TRIE_COMPILE_r(
1660         PerlIO_printf( Perl_debug_log, "%*sTRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
1661                 (int)depth * 2 + 2,"",
1662                 ( widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
1663                 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
1664                 (int)trie->minlen, (int)trie->maxlen )
1665     );
1666
1667     /*
1668         We now know what we are dealing with in terms of unique chars and
1669         string sizes so we can calculate how much memory a naive
1670         representation using a flat table  will take. If it's over a reasonable
1671         limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
1672         conservative but potentially much slower representation using an array
1673         of lists.
1674
1675         At the end we convert both representations into the same compressed
1676         form that will be used in regexec.c for matching with. The latter
1677         is a form that cannot be used to construct with but has memory
1678         properties similar to the list form and access properties similar
1679         to the table form making it both suitable for fast searches and
1680         small enough that its feasable to store for the duration of a program.
1681
1682         See the comment in the code where the compressed table is produced
1683         inplace from the flat tabe representation for an explanation of how
1684         the compression works.
1685
1686     */
1687
1688
1689     Newx(prev_states, TRIE_CHARCOUNT(trie) + 2, U32);
1690     prev_states[1] = 0;
1691
1692     if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1) > SvIV(re_trie_maxbuff) ) {
1693         /*
1694             Second Pass -- Array Of Lists Representation
1695
1696             Each state will be represented by a list of charid:state records
1697             (reg_trie_trans_le) the first such element holds the CUR and LEN
1698             points of the allocated array. (See defines above).
1699
1700             We build the initial structure using the lists, and then convert
1701             it into the compressed table form which allows faster lookups
1702             (but cant be modified once converted).
1703         */
1704
1705         STRLEN transcount = 1;
1706
1707         DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log, 
1708             "%*sCompiling trie using list compiler\n",
1709             (int)depth * 2 + 2, ""));
1710
1711         trie->states = (reg_trie_state *)
1712             PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
1713                                   sizeof(reg_trie_state) );
1714         TRIE_LIST_NEW(1);
1715         next_alloc = 2;
1716
1717         for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1718
1719             regnode * const noper = NEXTOPER( cur );
1720             U8 *uc           = (U8*)STRING( noper );
1721             const U8 * const e = uc + STR_LEN( noper );
1722             U32 state        = 1;         /* required init */
1723             U16 charid       = 0;         /* sanity init */
1724             U8 *scan         = (U8*)NULL; /* sanity init */
1725             STRLEN foldlen   = 0;         /* required init */
1726             U32 wordlen      = 0;         /* required init */
1727             U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1728
1729             if (OP(noper) != NOTHING) {
1730                 for ( ; uc < e ; uc += len ) {
1731
1732                     TRIE_READ_CHAR;
1733
1734                     if ( uvc < 256 ) {
1735                         charid = trie->charmap[ uvc ];
1736                     } else {
1737                         SV** const svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 0);
1738                         if ( !svpp ) {
1739                             charid = 0;
1740                         } else {
1741                             charid=(U16)SvIV( *svpp );
1742                         }
1743                     }
1744                     /* charid is now 0 if we dont know the char read, or nonzero if we do */
1745                     if ( charid ) {
1746
1747                         U16 check;
1748                         U32 newstate = 0;
1749
1750                         charid--;
1751                         if ( !trie->states[ state ].trans.list ) {
1752                             TRIE_LIST_NEW( state );
1753                         }
1754                         for ( check = 1; check <= TRIE_LIST_USED( state ); check++ ) {
1755                             if ( TRIE_LIST_ITEM( state, check ).forid == charid ) {
1756                                 newstate = TRIE_LIST_ITEM( state, check ).newstate;
1757                                 break;
1758                             }
1759                         }
1760                         if ( ! newstate ) {
1761                             newstate = next_alloc++;
1762                             prev_states[newstate] = state;
1763                             TRIE_LIST_PUSH( state, charid, newstate );
1764                             transcount++;
1765                         }
1766                         state = newstate;
1767                     } else {
1768                         Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
1769                     }
1770                 }
1771             }
1772             TRIE_HANDLE_WORD(state);
1773
1774         } /* end second pass */
1775
1776         /* next alloc is the NEXT state to be allocated */
1777         trie->statecount = next_alloc; 
1778         trie->states = (reg_trie_state *)
1779             PerlMemShared_realloc( trie->states,
1780                                    next_alloc
1781                                    * sizeof(reg_trie_state) );
1782
1783         /* and now dump it out before we compress it */
1784         DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_list(trie, widecharmap,
1785                                                          revcharmap, next_alloc,
1786                                                          depth+1)
1787         );
1788
1789         trie->trans = (reg_trie_trans *)
1790             PerlMemShared_calloc( transcount, sizeof(reg_trie_trans) );
1791         {
1792             U32 state;
1793             U32 tp = 0;
1794             U32 zp = 0;
1795
1796
1797             for( state=1 ; state < next_alloc ; state ++ ) {
1798                 U32 base=0;
1799
1800                 /*
1801                 DEBUG_TRIE_COMPILE_MORE_r(
1802                     PerlIO_printf( Perl_debug_log, "tp: %d zp: %d ",tp,zp)
1803                 );
1804                 */
1805
1806                 if (trie->states[state].trans.list) {
1807                     U16 minid=TRIE_LIST_ITEM( state, 1).forid;
1808                     U16 maxid=minid;
1809                     U16 idx;
1810
1811                     for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
1812                         const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
1813                         if ( forid < minid ) {
1814                             minid=forid;
1815                         } else if ( forid > maxid ) {
1816                             maxid=forid;
1817                         }
1818                     }
1819                     if ( transcount < tp + maxid - minid + 1) {
1820                         transcount *= 2;
1821                         trie->trans = (reg_trie_trans *)
1822                             PerlMemShared_realloc( trie->trans,
1823                                                      transcount
1824                                                      * sizeof(reg_trie_trans) );
1825                         Zero( trie->trans + (transcount / 2), transcount / 2 , reg_trie_trans );
1826                     }
1827                     base = trie->uniquecharcount + tp - minid;
1828                     if ( maxid == minid ) {
1829                         U32 set = 0;
1830                         for ( ; zp < tp ; zp++ ) {
1831                             if ( ! trie->trans[ zp ].next ) {
1832                                 base = trie->uniquecharcount + zp - minid;
1833                                 trie->trans[ zp ].next = TRIE_LIST_ITEM( state, 1).newstate;
1834                                 trie->trans[ zp ].check = state;
1835                                 set = 1;
1836                                 break;
1837                             }
1838                         }
1839                         if ( !set ) {
1840                             trie->trans[ tp ].next = TRIE_LIST_ITEM( state, 1).newstate;
1841                             trie->trans[ tp ].check = state;
1842                             tp++;
1843                             zp = tp;
1844                         }
1845                     } else {
1846                         for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
1847                             const U32 tid = base -  trie->uniquecharcount + TRIE_LIST_ITEM( state, idx ).forid;
1848                             trie->trans[ tid ].next = TRIE_LIST_ITEM( state, idx ).newstate;
1849                             trie->trans[ tid ].check = state;
1850                         }
1851                         tp += ( maxid - minid + 1 );
1852                     }
1853                     Safefree(trie->states[ state ].trans.list);
1854                 }
1855                 /*
1856                 DEBUG_TRIE_COMPILE_MORE_r(
1857                     PerlIO_printf( Perl_debug_log, " base: %d\n",base);
1858                 );
1859                 */
1860                 trie->states[ state ].trans.base=base;
1861             }
1862             trie->lasttrans = tp + 1;
1863         }
1864     } else {
1865         /*
1866            Second Pass -- Flat Table Representation.
1867
1868            we dont use the 0 slot of either trans[] or states[] so we add 1 to each.
1869            We know that we will need Charcount+1 trans at most to store the data
1870            (one row per char at worst case) So we preallocate both structures
1871            assuming worst case.
1872
1873            We then construct the trie using only the .next slots of the entry
1874            structs.
1875
1876            We use the .check field of the first entry of the node temporarily to
1877            make compression both faster and easier by keeping track of how many non
1878            zero fields are in the node.
1879
1880            Since trans are numbered from 1 any 0 pointer in the table is a FAIL
1881            transition.
1882
1883            There are two terms at use here: state as a TRIE_NODEIDX() which is a
1884            number representing the first entry of the node, and state as a
1885            TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1) and
1886            TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3) if there
1887            are 2 entrys per node. eg:
1888
1889              A B       A B
1890           1. 2 4    1. 3 7
1891           2. 0 3    3. 0 5
1892           3. 0 0    5. 0 0
1893           4. 0 0    7. 0 0
1894
1895            The table is internally in the right hand, idx form. However as we also
1896            have to deal with the states array which is indexed by nodenum we have to
1897            use TRIE_NODENUM() to convert.
1898
1899         */
1900         DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log, 
1901             "%*sCompiling trie using table compiler\n",
1902             (int)depth * 2 + 2, ""));
1903
1904         trie->trans = (reg_trie_trans *)
1905             PerlMemShared_calloc( ( TRIE_CHARCOUNT(trie) + 1 )
1906                                   * trie->uniquecharcount + 1,
1907                                   sizeof(reg_trie_trans) );
1908         trie->states = (reg_trie_state *)
1909             PerlMemShared_calloc( TRIE_CHARCOUNT(trie) + 2,
1910                                   sizeof(reg_trie_state) );
1911         next_alloc = trie->uniquecharcount + 1;
1912
1913
1914         for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1915
1916             regnode * const noper   = NEXTOPER( cur );
1917             const U8 *uc     = (U8*)STRING( noper );
1918             const U8 * const e = uc + STR_LEN( noper );
1919
1920             U32 state        = 1;         /* required init */
1921
1922             U16 charid       = 0;         /* sanity init */
1923             U32 accept_state = 0;         /* sanity init */
1924             U8 *scan         = (U8*)NULL; /* sanity init */
1925
1926             STRLEN foldlen   = 0;         /* required init */
1927             U32 wordlen      = 0;         /* required init */
1928             U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1929
1930             if ( OP(noper) != NOTHING ) {
1931                 for ( ; uc < e ; uc += len ) {
1932
1933                     TRIE_READ_CHAR;
1934
1935                     if ( uvc < 256 ) {
1936                         charid = trie->charmap[ uvc ];
1937                     } else {
1938                         SV* const * const svpp = hv_fetch( widecharmap, (char*)&uvc, sizeof( UV ), 0);
1939                         charid = svpp ? (U16)SvIV(*svpp) : 0;
1940                     }
1941                     if ( charid ) {
1942                         charid--;
1943                         if ( !trie->trans[ state + charid ].next ) {
1944                             trie->trans[ state + charid ].next = next_alloc;
1945                             trie->trans[ state ].check++;
1946                             prev_states[TRIE_NODENUM(next_alloc)]
1947                                     = TRIE_NODENUM(state);
1948                             next_alloc += trie->uniquecharcount;
1949                         }
1950                         state = trie->trans[ state + charid ].next;
1951                     } else {
1952                         Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
1953                     }
1954                     /* charid is now 0 if we dont know the char read, or nonzero if we do */
1955                 }
1956             }
1957             accept_state = TRIE_NODENUM( state );
1958             TRIE_HANDLE_WORD(accept_state);
1959
1960         } /* end second pass */
1961
1962         /* and now dump it out before we compress it */
1963         DEBUG_TRIE_COMPILE_MORE_r(dump_trie_interim_table(trie, widecharmap,
1964                                                           revcharmap,
1965                                                           next_alloc, depth+1));
1966
1967         {
1968         /*
1969            * Inplace compress the table.*
1970
1971            For sparse data sets the table constructed by the trie algorithm will
1972            be mostly 0/FAIL transitions or to put it another way mostly empty.
1973            (Note that leaf nodes will not contain any transitions.)
1974
1975            This algorithm compresses the tables by eliminating most such
1976            transitions, at the cost of a modest bit of extra work during lookup:
1977
1978            - Each states[] entry contains a .base field which indicates the
1979            index in the state[] array wheres its transition data is stored.
1980
1981            - If .base is 0 there are no valid transitions from that node.
1982
1983            - If .base is nonzero then charid is added to it to find an entry in
1984            the trans array.
1985
1986            -If trans[states[state].base+charid].check!=state then the
1987            transition is taken to be a 0/Fail transition. Thus if there are fail
1988            transitions at the front of the node then the .base offset will point
1989            somewhere inside the previous nodes data (or maybe even into a node
1990            even earlier), but the .check field determines if the transition is
1991            valid.
1992
1993            XXX - wrong maybe?
1994            The following process inplace converts the table to the compressed
1995            table: We first do not compress the root node 1,and mark all its
1996            .check pointers as 1 and set its .base pointer as 1 as well. This
1997            allows us to do a DFA construction from the compressed table later,
1998            and ensures that any .base pointers we calculate later are greater
1999            than 0.
2000
2001            - We set 'pos' to indicate the first entry of the second node.
2002
2003            - We then iterate over the columns of the node, finding the first and
2004            last used entry at l and m. We then copy l..m into pos..(pos+m-l),
2005            and set the .check pointers accordingly, and advance pos
2006            appropriately and repreat for the next node. Note that when we copy
2007            the next pointers we have to convert them from the original
2008            NODEIDX form to NODENUM form as the former is not valid post
2009            compression.
2010
2011            - If a node has no transitions used we mark its base as 0 and do not
2012            advance the pos pointer.
2013
2014            - If a node only has one transition we use a second pointer into the
2015            structure to fill in allocated fail transitions from other states.
2016            This pointer is independent of the main pointer and scans forward
2017            looking for null transitions that are allocated to a state. When it
2018            finds one it writes the single transition into the "hole".  If the
2019            pointer doesnt find one the single transition is appended as normal.
2020
2021            - Once compressed we can Renew/realloc the structures to release the
2022            excess space.
2023
2024            See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
2025            specifically Fig 3.47 and the associated pseudocode.
2026
2027            demq
2028         */
2029         const U32 laststate = TRIE_NODENUM( next_alloc );
2030         U32 state, charid;
2031         U32 pos = 0, zp=0;
2032         trie->statecount = laststate;
2033
2034         for ( state = 1 ; state < laststate ; state++ ) {
2035             U8 flag = 0;
2036             const U32 stateidx = TRIE_NODEIDX( state );
2037             const U32 o_used = trie->trans[ stateidx ].check;
2038             U32 used = trie->trans[ stateidx ].check;
2039             trie->trans[ stateidx ].check = 0;
2040
2041             for ( charid = 0 ; used && charid < trie->uniquecharcount ; charid++ ) {
2042                 if ( flag || trie->trans[ stateidx + charid ].next ) {
2043                     if ( trie->trans[ stateidx + charid ].next ) {
2044                         if (o_used == 1) {
2045                             for ( ; zp < pos ; zp++ ) {
2046                                 if ( ! trie->trans[ zp ].next ) {
2047                                     break;
2048                                 }
2049                             }
2050                             trie->states[ state ].trans.base = zp + trie->uniquecharcount - charid ;
2051                             trie->trans[ zp ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
2052                             trie->trans[ zp ].check = state;
2053                             if ( ++zp > pos ) pos = zp;
2054                             break;
2055                         }
2056                         used--;
2057                     }
2058                     if ( !flag ) {
2059                         flag = 1;
2060                         trie->states[ state ].trans.base = pos + trie->uniquecharcount - charid ;
2061                     }
2062                     trie->trans[ pos ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
2063                     trie->trans[ pos ].check = state;
2064                     pos++;
2065                 }
2066             }
2067         }
2068         trie->lasttrans = pos + 1;
2069         trie->states = (reg_trie_state *)
2070             PerlMemShared_realloc( trie->states, laststate
2071                                    * sizeof(reg_trie_state) );
2072         DEBUG_TRIE_COMPILE_MORE_r(
2073                 PerlIO_printf( Perl_debug_log,
2074                     "%*sAlloc: %d Orig: %"IVdf" elements, Final:%"IVdf". Savings of %%%5.2f\n",
2075                     (int)depth * 2 + 2,"",
2076                     (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1 ),
2077                     (IV)next_alloc,
2078                     (IV)pos,
2079                     ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
2080             );
2081
2082         } /* end table compress */
2083     }
2084     DEBUG_TRIE_COMPILE_MORE_r(
2085             PerlIO_printf(Perl_debug_log, "%*sStatecount:%"UVxf" Lasttrans:%"UVxf"\n",
2086                 (int)depth * 2 + 2, "",
2087                 (UV)trie->statecount,
2088                 (UV)trie->lasttrans)
2089     );
2090     /* resize the trans array to remove unused space */
2091     trie->trans = (reg_trie_trans *)
2092         PerlMemShared_realloc( trie->trans, trie->lasttrans
2093                                * sizeof(reg_trie_trans) );
2094
2095     {   /* Modify the program and insert the new TRIE node */ 
2096         U8 nodetype =(U8)(flags & 0xFF);
2097         char *str=NULL;
2098         
2099 #ifdef DEBUGGING
2100         regnode *optimize = NULL;
2101 #ifdef RE_TRACK_PATTERN_OFFSETS
2102
2103         U32 mjd_offset = 0;
2104         U32 mjd_nodelen = 0;
2105 #endif /* RE_TRACK_PATTERN_OFFSETS */
2106 #endif /* DEBUGGING */
2107         /*
2108            This means we convert either the first branch or the first Exact,
2109            depending on whether the thing following (in 'last') is a branch
2110            or not and whther first is the startbranch (ie is it a sub part of
2111            the alternation or is it the whole thing.)
2112            Assuming its a sub part we convert the EXACT otherwise we convert
2113            the whole branch sequence, including the first.
2114          */
2115         /* Find the node we are going to overwrite */
2116         if ( first != startbranch || OP( last ) == BRANCH ) {
2117             /* branch sub-chain */
2118             NEXT_OFF( first ) = (U16)(last - first);
2119 #ifdef RE_TRACK_PATTERN_OFFSETS
2120             DEBUG_r({
2121                 mjd_offset= Node_Offset((convert));
2122                 mjd_nodelen= Node_Length((convert));
2123             });
2124 #endif
2125             /* whole branch chain */
2126         }
2127 #ifdef RE_TRACK_PATTERN_OFFSETS
2128         else {
2129             DEBUG_r({
2130                 const  regnode *nop = NEXTOPER( convert );
2131                 mjd_offset= Node_Offset((nop));
2132                 mjd_nodelen= Node_Length((nop));
2133             });
2134         }
2135         DEBUG_OPTIMISE_r(
2136             PerlIO_printf(Perl_debug_log, "%*sMJD offset:%"UVuf" MJD length:%"UVuf"\n",
2137                 (int)depth * 2 + 2, "",
2138                 (UV)mjd_offset, (UV)mjd_nodelen)
2139         );
2140 #endif
2141         /* But first we check to see if there is a common prefix we can 
2142            split out as an EXACT and put in front of the TRIE node.  */
2143         trie->startstate= 1;
2144         if ( trie->bitmap && !widecharmap && !trie->jump  ) {
2145             U32 state;
2146             for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
2147                 U32 ofs = 0;
2148                 I32 idx = -1;
2149                 U32 count = 0;
2150                 const U32 base = trie->states[ state ].trans.base;
2151
2152                 if ( trie->states[state].wordnum )
2153                         count = 1;
2154
2155                 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
2156                     if ( ( base + ofs >= trie->uniquecharcount ) &&
2157                          ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
2158                          trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
2159                     {
2160                         if ( ++count > 1 ) {
2161                             SV **tmp = av_fetch( revcharmap, ofs, 0);
2162                             const U8 *ch = (U8*)SvPV_nolen_const( *tmp );
2163                             if ( state == 1 ) break;
2164                             if ( count == 2 ) {
2165                                 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
2166                                 DEBUG_OPTIMISE_r(
2167                                     PerlIO_printf(Perl_debug_log,
2168                                         "%*sNew Start State=%"UVuf" Class: [",
2169                                         (int)depth * 2 + 2, "",
2170                                         (UV)state));
2171                                 if (idx >= 0) {
2172                                     SV ** const tmp = av_fetch( revcharmap, idx, 0);
2173                                     const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
2174
2175                                     TRIE_BITMAP_SET(trie,*ch);
2176                                     if ( folder )
2177                                         TRIE_BITMAP_SET(trie, folder[ *ch ]);
2178                                     DEBUG_OPTIMISE_r(
2179                                         PerlIO_printf(Perl_debug_log, "%s", (char*)ch)
2180                                     );
2181                                 }
2182                             }
2183                             TRIE_BITMAP_SET(trie,*ch);
2184                             if ( folder )
2185                                 TRIE_BITMAP_SET(trie,folder[ *ch ]);
2186                             DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"%s", ch));
2187                         }
2188                         idx = ofs;
2189                     }
2190                 }
2191                 if ( count == 1 ) {
2192                     SV **tmp = av_fetch( revcharmap, idx, 0);
2193                     STRLEN len;
2194                     char *ch = SvPV( *tmp, len );
2195                     DEBUG_OPTIMISE_r({
2196                         SV *sv=sv_newmortal();
2197                         PerlIO_printf( Perl_debug_log,
2198                             "%*sPrefix State: %"UVuf" Idx:%"UVuf" Char='%s'\n",
2199                             (int)depth * 2 + 2, "",
2200                             (UV)state, (UV)idx, 
2201                             pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6, 
2202                                 PL_colors[0], PL_colors[1],
2203                                 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
2204                                 PERL_PV_ESCAPE_FIRSTCHAR 
2205                             )
2206                         );
2207                     });
2208                     if ( state==1 ) {
2209                         OP( convert ) = nodetype;
2210                         str=STRING(convert);
2211                         STR_LEN(convert)=0;
2212                     }
2213                     STR_LEN(convert) += len;
2214                     while (len--)
2215                         *str++ = *ch++;
2216                 } else {
2217 #ifdef DEBUGGING            
2218                     if (state>1)
2219                         DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"]\n"));
2220 #endif
2221                     break;
2222                 }
2223             }
2224             trie->prefixlen = (state-1);
2225             if (str) {
2226                 regnode *n = convert+NODE_SZ_STR(convert);
2227                 NEXT_OFF(convert) = NODE_SZ_STR(convert);
2228                 trie->startstate = state;
2229                 trie->minlen -= (state - 1);
2230                 trie->maxlen -= (state - 1);
2231 #ifdef DEBUGGING
2232                /* At least the UNICOS C compiler choked on this
2233                 * being argument to DEBUG_r(), so let's just have
2234                 * it right here. */
2235                if (
2236 #ifdef PERL_EXT_RE_BUILD
2237                    1
2238 #else
2239                    DEBUG_r_TEST
2240 #endif
2241                    ) {
2242                    regnode *fix = convert;
2243                    U32 word = trie->wordcount;
2244                    mjd_nodelen++;
2245                    Set_Node_Offset_Length(convert, mjd_offset, state - 1);
2246                    while( ++fix < n ) {
2247                        Set_Node_Offset_Length(fix, 0, 0);
2248                    }
2249                    while (word--) {
2250                        SV ** const tmp = av_fetch( trie_words, word, 0 );
2251                        if (tmp) {
2252                            if ( STR_LEN(convert) <= SvCUR(*tmp) )
2253                                sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
2254                            else
2255                                sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
2256                        }
2257                    }
2258                }
2259 #endif
2260                 if (trie->maxlen) {
2261                     convert = n;
2262                 } else {
2263                     NEXT_OFF(convert) = (U16)(tail - convert);
2264                     DEBUG_r(optimize= n);
2265                 }
2266             }
2267         }
2268         if (!jumper) 
2269             jumper = last; 
2270         if ( trie->maxlen ) {
2271             NEXT_OFF( convert ) = (U16)(tail - convert);
2272             ARG_SET( convert, data_slot );
2273             /* Store the offset to the first unabsorbed branch in 
2274                jump[0], which is otherwise unused by the jump logic. 
2275                We use this when dumping a trie and during optimisation. */
2276             if (trie->jump) 
2277                 trie->jump[0] = (U16)(nextbranch - convert);
2278             
2279             /* If the start state is not accepting (meaning there is no empty string/NOTHING)
2280              *   and there is a bitmap
2281              *   and the first "jump target" node we found leaves enough room
2282              * then convert the TRIE node into a TRIEC node, with the bitmap
2283              * embedded inline in the opcode - this is hypothetically faster.
2284              */
2285             if ( !trie->states[trie->startstate].wordnum
2286                  && trie->bitmap
2287                  && ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
2288             {
2289                 OP( convert ) = TRIEC;
2290                 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
2291                 PerlMemShared_free(trie->bitmap);
2292                 trie->bitmap= NULL;
2293             } else 
2294                 OP( convert ) = TRIE;
2295
2296             /* store the type in the flags */
2297             convert->flags = nodetype;
2298             DEBUG_r({
2299             optimize = convert 
2300                       + NODE_STEP_REGNODE 
2301                       + regarglen[ OP( convert ) ];
2302             });
2303             /* XXX We really should free up the resource in trie now, 
2304                    as we won't use them - (which resources?) dmq */
2305         }
2306         /* needed for dumping*/
2307         DEBUG_r(if (optimize) {
2308             regnode *opt = convert;
2309
2310             while ( ++opt < optimize) {
2311                 Set_Node_Offset_Length(opt,0,0);
2312             }
2313             /* 
2314                 Try to clean up some of the debris left after the 
2315                 optimisation.
2316              */
2317             while( optimize < jumper ) {
2318                 mjd_nodelen += Node_Length((optimize));
2319                 OP( optimize ) = OPTIMIZED;
2320                 Set_Node_Offset_Length(optimize,0,0);
2321                 optimize++;
2322             }
2323             Set_Node_Offset_Length(convert,mjd_offset,mjd_nodelen);
2324         });
2325     } /* end node insert */
2326     REH_CALL_COMP_NODE_HOOK(pRExC_state->rx, convert);
2327
2328     /*  Finish populating the prev field of the wordinfo array.  Walk back
2329      *  from each accept state until we find another accept state, and if
2330      *  so, point the first word's .prev field at the second word. If the
2331      *  second already has a .prev field set, stop now. This will be the
2332      *  case either if we've already processed that word's accept state,
2333      *  or that state had multiple words, and the overspill words were
2334      *  already linked up earlier.
2335      */
2336     {
2337         U16 word;
2338         U32 state;
2339         U16 prev;
2340
2341         for (word=1; word <= trie->wordcount; word++) {
2342             prev = 0;
2343             if (trie->wordinfo[word].prev)
2344                 continue;
2345             state = trie->wordinfo[word].accept;
2346             while (state) {
2347                 state = prev_states[state];
2348                 if (!state)
2349                     break;
2350                 prev = trie->states[state].wordnum;
2351                 if (prev)
2352                     break;
2353             }
2354             trie->wordinfo[word].prev = prev;
2355         }
2356         Safefree(prev_states);
2357     }
2358
2359
2360     /* and now dump out the compressed format */
2361     DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
2362
2363     RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
2364 #ifdef DEBUGGING
2365     RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
2366     RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
2367 #else
2368     SvREFCNT_dec(revcharmap);
2369 #endif
2370     return trie->jump 
2371            ? MADE_JUMP_TRIE 
2372            : trie->startstate>1 
2373              ? MADE_EXACT_TRIE 
2374              : MADE_TRIE;
2375 }
2376
2377 STATIC void
2378 S_make_trie_failtable(pTHX_ RExC_state_t *pRExC_state, regnode *source,  regnode *stclass, U32 depth)
2379 {
2380 /* The Trie is constructed and compressed now so we can build a fail array if it's needed
2381
2382    This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and 3.32 in the
2383    "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi, Ullman 1985/88
2384    ISBN 0-201-10088-6
2385
2386    We find the fail state for each state in the trie, this state is the longest proper
2387    suffix of the current state's 'word' that is also a proper prefix of another word in our
2388    trie. State 1 represents the word '' and is thus the default fail state. This allows
2389    the DFA not to have to restart after its tried and failed a word at a given point, it
2390    simply continues as though it had been matching the other word in the first place.
2391    Consider
2392       'abcdgu'=~/abcdefg|cdgu/
2393    When we get to 'd' we are still matching the first word, we would encounter 'g' which would
2394    fail, which would bring us to the state representing 'd' in the second word where we would
2395    try 'g' and succeed, proceeding to match 'cdgu'.
2396  */
2397  /* add a fail transition */
2398     const U32 trie_offset = ARG(source);
2399     reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
2400     U32 *q;
2401     const U32 ucharcount = trie->uniquecharcount;
2402     const U32 numstates = trie->statecount;
2403     const U32 ubound = trie->lasttrans + ucharcount;
2404     U32 q_read = 0;
2405     U32 q_write = 0;
2406     U32 charid;
2407     U32 base = trie->states[ 1 ].trans.base;
2408     U32 *fail;
2409     reg_ac_data *aho;
2410     const U32 data_slot = add_data( pRExC_state, 1, "T" );
2411     GET_RE_DEBUG_FLAGS_DECL;
2412
2413     PERL_ARGS_ASSERT_MAKE_TRIE_FAILTABLE;
2414 #ifndef DEBUGGING
2415     PERL_UNUSED_ARG(depth);
2416 #endif
2417
2418
2419     ARG_SET( stclass, data_slot );
2420     aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
2421     RExC_rxi->data->data[ data_slot ] = (void*)aho;
2422     aho->trie=trie_offset;
2423     aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
2424     Copy( trie->states, aho->states, numstates, reg_trie_state );
2425     Newxz( q, numstates, U32);
2426     aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
2427     aho->refcount = 1;
2428     fail = aho->fail;
2429     /* initialize fail[0..1] to be 1 so that we always have
2430        a valid final fail state */
2431     fail[ 0 ] = fail[ 1 ] = 1;
2432
2433     for ( charid = 0; charid < ucharcount ; charid++ ) {
2434         const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
2435         if ( newstate ) {
2436             q[ q_write ] = newstate;
2437             /* set to point at the root */
2438             fail[ q[ q_write++ ] ]=1;
2439         }
2440     }
2441     while ( q_read < q_write) {
2442         const U32 cur = q[ q_read++ % numstates ];
2443         base = trie->states[ cur ].trans.base;
2444
2445         for ( charid = 0 ; charid < ucharcount ; charid++ ) {
2446             const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
2447             if (ch_state) {
2448                 U32 fail_state = cur;
2449                 U32 fail_base;
2450                 do {
2451                     fail_state = fail[ fail_state ];
2452                     fail_base = aho->states[ fail_state ].trans.base;
2453                 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
2454
2455                 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
2456                 fail[ ch_state ] = fail_state;
2457                 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
2458                 {
2459                         aho->states[ ch_state ].wordnum =  aho->states[ fail_state ].wordnum;
2460                 }
2461                 q[ q_write++ % numstates] = ch_state;
2462             }
2463         }
2464     }
2465     /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
2466        when we fail in state 1, this allows us to use the
2467        charclass scan to find a valid start char. This is based on the principle
2468        that theres a good chance the string being searched contains lots of stuff
2469        that cant be a start char.
2470      */
2471     fail[ 0 ] = fail[ 1 ] = 0;
2472     DEBUG_TRIE_COMPILE_r({
2473         PerlIO_printf(Perl_debug_log,
2474                       "%*sStclass Failtable (%"UVuf" states): 0", 
2475                       (int)(depth * 2), "", (UV)numstates
2476         );
2477         for( q_read=1; q_read<numstates; q_read++ ) {
2478             PerlIO_printf(Perl_debug_log, ", %"UVuf, (UV)fail[q_read]);
2479         }
2480         PerlIO_printf(Perl_debug_log, "\n");
2481     });
2482     Safefree(q);
2483     /*RExC_seen |= REG_SEEN_TRIEDFA;*/
2484 }
2485
2486
2487 /*
2488  * There are strange code-generation bugs caused on sparc64 by gcc-2.95.2.
2489  * These need to be revisited when a newer toolchain becomes available.
2490  */
2491 #if defined(__sparc64__) && defined(__GNUC__)
2492 #   if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 96)
2493 #       undef  SPARC64_GCC_WORKAROUND
2494 #       define SPARC64_GCC_WORKAROUND 1
2495 #   endif
2496 #endif
2497
2498 #define DEBUG_PEEP(str,scan,depth) \
2499     DEBUG_OPTIMISE_r({if (scan){ \
2500        SV * const mysv=sv_newmortal(); \
2501        regnode *Next = regnext(scan); \
2502        regprop(RExC_rx, mysv, scan); \
2503        PerlIO_printf(Perl_debug_log, "%*s" str ">%3d: %s (%d)\n", \
2504        (int)depth*2, "", REG_NODE_NUM(scan), SvPV_nolen_const(mysv),\
2505        Next ? (REG_NODE_NUM(Next)) : 0 ); \
2506    }});
2507
2508
2509 /* The below joins as many adjacent EXACTish nodes as possible into a single
2510  * one, and looks for problematic sequences of characters whose folds vs.
2511  * non-folds have sufficiently different lengths, that the optimizer would be
2512  * fooled into rejecting legitimate matches of them, and the trie construction
2513  * code can't cope with them.  The joining is only done if:
2514  * 1) there is room in the current conglomerated node to entirely contain the
2515  *    next one.
2516  * 2) they are the exact same node type
2517  *
2518  * The adjacent nodes actually may be separated by NOTHING kind nodes, and
2519  * these get optimized out
2520  *
2521  * If there are problematic code sequences, *min_subtract is set to the delta
2522  * that the minimum size of the node can be less than its actual size.  And,
2523  * the node type of the result is changed to reflect that it contains these
2524  * sequences.
2525  *
2526  * And *has_exactf_sharp_s is set to indicate whether or not the node is EXACTF
2527  * and contains LATIN SMALL LETTER SHARP S
2528  *
2529  * This is as good a place as any to discuss the design of handling these
2530  * problematic sequences.  It's been wrong in Perl for a very long time.  There
2531  * are three code points in Unicode whose folded lengths differ so much from
2532  * the un-folded lengths that it causes problems for the optimizer and trie
2533  * construction.  Why only these are problematic, and not others where lengths
2534  * also differ is something I (khw) do not understand.  New versions of Unicode
2535  * might add more such code points.  Hopefully the logic in fold_grind.t that
2536  * figures out what to test (in part by verifying that each size-combination
2537  * gets tested) will catch any that do come along, so they can be added to the
2538  * special handling below.  The chances of new ones are actually rather small,
2539  * as most, if not all, of the world's scripts that have casefolding have
2540  * already been encoded by Unicode.  Also, a number of Unicode's decisions were
2541  * made to allow compatibility with pre-existing standards, and almost all of
2542  * those have already been dealt with.  These would otherwise be the most
2543  * likely candidates for generating further tricky sequences.  In other words,
2544  * Unicode by itself is unlikely to add new ones unless it is for compatibility
2545  * with pre-existing standards, and there aren't many of those left.
2546  *
2547  * The previous designs for dealing with these involved assigning a special
2548  * node for them.  This approach doesn't work, as evidenced by this example:
2549  *      "\xDFs" =~ /s\xDF/ui    # Used to fail before these patches
2550  * Both these fold to "sss", but if the pattern is parsed to create a node of
2551  * that would match just the \xDF, it won't be able to handle the case where a
2552  * successful match would have to cross the node's boundary.  The new approach
2553  * that hopefully generally solves the problem generates an EXACTFU_SS node
2554  * that is "sss".
2555  *
2556  * There are a number of components to the approach (a lot of work for just
2557  * three code points!):
2558  * 1)   This routine examines each EXACTFish node that could contain the
2559  *      problematic sequences.  It returns in *min_subtract how much to
2560  *      subtract from the the actual length of the string to get a real minimum
2561  *      for one that could match it.  This number is usually 0 except for the
2562  *      problematic sequences.  This delta is used by the caller to adjust the
2563  *      min length of the match, and the delta between min and max, so that the
2564  *      optimizer doesn't reject these possibilities based on size constraints.
2565  * 2)   These sequences are not currently correctly handled by the trie code
2566  *      either, so it changes the joined node type to ops that are not handled
2567  *      by trie's, those new ops being EXACTFU_SS and EXACTFU_NO_TRIE.
2568  * 3)   This is sufficient for the two Greek sequences (described below), but
2569  *      the one involving the Sharp s (\xDF) needs more.  The node type
2570  *      EXACTFU_SS is used for an EXACTFU node that contains at least one "ss"
2571  *      sequence in it.  For non-UTF-8 patterns and strings, this is the only
2572  *      case where there is a possible fold length change.  That means that a
2573  *      regular EXACTFU node without UTF-8 involvement doesn't have to concern
2574  *      itself with length changes, and so can be processed faster.  regexec.c
2575  *      takes advantage of this.  Generally, an EXACTFish node that is in UTF-8
2576  *      is pre-folded by regcomp.c.  This saves effort in regex matching.
2577  *      However, probably mostly for historical reasons, the pre-folding isn't
2578  *      done for non-UTF8 patterns (and it can't be for EXACTF and EXACTFL
2579  *      nodes, as what they fold to isn't known until runtime.)  The fold
2580  *      possibilities for the non-UTF8 patterns are quite simple, except for
2581  *      the sharp s.  All the ones that don't involve a UTF-8 target string
2582  *      are members of a fold-pair, and arrays are set up for all of them
2583  *      that quickly find the other member of the pair.  It might actually
2584  *      be faster to pre-fold these, but it isn't currently done, except for
2585  *      the sharp s.  Code elsewhere in this file makes sure that it gets
2586  *      folded to 'ss', even if the pattern isn't UTF-8.  This avoids the
2587  *      issues described in the next item.
2588  * 4)   A problem remains for the sharp s in EXACTF nodes.  Whether it matches
2589  *      'ss' or not is not knowable at compile time.  It will match iff the
2590  *      target string is in UTF-8, unlike the EXACTFU nodes, where it always
2591  *      matches; and the EXACTFL and EXACTFA nodes where it never does.  Thus
2592  *      it can't be folded to "ss" at compile time, unlike EXACTFU does as
2593  *      described in item 3).  An assumption that the optimizer part of
2594  *      regexec.c (probably unwittingly) makes is that a character in the
2595  *      pattern corresponds to at most a single character in the target string.
2596  *      (And I do mean character, and not byte here, unlike other parts of the
2597  *      documentation that have never been updated to account for multibyte
2598  *      Unicode.)  This assumption is wrong only in this case, as all other
2599  *      cases are either 1-1 folds when no UTF-8 is involved; or is true by
2600  *      virtue of having this file pre-fold UTF-8 patterns.   I'm
2601  *      reluctant to try to change this assumption, so instead the code punts.
2602  *      This routine examines EXACTF nodes for the sharp s, and returns a
2603  *      boolean indicating whether or not the node is an EXACTF node that
2604  *      contains a sharp s.  When it is true, the caller sets a flag that later
2605  *      causes the optimizer in this file to not set values for the floating
2606  *      and fixed string lengths, and thus avoids the optimizer code in
2607  *      regexec.c that makes the invalid assumption.  Thus, there is no
2608  *      optimization based on string lengths for EXACTF nodes that contain the
2609  *      sharp s.  This only happens for /id rules (which means the pattern
2610  *      isn't in UTF-8).
2611  */
2612
2613 #define JOIN_EXACT(scan,min_subtract,has_exactf_sharp_s, flags) \
2614     if (PL_regkind[OP(scan)] == EXACT) \
2615         join_exact(pRExC_state,(scan),(min_subtract),has_exactf_sharp_s, (flags),NULL,depth+1)
2616
2617 STATIC U32
2618 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) {
2619     /* Merge several consecutive EXACTish nodes into one. */
2620     regnode *n = regnext(scan);
2621     U32 stringok = 1;
2622     regnode *next = scan + NODE_SZ_STR(scan);
2623     U32 merged = 0;
2624     U32 stopnow = 0;
2625 #ifdef DEBUGGING
2626     regnode *stop = scan;
2627     GET_RE_DEBUG_FLAGS_DECL;
2628 #else
2629     PERL_UNUSED_ARG(depth);
2630 #endif
2631
2632     PERL_ARGS_ASSERT_JOIN_EXACT;
2633 #ifndef EXPERIMENTAL_INPLACESCAN
2634     PERL_UNUSED_ARG(flags);
2635     PERL_UNUSED_ARG(val);
2636 #endif
2637     DEBUG_PEEP("join",scan,depth);
2638
2639     /* Look through the subsequent nodes in the chain.  Skip NOTHING, merge
2640      * EXACT ones that are mergeable to the current one. */
2641     while (n
2642            && (PL_regkind[OP(n)] == NOTHING
2643                || (stringok && OP(n) == OP(scan)))
2644            && NEXT_OFF(n)
2645            && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX)
2646     {
2647         
2648         if (OP(n) == TAIL || n > next)
2649             stringok = 0;
2650         if (PL_regkind[OP(n)] == NOTHING) {
2651             DEBUG_PEEP("skip:",n,depth);
2652             NEXT_OFF(scan) += NEXT_OFF(n);
2653             next = n + NODE_STEP_REGNODE;
2654 #ifdef DEBUGGING
2655             if (stringok)
2656                 stop = n;
2657 #endif
2658             n = regnext(n);
2659         }
2660         else if (stringok) {
2661             const unsigned int oldl = STR_LEN(scan);
2662             regnode * const nnext = regnext(n);
2663
2664             if (oldl + STR_LEN(n) > U8_MAX)
2665                 break;
2666             
2667             DEBUG_PEEP("merg",n,depth);
2668             merged++;
2669
2670             NEXT_OFF(scan) += NEXT_OFF(n);
2671             STR_LEN(scan) += STR_LEN(n);
2672             next = n + NODE_SZ_STR(n);
2673             /* Now we can overwrite *n : */
2674             Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
2675 #ifdef DEBUGGING
2676             stop = next - 1;
2677 #endif
2678             n = nnext;
2679             if (stopnow) break;
2680         }
2681
2682 #ifdef EXPERIMENTAL_INPLACESCAN
2683         if (flags && !NEXT_OFF(n)) {
2684             DEBUG_PEEP("atch", val, depth);
2685             if (reg_off_by_arg[OP(n)]) {
2686                 ARG_SET(n, val - n);
2687             }
2688             else {
2689                 NEXT_OFF(n) = val - n;
2690             }
2691             stopnow = 1;
2692         }
2693 #endif
2694     }
2695
2696     *min_subtract = 0;
2697     *has_exactf_sharp_s = FALSE;
2698
2699     /* Here, all the adjacent mergeable EXACTish nodes have been merged.  We
2700      * can now analyze for sequences of problematic code points.  (Prior to
2701      * this final joining, sequences could have been split over boundaries, and
2702      * hence missed).  The sequences only happen in folding, hence for any
2703      * non-EXACT EXACTish node */
2704     if (OP(scan) != EXACT) {
2705         U8 *s;
2706         U8 * s0 = (U8*) STRING(scan);
2707         U8 * const s_end = s0 + STR_LEN(scan);
2708
2709         /* The below is perhaps overboard, but this allows us to save a test
2710          * each time through the loop at the expense of a mask.  This is
2711          * because on both EBCDIC and ASCII machines, 'S' and 's' differ by a
2712          * single bit.  On ASCII they are 32 apart; on EBCDIC, they are 64.
2713          * This uses an exclusive 'or' to find that bit and then inverts it to
2714          * form a mask, with just a single 0, in the bit position where 'S' and
2715          * 's' differ. */
2716         const U8 S_or_s_mask = ~ ('S' ^ 's');
2717         const U8 s_masked = 's' & S_or_s_mask;
2718
2719         /* One pass is made over the node's string looking for all the
2720          * possibilities.  to avoid some tests in the loop, there are two main
2721          * cases, for UTF-8 patterns (which can't have EXACTF nodes) and
2722          * non-UTF-8 */
2723         if (UTF) {
2724
2725             /* There are two problematic Greek code points in Unicode
2726              * casefolding
2727              *
2728              * U+0390 - GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS
2729              * U+03B0 - GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS
2730              *
2731              * which casefold to
2732              *
2733              * Unicode                      UTF-8
2734              *
2735              * U+03B9 U+0308 U+0301         0xCE 0xB9 0xCC 0x88 0xCC 0x81
2736              * U+03C5 U+0308 U+0301         0xCF 0x85 0xCC 0x88 0xCC 0x81
2737              *
2738              * This means that in case-insensitive matching (or "loose
2739              * matching", as Unicode calls it), an EXACTF of length six (the
2740              * UTF-8 encoded byte length of the above casefolded versions) can
2741              * match a target string of length two (the byte length of UTF-8
2742              * encoded U+0390 or U+03B0).  This would rather mess up the
2743              * minimum length computation.  (there are other code points that
2744              * also fold to these two sequences, but the delta is smaller)
2745              *
2746              * If these sequences are found, the minimum length is decreased by
2747              * four (six minus two).
2748              *
2749              * Similarly, 'ss' may match the single char and byte LATIN SMALL
2750              * LETTER SHARP S.  We decrease the min length by 1 for each
2751              * occurrence of 'ss' found */
2752
2753 #ifdef EBCDIC /* RD tunifold greek 0390 and 03B0 */
2754 #           define U390_first_byte 0xb4
2755             const U8 U390_tail[] = "\x68\xaf\x49\xaf\x42";
2756 #           define U3B0_first_byte 0xb5
2757             const U8 U3B0_tail[] = "\x46\xaf\x49\xaf\x42";
2758 #else
2759 #           define U390_first_byte 0xce
2760             const U8 U390_tail[] = "\xb9\xcc\x88\xcc\x81";
2761 #           define U3B0_first_byte 0xcf
2762             const U8 U3B0_tail[] = "\x85\xcc\x88\xcc\x81";
2763 #endif
2764             const U8 len = sizeof(U390_tail); /* (-1 for NUL; +1 for 1st byte;
2765                                                  yields a net of 0 */
2766             /* Examine the string for one of the problematic sequences */
2767             for (s = s0;
2768                  s < s_end - 1; /* Can stop 1 before the end, as minimum length
2769                                  * sequence we are looking for is 2 */
2770                  s += UTF8SKIP(s))
2771             {
2772
2773                 /* Look for the first byte in each problematic sequence */
2774                 switch (*s) {
2775                     /* We don't have to worry about other things that fold to
2776                      * 's' (such as the long s, U+017F), as all above-latin1
2777                      * code points have been pre-folded */
2778                     case 's':
2779                     case 'S':
2780
2781                         /* Current character is an 's' or 'S'.  If next one is
2782                          * as well, we have the dreaded sequence */
2783                         if (((*(s+1) & S_or_s_mask) == s_masked)
2784                             /* These two node types don't have special handling
2785                              * for 'ss' */
2786                             && OP(scan) != EXACTFL && OP(scan) != EXACTFA)
2787                         {
2788                             *min_subtract += 1;
2789                             OP(scan) = EXACTFU_SS;
2790                             s++;    /* No need to look at this character again */
2791                         }
2792                         break;
2793
2794                     case U390_first_byte:
2795                         if (s_end - s >= len
2796
2797                             /* The 1's are because are skipping comparing the
2798                              * first byte */
2799                             && memEQ(s + 1, U390_tail, len - 1))
2800                         {
2801                             goto greek_sequence;
2802                         }
2803                         break;
2804
2805                     case U3B0_first_byte:
2806                         if (! (s_end - s >= len
2807                                && memEQ(s + 1, U3B0_tail, len - 1)))
2808                         {
2809                             break;
2810                         }
2811                       greek_sequence:
2812                         *min_subtract += 4;
2813
2814                         /* This can't currently be handled by trie's, so change
2815                          * the node type to indicate this.  If EXACTFA and
2816                          * EXACTFL were ever to be handled by trie's, this
2817                          * would have to be changed.  If this node has already
2818                          * been changed to EXACTFU_SS in this loop, leave it as
2819                          * is.  (I (khw) think it doesn't matter in regexec.c
2820                          * for UTF patterns, but no need to change it */
2821                         if (OP(scan) == EXACTFU) {
2822                             OP(scan) = EXACTFU_NO_TRIE;
2823                         }
2824                         s += 6; /* We already know what this sequence is.  Skip
2825                                    the rest of it */
2826                         break;
2827                 }
2828             }
2829         }
2830         else if (OP(scan) != EXACTFL && OP(scan) != EXACTFA) {
2831
2832             /* Here, the pattern is not UTF-8.  We need to look only for the
2833              * 'ss' sequence, and in the EXACTF case, the sharp s, which can be
2834              * in the final position.  Otherwise we can stop looking 1 byte
2835              * earlier because have to find both the first and second 's' */
2836             const U8* upper = (OP(scan) == EXACTF) ? s_end : s_end -1;
2837
2838             for (s = s0; s < upper; s++) {
2839                 switch (*s) {
2840                     case 'S':
2841                     case 's':
2842                         if (s_end - s > 1
2843                             && ((*(s+1) & S_or_s_mask) == s_masked))
2844                         {
2845                             *min_subtract += 1;
2846
2847                             /* EXACTF nodes need to know that the minimum
2848                              * length changed so that a sharp s in the string
2849                              * can match this ss in the pattern, but they
2850                              * remain EXACTF nodes, as they are not trie'able,
2851                              * so don't have to invent a new node type to
2852                              * exclude them from the trie code */
2853                             if (OP(scan) != EXACTF) {
2854                                 OP(scan) = EXACTFU_SS;
2855                             }
2856                             s++;
2857                         }
2858                         break;
2859                     case LATIN_SMALL_LETTER_SHARP_S:
2860                         if (OP(scan) == EXACTF) {
2861                             *has_exactf_sharp_s = TRUE;
2862                         }
2863                         break;
2864                 }
2865             }
2866         }
2867     }
2868
2869 #ifdef DEBUGGING
2870     /* Allow dumping but overwriting the collection of skipped
2871      * ops and/or strings with fake optimized ops */
2872     n = scan + NODE_SZ_STR(scan);
2873     while (n <= stop) {
2874         OP(n) = OPTIMIZED;
2875         FLAGS(n) = 0;
2876         NEXT_OFF(n) = 0;
2877         n++;
2878     }
2879 #endif
2880     DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl",scan,depth)});
2881     return stopnow;
2882 }
2883
2884 /* REx optimizer.  Converts nodes into quicker variants "in place".
2885    Finds fixed substrings.  */
2886
2887 /* Stops at toplevel WHILEM as well as at "last". At end *scanp is set
2888    to the position after last scanned or to NULL. */
2889
2890 #define INIT_AND_WITHP \
2891     assert(!and_withp); \
2892     Newx(and_withp,1,struct regnode_charclass_class); \
2893     SAVEFREEPV(and_withp)
2894
2895 /* this is a chain of data about sub patterns we are processing that
2896    need to be handled separately/specially in study_chunk. Its so
2897    we can simulate recursion without losing state.  */
2898 struct scan_frame;
2899 typedef struct scan_frame {
2900     regnode *last;  /* last node to process in this frame */
2901     regnode *next;  /* next node to process when last is reached */
2902     struct scan_frame *prev; /*previous frame*/
2903     I32 stop; /* what stopparen do we use */
2904 } scan_frame;
2905
2906
2907 #define SCAN_COMMIT(s, data, m) scan_commit(s, data, m, is_inf)
2908
2909 #define CASE_SYNST_FNC(nAmE)                                       \
2910 case nAmE:                                                         \
2911     if (flags & SCF_DO_STCLASS_AND) {                              \
2912             for (value = 0; value < 256; value++)                  \
2913                 if (!is_ ## nAmE ## _cp(value))                       \
2914                     ANYOF_BITMAP_CLEAR(data->start_class, value);  \
2915     }                                                              \
2916     else {                                                         \
2917             for (value = 0; value < 256; value++)                  \
2918                 if (is_ ## nAmE ## _cp(value))                        \
2919                     ANYOF_BITMAP_SET(data->start_class, value);    \
2920     }                                                              \
2921     break;                                                         \
2922 case N ## nAmE:                                                    \
2923     if (flags & SCF_DO_STCLASS_AND) {                              \
2924             for (value = 0; value < 256; value++)                   \
2925                 if (is_ ## nAmE ## _cp(value))                         \
2926                     ANYOF_BITMAP_CLEAR(data->start_class, value);   \
2927     }                                                               \
2928     else {                                                          \
2929             for (value = 0; value < 256; value++)                   \
2930                 if (!is_ ## nAmE ## _cp(value))                        \
2931                     ANYOF_BITMAP_SET(data->start_class, value);     \
2932     }                                                               \
2933     break
2934
2935
2936
2937 STATIC I32
2938 S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
2939                         I32 *minlenp, I32 *deltap,
2940                         regnode *last,
2941                         scan_data_t *data,
2942                         I32 stopparen,
2943                         U8* recursed,
2944                         struct regnode_charclass_class *and_withp,
2945                         U32 flags, U32 depth)
2946                         /* scanp: Start here (read-write). */
2947                         /* deltap: Write maxlen-minlen here. */
2948                         /* last: Stop before this one. */
2949                         /* data: string data about the pattern */
2950                         /* stopparen: treat close N as END */
2951                         /* recursed: which subroutines have we recursed into */
2952                         /* and_withp: Valid if flags & SCF_DO_STCLASS_OR */
2953 {
2954     dVAR;
2955     I32 min = 0, pars = 0, code;
2956     regnode *scan = *scanp, *next;
2957     I32 delta = 0;
2958     int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
2959     int is_inf_internal = 0;            /* The studied chunk is infinite */
2960     I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
2961     scan_data_t data_fake;
2962     SV *re_trie_maxbuff = NULL;
2963     regnode *first_non_open = scan;
2964     I32 stopmin = I32_MAX;
2965     scan_frame *frame = NULL;
2966     GET_RE_DEBUG_FLAGS_DECL;
2967
2968     PERL_ARGS_ASSERT_STUDY_CHUNK;
2969
2970 #ifdef DEBUGGING
2971     StructCopy(&zero_scan_data, &data_fake, scan_data_t);
2972 #endif
2973
2974     if ( depth == 0 ) {
2975         while (first_non_open && OP(first_non_open) == OPEN)
2976             first_non_open=regnext(first_non_open);
2977     }
2978
2979
2980   fake_study_recurse:
2981     while ( scan && OP(scan) != END && scan < last ){
2982         UV min_subtract = 0;    /* How much to subtract from the minimum node
2983                                    length to get a real minimum (because the
2984                                    folded version may be shorter) */
2985         bool has_exactf_sharp_s = FALSE;
2986         /* Peephole optimizer: */
2987         DEBUG_STUDYDATA("Peep:", data,depth);
2988         DEBUG_PEEP("Peep",scan,depth);
2989
2990         /* Its not clear to khw or hv why this is done here, and not in the
2991          * clauses that deal with EXACT nodes.  khw's guess is that it's
2992          * because of a previous design */
2993         JOIN_EXACT(scan,&min_subtract, &has_exactf_sharp_s, 0);
2994
2995         /* Follow the next-chain of the current node and optimize
2996            away all the NOTHINGs from it.  */
2997         if (OP(scan) != CURLYX) {
2998             const int max = (reg_off_by_arg[OP(scan)]
2999                        ? I32_MAX
3000                        /* I32 may be smaller than U16 on CRAYs! */
3001                        : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
3002             int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
3003             int noff;
3004             regnode *n = scan;
3005
3006             /* Skip NOTHING and LONGJMP. */
3007             while ((n = regnext(n))
3008                    && ((PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
3009                        || ((OP(n) == LONGJMP) && (noff = ARG(n))))
3010                    && off + noff < max)
3011                 off += noff;
3012             if (reg_off_by_arg[OP(scan)])
3013                 ARG(scan) = off;
3014             else
3015                 NEXT_OFF(scan) = off;
3016         }
3017
3018
3019
3020         /* The principal pseudo-switch.  Cannot be a switch, since we
3021            look into several different things.  */
3022         if (OP(scan) == BRANCH || OP(scan) == BRANCHJ
3023                    || OP(scan) == IFTHEN) {
3024             next = regnext(scan);
3025             code = OP(scan);
3026             /* demq: the op(next)==code check is to see if we have "branch-branch" AFAICT */
3027
3028             if (OP(next) == code || code == IFTHEN) {
3029                 /* NOTE - There is similar code to this block below for handling
3030                    TRIE nodes on a re-study.  If you change stuff here check there
3031                    too. */
3032                 I32 max1 = 0, min1 = I32_MAX, num = 0;
3033                 struct regnode_charclass_class accum;
3034                 regnode * const startbranch=scan;
3035
3036                 if (flags & SCF_DO_SUBSTR)
3037                     SCAN_COMMIT(pRExC_state, data, minlenp); /* Cannot merge strings after this. */
3038                 if (flags & SCF_DO_STCLASS)
3039                     cl_init_zero(pRExC_state, &accum);
3040
3041                 while (OP(scan) == code) {
3042                     I32 deltanext, minnext, f = 0, fake;
3043                     struct regnode_charclass_class this_class;
3044
3045                     num++;
3046                     data_fake.flags = 0;
3047                     if (data) {
3048                         data_fake.whilem_c = data->whilem_c;
3049                         data_fake.last_closep = data->last_closep;
3050                     }
3051                     else
3052                         data_fake.last_closep = &fake;
3053
3054                     data_fake.pos_delta = delta;
3055                     next = regnext(scan);
3056                     scan = NEXTOPER(scan);
3057                     if (code != BRANCH)
3058                         scan = NEXTOPER(scan);
3059                     if (flags & SCF_DO_STCLASS) {
3060                         cl_init(pRExC_state, &this_class);
3061                         data_fake.start_class = &this_class;
3062                         f = SCF_DO_STCLASS_AND;
3063                     }
3064                     if (flags & SCF_WHILEM_VISITED_POS)
3065                         f |= SCF_WHILEM_VISITED_POS;
3066
3067                     /* we suppose the run is continuous, last=next...*/
3068                     minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
3069                                           next, &data_fake,
3070                                           stopparen, recursed, NULL, f,depth+1);
3071                     if (min1 > minnext)
3072                         min1 = minnext;
3073                     if (max1 < minnext + deltanext)
3074                         max1 = minnext + deltanext;
3075                     if (deltanext == I32_MAX)
3076                         is_inf = is_inf_internal = 1;
3077                     scan = next;
3078                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
3079                         pars++;
3080                     if (data_fake.flags & SCF_SEEN_ACCEPT) {
3081                         if ( stopmin > minnext) 
3082                             stopmin = min + min1;
3083                         flags &= ~SCF_DO_SUBSTR;
3084                         if (data)
3085                             data->flags |= SCF_SEEN_ACCEPT;
3086                     }
3087                     if (data) {
3088                         if (data_fake.flags & SF_HAS_EVAL)
3089                             data->flags |= SF_HAS_EVAL;
3090                         data->whilem_c = data_fake.whilem_c;
3091                     }
3092                     if (flags & SCF_DO_STCLASS)
3093                         cl_or(pRExC_state, &accum, &this_class);
3094                 }
3095                 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
3096                     min1 = 0;
3097                 if (flags & SCF_DO_SUBSTR) {
3098                     data->pos_min += min1;
3099                     data->pos_delta += max1 - min1;
3100                     if (max1 != min1 || is_inf)
3101                         data->longest = &(data->longest_float);
3102                 }
3103                 min += min1;
3104                 delta += max1 - min1;
3105                 if (flags & SCF_DO_STCLASS_OR) {
3106                     cl_or(pRExC_state, data->start_class, &accum);
3107                     if (min1) {
3108                         cl_and(data->start_class, and_withp);
3109                         flags &= ~SCF_DO_STCLASS;
3110                     }
3111                 }
3112                 else if (flags & SCF_DO_STCLASS_AND) {
3113                     if (min1) {
3114                         cl_and(data->start_class, &accum);
3115                         flags &= ~SCF_DO_STCLASS;
3116                     }
3117                     else {
3118                         /* Switch to OR mode: cache the old value of
3119                          * data->start_class */
3120                         INIT_AND_WITHP;
3121                         StructCopy(data->start_class, and_withp,
3122                                    struct regnode_charclass_class);
3123                         flags &= ~SCF_DO_STCLASS_AND;
3124                         StructCopy(&accum, data->start_class,
3125                                    struct regnode_charclass_class);
3126                         flags |= SCF_DO_STCLASS_OR;
3127                         data->start_class->flags |= ANYOF_EOS;
3128                     }
3129                 }
3130
3131                 if (PERL_ENABLE_TRIE_OPTIMISATION && OP( startbranch ) == BRANCH ) {
3132                 /* demq.
3133
3134                    Assuming this was/is a branch we are dealing with: 'scan' now
3135                    points at the item that follows the branch sequence, whatever
3136                    it is. We now start at the beginning of the sequence and look
3137                    for subsequences of
3138
3139                    BRANCH->EXACT=>x1
3140                    BRANCH->EXACT=>x2
3141                    tail
3142
3143                    which would be constructed from a pattern like /A|LIST|OF|WORDS/
3144
3145                    If we can find such a subsequence we need to turn the first
3146                    element into a trie and then add the subsequent branch exact
3147                    strings to the trie.
3148
3149                    We have two cases
3150
3151                      1. patterns where the whole set of branches can be converted. 
3152
3153                      2. patterns where only a subset can be converted.
3154
3155                    In case 1 we can replace the whole set with a single regop
3156                    for the trie. In case 2 we need to keep the start and end
3157                    branches so
3158
3159                      'BRANCH EXACT; BRANCH EXACT; BRANCH X'
3160                      becomes BRANCH TRIE; BRANCH X;
3161
3162                   There is an additional case, that being where there is a 
3163                   common prefix, which gets split out into an EXACT like node
3164                   preceding the TRIE node.
3165
3166                   If x(1..n)==tail then we can do a simple trie, if not we make
3167                   a "jump" trie, such that when we match the appropriate word
3168                   we "jump" to the appropriate tail node. Essentially we turn
3169                   a nested if into a case structure of sorts.
3170
3171                 */
3172
3173                     int made=0;
3174                     if (!re_trie_maxbuff) {
3175                         re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
3176                         if (!SvIOK(re_trie_maxbuff))
3177                             sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
3178                     }
3179                     if ( SvIV(re_trie_maxbuff)>=0  ) {
3180                         regnode *cur;
3181                         regnode *first = (regnode *)NULL;
3182                         regnode *last = (regnode *)NULL;
3183                         regnode *tail = scan;
3184                         U8 optype = 0;
3185                         U32 count=0;
3186
3187 #ifdef DEBUGGING
3188                         SV * const mysv = sv_newmortal();       /* for dumping */
3189 #endif
3190                         /* var tail is used because there may be a TAIL
3191                            regop in the way. Ie, the exacts will point to the
3192                            thing following the TAIL, but the last branch will
3193                            point at the TAIL. So we advance tail. If we
3194                            have nested (?:) we may have to move through several
3195                            tails.
3196                          */
3197
3198                         while ( OP( tail ) == TAIL ) {
3199                             /* this is the TAIL generated by (?:) */
3200                             tail = regnext( tail );
3201                         }
3202
3203                         
3204                         DEBUG_OPTIMISE_r({
3205                             regprop(RExC_rx, mysv, tail );
3206                             PerlIO_printf( Perl_debug_log, "%*s%s%s\n",
3207                                 (int)depth * 2 + 2, "", 
3208                                 "Looking for TRIE'able sequences. Tail node is: ", 
3209                                 SvPV_nolen_const( mysv )
3210                             );
3211                         });
3212                         
3213                         /*
3214
3215                            step through the branches, cur represents each
3216                            branch, noper is the first thing to be matched
3217                            as part of that branch and noper_next is the
3218                            regnext() of that node. if noper is an EXACT
3219                            and noper_next is the same as scan (our current
3220                            position in the regex) then the EXACT branch is
3221                            a possible optimization target. Once we have
3222                            two or more consecutive such branches we can
3223                            create a trie of the EXACT's contents and stich
3224                            it in place. If the sequence represents all of
3225                            the branches we eliminate the whole thing and
3226                            replace it with a single TRIE. If it is a
3227                            subsequence then we need to stitch it in. This
3228                            means the first branch has to remain, and needs
3229                            to be repointed at the item on the branch chain
3230                            following the last branch optimized. This could
3231                            be either a BRANCH, in which case the
3232                            subsequence is internal, or it could be the
3233                            item following the branch sequence in which
3234                            case the subsequence is at the end.
3235
3236                         */
3237
3238                         /* dont use tail as the end marker for this traverse */
3239                         for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {
3240                             regnode * const noper = NEXTOPER( cur );
3241 #if defined(DEBUGGING) || defined(NOJUMPTRIE)
3242                             regnode * const noper_next = regnext( noper );
3243 #endif
3244
3245                             DEBUG_OPTIMISE_r({
3246                                 regprop(RExC_rx, mysv, cur);
3247                                 PerlIO_printf( Perl_debug_log, "%*s- %s (%d)",
3248                                    (int)depth * 2 + 2,"", SvPV_nolen_const( mysv ), REG_NODE_NUM(cur) );
3249
3250                                 regprop(RExC_rx, mysv, noper);
3251                                 PerlIO_printf( Perl_debug_log, " -> %s",
3252                                     SvPV_nolen_const(mysv));
3253
3254                                 if ( noper_next ) {
3255                                   regprop(RExC_rx, mysv, noper_next );
3256                                   PerlIO_printf( Perl_debug_log,"\t=> %s\t",
3257                                     SvPV_nolen_const(mysv));
3258                                 }
3259                                 PerlIO_printf( Perl_debug_log, "(First==%d,Last==%d,Cur==%d)\n",
3260                                    REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur) );
3261                             });
3262                             if ( (((first && optype!=NOTHING) ? OP( noper ) == optype
3263                                          : PL_regkind[ OP( noper ) ] == EXACT )
3264                                   || OP(noper) == NOTHING )
3265 #ifdef NOJUMPTRIE
3266                                   && noper_next == tail
3267 #endif
3268                                   && count < U16_MAX)
3269                             {
3270                                 count++;
3271                                 if ( !first || optype == NOTHING ) {
3272                                     if (!first) first = cur;
3273                                     optype = OP( noper );
3274                                 } else {
3275                                     last = cur;
3276                                 }
3277                             } else {
3278 /* 
3279     Currently the trie logic handles case insensitive matching properly only
3280     when the pattern is UTF-8 and the node is EXACTFU (thus forcing unicode
3281     semantics).
3282
3283     If/when this is fixed the following define can be swapped
3284     in below to fully enable trie logic.
3285
3286 #define TRIE_TYPE_IS_SAFE 1
3287
3288 Note that join_exact() assumes that the other types of EXACTFish nodes are not
3289 used in tries, so that would have to be updated if this changed
3290
3291 */
3292 #define TRIE_TYPE_IS_SAFE ((UTF && optype == EXACTFU) || optype==EXACT)
3293
3294                                 if ( last && TRIE_TYPE_IS_SAFE ) {
3295                                     make_trie( pRExC_state, 
3296                                             startbranch, first, cur, tail, count, 
3297                                             optype, depth+1 );
3298                                 }
3299                                 if ( PL_regkind[ OP( noper ) ] == EXACT
3300 #ifdef NOJUMPTRIE
3301                                      && noper_next == tail
3302 #endif
3303                                 ){
3304                                     count = 1;
3305                                     first = cur;
3306                                     optype = OP( noper );
3307                                 } else {
3308                                     count = 0;
3309                                     first = NULL;
3310                                     optype = 0;
3311                                 }
3312                                 last = NULL;
3313                             }
3314                         }
3315                         DEBUG_OPTIMISE_r({
3316                             regprop(RExC_rx, mysv, cur);
3317                             PerlIO_printf( Perl_debug_log,
3318                               "%*s- %s (%d) <SCAN FINISHED>\n", (int)depth * 2 + 2,
3319                               "", SvPV_nolen_const( mysv ),REG_NODE_NUM(cur));
3320
3321                         });
3322                         
3323                         if ( last && TRIE_TYPE_IS_SAFE ) {
3324                             made= make_trie( pRExC_state, startbranch, first, scan, tail, count, optype, depth+1 );
3325 #ifdef TRIE_STUDY_OPT
3326                             if ( ((made == MADE_EXACT_TRIE && 
3327                                  startbranch == first) 
3328                                  || ( first_non_open == first )) && 
3329                                  depth==0 ) {
3330                                 flags |= SCF_TRIE_RESTUDY;
3331                                 if ( startbranch == first 
3332                                      && scan == tail ) 
3333                                 {
3334                                     RExC_seen &=~REG_TOP_LEVEL_BRANCHES;
3335                                 }
3336                             }
3337 #endif
3338                         }
3339                     }
3340                     
3341                 } /* do trie */
3342                 
3343             }
3344             else if ( code == BRANCHJ ) {  /* single branch is optimized. */
3345                 scan = NEXTOPER(NEXTOPER(scan));
3346             } else                      /* single branch is optimized. */
3347                 scan = NEXTOPER(scan);
3348             continue;
3349         } else if (OP(scan) == SUSPEND || OP(scan) == GOSUB || OP(scan) == GOSTART) {
3350             scan_frame *newframe = NULL;
3351             I32 paren;
3352             regnode *start;
3353             regnode *end;
3354
3355             if (OP(scan) != SUSPEND) {
3356             /* set the pointer */
3357                 if (OP(scan) == GOSUB) {
3358                     paren = ARG(scan);
3359                     RExC_recurse[ARG2L(scan)] = scan;
3360                     start = RExC_open_parens[paren-1];
3361                     end   = RExC_close_parens[paren-1];
3362                 } else {
3363                     paren = 0;
3364                     start = RExC_rxi->program + 1;
3365                     end   = RExC_opend;
3366                 }
3367                 if (!recursed) {
3368                     Newxz(recursed, (((RExC_npar)>>3) +1), U8);
3369                     SAVEFREEPV(recursed);
3370                 }
3371                 if (!PAREN_TEST(recursed,paren+1)) {
3372                     PAREN_SET(recursed,paren+1);
3373                     Newx(newframe,1,scan_frame);
3374                 } else {
3375                     if (flags & SCF_DO_SUBSTR) {
3376                         SCAN_COMMIT(pRExC_state,data,minlenp);
3377                         data->longest = &(data->longest_float);
3378                     }
3379                     is_inf = is_inf_internal = 1;
3380                     if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
3381                         cl_anything(pRExC_state, data->start_class);
3382                     flags &= ~SCF_DO_STCLASS;
3383                 }
3384             } else {
3385                 Newx(newframe,1,scan_frame);
3386                 paren = stopparen;
3387                 start = scan+2;
3388                 end = regnext(scan);
3389             }
3390             if (newframe) {
3391                 assert(start);
3392                 assert(end);
3393                 SAVEFREEPV(newframe);
3394                 newframe->next = regnext(scan);
3395                 newframe->last = last;
3396                 newframe->stop = stopparen;
3397                 newframe->prev = frame;
3398
3399                 frame = newframe;
3400                 scan =  start;
3401                 stopparen = paren;
3402                 last = end;
3403
3404                 continue;
3405             }
3406         }
3407         else if (OP(scan) == EXACT) {
3408             I32 l = STR_LEN(scan);
3409             UV uc;
3410             if (UTF) {
3411                 const U8 * const s = (U8*)STRING(scan);
3412                 l = utf8_length(s, s + l);
3413                 uc = utf8_to_uvchr(s, NULL);
3414             } else {
3415                 uc = *((U8*)STRING(scan));
3416             }
3417             min += l;
3418             if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
3419                 /* The code below prefers earlier match for fixed
3420                    offset, later match for variable offset.  */
3421                 if (data->last_end == -1) { /* Update the start info. */
3422                     data->last_start_min = data->pos_min;
3423                     data->last_start_max = is_inf
3424                         ? I32_MAX : data->pos_min + data->pos_delta;
3425                 }
3426                 sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));
3427                 if (UTF)
3428                     SvUTF8_on(data->last_found);
3429                 {
3430                     SV * const sv = data->last_found;
3431                     MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
3432                         mg_find(sv, PERL_MAGIC_utf8) : NULL;
3433                     if (mg && mg->mg_len >= 0)
3434                         mg->mg_len += utf8_length((U8*)STRING(scan),
3435                                                   (U8*)STRING(scan)+STR_LEN(scan));
3436                 }
3437                 data->last_end = data->pos_min + l;
3438                 data->pos_min += l; /* As in the first entry. */
3439                 data->flags &= ~SF_BEFORE_EOL;
3440             }
3441             if (flags & SCF_DO_STCLASS_AND) {
3442                 /* Check whether it is compatible with what we know already! */
3443                 int compat = 1;
3444
3445
3446                 /* If compatible, we or it in below.  It is compatible if is
3447                  * in the bitmp and either 1) its bit or its fold is set, or 2)
3448                  * it's for a locale.  Even if there isn't unicode semantics
3449                  * here, at runtime there may be because of matching against a
3450                  * utf8 string, so accept a possible false positive for
3451                  * latin1-range folds */
3452                 if (uc >= 0x100 ||
3453                     (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
3454                     && !ANYOF_BITMAP_TEST(data->start_class, uc)
3455                     && (!(data->start_class->flags & ANYOF_LOC_NONBITMAP_FOLD)
3456                         || !ANYOF_BITMAP_TEST(data->start_class, PL_fold_latin1[uc])))
3457                     )
3458                 {
3459                     compat = 0;
3460                 }
3461                 ANYOF_CLASS_ZERO(data->start_class);
3462                 ANYOF_BITMAP_ZERO(data->start_class);
3463                 if (compat)
3464                     ANYOF_BITMAP_SET(data->start_class, uc);
3465                 else if (uc >= 0x100) {
3466                     int i;
3467
3468                     /* Some Unicode code points fold to the Latin1 range; as
3469                      * XXX temporary code, instead of figuring out if this is
3470                      * one, just assume it is and set all the start class bits
3471                      * that could be some such above 255 code point's fold
3472                      * which will generate fals positives.  As the code
3473                      * elsewhere that does compute the fold settles down, it
3474                      * can be extracted out and re-used here */
3475                     for (i = 0; i < 256; i++){
3476                         if (_HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)) {
3477                             ANYOF_BITMAP_SET(data->start_class, i);
3478                         }
3479                     }
3480                 }
3481                 data->start_class->flags &= ~ANYOF_EOS;
3482                 if (uc < 0x100)
3483                   data->start_class->flags &= ~ANYOF_UNICODE_ALL;
3484             }
3485             else if (flags & SCF_DO_STCLASS_OR) {
3486                 /* false positive possible if the class is case-folded */
3487                 if (uc < 0x100)
3488                     ANYOF_BITMAP_SET(data->start_class, uc);
3489                 else
3490                     data->start_class->flags |= ANYOF_UNICODE_ALL;
3491                 data->start_class->flags &= ~ANYOF_EOS;
3492                 cl_and(data->start_class, and_withp);
3493             }
3494             flags &= ~SCF_DO_STCLASS;
3495         }
3496         else if (PL_regkind[OP(scan)] == EXACT) { /* But OP != EXACT! */
3497             I32 l = STR_LEN(scan);
3498             UV uc = *((U8*)STRING(scan));
3499
3500             /* Search for fixed substrings supports EXACT only. */
3501             if (flags & SCF_DO_SUBSTR) {
3502                 assert(data);
3503                 SCAN_COMMIT(pRExC_state, data, minlenp);
3504             }
3505             if (UTF) {
3506                 const U8 * const s = (U8 *)STRING(scan);
3507                 l = utf8_length(s, s + l);
3508                 uc = utf8_to_uvchr(s, NULL);
3509             }
3510             else if (has_exactf_sharp_s) {
3511                 RExC_seen |= REG_SEEN_EXACTF_SHARP_S;
3512             }
3513             min += l - min_subtract;
3514             if (min < 0) {
3515                 min = 0;
3516             }
3517             delta += min_subtract;
3518             if (flags & SCF_DO_SUBSTR) {
3519                 data->pos_min += l - min_subtract;
3520                 if (data->pos_min < 0) {
3521                     data->pos_min = 0;
3522                 }
3523                 data->pos_delta += min_subtract;
3524                 if (min_subtract) {
3525                     data->longest = &(data->longest_float);
3526                 }
3527             }
3528             if (flags & SCF_DO_STCLASS_AND) {
3529                 /* Check whether it is compatible with what we know already! */
3530                 int compat = 1;
3531                 if (uc >= 0x100 ||
3532                  (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
3533                   && !ANYOF_BITMAP_TEST(data->start_class, uc)
3534                   && !ANYOF_BITMAP_TEST(data->start_class, PL_fold_latin1[uc])))
3535                 {
3536                     compat = 0;
3537                 }
3538                 ANYOF_CLASS_ZERO(data->start_class);
3539                 ANYOF_BITMAP_ZERO(data->start_class);
3540                 if (compat) {
3541                     ANYOF_BITMAP_SET(data->start_class, uc);
3542                     data->start_class->flags &= ~ANYOF_EOS;
3543                     data->start_class->flags |= ANYOF_LOC_NONBITMAP_FOLD;
3544                     if (OP(scan) == EXACTFL) {
3545                         /* XXX This set is probably no longer necessary, and
3546                          * probably wrong as LOCALE now is on in the initial
3547                          * state */
3548                         data->start_class->flags |= ANYOF_LOCALE;
3549                     }
3550                     else {
3551
3552                         /* Also set the other member of the fold pair.  In case
3553                          * that unicode semantics is called for at runtime, use
3554                          * the full latin1 fold.  (Can't do this for locale,
3555                          * because not known until runtime) */
3556                         ANYOF_BITMAP_SET(data->start_class, PL_fold_latin1[uc]);
3557
3558                         /* All other (EXACTFL handled above) folds except under
3559                          * /iaa that include s, S, and sharp_s also may include
3560                          * the others */
3561                         if (OP(scan) != EXACTFA) {
3562                             if (uc == 's' || uc == 'S') {
3563                                 ANYOF_BITMAP_SET(data->start_class,
3564                                                  LATIN_SMALL_LETTER_SHARP_S);
3565                             }
3566                             else if (uc == LATIN_SMALL_LETTER_SHARP_S) {
3567                                 ANYOF_BITMAP_SET(data->start_class, 's');
3568                                 ANYOF_BITMAP_SET(data->start_class, 'S');
3569                             }
3570                         }
3571                     }
3572                 }
3573                 else if (uc >= 0x100) {
3574                     int i;
3575                     for (i = 0; i < 256; i++){
3576                         if (_HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)) {
3577                             ANYOF_BITMAP_SET(data->start_class, i);
3578                         }
3579                     }
3580                 }
3581             }
3582             else if (flags & SCF_DO_STCLASS_OR) {
3583                 if (data->start_class->flags & ANYOF_LOC_NONBITMAP_FOLD) {
3584                     /* false positive possible if the class is case-folded.
3585                        Assume that the locale settings are the same... */
3586                     if (uc < 0x100) {
3587                         ANYOF_BITMAP_SET(data->start_class, uc);
3588                         if (OP(scan) != EXACTFL) {
3589
3590                             /* And set the other member of the fold pair, but
3591                              * can't do that in locale because not known until
3592                              * run-time */
3593                             ANYOF_BITMAP_SET(data->start_class,
3594                                              PL_fold_latin1[uc]);
3595
3596                             /* All folds except under /iaa that include s, S,
3597                              * and sharp_s also may include the others */
3598                             if (OP(scan) != EXACTFA) {
3599                                 if (uc == 's' || uc == 'S') {
3600                                     ANYOF_BITMAP_SET(data->start_class,
3601                                                    LATIN_SMALL_LETTER_SHARP_S);
3602                                 }
3603                                 else if (uc == LATIN_SMALL_LETTER_SHARP_S) {
3604                                     ANYOF_BITMAP_SET(data->start_class, 's');
3605                                     ANYOF_BITMAP_SET(data->start_class, 'S');
3606                                 }
3607                             }
3608                         }
3609                     }
3610                     data->start_class->flags &= ~ANYOF_EOS;
3611                 }
3612                 cl_and(data->start_class, and_withp);
3613             }
3614             flags &= ~SCF_DO_STCLASS;
3615         }
3616         else if (REGNODE_VARIES(OP(scan))) {
3617             I32 mincount, maxcount, minnext, deltanext, fl = 0;
3618             I32 f = flags, pos_before = 0;
3619             regnode * const oscan = scan;
3620             struct regnode_charclass_class this_class;
3621             struct regnode_charclass_class *oclass = NULL;
3622             I32 next_is_eval = 0;
3623
3624             switch (PL_regkind[OP(scan)]) {
3625             case WHILEM:                /* End of (?:...)* . */
3626                 scan = NEXTOPER(scan);
3627                 goto finish;
3628             case PLUS:
3629                 if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
3630                     next = NEXTOPER(scan);
3631                     if (OP(next) == EXACT || (flags & SCF_DO_STCLASS)) {
3632                         mincount = 1;
3633                         maxcount = REG_INFTY;
3634                         next = regnext(scan);
3635                         scan = NEXTOPER(scan);
3636                         goto do_curly;
3637                     }
3638                 }
3639                 if (flags & SCF_DO_SUBSTR)
3640                     data->pos_min++;
3641                 min++;
3642                 /* Fall through. */
3643             case STAR:
3644                 if (flags & SCF_DO_STCLASS) {
3645                     mincount = 0;
3646                     maxcount = REG_INFTY;
3647                     next = regnext(scan);
3648                     scan = NEXTOPER(scan);
3649                     goto do_curly;
3650                 }
3651                 is_inf = is_inf_internal = 1;
3652                 scan = regnext(scan);
3653                 if (flags & SCF_DO_SUBSTR) {
3654                     SCAN_COMMIT(pRExC_state, data, minlenp); /* Cannot extend fixed substrings */
3655                     data->longest = &(data->longest_float);
3656                 }
3657                 goto optimize_curly_tail;
3658             case CURLY:
3659                 if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM)
3660                     && (scan->flags == stopparen))
3661                 {
3662                     mincount = 1;
3663                     maxcount = 1;
3664                 } else {
3665                     mincount = ARG1(scan);
3666                     maxcount = ARG2(scan);
3667                 }
3668                 next = regnext(scan);
3669                 if (OP(scan) == CURLYX) {
3670                     I32 lp = (data ? *(data->last_closep) : 0);
3671                     scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);
3672                 }
3673                 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
3674                 next_is_eval = (OP(scan) == EVAL);
3675               do_curly:
3676                 if (flags & SCF_DO_SUBSTR) {
3677                     if (mincount == 0) SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot extend fixed substrings */
3678                     pos_before = data->pos_min;
3679                 }
3680                 if (data) {
3681                     fl = data->flags;
3682                     data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
3683                     if (is_inf)
3684                         data->flags |= SF_IS_INF;
3685                 }
3686                 if (flags & SCF_DO_STCLASS) {
3687                     cl_init(pRExC_state, &this_class);
3688                     oclass = data->start_class;
3689                     data->start_class = &this_class;
3690                     f |= SCF_DO_STCLASS_AND;
3691                     f &= ~SCF_DO_STCLASS_OR;
3692                 }
3693                 /* Exclude from super-linear cache processing any {n,m}
3694                    regops for which the combination of input pos and regex
3695                    pos is not enough information to determine if a match
3696                    will be possible.
3697
3698                    For example, in the regex /foo(bar\s*){4,8}baz/ with the
3699                    regex pos at the \s*, the prospects for a match depend not
3700                    only on the input position but also on how many (bar\s*)
3701                    repeats into the {4,8} we are. */
3702                if ((mincount > 1) || (maxcount > 1 && maxcount != REG_INFTY))
3703                     f &= ~SCF_WHILEM_VISITED_POS;
3704
3705                 /* This will finish on WHILEM, setting scan, or on NULL: */
3706                 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext, 
3707                                       last, data, stopparen, recursed, NULL,
3708                                       (mincount == 0
3709                                         ? (f & ~SCF_DO_SUBSTR) : f),depth+1);
3710
3711                 if (flags & SCF_DO_STCLASS)
3712                     data->start_class = oclass;
3713                 if (mincount == 0 || minnext == 0) {
3714                     if (flags & SCF_DO_STCLASS_OR) {
3715                         cl_or(pRExC_state, data->start_class, &this_class);
3716                     }
3717                     else if (flags & SCF_DO_STCLASS_AND) {
3718                         /* Switch to OR mode: cache the old value of
3719                          * data->start_class */
3720                         INIT_AND_WITHP;
3721                         StructCopy(data->start_class, and_withp,
3722                                    struct regnode_charclass_class);
3723                         flags &= ~SCF_DO_STCLASS_AND;
3724                         StructCopy(&this_class, data->start_class,
3725                                    struct regnode_charclass_class);
3726                         flags |= SCF_DO_STCLASS_OR;
3727                         data->start_class->flags |= ANYOF_EOS;
3728                     }
3729                 } else {                /* Non-zero len */
3730                     if (flags & SCF_DO_STCLASS_OR) {
3731                         cl_or(pRExC_state, data->start_class, &this_class);
3732                         cl_and(data->start_class, and_withp);
3733                     }
3734                     else if (flags & SCF_DO_STCLASS_AND)
3735                         cl_and(data->start_class, &this_class);
3736                     flags &= ~SCF_DO_STCLASS;
3737                 }
3738                 if (!scan)              /* It was not CURLYX, but CURLY. */
3739                     scan = next;
3740                 if ( /* ? quantifier ok, except for (?{ ... }) */
3741                     (next_is_eval || !(mincount == 0 && maxcount == 1))
3742                     && (minnext == 0) && (deltanext == 0)
3743                     && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
3744                     && maxcount <= REG_INFTY/3) /* Complement check for big count */
3745                 {
3746                     ckWARNreg(RExC_parse,
3747                               "Quantifier unexpected on zero-length expression");
3748                 }
3749
3750                 min += minnext * mincount;
3751                 is_inf_internal |= ((maxcount == REG_INFTY
3752                                      && (minnext + deltanext) > 0)
3753                                     || deltanext == I32_MAX);
3754                 is_inf |= is_inf_internal;
3755                 delta += (minnext + deltanext) * maxcount - minnext * mincount;
3756
3757                 /* Try powerful optimization CURLYX => CURLYN. */
3758                 if (  OP(oscan) == CURLYX && data
3759                       && data->flags & SF_IN_PAR
3760                       && !(data->flags & SF_HAS_EVAL)
3761                       && !deltanext && minnext == 1 ) {
3762                     /* Try to optimize to CURLYN.  */
3763                     regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
3764                     regnode * const nxt1 = nxt;
3765 #ifdef DEBUGGING
3766                     regnode *nxt2;
3767 #endif
3768
3769                     /* Skip open. */
3770                     nxt = regnext(nxt);
3771                     if (!REGNODE_SIMPLE(OP(nxt))
3772                         && !(PL_regkind[OP(nxt)] == EXACT
3773                              && STR_LEN(nxt) == 1))
3774                         goto nogo;
3775 #ifdef DEBUGGING
3776                     nxt2 = nxt;
3777 #endif
3778                     nxt = regnext(nxt);
3779                     if (OP(nxt) != CLOSE)
3780                         goto nogo;
3781                     if (RExC_open_parens) {
3782                         RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
3783                         RExC_close_parens[ARG(nxt1)-1]=nxt+2; /*close->while*/
3784                     }
3785                     /* Now we know that nxt2 is the only contents: */
3786                     oscan->flags = (U8)ARG(nxt);
3787                     OP(oscan) = CURLYN;
3788                     OP(nxt1) = NOTHING; /* was OPEN. */
3789
3790 #ifdef DEBUGGING
3791                     OP(nxt1 + 1) = OPTIMIZED; /* was count. */
3792                     NEXT_OFF(nxt1+ 1) = 0; /* just for consistency. */
3793                     NEXT_OFF(nxt2) = 0; /* just for consistency with CURLY. */
3794                     OP(nxt) = OPTIMIZED;        /* was CLOSE. */
3795                     OP(nxt + 1) = OPTIMIZED; /* was count. */
3796                     NEXT_OFF(nxt+ 1) = 0; /* just for consistency. */
3797 #endif
3798                 }
3799               nogo:
3800
3801                 /* Try optimization CURLYX => CURLYM. */
3802                 if (  OP(oscan) == CURLYX && data
3803                       && !(data->flags & SF_HAS_PAR)
3804                       && !(data->flags & SF_HAS_EVAL)
3805                       && !deltanext     /* atom is fixed width */
3806                       && minnext != 0   /* CURLYM can't handle zero width */
3807                 ) {
3808                     /* XXXX How to optimize if data == 0? */
3809                     /* Optimize to a simpler form.  */
3810                     regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
3811                     regnode *nxt2;
3812
3813                     OP(oscan) = CURLYM;
3814                     while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
3815                             && (OP(nxt2) != WHILEM))
3816                         nxt = nxt2;
3817                     OP(nxt2)  = SUCCEED; /* Whas WHILEM */
3818                     /* Need to optimize away parenths. */
3819                     if ((data->flags & SF_IN_PAR) && OP(nxt) == CLOSE) {
3820                         /* Set the parenth number.  */
3821                         regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
3822
3823                         oscan->flags = (U8)ARG(nxt);
3824                         if (RExC_open_parens) {
3825                             RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
3826                             RExC_close_parens[ARG(nxt1)-1]=nxt2+1; /*close->NOTHING*/
3827                         }
3828                         OP(nxt1) = OPTIMIZED;   /* was OPEN. */
3829                         OP(nxt) = OPTIMIZED;    /* was CLOSE. */
3830
3831 #ifdef DEBUGGING
3832                         OP(nxt1 + 1) = OPTIMIZED; /* was count. */
3833                         OP(nxt + 1) = OPTIMIZED; /* was count. */
3834                         NEXT_OFF(nxt1 + 1) = 0; /* just for consistency. */
3835                         NEXT_OFF(nxt + 1) = 0; /* just for consistency. */
3836 #endif
3837 #if 0
3838                         while ( nxt1 && (OP(nxt1) != WHILEM)) {
3839                             regnode *nnxt = regnext(nxt1);
3840                             if (nnxt == nxt) {
3841                                 if (reg_off_by_arg[OP(nxt1)])
3842                                     ARG_SET(nxt1, nxt2 - nxt1);
3843                                 else if (nxt2 - nxt1 < U16_MAX)
3844                                     NEXT_OFF(nxt1) = nxt2 - nxt1;
3845                                 else
3846                                     OP(nxt) = NOTHING;  /* Cannot beautify */
3847                             }
3848                             nxt1 = nnxt;
3849                         }
3850 #endif
3851                         /* Optimize again: */
3852                         study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,
3853                                     NULL, stopparen, recursed, NULL, 0,depth+1);
3854                     }
3855                     else
3856                         oscan->flags = 0;
3857                 }
3858                 else if ((OP(oscan) == CURLYX)
3859                          && (flags & SCF_WHILEM_VISITED_POS)
3860                          /* See the comment on a similar expression above.
3861                             However, this time it's not a subexpression
3862                             we care about, but the expression itself. */
3863                          && (maxcount == REG_INFTY)
3864                          && data && ++data->whilem_c < 16) {
3865                     /* This stays as CURLYX, we can put the count/of pair. */
3866                     /* Find WHILEM (as in regexec.c) */
3867                     regnode *nxt = oscan + NEXT_OFF(oscan);
3868
3869                     if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
3870                         nxt += ARG(nxt);
3871                     PREVOPER(nxt)->flags = (U8)(data->whilem_c
3872                         | (RExC_whilem_seen << 4)); /* On WHILEM */
3873                 }
3874                 if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
3875                     pars++;
3876                 if (flags & SCF_DO_SUBSTR) {
3877                     SV *last_str = NULL;
3878                     int counted = mincount != 0;
3879
3880                     if (data->last_end > 0 && mincount != 0) { /* Ends with a string. */
3881 #if defined(SPARC64_GCC_WORKAROUND)
3882                         I32 b = 0;
3883                         STRLEN l = 0;
3884                         const char *s = NULL;
3885                         I32 old = 0;
3886
3887                         if (pos_before >= data->last_start_min)
3888                             b = pos_before;
3889                         else
3890                             b = data->last_start_min;
3891
3892                         l = 0;
3893                         s = SvPV_const(data->last_found, l);
3894                         old = b - data->last_start_min;
3895
3896 #else
3897                         I32 b = pos_before >= data->last_start_min
3898                             ? pos_before : data->last_start_min;
3899                         STRLEN l;
3900                         const char * const s = SvPV_const(data->last_found, l);
3901                         I32 old = b - data->last_start_min;
3902 #endif
3903
3904                         if (UTF)
3905                             old = utf8_hop((U8*)s, old) - (U8*)s;
3906                         l -= old;
3907                         /* Get the added string: */
3908                         last_str = newSVpvn_utf8(s  + old, l, UTF);
3909                         if (deltanext == 0 && pos_before == b) {
3910                             /* What was added is a constant string */
3911                             if (mincount > 1) {
3912                                 SvGROW(last_str, (mincount * l) + 1);
3913                                 repeatcpy(SvPVX(last_str) + l,
3914                                           SvPVX_const(last_str), l, mincount - 1);
3915                                 SvCUR_set(last_str, SvCUR(last_str) * mincount);
3916                                 /* Add additional parts. */
3917                                 SvCUR_set(data->last_found,
3918                                           SvCUR(data->last_found) - l);
3919                                 sv_catsv(data->last_found, last_str);
3920                                 {
3921                                     SV * sv = data->last_found;
3922                                     MAGIC *mg =
3923                                         SvUTF8(sv) && SvMAGICAL(sv) ?
3924                                         mg_find(sv, PERL_MAGIC_utf8) : NULL;
3925                                     if (mg && mg->mg_len >= 0)
3926                                         mg->mg_len += CHR_SVLEN(last_str) - l;
3927                                 }
3928                                 data->last_end += l * (mincount - 1);
3929                             }
3930                         } else {
3931                             /* start offset must point into the last copy */
3932                             data->last_start_min += minnext * (mincount - 1);
3933                             data->last_start_max += is_inf ? I32_MAX
3934                                 : (maxcount - 1) * (minnext + data->pos_delta);
3935                         }
3936                     }
3937                     /* It is counted once already... */
3938                     data->pos_min += minnext * (mincount - counted);
3939                     data->pos_delta += - counted * deltanext +
3940                         (minnext + deltanext) * maxcount - minnext * mincount;
3941                     if (mincount != maxcount) {
3942                          /* Cannot extend fixed substrings found inside
3943                             the group.  */
3944                         SCAN_COMMIT(pRExC_state,data,minlenp);
3945                         if (mincount && last_str) {
3946                             SV * const sv = data->last_found;
3947                             MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
3948                                 mg_find(sv, PERL_MAGIC_utf8) : NULL;
3949
3950                             if (mg)
3951                                 mg->mg_len = -1;
3952                             sv_setsv(sv, last_str);
3953                             data->last_end = data->pos_min;
3954                             data->last_start_min =
3955                                 data->pos_min - CHR_SVLEN(last_str);
3956                             data->last_start_max = is_inf
3957                                 ? I32_MAX
3958                                 : data->pos_min + data->pos_delta
3959                                 - CHR_SVLEN(last_str);
3960                         }
3961                         data->longest = &(data->longest_float);
3962                     }
3963                     SvREFCNT_dec(last_str);
3964                 }
3965                 if (data && (fl & SF_HAS_EVAL))
3966                     data->flags |= SF_HAS_EVAL;
3967               optimize_curly_tail:
3968                 if (OP(oscan) != CURLYX) {
3969                     while (PL_regkind[OP(next = regnext(oscan))] == NOTHING
3970                            && NEXT_OFF(next))
3971                         NEXT_OFF(oscan) += NEXT_OFF(next);
3972                 }
3973                 continue;
3974             default:                    /* REF, ANYOFV, and CLUMP only? */
3975                 if (flags & SCF_DO_SUBSTR) {
3976                     SCAN_COMMIT(pRExC_state,data,minlenp);      /* Cannot expect anything... */
3977                     data->longest = &(data->longest_float);
3978                 }
3979                 is_inf = is_inf_internal = 1;
3980                 if (flags & SCF_DO_STCLASS_OR)
3981                     cl_anything(pRExC_state, data->start_class);
3982                 flags &= ~SCF_DO_STCLASS;
3983                 break;
3984             }
3985         }
3986         else if (OP(scan) == LNBREAK) {
3987             if (flags & SCF_DO_STCLASS) {
3988                 int value = 0;
3989                 data->start_class->flags &= ~ANYOF_EOS; /* No match on empty */
3990                 if (flags & SCF_DO_STCLASS_AND) {
3991                     for (value = 0; value < 256; value++)
3992                         if (!is_VERTWS_cp(value))
3993                             ANYOF_BITMAP_CLEAR(data->start_class, value);
3994                 }
3995                 else {
3996                     for (value = 0; value < 256; value++)
3997                         if (is_VERTWS_cp(value))
3998                             ANYOF_BITMAP_SET(data->start_class, value);
3999                 }
4000                 if (flags & SCF_DO_STCLASS_OR)
4001                     cl_and(data->start_class, and_withp);
4002                 flags &= ~SCF_DO_STCLASS;
4003             }
4004             min += 1;
4005             delta += 1;
4006             if (flags & SCF_DO_SUBSTR) {
4007                 SCAN_COMMIT(pRExC_state,data,minlenp);  /* Cannot expect anything... */
4008                 data->pos_min += 1;
4009                 data->pos_delta += 1;
4010                 data->longest = &(data->longest_float);
4011             }
4012         }
4013         else if (REGNODE_SIMPLE(OP(scan))) {
4014             int value = 0;
4015
4016             if (flags & SCF_DO_SUBSTR) {
4017                 SCAN_COMMIT(pRExC_state,data,minlenp);
4018                 data->pos_min++;
4019             }
4020             min++;
4021             if (flags & SCF_DO_STCLASS) {
4022                 data->start_class->flags &= ~ANYOF_EOS; /* No match on empty */
4023
4024                 /* Some of the logic below assumes that switching
4025                    locale on will only add false positives. */
4026                 switch (PL_regkind[OP(scan)]) {
4027                 case SANY:
4028                 default:
4029                   do_default:
4030                     /* Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d", OP(scan)); */
4031                     if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
4032                         cl_anything(pRExC_state, data->start_class);
4033                     break;
4034                 case REG_ANY:
4035                     if (OP(scan) == SANY)
4036                         goto do_default;
4037                     if (flags & SCF_DO_STCLASS_OR) { /* Everything but \n */
4038                         value = (ANYOF_BITMAP_TEST(data->start_class,'\n')
4039                                  || ANYOF_CLASS_TEST_ANY_SET(data->start_class));
4040                         cl_anything(pRExC_state, data->start_class);
4041                     }
4042                     if (flags & SCF_DO_STCLASS_AND || !value)
4043                         ANYOF_BITMAP_CLEAR(data->start_class,'\n');
4044                     break;
4045                 case ANYOF:
4046                     if (flags & SCF_DO_STCLASS_AND)
4047                         cl_and(data->start_class,
4048                                (struct regnode_charclass_class*)scan);
4049                     else
4050                         cl_or(pRExC_state, data->start_class,
4051                               (struct regnode_charclass_class*)scan);
4052                     break;
4053                 case ALNUM:
4054                     if (flags & SCF_DO_STCLASS_AND) {
4055                         if (!(data->start_class->flags & ANYOF_LOCALE)) {
4056                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
4057                             if (OP(scan) == ALNUMU) {
4058                                 for (value = 0; value < 256; value++) {
4059                                     if (!isWORDCHAR_L1(value)) {
4060                                         ANYOF_BITMAP_CLEAR(data->start_class, value);
4061                                     }
4062                                 }
4063                             } else {
4064                                 for (value = 0; value < 256; value++) {
4065                                     if (!isALNUM(value)) {
4066                                         ANYOF_BITMAP_CLEAR(data->start_class, value);
4067                                     }
4068                                 }
4069                             }
4070                         }
4071                     }
4072                     else {
4073                         if (data->start_class->flags & ANYOF_LOCALE)
4074                             ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
4075
4076                         /* Even if under locale, set the bits for non-locale
4077                          * in case it isn't a true locale-node.  This will
4078                          * create false positives if it truly is locale */
4079                         if (OP(scan) == ALNUMU) {
4080                             for (value = 0; value < 256; value++) {
4081                                 if (isWORDCHAR_L1(value)) {
4082                                     ANYOF_BITMAP_SET(data->start_class, value);
4083                                 }
4084                             }
4085                         } else {
4086                             for (value = 0; value < 256; value++) {
4087                                 if (isALNUM(value)) {
4088                                     ANYOF_BITMAP_SET(data->start_class, value);
4089                                 }
4090                             }
4091                         }
4092                     }
4093                     break;
4094                 case NALNUM:
4095                     if (flags & SCF_DO_STCLASS_AND) {
4096                         if (!(data->start_class->flags & ANYOF_LOCALE)) {
4097                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
4098                             if (OP(scan) == NALNUMU) {
4099                                 for (value = 0; value < 256; value++) {
4100                                     if (isWORDCHAR_L1(value)) {
4101                                         ANYOF_BITMAP_CLEAR(data->start_class, value);
4102                                     }
4103                                 }
4104                             } else {
4105                                 for (value = 0; value < 256; value++) {
4106                                     if (isALNUM(value)) {
4107                                         ANYOF_BITMAP_CLEAR(data->start_class, value);
4108                                     }
4109                                 }
4110                             }
4111                         }
4112                     }
4113                     else {
4114                         if (data->start_class->flags & ANYOF_LOCALE)
4115                             ANYOF_CLASS_SET(data->start_class,ANYOF_NALNUM);
4116
4117                         /* Even if under locale, set the bits for non-locale in
4118                          * case it isn't a true locale-node.  This will create
4119                          * false positives if it truly is locale */
4120                         if (OP(scan) == NALNUMU) {
4121                             for (value = 0; value < 256; value++) {
4122                                 if (! isWORDCHAR_L1(value)) {
4123                                     ANYOF_BITMAP_SET(data->start_class, value);
4124                                 }
4125                             }
4126                         } else {
4127                             for (value = 0; value < 256; value++) {
4128                                 if (! isALNUM(value)) {
4129                                     ANYOF_BITMAP_SET(data->start_class, value);
4130                                 }
4131                             }
4132                         }
4133                     }
4134                     break;
4135                 case SPACE:
4136                     if (flags & SCF_DO_STCLASS_AND) {
4137                         if (!(data->start_class->flags & ANYOF_LOCALE)) {
4138                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NSPACE);
4139                             if (OP(scan) == SPACEU) {
4140                                 for (value = 0; value < 256; value++) {
4141                                     if (!isSPACE_L1(value)) {
4142                                         ANYOF_BITMAP_CLEAR(data->start_class, value);
4143                                     }
4144                                 }
4145                             } else {
4146                                 for (value = 0; value < 256; value++) {
4147                                     if (!isSPACE(value)) {
4148                                         ANYOF_BITMAP_CLEAR(data->start_class, value);
4149                                     }
4150                                 }
4151                             }
4152                         }
4153                     }
4154                     else {
4155                         if (data->start_class->flags & ANYOF_LOCALE) {
4156                             ANYOF_CLASS_SET(data->start_class,ANYOF_SPACE);
4157                         }
4158                         if (OP(scan) == SPACEU) {
4159                             for (value = 0; value < 256; value++) {
4160                                 if (isSPACE_L1(value)) {
4161                                     ANYOF_BITMAP_SET(data->start_class, value);
4162                                 }
4163                             }
4164                         } else {
4165                             for (value = 0; value < 256; value++) {
4166                                 if (isSPACE(value)) {
4167                                     ANYOF_BITMAP_SET(data->start_class, value);
4168                                 }
4169                             }
4170                         }
4171                     }
4172                     break;
4173                 case NSPACE:
4174                     if (flags & SCF_DO_STCLASS_AND) {
4175                         if (!(data->start_class->flags & ANYOF_LOCALE)) {
4176                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_SPACE);
4177                             if (OP(scan) == NSPACEU) {
4178                                 for (value = 0; value < 256; value++) {
4179                                     if (isSPACE_L1(value)) {
4180                                         ANYOF_BITMAP_CLEAR(data->start_class, value);
4181                                     }
4182                                 }
4183                             } else {
4184                                 for (value = 0; value < 256; value++) {
4185                                     if (isSPACE(value)) {
4186                                         ANYOF_BITMAP_CLEAR(data->start_class, value);
4187                                     }
4188                                 }
4189                             }
4190                         }
4191                     }
4192                     else {
4193                         if (data->start_class->flags & ANYOF_LOCALE)
4194                             ANYOF_CLASS_SET(data->start_class,ANYOF_NSPACE);
4195                         if (OP(scan) == NSPACEU) {
4196                             for (value = 0; value < 256; value++) {
4197                                 if (!isSPACE_L1(value)) {
4198                                     ANYOF_BITMAP_SET(data->start_class, value);
4199                                 }
4200                             }
4201                         }
4202                         else {
4203                             for (value = 0; value < 256; value++) {
4204                                 if (!isSPACE(value)) {
4205                                     ANYOF_BITMAP_SET(data->start_class, value);
4206                                 }
4207                             }
4208                         }
4209                     }
4210                     break;
4211                 case DIGIT:
4212                     if (flags & SCF_DO_STCLASS_AND) {
4213                         if (!(data->start_class->flags & ANYOF_LOCALE)) {
4214                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NDIGIT);
4215                             for (value = 0; value < 256; value++)
4216                                 if (!isDIGIT(value))
4217                                     ANYOF_BITMAP_CLEAR(data->start_class, value);
4218                         }
4219                     }
4220                     else {
4221                         if (data->start_class->flags & ANYOF_LOCALE)
4222                             ANYOF_CLASS_SET(data->start_class,ANYOF_DIGIT);
4223                         for (value = 0; value < 256; value++)
4224                             if (isDIGIT(value))
4225                                 ANYOF_BITMAP_SET(data->start_class, value);
4226                     }
4227                     break;
4228                 case NDIGIT:
4229                     if (flags & SCF_DO_STCLASS_AND) {
4230                         if (!(data->start_class->flags & ANYOF_LOCALE))
4231                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_DIGIT);
4232                         for (value = 0; value < 256; value++)
4233                             if (isDIGIT(value))
4234                                 ANYOF_BITMAP_CLEAR(data->start_class, value);
4235                     }
4236                     else {
4237                         if (data->start_class->flags & ANYOF_LOCALE)
4238                             ANYOF_CLASS_SET(data->start_class,ANYOF_NDIGIT);
4239                         for (value = 0; value < 256; value++)
4240                             if (!isDIGIT(value))
4241                                 ANYOF_BITMAP_SET(data->start_class, value);
4242                     }
4243                     break;
4244                 CASE_SYNST_FNC(VERTWS);
4245                 CASE_SYNST_FNC(HORIZWS);
4246
4247                 }
4248                 if (flags & SCF_DO_STCLASS_OR)
4249                     cl_and(data->start_class, and_withp);
4250                 flags &= ~SCF_DO_STCLASS;
4251             }
4252         }
4253         else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
4254             data->flags |= (OP(scan) == MEOL
4255                             ? SF_BEFORE_MEOL
4256                             : SF_BEFORE_SEOL);
4257         }
4258         else if (  PL_regkind[OP(scan)] == BRANCHJ
4259                  /* Lookbehind, or need to calculate parens/evals/stclass: */
4260                    && (scan->flags || data || (flags & SCF_DO_STCLASS))
4261                    && (OP(scan) == IFMATCH || OP(scan) == UNLESSM)) {
4262             if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY 
4263                 || OP(scan) == UNLESSM )
4264             {
4265                 /* Negative Lookahead/lookbehind
4266                    In this case we can't do fixed string optimisation.
4267                 */
4268
4269                 I32 deltanext, minnext, fake = 0;
4270                 regnode *nscan;
4271                 struct regnode_charclass_class intrnl;
4272                 int f = 0;
4273
4274                 data_fake.flags = 0;
4275                 if (data) {
4276                     data_fake.whilem_c = data->whilem_c;
4277                     data_fake.last_closep = data->last_closep;
4278                 }
4279                 else
4280                     data_fake.last_closep = &fake;
4281                 data_fake.pos_delta = delta;
4282                 if ( flags & SCF_DO_STCLASS && !scan->flags
4283                      && OP(scan) == IFMATCH ) { /* Lookahead */
4284                     cl_init(pRExC_state, &intrnl);
4285                     data_fake.start_class = &intrnl;
4286                     f |= SCF_DO_STCLASS_AND;
4287                 }
4288                 if (flags & SCF_WHILEM_VISITED_POS)
4289                     f |= SCF_WHILEM_VISITED_POS;
4290                 next = regnext(scan);
4291                 nscan = NEXTOPER(NEXTOPER(scan));
4292                 minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext, 
4293                     last, &data_fake, stopparen, recursed, NULL, f, depth+1);
4294                 if (scan->flags) {
4295                     if (deltanext) {
4296                         FAIL("Variable length lookbehind not implemented");
4297                     }
4298                     else if (minnext > (I32)U8_MAX) {
4299                         FAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
4300                     }
4301                     scan->flags = (U8)minnext;
4302                 }
4303                 if (data) {
4304                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
4305                         pars++;
4306                     if (data_fake.flags & SF_HAS_EVAL)
4307                         data->flags |= SF_HAS_EVAL;
4308                     data->whilem_c = data_fake.whilem_c;
4309                 }
4310                 if (f & SCF_DO_STCLASS_AND) {
4311                     if (flags & SCF_DO_STCLASS_OR) {
4312                         /* OR before, AND after: ideally we would recurse with
4313                          * data_fake to get the AND applied by study of the
4314                          * remainder of the pattern, and then derecurse;
4315                          * *** HACK *** for now just treat as "no information".
4316                          * See [perl #56690].
4317                          */
4318                         cl_init(pRExC_state, data->start_class);
4319                     }  else {
4320                         /* AND before and after: combine and continue */
4321                         const int was = (data->start_class->flags & ANYOF_EOS);
4322
4323                         cl_and(data->start_class, &intrnl);
4324                         if (was)
4325                             data->start_class->flags |= ANYOF_EOS;
4326                     }
4327                 }
4328             }
4329 #if PERL_ENABLE_POSITIVE_ASSERTION_STUDY
4330             else {
4331                 /* Positive Lookahead/lookbehind
4332                    In this case we can do fixed string optimisation,
4333                    but we must be careful about it. Note in the case of
4334                    lookbehind the positions will be offset by the minimum
4335                    length of the pattern, something we won't know about
4336                    until after the recurse.
4337                 */
4338                 I32 deltanext, fake = 0;
4339                 regnode *nscan;
4340                 struct regnode_charclass_class intrnl;
4341                 int f = 0;
4342                 /* We use SAVEFREEPV so that when the full compile 
4343                     is finished perl will clean up the allocated 
4344                     minlens when it's all done. This way we don't
4345                     have to worry about freeing them when we know
4346                     they wont be used, which would be a pain.
4347                  */
4348                 I32 *minnextp;
4349                 Newx( minnextp, 1, I32 );
4350                 SAVEFREEPV(minnextp);
4351
4352                 if (data) {
4353                     StructCopy(data, &data_fake, scan_data_t);
4354                     if ((flags & SCF_DO_SUBSTR) && data->last_found) {
4355                         f |= SCF_DO_SUBSTR;
4356                         if (scan->flags) 
4357                             SCAN_COMMIT(pRExC_state, &data_fake,minlenp);
4358                         data_fake.last_found=newSVsv(data->last_found);
4359                     }
4360                 }
4361                 else
4362                     data_fake.last_closep = &fake;
4363                 data_fake.flags = 0;
4364                 data_fake.pos_delta = delta;
4365                 if (is_inf)
4366                     data_fake.flags |= SF_IS_INF;
4367                 if ( flags & SCF_DO_STCLASS && !scan->flags
4368                      && OP(scan) == IFMATCH ) { /* Lookahead */
4369                     cl_init(pRExC_state, &intrnl);
4370                     data_fake.start_class = &intrnl;
4371                     f |= SCF_DO_STCLASS_AND;
4372                 }
4373                 if (flags & SCF_WHILEM_VISITED_POS)
4374                     f |= SCF_WHILEM_VISITED_POS;
4375                 next = regnext(scan);
4376                 nscan = NEXTOPER(NEXTOPER(scan));
4377
4378                 *minnextp = study_chunk(pRExC_state, &nscan, minnextp, &deltanext, 
4379                     last, &data_fake, stopparen, recursed, NULL, f,depth+1);
4380                 if (scan->flags) {
4381                     if (deltanext) {
4382                         FAIL("Variable length lookbehind not implemented");
4383                     }
4384                     else if (*minnextp > (I32)U8_MAX) {
4385                         FAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
4386                     }
4387                     scan->flags = (U8)*minnextp;
4388                 }
4389
4390                 *minnextp += min;
4391
4392                 if (f & SCF_DO_STCLASS_AND) {
4393                     const int was = (data->start_class->flags & ANYOF_EOS);
4394
4395                     cl_and(data->start_class, &intrnl);
4396                     if (was)
4397                         data->start_class->flags |= ANYOF_EOS;
4398                 }
4399                 if (data) {
4400                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
4401                         pars++;
4402                     if (data_fake.flags & SF_HAS_EVAL)
4403                         data->flags |= SF_HAS_EVAL;
4404                     data->whilem_c = data_fake.whilem_c;
4405                     if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) {
4406                         if (RExC_rx->minlen<*minnextp)
4407                             RExC_rx->minlen=*minnextp;
4408                         SCAN_COMMIT(pRExC_state, &data_fake, minnextp);
4409                         SvREFCNT_dec(data_fake.last_found);
4410                         
4411                         if ( data_fake.minlen_fixed != minlenp ) 
4412                         {
4413                             data->offset_fixed= data_fake.offset_fixed;
4414                             data->minlen_fixed= data_fake.minlen_fixed;
4415                             data->lookbehind_fixed+= scan->flags;
4416                         }
4417                         if ( data_fake.minlen_float != minlenp )
4418                         {
4419                             data->minlen_float= data_fake.minlen_float;
4420                             data->offset_float_min=data_fake.offset_float_min;
4421                             data->offset_float_max=data_fake.offset_float_max;
4422                             data->lookbehind_float+= scan->flags;
4423                         }
4424                     }
4425                 }
4426
4427
4428             }
4429 #endif
4430         }
4431         else if (OP(scan) == OPEN) {
4432             if (stopparen != (I32)ARG(scan))
4433                 pars++;
4434         }
4435         else if (OP(scan) == CLOSE) {
4436             if (stopparen == (I32)ARG(scan)) {
4437                 break;
4438             }
4439             if ((I32)ARG(scan) == is_par) {
4440                 next = regnext(scan);
4441
4442                 if ( next && (OP(next) != WHILEM) && next < last)
4443                     is_par = 0;         /* Disable optimization */
4444             }
4445             if (data)
4446                 *(data->last_closep) = ARG(scan);
4447         }
4448         else if (OP(scan) == EVAL) {
4449                 if (data)
4450                     data->flags |= SF_HAS_EVAL;
4451         }
4452         else if ( PL_regkind[OP(scan)] == ENDLIKE ) {
4453             if (flags & SCF_DO_SUBSTR) {
4454                 SCAN_COMMIT(pRExC_state,data,minlenp);
4455                 flags &= ~SCF_DO_SUBSTR;
4456             }
4457             if (data && OP(scan)==ACCEPT) {
4458                 data->flags |= SCF_SEEN_ACCEPT;
4459                 if (stopmin > min)
4460                     stopmin = min;
4461             }
4462         }
4463         else if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */
4464         {
4465                 if (flags & SCF_DO_SUBSTR) {
4466                     SCAN_COMMIT(pRExC_state,data,minlenp);
4467                     data->longest = &(data->longest_float);
4468                 }
4469                 is_inf = is_inf_internal = 1;
4470                 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
4471                     cl_anything(pRExC_state, data->start_class);
4472                 flags &= ~SCF_DO_STCLASS;
4473         }
4474         else if (OP(scan) == GPOS) {
4475             if (!(RExC_rx->extflags & RXf_GPOS_FLOAT) &&
4476                 !(delta || is_inf || (data && data->pos_delta))) 
4477             {
4478                 if (!(RExC_rx->extflags & RXf_ANCH) && (flags & SCF_DO_SUBSTR))
4479                     RExC_rx->extflags |= RXf_ANCH_GPOS;
4480                 if (RExC_rx->gofs < (U32)min)
4481                     RExC_rx->gofs = min;
4482             } else {
4483                 RExC_rx->extflags |= RXf_GPOS_FLOAT;
4484                 RExC_rx->gofs = 0;
4485             }       
4486         }
4487 #ifdef TRIE_STUDY_OPT
4488 #ifdef FULL_TRIE_STUDY
4489         else if (PL_regkind[OP(scan)] == TRIE) {
4490             /* NOTE - There is similar code to this block above for handling
4491                BRANCH nodes on the initial study.  If you change stuff here
4492                check there too. */
4493             regnode *trie_node= scan;
4494             regnode *tail= regnext(scan);
4495             reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
4496             I32 max1 = 0, min1 = I32_MAX;
4497             struct regnode_charclass_class accum;
4498
4499             if (flags & SCF_DO_SUBSTR) /* XXXX Add !SUSPEND? */
4500                 SCAN_COMMIT(pRExC_state, data,minlenp); /* Cannot merge strings after this. */
4501             if (flags & SCF_DO_STCLASS)
4502                 cl_init_zero(pRExC_state, &accum);
4503                 
4504             if (!trie->jump) {
4505                 min1= trie->minlen;
4506                 max1= trie->maxlen;
4507             } else {
4508                 const regnode *nextbranch= NULL;
4509                 U32 word;
4510                 
4511                 for ( word=1 ; word <= trie->wordcount ; word++) 
4512                 {
4513                     I32 deltanext=0, minnext=0, f = 0, fake;
4514                     struct regnode_charclass_class this_class;
4515                     
4516                     data_fake.flags = 0;
4517                     if (data) {
4518                         data_fake.whilem_c = data->whilem_c;
4519                         data_fake.last_closep = data->last_closep;
4520                     }
4521                     else
4522                         data_fake.last_closep = &fake;
4523                     data_fake.pos_delta = delta;
4524                     if (flags & SCF_DO_STCLASS) {
4525                         cl_init(pRExC_state, &this_class);
4526                         data_fake.start_class = &this_class;
4527                         f = SCF_DO_STCLASS_AND;
4528                     }
4529                     if (flags & SCF_WHILEM_VISITED_POS)
4530                         f |= SCF_WHILEM_VISITED_POS;
4531     
4532                     if (trie->jump[word]) {
4533                         if (!nextbranch)
4534                             nextbranch = trie_node + trie->jump[0];
4535                         scan= trie_node + trie->jump[word];
4536                         /* We go from the jump point to the branch that follows
4537                            it. Note this means we need the vestigal unused branches
4538                            even though they arent otherwise used.
4539                          */
4540                         minnext = study_chunk(pRExC_state, &scan, minlenp, 
4541                             &deltanext, (regnode *)nextbranch, &data_fake, 
4542                             stopparen, recursed, NULL, f,depth+1);
4543                     }
4544                     if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
4545                         nextbranch= regnext((regnode*)nextbranch);
4546                     
4547                     if (min1 > (I32)(minnext + trie->minlen))
4548                         min1 = minnext + trie->minlen;
4549                     if (max1 < (I32)(minnext + deltanext + trie->maxlen))
4550                         max1 = minnext + deltanext + trie->maxlen;
4551                     if (deltanext == I32_MAX)
4552                         is_inf = is_inf_internal = 1;
4553                     
4554                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
4555                         pars++;
4556                     if (data_fake.flags & SCF_SEEN_ACCEPT) {
4557                         if ( stopmin > min + min1) 
4558                             stopmin = min + min1;
4559                         flags &= ~SCF_DO_SUBSTR;
4560                         if (data)
4561                             data->flags |= SCF_SEEN_ACCEPT;
4562                     }
4563                     if (data) {
4564                         if (data_fake.flags & SF_HAS_EVAL)
4565                             data->flags |= SF_HAS_EVAL;
4566                         data->whilem_c = data_fake.whilem_c;
4567                     }
4568                     if (flags & SCF_DO_STCLASS)
4569                         cl_or(pRExC_state, &accum, &this_class);
4570                 }
4571             }
4572             if (flags & SCF_DO_SUBSTR) {
4573                 data->pos_min += min1;
4574                 data->pos_delta += max1 - min1;
4575                 if (max1 != min1 || is_inf)
4576                     data->longest = &(data->longest_float);
4577             }
4578             min += min1;
4579             delta += max1 - min1;
4580             if (flags & SCF_DO_STCLASS_OR) {
4581                 cl_or(pRExC_state, data->start_class, &accum);
4582                 if (min1) {
4583                     cl_and(data->start_class, and_withp);
4584                     flags &= ~SCF_DO_STCLASS;
4585                 }
4586             }
4587             else if (flags & SCF_DO_STCLASS_AND) {
4588                 if (min1) {
4589                     cl_and(data->start_class, &accum);
4590                     flags &= ~SCF_DO_STCLASS;
4591                 }
4592                 else {
4593                     /* Switch to OR mode: cache the old value of
4594                      * data->start_class */
4595                     INIT_AND_WITHP;
4596                     StructCopy(data->start_class, and_withp,
4597                                struct regnode_charclass_class);
4598                     flags &= ~SCF_DO_STCLASS_AND;
4599                     StructCopy(&accum, data->start_class,
4600                                struct regnode_charclass_class);
4601                     flags |= SCF_DO_STCLASS_OR;
4602                     data->start_class->flags |= ANYOF_EOS;
4603                 }
4604             }
4605             scan= tail;
4606             continue;
4607         }
4608 #else
4609         else if (PL_regkind[OP(scan)] == TRIE) {
4610             reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
4611             U8*bang=NULL;
4612             
4613             min += trie->minlen;
4614             delta += (trie->maxlen - trie->minlen);
4615             flags &= ~SCF_DO_STCLASS; /* xxx */
4616             if (flags & SCF_DO_SUBSTR) {
4617                 SCAN_COMMIT(pRExC_state,data,minlenp);  /* Cannot expect anything... */
4618                 data->pos_min += trie->minlen;
4619                 data->pos_delta += (trie->maxlen - trie->minlen);
4620                 if (trie->maxlen != trie->minlen)
4621                     data->longest = &(data->longest_float);
4622             }
4623             if (trie->jump) /* no more substrings -- for now /grr*/
4624                 flags &= ~SCF_DO_SUBSTR; 
4625         }
4626 #endif /* old or new */
4627 #endif /* TRIE_STUDY_OPT */
4628
4629         /* Else: zero-length, ignore. */
4630         scan = regnext(scan);
4631     }
4632     if (frame) {
4633         last = frame->last;
4634         scan = frame->next;
4635         stopparen = frame->stop;
4636         frame = frame->prev;
4637         goto fake_study_recurse;
4638     }
4639
4640   finish:
4641     assert(!frame);
4642     DEBUG_STUDYDATA("pre-fin:",data,depth);
4643
4644     *scanp = scan;
4645     *deltap = is_inf_internal ? I32_MAX : delta;
4646     if (flags & SCF_DO_SUBSTR && is_inf)
4647         data->pos_delta = I32_MAX - data->pos_min;
4648     if (is_par > (I32)U8_MAX)
4649         is_par = 0;
4650     if (is_par && pars==1 && data) {
4651         data->flags |= SF_IN_PAR;
4652         data->flags &= ~SF_HAS_PAR;
4653     }
4654     else if (pars && data) {
4655         data->flags |= SF_HAS_PAR;
4656         data->flags &= ~SF_IN_PAR;
4657     }
4658     if (flags & SCF_DO_STCLASS_OR)
4659         cl_and(data->start_class, and_withp);
4660     if (flags & SCF_TRIE_RESTUDY)
4661         data->flags |=  SCF_TRIE_RESTUDY;
4662     
4663     DEBUG_STUDYDATA("post-fin:",data,depth);
4664     
4665     return min < stopmin ? min : stopmin;
4666 }
4667
4668 STATIC U32
4669 S_add_data(RExC_state_t *pRExC_state, U32 n, const char *s)
4670 {
4671     U32 count = RExC_rxi->data ? RExC_rxi->data->count : 0;
4672
4673     PERL_ARGS_ASSERT_ADD_DATA;
4674
4675     Renewc(RExC_rxi->data,
4676            sizeof(*RExC_rxi->data) + sizeof(void*) * (count + n - 1),
4677            char, struct reg_data);
4678     if(count)
4679         Renew(RExC_rxi->data->what, count + n, U8);
4680     else
4681         Newx(RExC_rxi->data->what, n, U8);
4682     RExC_rxi->data->count = count + n;
4683     Copy(s, RExC_rxi->data->what + count, n, U8);
4684     return count;
4685 }
4686
4687 /*XXX: todo make this not included in a non debugging perl */
4688 #ifndef PERL_IN_XSUB_RE
4689 void
4690 Perl_reginitcolors(pTHX)
4691 {
4692     dVAR;
4693     const char * const s = PerlEnv_getenv("PERL_RE_COLORS");
4694     if (s) {
4695         char *t = savepv(s);
4696         int i = 0;
4697         PL_colors[0] = t;
4698         while (++i < 6) {
4699             t = strchr(t, '\t');
4700             if (t) {
4701                 *t = '\0';
4702                 PL_colors[i] = ++t;
4703             }
4704             else
4705                 PL_colors[i] = t = (char *)"";
4706         }
4707     } else {
4708         int i = 0;
4709         while (i < 6)
4710             PL_colors[i++] = (char *)"";
4711     }
4712     PL_colorset = 1;
4713 }
4714 #endif
4715
4716
4717 #ifdef TRIE_STUDY_OPT
4718 #define CHECK_RESTUDY_GOTO                                  \
4719         if (                                                \
4720               (data.flags & SCF_TRIE_RESTUDY)               \
4721               && ! restudied++                              \
4722         )     goto reStudy
4723 #else
4724 #define CHECK_RESTUDY_GOTO
4725 #endif        
4726
4727 /*
4728  - pregcomp - compile a regular expression into internal code
4729  *
4730  * We can't allocate space until we know how big the compiled form will be,
4731  * but we can't compile it (and thus know how big it is) until we've got a
4732  * place to put the code.  So we cheat:  we compile it twice, once with code
4733  * generation turned off and size counting turned on, and once "for real".
4734  * This also means that we don't allocate space until we are sure that the
4735  * thing really will compile successfully, and we never have to move the
4736  * code and thus invalidate pointers into it.  (Note that it has to be in
4737  * one piece because free() must be able to free it all.) [NB: not true in perl]
4738  *
4739  * Beware that the optimization-preparation code in here knows about some
4740  * of the structure of the compiled regexp.  [I'll say.]
4741  */
4742
4743
4744
4745 #ifndef PERL_IN_XSUB_RE
4746 #define RE_ENGINE_PTR &PL_core_reg_engine
4747 #else
4748 extern const struct regexp_engine my_reg_engine;
4749 #define RE_ENGINE_PTR &my_reg_engine
4750 #endif
4751
4752 #ifndef PERL_IN_XSUB_RE 
4753 REGEXP *
4754 Perl_pregcomp(pTHX_ SV * const pattern, const U32 flags)
4755 {
4756     dVAR;
4757     HV * const table = GvHV(PL_hintgv);
4758
4759     PERL_ARGS_ASSERT_PREGCOMP;
4760
4761     /* Dispatch a request to compile a regexp to correct 
4762        regexp engine. */
4763     if (table) {
4764         SV **ptr= hv_fetchs(table, "regcomp", FALSE);
4765         GET_RE_DEBUG_FLAGS_DECL;
4766         if (ptr && SvIOK(*ptr) && SvIV(*ptr)) {
4767             const regexp_engine *eng=INT2PTR(regexp_engine*,SvIV(*ptr));
4768             DEBUG_COMPILE_r({
4769                 PerlIO_printf(Perl_debug_log, "Using engine %"UVxf"\n",
4770                     SvIV(*ptr));
4771             });            
4772             return CALLREGCOMP_ENG(eng, pattern, flags);
4773         } 
4774     }
4775     return Perl_re_compile(aTHX_ pattern, flags);
4776 }
4777 #endif
4778
4779 REGEXP *
4780 Perl_re_compile(pTHX_ SV * const pattern, U32 orig_pm_flags)
4781 {
4782     dVAR;
4783     REGEXP *rx;
4784     struct regexp *r;
4785     register regexp_internal *ri;
4786     STRLEN plen;
4787     char* VOL exp;
4788     char* xend;
4789     regnode *scan;
4790     I32 flags;
4791     I32 minlen = 0;
4792     U32 pm_flags;
4793
4794     /* these are all flags - maybe they should be turned
4795      * into a single int with different bit masks */
4796     I32 sawlookahead = 0;
4797     I32 sawplus = 0;
4798     I32 sawopen = 0;
4799     bool used_setjump = FALSE;
4800     regex_charset initial_charset = get_regex_charset(orig_pm_flags);
4801
4802     U8 jump_ret = 0;
4803     dJMPENV;
4804     scan_data_t data;
4805     RExC_state_t RExC_state;
4806     RExC_state_t * const pRExC_state = &RExC_state;
4807 #ifdef TRIE_STUDY_OPT    
4808     int restudied;
4809     RExC_state_t copyRExC_state;
4810 #endif    
4811     GET_RE_DEBUG_FLAGS_DECL;
4812
4813     PERL_ARGS_ASSERT_RE_COMPILE;
4814
4815     DEBUG_r(if (!PL_colorset) reginitcolors());
4816
4817     exp = SvPV(pattern, plen);
4818
4819     if (plen == 0) { /* ignore the utf8ness if the pattern is 0 length */
4820         RExC_utf8 = RExC_orig_utf8 = 0;
4821     }
4822     else {
4823         RExC_utf8 = RExC_orig_utf8 = SvUTF8(pattern);
4824     }
4825     RExC_uni_semantics = 0;
4826     RExC_contains_locale = 0;
4827
4828     /****************** LONG JUMP TARGET HERE***********************/
4829     /* Longjmp back to here if have to switch in midstream to utf8 */
4830     if (! RExC_orig_utf8) {
4831         JMPENV_PUSH(jump_ret);
4832         used_setjump = TRUE;
4833     }
4834
4835     if (jump_ret == 0) {    /* First time through */
4836         xend = exp + plen;
4837
4838         DEBUG_COMPILE_r({
4839             SV *dsv= sv_newmortal();
4840             RE_PV_QUOTED_DECL(s, RExC_utf8,
4841                 dsv, exp, plen, 60);
4842             PerlIO_printf(Perl_debug_log, "%sCompiling REx%s %s\n",
4843                            PL_colors[4],PL_colors[5],s);
4844         });
4845     }
4846     else {  /* longjumped back */
4847         STRLEN len = plen;
4848
4849         /* If the cause for the longjmp was other than changing to utf8, pop
4850          * our own setjmp, and longjmp to the correct handler */
4851         if (jump_ret != UTF8_LONGJMP) {
4852             JMPENV_POP;
4853             JMPENV_JUMP(jump_ret);
4854         }
4855
4856         GET_RE_DEBUG_FLAGS;
4857
4858         /* It's possible to write a regexp in ascii that represents Unicode
4859         codepoints outside of the byte range, such as via \x{100}. If we
4860         detect such a sequence we have to convert the entire pattern to utf8
4861         and then recompile, as our sizing calculation will have been based
4862         on 1 byte == 1 character, but we will need to use utf8 to encode
4863         at least some part of the pattern, and therefore must convert the whole
4864         thing.
4865         -- dmq */
4866         DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log,
4867             "UTF8 mismatch! Converting to utf8 for resizing and compile\n"));
4868         exp = (char*)Perl_bytes_to_utf8(aTHX_
4869                                         (U8*)SvPV_nomg(pattern, plen),
4870                                         &len);
4871         xend = exp + len;
4872         RExC_orig_utf8 = RExC_utf8 = 1;
4873         SAVEFREEPV(exp);
4874     }
4875
4876 #ifdef TRIE_STUDY_OPT
4877     restudied = 0;
4878 #endif
4879
4880     pm_flags = orig_pm_flags;
4881
4882     if (initial_charset == REGEX_LOCALE_CHARSET) {
4883         RExC_contains_locale = 1;
4884     }
4885     else if (RExC_utf8 && initial_charset == REGEX_DEPENDS_CHARSET) {
4886
4887         /* Set to use unicode semantics if the pattern is in utf8 and has the
4888          * 'depends' charset specified, as it means unicode when utf8  */
4889         set_regex_charset(&pm_flags, REGEX_UNICODE_CHARSET);
4890     }
4891
4892     RExC_precomp = exp;
4893     RExC_flags = pm_flags;
4894     RExC_sawback = 0;
4895
4896     RExC_seen = 0;
4897     RExC_in_lookbehind = 0;
4898     RExC_seen_zerolen = *exp == '^' ? -1 : 0;
4899     RExC_seen_evals = 0;
4900     RExC_extralen = 0;
4901     RExC_override_recoding = 0;
4902
4903     /* First pass: determine size, legality. */
4904     RExC_parse = exp;
4905     RExC_start = exp;
4906     RExC_end = xend;
4907     RExC_naughty = 0;
4908     RExC_npar = 1;
4909     RExC_nestroot = 0;
4910     RExC_size = 0L;
4911     RExC_emit = &PL_regdummy;
4912     RExC_whilem_seen = 0;
4913     RExC_open_parens = NULL;
4914     RExC_close_parens = NULL;
4915     RExC_opend = NULL;
4916     RExC_paren_names = NULL;
4917 #ifdef DEBUGGING
4918     RExC_paren_name_list = NULL;
4919 #endif
4920     RExC_recurse = NULL;
4921     RExC_recurse_count = 0;
4922
4923 #if 0 /* REGC() is (currently) a NOP at the first pass.
4924        * Clever compilers notice this and complain. --jhi */
4925     REGC((U8)REG_MAGIC, (char*)RExC_emit);
4926 #endif
4927     DEBUG_PARSE_r(
4928         PerlIO_printf(Perl_debug_log, "Starting first pass (sizing)\n");
4929         RExC_lastnum=0;
4930         RExC_lastparse=NULL;
4931     );
4932     if (reg(pRExC_state, 0, &flags,1) == NULL) {
4933         RExC_precomp = NULL;
4934         return(NULL);
4935     }
4936
4937     /* Here, finished first pass.  Get rid of any added setjmp */
4938     if (used_setjump) {
4939         JMPENV_POP;
4940     }
4941
4942     DEBUG_PARSE_r({
4943         PerlIO_printf(Perl_debug_log, 
4944             "Required size %"IVdf" nodes\n"
4945             "Starting second pass (creation)\n", 
4946             (IV)RExC_size);
4947         RExC_lastnum=0; 
4948         RExC_lastparse=NULL; 
4949     });
4950
4951     /* The first pass could have found things that force Unicode semantics */
4952     if ((RExC_utf8 || RExC_uni_semantics)
4953          && get_regex_charset(pm_flags) == REGEX_DEPENDS_CHARSET)
4954     {
4955         set_regex_charset(&pm_flags, REGEX_UNICODE_CHARSET);
4956     }
4957
4958     /* Small enough for pointer-storage convention?
4959        If extralen==0, this means that we will not need long jumps. */
4960     if (RExC_size >= 0x10000L && RExC_extralen)
4961         RExC_size += RExC_extralen;
4962     else
4963         RExC_extralen = 0;
4964     if (RExC_whilem_seen > 15)
4965         RExC_whilem_seen = 15;
4966
4967     /* Allocate space and zero-initialize. Note, the two step process 
4968        of zeroing when in debug mode, thus anything assigned has to 
4969        happen after that */
4970     rx = (REGEXP*) newSV_type(SVt_REGEXP);
4971     r = (struct regexp*)SvANY(rx);
4972     Newxc(ri, sizeof(regexp_internal) + (unsigned)RExC_size * sizeof(regnode),
4973          char, regexp_internal);
4974     if ( r == NULL || ri == NULL )
4975         FAIL("Regexp out of space");
4976 #ifdef DEBUGGING
4977     /* avoid reading uninitialized memory in DEBUGGING code in study_chunk() */
4978     Zero(ri, sizeof(regexp_internal) + (unsigned)RExC_size * sizeof(regnode), char);
4979 #else 
4980     /* bulk initialize base fields with 0. */
4981     Zero(ri, sizeof(regexp_internal), char);        
4982 #endif
4983
4984     /* non-zero initialization begins here */
4985     RXi_SET( r, ri );
4986     r->engine= RE_ENGINE_PTR;
4987     r->extflags = pm_flags;
4988     {
4989         bool has_p     = ((r->extflags & RXf_PMf_KEEPCOPY) == RXf_PMf_KEEPCOPY);
4990         bool has_charset = (get_regex_charset(r->extflags) != REGEX_DEPENDS_CHARSET);
4991
4992         /* The caret is output if there are any defaults: if not all the STD
4993          * flags are set, or if no character set specifier is needed */
4994         bool has_default =
4995                     (((r->extflags & RXf_PMf_STD_PMMOD) != RXf_PMf_STD_PMMOD)
4996                     || ! has_charset);
4997         bool has_runon = ((RExC_seen & REG_SEEN_RUN_ON_COMMENT)==REG_SEEN_RUN_ON_COMMENT);
4998         U16 reganch = (U16)((r->extflags & RXf_PMf_STD_PMMOD)
4999                             >> RXf_PMf_STD_PMMOD_SHIFT);
5000         const char *fptr = STD_PAT_MODS;        /*"msix"*/
5001         char *p;
5002         /* Allocate for the worst case, which is all the std flags are turned
5003          * on.  If more precision is desired, we could do a population count of
5004          * the flags set.  This could be done with a small lookup table, or by
5005          * shifting, masking and adding, or even, when available, assembly
5006          * language for a machine-language population count.
5007          * We never output a minus, as all those are defaults, so are
5008          * covered by the caret */
5009         const STRLEN wraplen = plen + has_p + has_runon
5010             + has_default       /* If needs a caret */
5011
5012                 /* If needs a character set specifier */
5013             + ((has_charset) ? MAX_CHARSET_NAME_LENGTH : 0)
5014             + (sizeof(STD_PAT_MODS) - 1)
5015             + (sizeof("(?:)") - 1);
5016
5017         p = sv_grow(MUTABLE_SV(rx), wraplen + 1); /* +1 for the ending NUL */
5018         SvPOK_on(rx);
5019         SvFLAGS(rx) |= SvUTF8(pattern);
5020         *p++='('; *p++='?';
5021
5022         /* If a default, cover it using the caret */
5023         if (has_default) {
5024             *p++= DEFAULT_PAT_MOD;
5025         }
5026         if (has_charset) {
5027             STRLEN len;
5028             const char* const name = get_regex_charset_name(r->extflags, &len);
5029             Copy(name, p, len, char);
5030             p += len;
5031         }
5032         if (has_p)
5033             *p++ = KEEPCOPY_PAT_MOD; /*'p'*/
5034         {
5035             char ch;
5036             while((ch = *fptr++)) {
5037                 if(reganch & 1)
5038                     *p++ = ch;
5039                 reganch >>= 1;
5040             }
5041         }
5042
5043         *p++ = ':';
5044         Copy(RExC_precomp, p, plen, char);
5045         assert ((RX_WRAPPED(rx) - p) < 16);
5046         r->pre_prefix = p - RX_WRAPPED(rx);
5047         p += plen;
5048         if (has_runon)
5049             *p++ = '\n';
5050         *p++ = ')';
5051         *p = 0;
5052         SvCUR_set(rx, p - SvPVX_const(rx));
5053     }
5054
5055     r->intflags = 0;
5056     r->nparens = RExC_npar - 1; /* set early to validate backrefs */
5057     
5058     if (RExC_seen & REG_SEEN_RECURSE) {
5059         Newxz(RExC_open_parens, RExC_npar,regnode *);
5060         SAVEFREEPV(RExC_open_parens);
5061         Newxz(RExC_close_parens,RExC_npar,regnode *);
5062         SAVEFREEPV(RExC_close_parens);
5063     }
5064
5065     /* Useful during FAIL. */
5066 #ifdef RE_TRACK_PATTERN_OFFSETS
5067     Newxz(ri->u.offsets, 2*RExC_size+1, U32); /* MJD 20001228 */
5068     DEBUG_OFFSETS_r(PerlIO_printf(Perl_debug_log,
5069                           "%s %"UVuf" bytes for offset annotations.\n",
5070                           ri->u.offsets ? "Got" : "Couldn't get",
5071                           (UV)((2*RExC_size+1) * sizeof(U32))));
5072 #endif
5073     SetProgLen(ri,RExC_size);
5074     RExC_rx_sv = rx;
5075     RExC_rx = r;
5076     RExC_rxi = ri;
5077     REH_CALL_COMP_BEGIN_HOOK(pRExC_state->rx);
5078
5079     /* Second pass: emit code. */
5080     RExC_flags = pm_flags;      /* don't let top level (?i) bleed */
5081     RExC_parse = exp;
5082     RExC_end = xend;
5083     RExC_naughty = 0;
5084     RExC_npar = 1;
5085     RExC_emit_start = ri->program;
5086     RExC_emit = ri->program;
5087     RExC_emit_bound = ri->program + RExC_size + 1;
5088
5089     /* Store the count of eval-groups for security checks: */
5090     RExC_rx->seen_evals = RExC_seen_evals;
5091     REGC((U8)REG_MAGIC, (char*) RExC_emit++);
5092     if (reg(pRExC_state, 0, &flags,1) == NULL) {
5093         ReREFCNT_dec(rx);   
5094         return(NULL);
5095     }
5096     /* XXXX To minimize changes to RE engine we always allocate
5097        3-units-long substrs field. */
5098     Newx(r->substrs, 1, struct reg_substr_data);
5099     if (RExC_recurse_count) {
5100         Newxz(RExC_recurse,RExC_recurse_count,regnode *);
5101         SAVEFREEPV(RExC_recurse);
5102     }
5103
5104 reStudy:
5105     r->minlen = minlen = sawlookahead = sawplus = sawopen = 0;
5106     Zero(r->substrs, 1, struct reg_substr_data);
5107
5108 #ifdef TRIE_STUDY_OPT
5109     if (!restudied) {
5110         StructCopy(&zero_scan_data, &data, scan_data_t);
5111         copyRExC_state = RExC_state;
5112     } else {
5113         U32 seen=RExC_seen;
5114         DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log,"Restudying\n"));
5115         
5116         RExC_state = copyRExC_state;
5117         if (seen & REG_TOP_LEVEL_BRANCHES) 
5118             RExC_seen |= REG_TOP_LEVEL_BRANCHES;
5119         else
5120             RExC_seen &= ~REG_TOP_LEVEL_BRANCHES;
5121         if (data.last_found) {
5122             SvREFCNT_dec(data.longest_fixed);
5123             SvREFCNT_dec(data.longest_float);
5124             SvREFCNT_dec(data.last_found);
5125         }
5126         StructCopy(&zero_scan_data, &data, scan_data_t);
5127     }
5128 #else
5129     StructCopy(&zero_scan_data, &data, scan_data_t);
5130 #endif    
5131
5132     /* Dig out information for optimizations. */
5133     r->extflags = RExC_flags; /* was pm_op */
5134     /*dmq: removed as part of de-PMOP: pm->op_pmflags = RExC_flags; */
5135  
5136     if (UTF)
5137         SvUTF8_on(rx);  /* Unicode in it? */
5138     ri->regstclass = NULL;
5139     if (RExC_naughty >= 10)     /* Probably an expensive pattern. */
5140         r->intflags |= PREGf_NAUGHTY;
5141     scan = ri->program + 1;             /* First BRANCH. */
5142
5143     /* testing for BRANCH here tells us whether there is "must appear"
5144        data in the pattern. If there is then we can use it for optimisations */
5145     if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES)) { /*  Only one top-level choice. */
5146         I32 fake;
5147         STRLEN longest_float_length, longest_fixed_length;
5148         struct regnode_charclass_class ch_class; /* pointed to by data */
5149         int stclass_flag;
5150         I32 last_close = 0; /* pointed to by data */
5151         regnode *first= scan;
5152         regnode *first_next= regnext(first);
5153         /*
5154          * Skip introductions and multiplicators >= 1
5155          * so that we can extract the 'meat' of the pattern that must 
5156          * match in the large if() sequence following.
5157          * NOTE that EXACT is NOT covered here, as it is normally
5158          * picked up by the optimiser separately. 
5159          *
5160          * This is unfortunate as the optimiser isnt handling lookahead
5161          * properly currently.
5162          *
5163          */
5164         while ((OP(first) == OPEN && (sawopen = 1)) ||
5165                /* An OR of *one* alternative - should not happen now. */
5166             (OP(first) == BRANCH && OP(first_next) != BRANCH) ||
5167             /* for now we can't handle lookbehind IFMATCH*/
5168             (OP(first) == IFMATCH && !first->flags && (sawlookahead = 1)) ||
5169             (OP(first) == PLUS) ||
5170             (OP(first) == MINMOD) ||
5171                /* An {n,m} with n>0 */
5172             (PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) ||
5173             (OP(first) == NOTHING && PL_regkind[OP(first_next)] != END ))
5174         {
5175                 /* 
5176                  * the only op that could be a regnode is PLUS, all the rest
5177                  * will be regnode_1 or regnode_2.
5178                  *
5179                  */
5180                 if (OP(first) == PLUS)
5181                     sawplus = 1;
5182                 else
5183                     first += regarglen[OP(first)];
5184
5185                 first = NEXTOPER(first);
5186                 first_next= regnext(first);
5187         }
5188
5189         /* Starting-point info. */
5190       again:
5191         DEBUG_PEEP("first:",first,0);
5192         /* Ignore EXACT as we deal with it later. */
5193         if (PL_regkind[OP(first)] == EXACT) {
5194             if (OP(first) == EXACT)
5195                 NOOP;   /* Empty, get anchored substr later. */
5196             else
5197                 ri->regstclass = first;
5198         }
5199 #ifdef TRIE_STCLASS
5200         else if (PL_regkind[OP(first)] == TRIE &&
5201                 ((reg_trie_data *)ri->data->data[ ARG(first) ])->minlen>0) 
5202         {
5203             regnode *trie_op;
5204             /* this can happen only on restudy */
5205             if ( OP(first) == TRIE ) {
5206                 struct regnode_1 *trieop = (struct regnode_1 *)
5207                     PerlMemShared_calloc(1, sizeof(struct regnode_1));
5208                 StructCopy(first,trieop,struct regnode_1);
5209                 trie_op=(regnode *)trieop;
5210             } else {
5211                 struct regnode_charclass *trieop = (struct regnode_charclass *)
5212                     PerlMemShared_calloc(1, sizeof(struct regnode_charclass));
5213                 StructCopy(first,trieop,struct regnode_charclass);
5214                 trie_op=(regnode *)trieop;
5215             }
5216             OP(trie_op)+=2;
5217             make_trie_failtable(pRExC_state, (regnode *)first, trie_op, 0);
5218             ri->regstclass = trie_op;
5219         }
5220 #endif
5221         else if (REGNODE_SIMPLE(OP(first)))
5222             ri->regstclass = first;
5223         else if (PL_regkind[OP(first)] == BOUND ||
5224                  PL_regkind[OP(first)] == NBOUND)
5225             ri->regstclass = first;
5226         else if (PL_regkind[OP(first)] == BOL) {
5227             r->extflags |= (OP(first) == MBOL
5228                            ? RXf_ANCH_MBOL
5229                            : (OP(first) == SBOL
5230                               ? RXf_ANCH_SBOL
5231                               : RXf_ANCH_BOL));
5232             first = NEXTOPER(first);
5233             goto again;
5234         }
5235         else if (OP(first) == GPOS) {
5236             r->extflags |= RXf_ANCH_GPOS;
5237             first = NEXTOPER(first);
5238             goto again;
5239         }
5240         else if ((!sawopen || !RExC_sawback) &&
5241             (OP(first) == STAR &&
5242             PL_regkind[OP(NEXTOPER(first))] == REG_ANY) &&
5243             !(r->extflags & RXf_ANCH) && !(RExC_seen & REG_SEEN_EVAL))
5244         {
5245             /* turn .* into ^.* with an implied $*=1 */
5246             const int type =
5247                 (OP(NEXTOPER(first)) == REG_ANY)
5248                     ? RXf_ANCH_MBOL
5249                     : RXf_ANCH_SBOL;
5250             r->extflags |= type;
5251             r->intflags |= PREGf_IMPLICIT;
5252             first = NEXTOPER(first);
5253             goto again;
5254         }
5255         if (sawplus && !sawlookahead && (!sawopen || !RExC_sawback)
5256             && !(RExC_seen & REG_SEEN_EVAL)) /* May examine pos and $& */
5257             /* x+ must match at the 1st pos of run of x's */
5258             r->intflags |= PREGf_SKIP;
5259
5260         /* Scan is after the zeroth branch, first is atomic matcher. */
5261 #ifdef TRIE_STUDY_OPT
5262         DEBUG_PARSE_r(
5263             if (!restudied)
5264                 PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
5265                               (IV)(first - scan + 1))
5266         );
5267 #else
5268         DEBUG_PARSE_r(
5269             PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
5270                 (IV)(first - scan + 1))
5271         );
5272 #endif
5273
5274
5275         /*
5276         * If there's something expensive in the r.e., find the
5277         * longest literal string that must appear and make it the
5278         * regmust.  Resolve ties in favor of later strings, since
5279         * the regstart check works with the beginning of the r.e.
5280         * and avoiding duplication strengthens checking.  Not a
5281         * strong reason, but sufficient in the absence of others.
5282         * [Now we resolve ties in favor of the earlier string if
5283         * it happens that c_offset_min has been invalidated, since the
5284         * earlier string may buy us something the later one won't.]
5285         */
5286
5287         data.longest_fixed = newSVpvs("");
5288         data.longest_float = newSVpvs("");
5289         data.last_found = newSVpvs("");
5290         data.longest = &(data.longest_fixed);
5291         first = scan;
5292         if (!ri->regstclass) {
5293             cl_init(pRExC_state, &ch_class);
5294             data.start_class = &ch_class;
5295             stclass_flag = SCF_DO_STCLASS_AND;
5296         } else                          /* XXXX Check for BOUND? */
5297             stclass_flag = 0;
5298         data.last_closep = &last_close;
5299         
5300         minlen = study_chunk(pRExC_state, &first, &minlen, &fake, scan + RExC_size, /* Up to end */
5301             &data, -1, NULL, NULL,
5302             SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag,0);
5303
5304
5305         CHECK_RESTUDY_GOTO;
5306
5307
5308         if ( RExC_npar == 1 && data.longest == &(data.longest_fixed)
5309              && data.last_start_min == 0 && data.last_end > 0
5310              && !RExC_seen_zerolen
5311              && !(RExC_seen & REG_SEEN_VERBARG)
5312              && (!(RExC_seen & REG_SEEN_GPOS) || (r->extflags & RXf_ANCH_GPOS)))
5313             r->extflags |= RXf_CHECK_ALL;
5314         scan_commit(pRExC_state, &data,&minlen,0);
5315         SvREFCNT_dec(data.last_found);
5316
5317         /* Note that code very similar to this but for anchored string 
5318            follows immediately below, changes may need to be made to both. 
5319            Be careful. 
5320          */
5321         longest_float_length = CHR_SVLEN(data.longest_float);
5322         if (longest_float_length
5323             || (data.flags & SF_FL_BEFORE_EOL
5324                 && (!(data.flags & SF_FL_BEFORE_MEOL)
5325                     || (RExC_flags & RXf_PMf_MULTILINE)))) 
5326         {
5327             I32 t,ml;
5328
5329             /* See comments for join_exact for why REG_SEEN_EXACTF_SHARP_S */
5330             if ((RExC_seen & REG_SEEN_EXACTF_SHARP_S)
5331                 || (SvCUR(data.longest_fixed)  /* ok to leave SvCUR */
5332                     && data.offset_fixed == data.offset_float_min
5333                     && SvCUR(data.longest_fixed) == SvCUR(data.longest_float)))
5334                     goto remove_float;          /* As in (a)+. */
5335
5336             /* copy the information about the longest float from the reg_scan_data
5337                over to the program. */
5338             if (SvUTF8(data.longest_float)) {
5339                 r->float_utf8 = data.longest_float;
5340                 r->float_substr = NULL;
5341             } else {
5342                 r->float_substr = data.longest_float;
5343                 r->float_utf8 = NULL;
5344             }
5345             /* float_end_shift is how many chars that must be matched that 
5346                follow this item. We calculate it ahead of time as once the
5347                lookbehind offset is added in we lose the ability to correctly
5348                calculate it.*/
5349             ml = data.minlen_float ? *(data.minlen_float) 
5350                                    : (I32)longest_float_length;
5351             r->float_end_shift = ml - data.offset_float_min
5352                 - longest_float_length + (SvTAIL(data.longest_float) != 0)
5353                 + data.lookbehind_float;
5354             r->float_min_offset = data.offset_float_min - data.lookbehind_float;
5355             r->float_max_offset = data.offset_float_max;
5356             if (data.offset_float_max < I32_MAX) /* Don't offset infinity */
5357                 r->float_max_offset -= data.lookbehind_float;
5358             
5359             t = (data.flags & SF_FL_BEFORE_EOL /* Can't have SEOL and MULTI */
5360                        && (!(data.flags & SF_FL_BEFORE_MEOL)
5361                            || (RExC_flags & RXf_PMf_MULTILINE)));
5362             fbm_compile(data.longest_float, t ? FBMcf_TAIL : 0);
5363         }
5364         else {
5365           remove_float:
5366             r->float_substr = r->float_utf8 = NULL;
5367             SvREFCNT_dec(data.longest_float);
5368             longest_float_length = 0;
5369         }
5370
5371         /* Note that code very similar to this but for floating string 
5372            is immediately above, changes may need to be made to both. 
5373            Be careful. 
5374          */
5375         longest_fixed_length = CHR_SVLEN(data.longest_fixed);
5376
5377         /* See comments for join_exact for why REG_SEEN_EXACTF_SHARP_S */
5378         if (! (RExC_seen & REG_SEEN_EXACTF_SHARP_S)
5379             && (longest_fixed_length
5380                 || (data.flags & SF_FIX_BEFORE_EOL /* Cannot have SEOL and MULTI */
5381                     && (!(data.flags & SF_FIX_BEFORE_MEOL)
5382                         || (RExC_flags & RXf_PMf_MULTILINE)))) )
5383         {
5384             I32 t,ml;
5385
5386             /* copy the information about the longest fixed 
5387                from the reg_scan_data over to the program. */
5388             if (SvUTF8(data.longest_fixed)) {
5389                 r->anchored_utf8 = data.longest_fixed;
5390                 r->anchored_substr = NULL;
5391             } else {
5392                 r->anchored_substr = data.longest_fixed;
5393                 r->anchored_utf8 = NULL;
5394             }
5395             /* fixed_end_shift is how many chars that must be matched that 
5396                follow this item. We calculate it ahead of time as once the
5397                lookbehind offset is added in we lose the ability to correctly
5398                calculate it.*/
5399             ml = data.minlen_fixed ? *(data.minlen_fixed) 
5400                                    : (I32)longest_fixed_length;
5401             r->anchored_end_shift = ml - data.offset_fixed
5402                 - longest_fixed_length + (SvTAIL(data.longest_fixed) != 0)
5403                 + data.lookbehind_fixed;
5404             r->anchored_offset = data.offset_fixed - data.lookbehind_fixed;
5405
5406             t = (data.flags & SF_FIX_BEFORE_EOL /* Can't have SEOL and MULTI */
5407                  && (!(data.flags & SF_FIX_BEFORE_MEOL)
5408                      || (RExC_flags & RXf_PMf_MULTILINE)));
5409             fbm_compile(data.longest_fixed, t ? FBMcf_TAIL : 0);
5410         }
5411         else {
5412             r->anchored_substr = r->anchored_utf8 = NULL;
5413             SvREFCNT_dec(data.longest_fixed);
5414             longest_fixed_length = 0;
5415         }
5416         if (ri->regstclass
5417             && (OP(ri->regstclass) == REG_ANY || OP(ri->regstclass) == SANY))
5418             ri->regstclass = NULL;
5419
5420         if ((!(r->anchored_substr || r->anchored_utf8) || r->anchored_offset)
5421             && stclass_flag
5422             && !(data.start_class->flags & ANYOF_EOS)
5423             && !cl_is_anything(data.start_class))
5424         {
5425             const U32 n = add_data(pRExC_state, 1, "f");
5426             data.start_class->flags |= ANYOF_IS_SYNTHETIC;
5427
5428             Newx(RExC_rxi->data->data[n], 1,
5429                 struct regnode_charclass_class);
5430             StructCopy(data.start_class,
5431                        (struct regnode_charclass_class*)RExC_rxi->data->data[n],
5432                        struct regnode_charclass_class);
5433             ri->regstclass = (regnode*)RExC_rxi->data->data[n];
5434             r->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
5435             DEBUG_COMPILE_r({ SV *sv = sv_newmortal();
5436                       regprop(r, sv, (regnode*)data.start_class);
5437                       PerlIO_printf(Perl_debug_log,
5438                                     "synthetic stclass \"%s\".\n",
5439                                     SvPVX_const(sv));});
5440         }
5441
5442         /* A temporary algorithm prefers floated substr to fixed one to dig more info. */
5443         if (longest_fixed_length > longest_float_length) {
5444             r->check_end_shift = r->anchored_end_shift;
5445             r->check_substr = r->anchored_substr;
5446             r->check_utf8 = r->anchored_utf8;
5447             r->check_offset_min = r->check_offset_max = r->anchored_offset;
5448             if (r->extflags & RXf_ANCH_SINGLE)
5449                 r->extflags |= RXf_NOSCAN;
5450         }
5451         else {
5452             r->check_end_shift = r->float_end_shift;
5453             r->check_substr = r->float_substr;
5454             r->check_utf8 = r->float_utf8;
5455             r->check_offset_min = r->float_min_offset;
5456             r->check_offset_max = r->float_max_offset;
5457         }
5458         /* XXXX Currently intuiting is not compatible with ANCH_GPOS.
5459            This should be changed ASAP!  */
5460         if ((r->check_substr || r->check_utf8) && !(r->extflags & RXf_ANCH_GPOS)) {
5461             r->extflags |= RXf_USE_INTUIT;
5462             if (SvTAIL(r->check_substr ? r->check_substr : r->check_utf8))
5463                 r->extflags |= RXf_INTUIT_TAIL;
5464         }
5465         /* XXX Unneeded? dmq (shouldn't as this is handled elsewhere)
5466         if ( (STRLEN)minlen < longest_float_length )
5467             minlen= longest_float_length;
5468         if ( (STRLEN)minlen < longest_fixed_length )
5469             minlen= longest_fixed_length;     
5470         */
5471     }
5472     else {
5473         /* Several toplevels. Best we can is to set minlen. */
5474         I32 fake;
5475         struct regnode_charclass_class ch_class;
5476         I32 last_close = 0;
5477
5478         DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log, "\nMulti Top Level\n"));
5479
5480         scan = ri->program + 1;
5481         cl_init(pRExC_state, &ch_class);
5482         data.start_class = &ch_class;
5483         data.last_closep = &last_close;
5484
5485         
5486         minlen = study_chunk(pRExC_state, &scan, &minlen, &fake, scan + RExC_size,
5487             &data, -1, NULL, NULL, SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS,0);
5488         
5489         CHECK_RESTUDY_GOTO;
5490
5491         r->check_substr = r->check_utf8 = r->anchored_substr = r->anchored_utf8
5492                 = r->float_substr = r->float_utf8 = NULL;
5493
5494         if (!(data.start_class->flags & ANYOF_EOS)
5495             && !cl_is_anything(data.start_class))
5496         {
5497             const U32 n = add_data(pRExC_state, 1, "f");
5498             data.start_class->flags |= ANYOF_IS_SYNTHETIC;
5499
5500             Newx(RExC_rxi->data->data[n], 1,
5501                 struct regnode_charclass_class);
5502             StructCopy(data.start_class,
5503                        (struct regnode_charclass_class*)RExC_rxi->data->data[n],
5504                        struct regnode_charclass_class);
5505             ri->regstclass = (regnode*)RExC_rxi->data->data[n];
5506             r->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
5507             DEBUG_COMPILE_r({ SV* sv = sv_newmortal();
5508                       regprop(r, sv, (regnode*)data.start_class);
5509                       PerlIO_printf(Perl_debug_log,
5510                                     "synthetic stclass \"%s\".\n",
5511                                     SvPVX_const(sv));});
5512         }
5513     }
5514
5515     /* Guard against an embedded (?=) or (?<=) with a longer minlen than
5516        the "real" pattern. */
5517     DEBUG_OPTIMISE_r({
5518         PerlIO_printf(Perl_debug_log,"minlen: %"IVdf" r->minlen:%"IVdf"\n",
5519                       (IV)minlen, (IV)r->minlen);
5520     });
5521     r->minlenret = minlen;
5522     if (r->minlen < minlen) 
5523         r->minlen = minlen;
5524     
5525     if (RExC_seen & REG_SEEN_GPOS)
5526         r->extflags |= RXf_GPOS_SEEN;
5527     if (RExC_seen & REG_SEEN_LOOKBEHIND)
5528         r->extflags |= RXf_LOOKBEHIND_SEEN;
5529     if (RExC_seen & REG_SEEN_EVAL)
5530         r->extflags |= RXf_EVAL_SEEN;
5531     if (RExC_seen & REG_SEEN_CANY)
5532         r->extflags |= RXf_CANY_SEEN;
5533     if (RExC_seen & REG_SEEN_VERBARG)
5534         r->intflags |= PREGf_VERBARG_SEEN;
5535     if (RExC_seen & REG_SEEN_CUTGROUP)
5536         r->intflags |= PREGf_CUTGROUP_SEEN;
5537     if (RExC_paren_names)
5538         RXp_PAREN_NAMES(r) = MUTABLE_HV(SvREFCNT_inc(RExC_paren_names));
5539     else
5540         RXp_PAREN_NAMES(r) = NULL;
5541
5542 #ifdef STUPID_PATTERN_CHECKS            
5543     if (RX_PRELEN(rx) == 0)
5544         r->extflags |= RXf_NULL;
5545     if (r->extflags & RXf_SPLIT && RX_PRELEN(rx) == 1 && RX_PRECOMP(rx)[0] == ' ')
5546         /* XXX: this should happen BEFORE we compile */
5547         r->extflags |= (RXf_SKIPWHITE|RXf_WHITE); 
5548     else if (RX_PRELEN(rx) == 3 && memEQ("\\s+", RX_PRECOMP(rx), 3))
5549         r->extflags |= RXf_WHITE;
5550     else if (RX_PRELEN(rx) == 1 && RXp_PRECOMP(rx)[0] == '^')
5551         r->extflags |= RXf_START_ONLY;
5552 #else
5553     if (r->extflags & RXf_SPLIT && RX_PRELEN(rx) == 1 && RX_PRECOMP(rx)[0] == ' ')
5554             /* XXX: this should happen BEFORE we compile */
5555             r->extflags |= (RXf_SKIPWHITE|RXf_WHITE); 
5556     else {
5557         regnode *first = ri->program + 1;
5558         U8 fop = OP(first);
5559
5560         if (PL_regkind[fop] == NOTHING && OP(NEXTOPER(first)) == END)
5561             r->extflags |= RXf_NULL;
5562         else if (PL_regkind[fop] == BOL && OP(NEXTOPER(first)) == END)
5563             r->extflags |= RXf_START_ONLY;
5564         else if (fop == PLUS && OP(NEXTOPER(first)) == SPACE
5565                              && OP(regnext(first)) == END)
5566             r->extflags |= RXf_WHITE;    
5567     }
5568 #endif
5569 #ifdef DEBUGGING
5570     if (RExC_paren_names) {
5571         ri->name_list_idx = add_data( pRExC_state, 1, "a" );
5572         ri->data->data[ri->name_list_idx] = (void*)SvREFCNT_inc(RExC_paren_name_list);
5573     } else
5574 #endif
5575         ri->name_list_idx = 0;
5576
5577     if (RExC_recurse_count) {
5578         for ( ; RExC_recurse_count ; RExC_recurse_count-- ) {
5579             const regnode *scan = RExC_recurse[RExC_recurse_count-1];
5580             ARG2L_SET( scan, RExC_open_parens[ARG(scan)-1] - scan );
5581         }
5582     }
5583     Newxz(r->offs, RExC_npar, regexp_paren_pair);
5584     /* assume we don't need to swap parens around before we match */
5585
5586     DEBUG_DUMP_r({
5587         PerlIO_printf(Perl_debug_log,"Final program:\n");
5588         regdump(r);
5589     });
5590 #ifdef RE_TRACK_PATTERN_OFFSETS
5591     DEBUG_OFFSETS_r(if (ri->u.offsets) {
5592         const U32 len = ri->u.offsets[0];
5593         U32 i;
5594         GET_RE_DEBUG_FLAGS_DECL;
5595         PerlIO_printf(Perl_debug_log, "Offsets: [%"UVuf"]\n\t", (UV)ri->u.offsets[0]);
5596         for (i = 1; i <= len; i++) {
5597             if (ri->u.offsets[i*2-1] || ri->u.offsets[i*2])
5598                 PerlIO_printf(Perl_debug_log, "%"UVuf":%"UVuf"[%"UVuf"] ",
5599                 (UV)i, (UV)ri->u.offsets[i*2-1], (UV)ri->u.offsets[i*2]);
5600             }
5601         PerlIO_printf(Perl_debug_log, "\n");
5602     });
5603 #endif
5604     return rx;
5605 }
5606
5607 #undef RE_ENGINE_PTR
5608
5609
5610 SV*
5611 Perl_reg_named_buff(pTHX_ REGEXP * const rx, SV * const key, SV * const value,
5612                     const U32 flags)
5613 {
5614     PERL_ARGS_ASSERT_REG_NAMED_BUFF;
5615
5616     PERL_UNUSED_ARG(value);
5617
5618     if (flags & RXapif_FETCH) {
5619         return reg_named_buff_fetch(rx, key, flags);
5620     } else if (flags & (RXapif_STORE | RXapif_DELETE | RXapif_CLEAR)) {
5621         Perl_croak_no_modify(aTHX);
5622         return NULL;
5623     } else if (flags & RXapif_EXISTS) {
5624         return reg_named_buff_exists(rx, key, flags)
5625             ? &PL_sv_yes
5626             : &PL_sv_no;
5627     } else if (flags & RXapif_REGNAMES) {
5628         return reg_named_buff_all(rx, flags);
5629     } else if (flags & (RXapif_SCALAR | RXapif_REGNAMES_COUNT)) {
5630         return reg_named_buff_scalar(rx, flags);
5631     } else {
5632         Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff", (int)flags);
5633         return NULL;
5634     }
5635 }
5636
5637 SV*
5638 Perl_reg_named_buff_iter(pTHX_ REGEXP * const rx, const SV * const lastkey,
5639                          const U32 flags)
5640 {
5641     PERL_ARGS_ASSERT_REG_NAMED_BUFF_ITER;
5642     PERL_UNUSED_ARG(lastkey);
5643
5644     if (flags & RXapif_FIRSTKEY)
5645         return reg_named_buff_firstkey(rx, flags);
5646     else if (flags & RXapif_NEXTKEY)
5647         return reg_named_buff_nextkey(rx, flags);
5648     else {
5649         Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_iter", (int)flags);
5650         return NULL;
5651     }
5652 }
5653
5654 SV*
5655 Perl_reg_named_buff_fetch(pTHX_ REGEXP * const r, SV * const namesv,
5656                           const U32 flags)
5657 {
5658     AV *retarray = NULL;
5659     SV *ret;
5660     struct regexp *const rx = (struct regexp *)SvANY(r);
5661
5662     PERL_ARGS_ASSERT_REG_NAMED_BUFF_FETCH;
5663
5664     if (flags & RXapif_ALL)
5665         retarray=newAV();
5666
5667     if (rx && RXp_PAREN_NAMES(rx)) {
5668         HE *he_str = hv_fetch_ent( RXp_PAREN_NAMES(rx), namesv, 0, 0 );
5669         if (he_str) {
5670             IV i;
5671             SV* sv_dat=HeVAL(he_str);
5672             I32 *nums=(I32*)SvPVX(sv_dat);
5673             for ( i=0; i<SvIVX(sv_dat); i++ ) {
5674                 if ((I32)(rx->nparens) >= nums[i]
5675                     && rx->offs[nums[i]].start != -1
5676                     && rx->offs[nums[i]].end != -1)
5677                 {
5678                     ret = newSVpvs("");
5679                     CALLREG_NUMBUF_FETCH(r,nums[i],ret);
5680                     if (!retarray)
5681                         return ret;
5682                 } else {
5683                     if (retarray)
5684                         ret = newSVsv(&PL_sv_undef);
5685                 }
5686                 if (retarray)
5687                     av_push(retarray, ret);
5688             }
5689             if (retarray)
5690                 return newRV_noinc(MUTABLE_SV(retarray));
5691         }
5692     }
5693     return NULL;
5694 }
5695
5696 bool
5697 Perl_reg_named_buff_exists(pTHX_ REGEXP * const r, SV * const key,
5698                            const U32 flags)
5699 {
5700     struct regexp *const rx = (struct regexp *)SvANY(r);
5701
5702     PERL_ARGS_ASSERT_REG_NAMED_BUFF_EXISTS;
5703
5704     if (rx && RXp_PAREN_NAMES(rx)) {
5705         if (flags & RXapif_ALL) {
5706             return hv_exists_ent(RXp_PAREN_NAMES(rx), key, 0);
5707         } else {
5708             SV *sv = CALLREG_NAMED_BUFF_FETCH(r, key, flags);
5709             if (sv) {
5710                 SvREFCNT_dec(sv);
5711                 return TRUE;
5712             } else {
5713                 return FALSE;
5714             }
5715         }
5716     } else {
5717         return FALSE;
5718     }
5719 }
5720
5721 SV*
5722 Perl_reg_named_buff_firstkey(pTHX_ REGEXP * const r, const U32 flags)
5723 {
5724     struct regexp *const rx = (struct regexp *)SvANY(r);
5725
5726     PERL_ARGS_ASSERT_REG_NAMED_BUFF_FIRSTKEY;
5727
5728     if ( rx && RXp_PAREN_NAMES(rx) ) {
5729         (void)hv_iterinit(RXp_PAREN_NAMES(rx));
5730
5731         return CALLREG_NAMED_BUFF_NEXTKEY(r, NULL, flags & ~RXapif_FIRSTKEY);
5732     } else {
5733         return FALSE;
5734     }
5735 }
5736
5737 SV*
5738 Perl_reg_named_buff_nextkey(pTHX_ REGEXP * const r, const U32 flags)
5739 {
5740     struct regexp *const rx = (struct regexp *)SvANY(r);
5741     GET_RE_DEBUG_FLAGS_DECL;
5742
5743     PERL_ARGS_ASSERT_REG_NAMED_BUFF_NEXTKEY;
5744
5745     if (rx && RXp_PAREN_NAMES(rx)) {
5746         HV *hv = RXp_PAREN_NAMES(rx);
5747         HE *temphe;
5748         while ( (temphe = hv_iternext_flags(hv,0)) ) {
5749             IV i;
5750             IV parno = 0;
5751             SV* sv_dat = HeVAL(temphe);
5752             I32 *nums = (I32*)SvPVX(sv_dat);
5753             for ( i = 0; i < SvIVX(sv_dat); i++ ) {
5754                 if ((I32)(rx->lastparen) >= nums[i] &&
5755                     rx->offs[nums[i]].start != -1 &&
5756                     rx->offs[nums[i]].end != -1)
5757                 {
5758                     parno = nums[i];
5759                     break;
5760                 }
5761             }
5762             if (parno || flags & RXapif_ALL) {
5763                 return newSVhek(HeKEY_hek(temphe));
5764             }
5765         }
5766     }
5767     return NULL;
5768 }
5769
5770 SV*
5771 Perl_reg_named_buff_scalar(pTHX_ REGEXP * const r, const U32 flags)
5772 {
5773     SV *ret;
5774     AV *av;
5775     I32 length;
5776     struct regexp *const rx = (struct regexp *)SvANY(r);
5777
5778     PERL_ARGS_ASSERT_REG_NAMED_BUFF_SCALAR;
5779
5780     if (rx && RXp_PAREN_NAMES(rx)) {
5781         if (flags & (RXapif_ALL | RXapif_REGNAMES_COUNT)) {
5782             return newSViv(HvTOTALKEYS(RXp_PAREN_NAMES(rx)));
5783         } else if (flags & RXapif_ONE) {
5784             ret = CALLREG_NAMED_BUFF_ALL(r, (flags | RXapif_REGNAMES));
5785             av = MUTABLE_AV(SvRV(ret));
5786             length = av_len(av);
5787             SvREFCNT_dec(ret);
5788             return newSViv(length + 1);
5789         } else {
5790             Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_scalar", (int)flags);
5791             return NULL;
5792         }
5793     }
5794     return &PL_sv_undef;
5795 }
5796
5797 SV*
5798 Perl_reg_named_buff_all(pTHX_ REGEXP * const r, const U32 flags)
5799 {
5800     struct regexp *const rx = (struct regexp *)SvANY(r);
5801     AV *av = newAV();
5802
5803     PERL_ARGS_ASSERT_REG_NAMED_BUFF_ALL;
5804
5805     if (rx && RXp_PAREN_NAMES(rx)) {
5806         HV *hv= RXp_PAREN_NAMES(rx);
5807         HE *temphe;
5808         (void)hv_iterinit(hv);
5809         while ( (temphe = hv_iternext_flags(hv,0)) ) {
5810             IV i;
5811             IV parno = 0;
5812             SV* sv_dat = HeVAL(temphe);
5813             I32 *nums = (I32*)SvPVX(sv_dat);
5814             for ( i = 0; i < SvIVX(sv_dat); i++ ) {
5815                 if ((I32)(rx->lastparen) >= nums[i] &&
5816                     rx->offs[nums[i]].start != -1 &&
5817                     rx->offs[nums[i]].end != -1)
5818                 {
5819                     parno = nums[i];
5820                     break;
5821                 }
5822             }
5823             if (parno || flags & RXapif_ALL) {
5824                 av_push(av, newSVhek(HeKEY_hek(temphe)));
5825             }
5826         }
5827     }
5828
5829     return newRV_noinc(MUTABLE_SV(av));
5830 }
5831
5832 void
5833 Perl_reg_numbered_buff_fetch(pTHX_ REGEXP * const r, const I32 paren,
5834                              SV * const sv)
5835 {
5836     struct regexp *const rx = (struct regexp *)SvANY(r);
5837     char *s = NULL;
5838     I32 i = 0;
5839     I32 s1, t1;
5840
5841     PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_FETCH;
5842         
5843     if (!rx->subbeg) {
5844         sv_setsv(sv,&PL_sv_undef);
5845         return;
5846     } 
5847     else               
5848     if (paren == RX_BUFF_IDX_PREMATCH && rx->offs[0].start != -1) {
5849         /* $` */
5850         i = rx->offs[0].start;
5851         s = rx->subbeg;
5852     }
5853     else 
5854     if (paren == RX_BUFF_IDX_POSTMATCH && rx->offs[0].end != -1) {
5855         /* $' */
5856         s = rx->subbeg + rx->offs[0].end;
5857         i = rx->sublen - rx->offs[0].end;
5858     } 
5859     else
5860     if ( 0 <= paren && paren <= (I32)rx->nparens &&
5861         (s1 = rx->offs[paren].start) != -1 &&
5862         (t1 = rx->offs[paren].end) != -1)
5863     {
5864         /* $& $1 ... */
5865         i = t1 - s1;
5866         s = rx->subbeg + s1;
5867     } else {
5868         sv_setsv(sv,&PL_sv_undef);
5869         return;
5870     }          
5871     assert(rx->sublen >= (s - rx->subbeg) + i );
5872     if (i >= 0) {
5873         const int oldtainted = PL_tainted;
5874         TAINT_NOT;
5875         sv_setpvn(sv, s, i);
5876         PL_tainted = oldtainted;
5877         if ( (rx->extflags & RXf_CANY_SEEN)
5878             ? (RXp_MATCH_UTF8(rx)
5879                         && (!i || is_utf8_string((U8*)s, i)))
5880             : (RXp_MATCH_UTF8(rx)) )
5881         {
5882             SvUTF8_on(sv);
5883         }
5884         else
5885             SvUTF8_off(sv);
5886         if (PL_tainting) {
5887             if (RXp_MATCH_TAINTED(rx)) {
5888                 if (SvTYPE(sv) >= SVt_PVMG) {
5889                     MAGIC* const mg = SvMAGIC(sv);
5890                     MAGIC* mgt;
5891                     PL_tainted = 1;
5892                     SvMAGIC_set(sv, mg->mg_moremagic);
5893                     SvTAINT(sv);
5894                     if ((mgt = SvMAGIC(sv))) {
5895                         mg->mg_moremagic = mgt;
5896                         SvMAGIC_set(sv, mg);
5897                     }
5898                 } else {
5899                     PL_tainted = 1;
5900                     SvTAINT(sv);
5901                 }
5902             } else 
5903                 SvTAINTED_off(sv);
5904         }
5905     } else {
5906         sv_setsv(sv,&PL_sv_undef);
5907         return;
5908     }
5909 }
5910
5911 void
5912 Perl_reg_numbered_buff_store(pTHX_ REGEXP * const rx, const I32 paren,
5913                                                          SV const * const value)
5914 {
5915     PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_STORE;
5916
5917     PERL_UNUSED_ARG(rx);
5918     PERL_UNUSED_ARG(paren);
5919     PERL_UNUSED_ARG(value);
5920
5921     if (!PL_localizing)
5922         Perl_croak_no_modify(aTHX);
5923 }
5924
5925 I32
5926 Perl_reg_numbered_buff_length(pTHX_ REGEXP * const r, const SV * const sv,
5927                               const I32 paren)
5928 {
5929     struct regexp *const rx = (struct regexp *)SvANY(r);
5930     I32 i;
5931     I32 s1, t1;
5932
5933     PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_LENGTH;
5934
5935     /* Some of this code was originally in C<Perl_magic_len> in F<mg.c> */
5936         switch (paren) {
5937       /* $` / ${^PREMATCH} */
5938       case RX_BUFF_IDX_PREMATCH:
5939         if (rx->offs[0].start != -1) {
5940                         i = rx->offs[0].start;
5941                         if (i > 0) {
5942                                 s1 = 0;
5943                                 t1 = i;
5944                                 goto getlen;
5945                         }
5946             }
5947         return 0;
5948       /* $' / ${^POSTMATCH} */
5949       case RX_BUFF_IDX_POSTMATCH:
5950             if (rx->offs[0].end != -1) {
5951                         i = rx->sublen - rx->offs[0].end;
5952                         if (i > 0) {
5953                                 s1 = rx->offs[0].end;
5954                                 t1 = rx->sublen;
5955                                 goto getlen;
5956                         }
5957             }
5958         return 0;
5959       /* $& / ${^MATCH}, $1, $2, ... */
5960       default:
5961             if (paren <= (I32)rx->nparens &&
5962             (s1 = rx->offs[paren].start) != -1 &&
5963             (t1 = rx->offs[paren].end) != -1)
5964             {
5965             i = t1 - s1;
5966             goto getlen;
5967         } else {
5968             if (ckWARN(WARN_UNINITIALIZED))
5969                 report_uninit((const SV *)sv);
5970             return 0;
5971         }
5972     }
5973   getlen:
5974     if (i > 0 && RXp_MATCH_UTF8(rx)) {
5975         const char * const s = rx->subbeg + s1;
5976         const U8 *ep;
5977         STRLEN el;
5978
5979         i = t1 - s1;
5980         if (is_utf8_string_loclen((U8*)s, i, &ep, &el))
5981                         i = el;
5982     }
5983     return i;
5984 }
5985
5986 SV*
5987 Perl_reg_qr_package(pTHX_ REGEXP * const rx)
5988 {
5989     PERL_ARGS_ASSERT_REG_QR_PACKAGE;
5990         PERL_UNUSED_ARG(rx);
5991         if (0)
5992             return NULL;
5993         else
5994             return newSVpvs("Regexp");
5995 }
5996
5997 /* Scans the name of a named buffer from the pattern.
5998  * If flags is REG_RSN_RETURN_NULL returns null.
5999  * If flags is REG_RSN_RETURN_NAME returns an SV* containing the name
6000  * If flags is REG_RSN_RETURN_DATA returns the data SV* corresponding
6001  * to the parsed name as looked up in the RExC_paren_names hash.
6002  * If there is an error throws a vFAIL().. type exception.
6003  */
6004
6005 #define REG_RSN_RETURN_NULL    0
6006 #define REG_RSN_RETURN_NAME    1
6007 #define REG_RSN_RETURN_DATA    2
6008
6009 STATIC SV*
6010 S_reg_scan_name(pTHX_ RExC_state_t *pRExC_state, U32 flags)
6011 {
6012     char *name_start = RExC_parse;
6013
6014     PERL_ARGS_ASSERT_REG_SCAN_NAME;
6015
6016     if (isIDFIRST_lazy_if(RExC_parse, UTF)) {
6017          /* skip IDFIRST by using do...while */
6018         if (UTF)
6019             do {
6020                 RExC_parse += UTF8SKIP(RExC_parse);
6021             } while (isALNUM_utf8((U8*)RExC_parse));
6022         else
6023             do {
6024                 RExC_parse++;
6025             } while (isALNUM(*RExC_parse));
6026     }
6027
6028     if ( flags ) {
6029         SV* sv_name
6030             = newSVpvn_flags(name_start, (int)(RExC_parse - name_start),
6031                              SVs_TEMP | (UTF ? SVf_UTF8 : 0));
6032         if ( flags == REG_RSN_RETURN_NAME)
6033             return sv_name;
6034         else if (flags==REG_RSN_RETURN_DATA) {
6035             HE *he_str = NULL;
6036             SV *sv_dat = NULL;
6037             if ( ! sv_name )      /* should not happen*/
6038                 Perl_croak(aTHX_ "panic: no svname in reg_scan_name");
6039             if (RExC_paren_names)
6040                 he_str = hv_fetch_ent( RExC_paren_names, sv_name, 0, 0 );
6041             if ( he_str )
6042                 sv_dat = HeVAL(he_str);
6043             if ( ! sv_dat )
6044                 vFAIL("Reference to nonexistent named group");
6045             return sv_dat;
6046         }
6047         else {
6048             Perl_croak(aTHX_ "panic: bad flag %lx in reg_scan_name",
6049                        (unsigned long) flags);
6050         }
6051         /* NOT REACHED */
6052     }
6053     return NULL;
6054 }
6055
6056 #define DEBUG_PARSE_MSG(funcname)     DEBUG_PARSE_r({           \
6057     int rem=(int)(RExC_end - RExC_parse);                       \
6058     int cut;                                                    \
6059     int num;                                                    \
6060     int iscut=0;                                                \
6061     if (rem>10) {                                               \
6062         rem=10;                                                 \
6063         iscut=1;                                                \
6064     }                                                           \
6065     cut=10-rem;                                                 \
6066     if (RExC_lastparse!=RExC_parse)                             \
6067         PerlIO_printf(Perl_debug_log," >%.*s%-*s",              \
6068             rem, RExC_parse,                                    \
6069             cut + 4,                                            \
6070             iscut ? "..." : "<"                                 \
6071         );                                                      \
6072     else                                                        \
6073         PerlIO_printf(Perl_debug_log,"%16s","");                \
6074                                                                 \
6075     if (SIZE_ONLY)                                              \
6076        num = RExC_size + 1;                                     \
6077     else                                                        \
6078        num=REG_NODE_NUM(RExC_emit);                             \
6079     if (RExC_lastnum!=num)                                      \
6080        PerlIO_printf(Perl_debug_log,"|%4d",num);                \
6081     else                                                        \
6082        PerlIO_printf(Perl_debug_log,"|%4s","");                 \
6083     PerlIO_printf(Perl_debug_log,"|%*s%-4s",                    \
6084         (int)((depth*2)), "",                                   \
6085         (funcname)                                              \
6086     );                                                          \
6087     RExC_lastnum=num;                                           \
6088     RExC_lastparse=RExC_parse;                                  \
6089 })
6090
6091
6092
6093 #define DEBUG_PARSE(funcname)     DEBUG_PARSE_r({           \
6094     DEBUG_PARSE_MSG((funcname));                            \
6095     PerlIO_printf(Perl_debug_log,"%4s","\n");               \
6096 })
6097 #define DEBUG_PARSE_FMT(funcname,fmt,args)     DEBUG_PARSE_r({           \
6098     DEBUG_PARSE_MSG((funcname));                            \
6099     PerlIO_printf(Perl_debug_log,fmt "\n",args);               \
6100 })
6101
6102 /* This section of code defines the inversion list object and its methods.  The
6103  * interfaces are highly subject to change, so as much as possible is static to
6104  * this file.  An inversion list is here implemented as a malloc'd C UV array
6105  * with some added info that is placed as UVs at the beginning in a header
6106  * portion.  An inversion list for Unicode is an array of code points, sorted
6107  * by ordinal number.  The zeroth element is the first code point in the list.
6108  * The 1th element is the first element beyond that not in the list.  In other
6109  * words, the first range is
6110  *  invlist[0]..(invlist[1]-1)
6111  * The other ranges follow.  Thus every element whose index is divisible by two
6112  * marks the beginning of a range that is in the list, and every element not
6113  * divisible by two marks the beginning of a range not in the list.  A single
6114  * element inversion list that contains the single code point N generally
6115  * consists of two elements
6116  *  invlist[0] == N
6117  *  invlist[1] == N+1
6118  * (The exception is when N is the highest representable value on the
6119  * machine, in which case the list containing just it would be a single
6120  * element, itself.  By extension, if the last range in the list extends to
6121  * infinity, then the first element of that range will be in the inversion list
6122  * at a position that is divisible by two, and is the final element in the
6123  * list.)
6124  * Taking the complement (inverting) an inversion list is quite simple, if the
6125  * first element is 0, remove it; otherwise add a 0 element at the beginning.
6126  * This implementation reserves an element at the beginning of each inversion list
6127  * to contain 0 when the list contains 0, and contains 1 otherwise.  The actual
6128  * beginning of the list is either that element if 0, or the next one if 1.
6129  *
6130  * More about inversion lists can be found in "Unicode Demystified"
6131  * Chapter 13 by Richard Gillam, published by Addison-Wesley.
6132  * More will be coming when functionality is added later.
6133  *
6134  * The inversion list data structure is currently implemented as an SV pointing
6135  * to an array of UVs that the SV thinks are bytes.  This allows us to have an
6136  * array of UV whose memory management is automatically handled by the existing
6137  * facilities for SV's.
6138  *
6139  * Some of the methods should always be private to the implementation, and some
6140  * should eventually be made public */
6141
6142 #define INVLIST_LEN_OFFSET 0    /* Number of elements in the inversion list */
6143 #define INVLIST_ITER_OFFSET 1   /* Current iteration position */
6144
6145 #define INVLIST_ZERO_OFFSET 2   /* 0 or 1; must be last element in header */
6146 /* The UV at position ZERO contains either 0 or 1.  If 0, the inversion list
6147  * contains the code point U+00000, and begins here.  If 1, the inversion list
6148  * doesn't contain U+0000, and it begins at the next UV in the array.
6149  * Inverting an inversion list consists of adding or removing the 0 at the
6150  * beginning of it.  By reserving a space for that 0, inversion can be made
6151  * very fast */
6152
6153 #define HEADER_LENGTH (INVLIST_ZERO_OFFSET + 1)
6154
6155 /* Internally things are UVs */
6156 #define TO_INTERNAL_SIZE(x) ((x + HEADER_LENGTH) * sizeof(UV))
6157 #define FROM_INTERNAL_SIZE(x) ((x / sizeof(UV)) - HEADER_LENGTH)
6158
6159 #define INVLIST_INITIAL_LEN 10
6160
6161 PERL_STATIC_INLINE UV*
6162 S__invlist_array_init(pTHX_ SV* const invlist, const bool will_have_0)
6163 {
6164     /* Returns a pointer to the first element in the inversion list's array.
6165      * This is called upon initialization of an inversion list.  Where the
6166      * array begins depends on whether the list has the code point U+0000
6167      * in it or not.  The other parameter tells it whether the code that
6168      * follows this call is about to put a 0 in the inversion list or not.
6169      * The first element is either the element with 0, if 0, or the next one,
6170      * if 1 */
6171
6172     UV* zero = get_invlist_zero_addr(invlist);
6173
6174     PERL_ARGS_ASSERT__INVLIST_ARRAY_INIT;
6175
6176     /* Must be empty */
6177     assert(! *get_invlist_len_addr(invlist));
6178
6179     /* 1^1 = 0; 1^0 = 1 */
6180     *zero = 1 ^ will_have_0;
6181     return zero + *zero;
6182 }
6183
6184 PERL_STATIC_INLINE UV*
6185 S_invlist_array(pTHX_ SV* const invlist)
6186 {
6187     /* Returns the pointer to the inversion list's array.  Every time the
6188      * length changes, this needs to be called in case malloc or realloc moved
6189      * it */
6190
6191     PERL_ARGS_ASSERT_INVLIST_ARRAY;
6192
6193     /* Must not be empty.  If these fail, you probably didn't check for <len>
6194      * being non-zero before trying to get the array */
6195     assert(*get_invlist_len_addr(invlist));
6196     assert(*get_invlist_zero_addr(invlist) == 0
6197            || *get_invlist_zero_addr(invlist) == 1);
6198
6199     /* The array begins either at the element reserved for zero if the
6200      * list contains 0 (that element will be set to 0), or otherwise the next
6201      * element (in which case the reserved element will be set to 1). */
6202     return (UV *) (get_invlist_zero_addr(invlist)
6203                    + *get_invlist_zero_addr(invlist));
6204 }
6205
6206 PERL_STATIC_INLINE UV*
6207 S_get_invlist_len_addr(pTHX_ SV* invlist)
6208 {
6209     /* Return the address of the UV that contains the current number
6210      * of used elements in the inversion list */
6211
6212     PERL_ARGS_ASSERT_GET_INVLIST_LEN_ADDR;
6213
6214     return (UV *) (SvPVX(invlist) + (INVLIST_LEN_OFFSET * sizeof (UV)));
6215 }
6216
6217 PERL_STATIC_INLINE UV
6218 S_invlist_len(pTHX_ SV* const invlist)
6219 {
6220     /* Returns the current number of elements stored in the inversion list's
6221      * array */
6222
6223     PERL_ARGS_ASSERT_INVLIST_LEN;
6224
6225     return *get_invlist_len_addr(invlist);
6226 }
6227
6228 PERL_STATIC_INLINE void
6229 S_invlist_set_len(pTHX_ SV* const invlist, const UV len)
6230 {
6231     /* Sets the current number of elements stored in the inversion list */
6232
6233     PERL_ARGS_ASSERT_INVLIST_SET_LEN;
6234
6235     *get_invlist_len_addr(invlist) = len;
6236
6237     assert(len <= SvLEN(invlist));
6238
6239     SvCUR_set(invlist, TO_INTERNAL_SIZE(len));
6240     /* If the list contains U+0000, that element is part of the header,
6241      * and should not be counted as part of the array.  It will contain
6242      * 0 in that case, and 1 otherwise.  So we could flop 0=>1, 1=>0 and
6243      * subtract:
6244      *  SvCUR_set(invlist,
6245      *            TO_INTERNAL_SIZE(len
6246      *                             - (*get_invlist_zero_addr(inv_list) ^ 1)));
6247      * But, this is only valid if len is not 0.  The consequences of not doing
6248      * this is that the memory allocation code may think that 1 more UV is
6249      * being used than actually is, and so might do an unnecessary grow.  That
6250      * seems worth not bothering to make this the precise amount.
6251      *
6252      * Note that when inverting, SvCUR shouldn't change */
6253 }
6254
6255 PERL_STATIC_INLINE UV
6256 S_invlist_max(pTHX_ SV* const invlist)
6257 {
6258     /* Returns the maximum number of elements storable in the inversion list's
6259      * array, without having to realloc() */
6260
6261     PERL_ARGS_ASSERT_INVLIST_MAX;
6262
6263     return FROM_INTERNAL_SIZE(SvLEN(invlist));
6264 }
6265
6266 PERL_STATIC_INLINE UV*
6267 S_get_invlist_zero_addr(pTHX_ SV* invlist)
6268 {
6269     /* Return the address of the UV that is reserved to hold 0 if the inversion
6270      * list contains 0.  This has to be the last element of the heading, as the
6271      * list proper starts with either it if 0, or the next element if not.
6272      * (But we force it to contain either 0 or 1) */
6273
6274     PERL_ARGS_ASSERT_GET_INVLIST_ZERO_ADDR;
6275
6276     return (UV *) (SvPVX(invlist) + (INVLIST_ZERO_OFFSET * sizeof (UV)));
6277 }
6278
6279 #ifndef PERL_IN_XSUB_RE
6280 SV*
6281 Perl__new_invlist(pTHX_ IV initial_size)
6282 {
6283
6284     /* Return a pointer to a newly constructed inversion list, with enough
6285      * space to store 'initial_size' elements.  If that number is negative, a
6286      * system default is used instead */
6287
6288     SV* new_list;
6289
6290     if (initial_size < 0) {
6291         initial_size = INVLIST_INITIAL_LEN;
6292     }
6293
6294     /* Allocate the initial space */
6295     new_list = newSV(TO_INTERNAL_SIZE(initial_size));
6296     invlist_set_len(new_list, 0);
6297
6298     /* Force iterinit() to be used to get iteration to work */
6299     *get_invlist_iter_addr(new_list) = UV_MAX;
6300
6301     /* This should force a segfault if a method doesn't initialize this
6302      * properly */
6303     *get_invlist_zero_addr(new_list) = UV_MAX;
6304
6305     return new_list;
6306 }
6307 #endif
6308
6309 STATIC void
6310 S_invlist_extend(pTHX_ SV* const invlist, const UV new_max)
6311 {
6312     /* Grow the maximum size of an inversion list */
6313
6314     PERL_ARGS_ASSERT_INVLIST_EXTEND;
6315
6316     SvGROW((SV *)invlist, TO_INTERNAL_SIZE(new_max));
6317 }
6318
6319 PERL_STATIC_INLINE void
6320 S_invlist_trim(pTHX_ SV* const invlist)
6321 {
6322     PERL_ARGS_ASSERT_INVLIST_TRIM;
6323
6324     /* Change the length of the inversion list to how many entries it currently
6325      * has */
6326
6327     SvPV_shrink_to_cur((SV *) invlist);
6328 }
6329
6330 /* An element is in an inversion list iff its index is even numbered: 0, 2, 4,
6331  * etc */
6332 #define ELEMENT_RANGE_MATCHES_INVLIST(i) (! ((i) & 1))
6333 #define PREV_RANGE_MATCHES_INVLIST(i) (! ELEMENT_RANGE_MATCHES_INVLIST(i))
6334
6335 #ifndef PERL_IN_XSUB_RE
6336 void
6337 Perl__append_range_to_invlist(pTHX_ SV* const invlist, const UV start, const UV end)
6338 {
6339    /* Subject to change or removal.  Append the range from 'start' to 'end' at
6340     * the end of the inversion list.  The range must be above any existing
6341     * ones. */
6342
6343     UV* array;
6344     UV max = invlist_max(invlist);
6345     UV len = invlist_len(invlist);
6346
6347     PERL_ARGS_ASSERT__APPEND_RANGE_TO_INVLIST;
6348
6349     if (len == 0) { /* Empty lists must be initialized */
6350         array = _invlist_array_init(invlist, start == 0);
6351     }
6352     else {
6353         /* Here, the existing list is non-empty. The current max entry in the
6354          * list is generally the first value not in the set, except when the
6355          * set extends to the end of permissible values, in which case it is
6356          * the first entry in that final set, and so this call is an attempt to
6357          * append out-of-order */
6358
6359         UV final_element = len - 1;
6360         array = invlist_array(invlist);
6361         if (array[final_element] > start
6362             || ELEMENT_RANGE_MATCHES_INVLIST(final_element))
6363         {
6364             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",
6365                        array[final_element], start,
6366                        ELEMENT_RANGE_MATCHES_INVLIST(final_element) ? 't' : 'f');
6367         }
6368
6369         /* Here, it is a legal append.  If the new range begins with the first
6370          * value not in the set, it is extending the set, so the new first
6371          * value not in the set is one greater than the newly extended range.
6372          * */
6373         if (array[final_element] == start) {
6374             if (end != UV_MAX) {
6375                 array[final_element] = end + 1;
6376             }
6377             else {
6378                 /* But if the end is the maximum representable on the machine,
6379                  * just let the range that this would extend to have no end */
6380                 invlist_set_len(invlist, len - 1);
6381             }
6382             return;
6383         }
6384     }
6385
6386     /* Here the new range doesn't extend any existing set.  Add it */
6387
6388     len += 2;   /* Includes an element each for the start and end of range */
6389
6390     /* If overflows the existing space, extend, which may cause the array to be
6391      * moved */
6392     if (max < len) {
6393         invlist_extend(invlist, len);
6394         invlist_set_len(invlist, len);  /* Have to set len here to avoid assert
6395                                            failure in invlist_array() */
6396         array = invlist_array(invlist);
6397     }
6398     else {
6399         invlist_set_len(invlist, len);
6400     }
6401
6402     /* The next item on the list starts the range, the one after that is
6403      * one past the new range.  */
6404     array[len - 2] = start;
6405     if (end != UV_MAX) {
6406         array[len - 1] = end + 1;
6407     }
6408     else {
6409         /* But if the end is the maximum representable on the machine, just let
6410          * the range have no end */
6411         invlist_set_len(invlist, len - 1);
6412     }
6413 }
6414
6415 STATIC IV
6416 S_invlist_search(pTHX_ SV* const invlist, const UV cp)
6417 {
6418     /* Searches the inversion list for the entry that contains the input code
6419      * point <cp>.  If <cp> is not in the list, -1 is returned.  Otherwise, the
6420      * return value is the index into the list's array of the range that
6421      * contains <cp> */
6422
6423     IV low = 0;
6424     IV high = invlist_len(invlist);
6425     const UV * const array = invlist_array(invlist);
6426
6427     PERL_ARGS_ASSERT_INVLIST_SEARCH;
6428
6429     /* If list is empty or the code point is before the first element, return
6430      * failure. */
6431     if (high == 0 || cp < array[0]) {
6432         return -1;
6433     }
6434
6435     /* Binary search.  What we are looking for is <i> such that
6436      *  array[i] <= cp < array[i+1]
6437      * The loop below converges on the i+1. */
6438     while (low < high) {
6439         IV mid = (low + high) / 2;
6440         if (array[mid] <= cp) {
6441             low = mid + 1;
6442
6443             /* We could do this extra test to exit the loop early.
6444             if (cp < array[low]) {
6445                 return mid;
6446             }
6447             */
6448         }
6449         else { /* cp < array[mid] */
6450             high = mid;
6451         }
6452     }
6453
6454     return high - 1;
6455 }
6456
6457 void
6458 Perl__invlist_populate_swatch(pTHX_ SV* const invlist, const UV start, const UV end, U8* swatch)
6459 {
6460     /* populates a swatch of a swash the same way swatch_get() does in utf8.c,
6461      * but is used when the swash has an inversion list.  This makes this much
6462      * faster, as it uses a binary search instead of a linear one.  This is
6463      * intimately tied to that function, and perhaps should be in utf8.c,
6464      * except it is intimately tied to inversion lists as well.  It assumes
6465      * that <swatch> is all 0's on input */
6466
6467     UV current = start;
6468     const IV len = invlist_len(invlist);
6469     IV i;
6470     const UV * array;
6471
6472     PERL_ARGS_ASSERT__INVLIST_POPULATE_SWATCH;
6473
6474     if (len == 0) { /* Empty inversion list */
6475         return;
6476     }
6477
6478     array = invlist_array(invlist);
6479
6480     /* Find which element it is */
6481     i = invlist_search(invlist, start);
6482
6483     /* We populate from <start> to <end> */
6484     while (current < end) {
6485         UV upper;
6486
6487         /* The inversion list gives the results for every possible code point
6488          * after the first one in the list.  Only those ranges whose index is
6489          * even are ones that the inversion list matches.  For the odd ones,
6490          * and if the initial code point is not in the list, we have to skip
6491          * forward to the next element */
6492         if (i == -1 || ! ELEMENT_RANGE_MATCHES_INVLIST(i)) {
6493             i++;
6494             if (i >= len) { /* Finished if beyond the end of the array */
6495                 return;
6496             }
6497             current = array[i];
6498             if (current >= end) {   /* Finished if beyond the end of what we
6499                                        are populating */
6500                 return;
6501             }
6502         }
6503         assert(current >= start);
6504
6505         /* The current range ends one below the next one, except don't go past
6506          * <end> */
6507         i++;
6508         upper = (i < len && array[i] < end) ? array[i] : end;
6509
6510         /* Here we are in a range that matches.  Populate a bit in the 3-bit U8
6511          * for each code point in it */
6512         for (; current < upper; current++) {
6513             const STRLEN offset = (STRLEN)(current - start);
6514             swatch[offset >> 3] |= 1 << (offset & 7);
6515         }
6516
6517         /* Quit if at the end of the list */
6518         if (i >= len) {
6519
6520             /* But first, have to deal with the highest possible code point on
6521              * the platform.  The previous code assumes that <end> is one
6522              * beyond where we want to populate, but that is impossible at the
6523              * platform's infinity, so have to handle it specially */
6524             if (UNLIKELY(end == UV_MAX && ELEMENT_RANGE_MATCHES_INVLIST(len-1)))
6525             {
6526                 const STRLEN offset = (STRLEN)(end - start);
6527                 swatch[offset >> 3] |= 1 << (offset & 7);
6528             }
6529             return;
6530         }
6531
6532         /* Advance to the next range, which will be for code points not in the
6533          * inversion list */
6534         current = array[i];
6535     }
6536
6537     return;
6538 }
6539
6540 void
6541 Perl__invlist_union(pTHX_ SV* const a, SV* const b, SV** output)
6542 {
6543     /* Take the union of two inversion lists and point <output> to it.  *output
6544      * should be defined upon input, and if it points to one of the two lists,
6545      * the reference count to that list will be decremented.
6546      * The basis for this comes from "Unicode Demystified" Chapter 13 by
6547      * Richard Gillam, published by Addison-Wesley, and explained at some
6548      * length there.  The preface says to incorporate its examples into your
6549      * code at your own risk.
6550      *
6551      * The algorithm is like a merge sort.
6552      *
6553      * XXX A potential performance improvement is to keep track as we go along
6554      * if only one of the inputs contributes to the result, meaning the other
6555      * is a subset of that one.  In that case, we can skip the final copy and
6556      * return the larger of the input lists, but then outside code might need
6557      * to keep track of whether to free the input list or not */
6558
6559     UV* array_a;    /* a's array */
6560     UV* array_b;
6561     UV len_a;       /* length of a's array */
6562     UV len_b;
6563
6564     SV* u;                      /* the resulting union */
6565     UV* array_u;
6566     UV len_u;
6567
6568     UV i_a = 0;             /* current index into a's array */
6569     UV i_b = 0;
6570     UV i_u = 0;
6571
6572     /* running count, as explained in the algorithm source book; items are
6573      * stopped accumulating and are output when the count changes to/from 0.
6574      * The count is incremented when we start a range that's in the set, and
6575      * decremented when we start a range that's not in the set.  So its range
6576      * is 0 to 2.  Only when the count is zero is something not in the set.
6577      */
6578     UV count = 0;
6579
6580     PERL_ARGS_ASSERT__INVLIST_UNION;
6581     assert(a != b);
6582
6583     /* If either one is empty, the union is the other one */
6584     len_a = invlist_len(a);
6585     if (len_a == 0) {
6586         if (*output == a) {
6587             SvREFCNT_dec(a);
6588         }
6589         if (*output != b) {
6590             *output = invlist_clone(b);
6591         } /* else *output already = b; */
6592         return;
6593     }
6594     else if ((len_b = invlist_len(b)) == 0) {
6595         if (*output == b) {
6596             SvREFCNT_dec(b);
6597         }
6598         if (*output != a) {
6599             *output = invlist_clone(a);
6600         }
6601         /* else *output already = a; */
6602         return;
6603     }
6604
6605     /* Here both lists exist and are non-empty */
6606     array_a = invlist_array(a);
6607     array_b = invlist_array(b);
6608
6609     /* Size the union for the worst case: that the sets are completely
6610      * disjoint */
6611     u = _new_invlist(len_a + len_b);
6612
6613     /* Will contain U+0000 if either component does */
6614     array_u = _invlist_array_init(u, (len_a > 0 && array_a[0] == 0)
6615                                       || (len_b > 0 && array_b[0] == 0));
6616
6617     /* Go through each list item by item, stopping when exhausted one of
6618      * them */
6619     while (i_a < len_a && i_b < len_b) {
6620         UV cp;      /* The element to potentially add to the union's array */
6621         bool cp_in_set;   /* is it in the the input list's set or not */
6622
6623         /* We need to take one or the other of the two inputs for the union.
6624          * Since we are merging two sorted lists, we take the smaller of the
6625          * next items.  In case of a tie, we take the one that is in its set
6626          * first.  If we took one not in the set first, it would decrement the
6627          * count, possibly to 0 which would cause it to be output as ending the
6628          * range, and the next time through we would take the same number, and
6629          * output it again as beginning the next range.  By doing it the
6630          * opposite way, there is no possibility that the count will be
6631          * momentarily decremented to 0, and thus the two adjoining ranges will
6632          * be seamlessly merged.  (In a tie and both are in the set or both not
6633          * in the set, it doesn't matter which we take first.) */
6634         if (array_a[i_a] < array_b[i_b]
6635             || (array_a[i_a] == array_b[i_b]
6636                 && ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
6637         {
6638             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
6639             cp= array_a[i_a++];
6640         }
6641         else {
6642             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
6643             cp= array_b[i_b++];
6644         }
6645
6646         /* Here, have chosen which of the two inputs to look at.  Only output
6647          * if the running count changes to/from 0, which marks the
6648          * beginning/end of a range in that's in the set */
6649         if (cp_in_set) {
6650             if (count == 0) {
6651                 array_u[i_u++] = cp;
6652             }
6653             count++;
6654         }
6655         else {
6656             count--;
6657             if (count == 0) {
6658                 array_u[i_u++] = cp;
6659             }
6660         }
6661     }
6662
6663     /* Here, we are finished going through at least one of the lists, which
6664      * means there is something remaining in at most one.  We check if the list
6665      * that hasn't been exhausted is positioned such that we are in the middle
6666      * of a range in its set or not.  (i_a and i_b point to the element beyond
6667      * the one we care about.) If in the set, we decrement 'count'; if 0, there
6668      * is potentially more to output.
6669      * There are four cases:
6670      *  1) Both weren't in their sets, count is 0, and remains 0.  What's left
6671      *     in the union is entirely from the non-exhausted set.
6672      *  2) Both were in their sets, count is 2.  Nothing further should
6673      *     be output, as everything that remains will be in the exhausted
6674      *     list's set, hence in the union; decrementing to 1 but not 0 insures
6675      *     that
6676      *  3) the exhausted was in its set, non-exhausted isn't, count is 1.
6677      *     Nothing further should be output because the union includes
6678      *     everything from the exhausted set.  Not decrementing ensures that.
6679      *  4) the exhausted wasn't in its set, non-exhausted is, count is 1;
6680      *     decrementing to 0 insures that we look at the remainder of the
6681      *     non-exhausted set */
6682     if ((i_a != len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
6683         || (i_b != len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
6684     {
6685         count--;
6686     }
6687
6688     /* The final length is what we've output so far, plus what else is about to
6689      * be output.  (If 'count' is non-zero, then the input list we exhausted
6690      * has everything remaining up to the machine's limit in its set, and hence
6691      * in the union, so there will be no further output. */
6692     len_u = i_u;
6693     if (count == 0) {
6694         /* At most one of the subexpressions will be non-zero */
6695         len_u += (len_a - i_a) + (len_b - i_b);
6696     }
6697
6698     /* Set result to final length, which can change the pointer to array_u, so
6699      * re-find it */
6700     if (len_u != invlist_len(u)) {
6701         invlist_set_len(u, len_u);
6702         invlist_trim(u);
6703         array_u = invlist_array(u);
6704     }
6705
6706     /* When 'count' is 0, the list that was exhausted (if one was shorter than
6707      * the other) ended with everything above it not in its set.  That means
6708      * that the remaining part of the union is precisely the same as the
6709      * non-exhausted list, so can just copy it unchanged.  (If both list were
6710      * exhausted at the same time, then the operations below will be both 0.)
6711      */
6712     if (count == 0) {
6713         IV copy_count; /* At most one will have a non-zero copy count */
6714         if ((copy_count = len_a - i_a) > 0) {
6715             Copy(array_a + i_a, array_u + i_u, copy_count, UV);
6716         }
6717         else if ((copy_count = len_b - i_b) > 0) {
6718             Copy(array_b + i_b, array_u + i_u, copy_count, UV);
6719         }
6720     }
6721
6722     /*  We may be removing a reference to one of the inputs */
6723     if (a == *output || b == *output) {
6724         SvREFCNT_dec(*output);
6725     }
6726
6727     *output = u;
6728     return;
6729 }
6730
6731 void
6732 Perl__invlist_intersection(pTHX_ SV* const a, SV* const b, SV** i)
6733 {
6734     /* Take the intersection of two inversion lists and point <i> to it.  *i
6735      * should be defined upon input, and if it points to one of the two lists,
6736      * the reference count to that list will be decremented.
6737      * The basis for this comes from "Unicode Demystified" Chapter 13 by
6738      * Richard Gillam, published by Addison-Wesley, and explained at some
6739      * length there.  The preface says to incorporate its examples into your
6740      * code at your own risk.  In fact, it had bugs
6741      *
6742      * The algorithm is like a merge sort, and is essentially the same as the
6743      * union above
6744      */
6745
6746     UV* array_a;                /* a's array */
6747     UV* array_b;
6748     UV len_a;   /* length of a's array */
6749     UV len_b;
6750
6751     SV* r;                   /* the resulting intersection */
6752     UV* array_r;
6753     UV len_r;
6754
6755     UV i_a = 0;             /* current index into a's array */
6756     UV i_b = 0;
6757     UV i_r = 0;
6758
6759     /* running count, as explained in the algorithm source book; items are
6760      * stopped accumulating and are output when the count changes to/from 2.
6761      * The count is incremented when we start a range that's in the set, and
6762      * decremented when we start a range that's not in the set.  So its range
6763      * is 0 to 2.  Only when the count is 2 is something in the intersection.
6764      */
6765     UV count = 0;
6766
6767     PERL_ARGS_ASSERT__INVLIST_INTERSECTION;
6768     assert(a != b);
6769
6770     /* If either one is empty, the intersection is null */
6771     len_a = invlist_len(a);
6772     if ((len_a == 0) || ((len_b = invlist_len(b)) == 0)) {
6773
6774         /* If the result is the same as one of the inputs, the input is being
6775          * overwritten */
6776         if (*i == a) {
6777             SvREFCNT_dec(a);
6778         }
6779         else if (*i == b) {
6780             SvREFCNT_dec(b);
6781         }
6782
6783         *i = _new_invlist(0);
6784         return;
6785     }
6786
6787     /* Here both lists exist and are non-empty */
6788     array_a = invlist_array(a);
6789     array_b = invlist_array(b);
6790
6791     /* Size the intersection for the worst case: that the intersection ends up
6792      * fragmenting everything to be completely disjoint */
6793     r= _new_invlist(len_a + len_b);
6794
6795     /* Will contain U+0000 iff both components do */
6796     array_r = _invlist_array_init(r, len_a > 0 && array_a[0] == 0
6797                                      && len_b > 0 && array_b[0] == 0);
6798
6799     /* Go through each list item by item, stopping when exhausted one of
6800      * them */
6801     while (i_a < len_a && i_b < len_b) {
6802         UV cp;      /* The element to potentially add to the intersection's
6803                        array */
6804         bool cp_in_set; /* Is it in the input list's set or not */
6805
6806         /* We need to take one or the other of the two inputs for the
6807          * intersection.  Since we are merging two sorted lists, we take the
6808          * smaller of the next items.  In case of a tie, we take the one that
6809          * is not in its set first (a difference from the union algorithm).  If
6810          * we took one in the set first, it would increment the count, possibly
6811          * to 2 which would cause it to be output as starting a range in the
6812          * intersection, and the next time through we would take that same
6813          * number, and output it again as ending the set.  By doing it the
6814          * opposite of this, there is no possibility that the count will be
6815          * momentarily incremented to 2.  (In a tie and both are in the set or
6816          * both not in the set, it doesn't matter which we take first.) */
6817         if (array_a[i_a] < array_b[i_b]
6818             || (array_a[i_a] == array_b[i_b]
6819                 && ! ELEMENT_RANGE_MATCHES_INVLIST(i_a)))
6820         {
6821             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_a);
6822             cp= array_a[i_a++];
6823         }
6824         else {
6825             cp_in_set = ELEMENT_RANGE_MATCHES_INVLIST(i_b);
6826             cp= array_b[i_b++];
6827         }
6828
6829         /* Here, have chosen which of the two inputs to look at.  Only output
6830          * if the running count changes to/from 2, which marks the
6831          * beginning/end of a range that's in the intersection */
6832         if (cp_in_set) {
6833             count++;
6834             if (count == 2) {
6835                 array_r[i_r++] = cp;
6836             }
6837         }
6838         else {
6839             if (count == 2) {
6840                 array_r[i_r++] = cp;
6841             }
6842             count--;
6843         }
6844     }
6845
6846     /* Here, we are finished going through at least one of the lists, which
6847      * means there is something remaining in at most one.  We check if the list
6848      * that has been exhausted is positioned such that we are in the middle
6849      * of a range in its set or not.  (i_a and i_b point to elements 1 beyond
6850      * the ones we care about.)  There are four cases:
6851      *  1) Both weren't in their sets, count is 0, and remains 0.  There's
6852      *     nothing left in the intersection.
6853      *  2) Both were in their sets, count is 2 and perhaps is incremented to
6854      *     above 2.  What should be output is exactly that which is in the
6855      *     non-exhausted set, as everything it has is also in the intersection
6856      *     set, and everything it doesn't have can't be in the intersection
6857      *  3) The exhausted was in its set, non-exhausted isn't, count is 1, and
6858      *     gets incremented to 2.  Like the previous case, the intersection is
6859      *     everything that remains in the non-exhausted set.
6860      *  4) the exhausted wasn't in its set, non-exhausted is, count is 1, and
6861      *     remains 1.  And the intersection has nothing more. */
6862     if ((i_a == len_a && PREV_RANGE_MATCHES_INVLIST(i_a))
6863         || (i_b == len_b && PREV_RANGE_MATCHES_INVLIST(i_b)))
6864     {
6865         count++;
6866     }
6867
6868     /* The final length is what we've output so far plus what else is in the
6869      * intersection.  At most one of the subexpressions below will be non-zero */
6870     len_r = i_r;
6871     if (count >= 2) {
6872         len_r += (len_a - i_a) + (len_b - i_b);
6873     }
6874
6875     /* Set result to final length, which can change the pointer to array_r, so
6876      * re-find it */
6877     if (len_r != invlist_len(r)) {
6878         invlist_set_len(r, len_r);
6879         invlist_trim(r);
6880         array_r = invlist_array(r);
6881     }
6882
6883     /* Finish outputting any remaining */
6884     if (count >= 2) { /* At most one will have a non-zero copy count */
6885         IV copy_count;
6886         if ((copy_count = len_a - i_a) > 0) {
6887             Copy(array_a + i_a, array_r + i_r, copy_count, UV);
6888         }
6889         else if ((copy_count = len_b - i_b) > 0) {
6890             Copy(array_b + i_b, array_r + i_r, copy_count, UV);
6891         }
6892     }
6893
6894     /*  We may be removing a reference to one of the inputs */
6895     if (a == *i || b == *i) {
6896         SvREFCNT_dec(*i);
6897     }
6898
6899     *i = r;
6900     return;
6901 }
6902
6903 #endif
6904
6905 STATIC SV*
6906 S_add_range_to_invlist(pTHX_ SV* invlist, const UV start, const UV end)
6907 {
6908     /* Add the range from 'start' to 'end' inclusive to the inversion list's
6909      * set.  A pointer to the inversion list is returned.  This may actually be
6910      * a new list, in which case the passed in one has been destroyed.  The
6911      * passed in inversion list can be NULL, in which case a new one is created
6912      * with just the one range in it */
6913
6914     SV* range_invlist;
6915     UV len;
6916
6917     if (invlist == NULL) {
6918         invlist = _new_invlist(2);
6919         len = 0;
6920     }
6921     else {
6922         len = invlist_len(invlist);
6923     }
6924
6925     /* If comes after the final entry, can just append it to the end */
6926     if (len == 0
6927         || start >= invlist_array(invlist)
6928                                     [invlist_len(invlist) - 1])
6929     {
6930         _append_range_to_invlist(invlist, start, end);
6931         return invlist;
6932     }
6933
6934     /* Here, can't just append things, create and return a new inversion list
6935      * which is the union of this range and the existing inversion list */
6936     range_invlist = _new_invlist(2);
6937     _append_range_to_invlist(range_invlist, start, end);
6938
6939     _invlist_union(invlist, range_invlist, &invlist);
6940
6941     /* The temporary can be freed */
6942     SvREFCNT_dec(range_invlist);
6943
6944     return invlist;
6945 }
6946
6947 PERL_STATIC_INLINE SV*
6948 S_add_cp_to_invlist(pTHX_ SV* invlist, const UV cp) {
6949     return add_range_to_invlist(invlist, cp, cp);
6950 }
6951
6952 #ifndef PERL_IN_XSUB_RE
6953 void
6954 Perl__invlist_invert(pTHX_ SV* const invlist)
6955 {
6956     /* Complement the input inversion list.  This adds a 0 if the list didn't
6957      * have a zero; removes it otherwise.  As described above, the data
6958      * structure is set up so that this is very efficient */
6959
6960     UV* len_pos = get_invlist_len_addr(invlist);
6961
6962     PERL_ARGS_ASSERT__INVLIST_INVERT;
6963
6964     /* The inverse of matching nothing is matching everything */
6965     if (*len_pos == 0) {
6966         _append_range_to_invlist(invlist, 0, UV_MAX);
6967         return;
6968     }
6969
6970     /* The exclusive or complents 0 to 1; and 1 to 0.  If the result is 1, the
6971      * zero element was a 0, so it is being removed, so the length decrements
6972      * by 1; and vice-versa.  SvCUR is unaffected */
6973     if (*get_invlist_zero_addr(invlist) ^= 1) {
6974         (*len_pos)--;
6975     }
6976     else {
6977         (*len_pos)++;
6978     }
6979 }
6980
6981 void
6982 Perl__invlist_invert_prop(pTHX_ SV* const invlist)
6983 {
6984     /* Complement the input inversion list (which must be a Unicode property,
6985      * all of which don't match above the Unicode maximum code point.)  And
6986      * Perl has chosen to not have the inversion match above that either.  This
6987      * adds a 0x110000 if the list didn't end with it, and removes it if it did
6988      */
6989
6990     UV len;
6991     UV* array;
6992
6993     PERL_ARGS_ASSERT__INVLIST_INVERT_PROP;
6994
6995     _invlist_invert(invlist);
6996
6997     len = invlist_len(invlist);
6998
6999     if (len != 0) { /* If empty do nothing */
7000         array = invlist_array(invlist);
7001         if (array[len - 1] != PERL_UNICODE_MAX + 1) {
7002             /* Add 0x110000.  First, grow if necessary */
7003             len++;
7004             if (invlist_max(invlist) < len) {
7005                 invlist_extend(invlist, len);
7006                 array = invlist_array(invlist);
7007             }
7008             invlist_set_len(invlist, len);
7009             array[len - 1] = PERL_UNICODE_MAX + 1;
7010         }
7011         else {  /* Remove the 0x110000 */
7012             invlist_set_len(invlist, len - 1);
7013         }
7014     }
7015
7016     return;
7017 }
7018 #endif
7019
7020 PERL_STATIC_INLINE SV*
7021 S_invlist_clone(pTHX_ SV* const invlist)
7022 {
7023
7024     /* Return a new inversion list that is a copy of the input one, which is
7025      * unchanged */
7026
7027     /* Need to allocate extra space to accommodate Perl's addition of a
7028      * trailing NUL to SvPV's, since it thinks they are always strings */
7029     SV* new_invlist = _new_invlist(invlist_len(invlist) + 1);
7030     STRLEN length = SvCUR(invlist);
7031
7032     PERL_ARGS_ASSERT_INVLIST_CLONE;
7033
7034     SvCUR_set(new_invlist, length); /* This isn't done automatically */
7035     Copy(SvPVX(invlist), SvPVX(new_invlist), length, char);
7036
7037     return new_invlist;
7038 }
7039
7040 #ifndef PERL_IN_XSUB_RE
7041 void
7042 Perl__invlist_subtract(pTHX_ SV* const a, SV* const b, SV** result)
7043 {
7044     /* Point <result> to an inversion list which consists of all elements in
7045      * <a> that aren't also in <b>.  *result should be defined upon input, and
7046      * if it points to C<b> its reference count will be decremented. */
7047
7048     PERL_ARGS_ASSERT__INVLIST_SUBTRACT;
7049     assert(a != b);
7050
7051     /* Subtracting nothing retains the original */
7052     if (invlist_len(b) == 0) {
7053
7054         if (*result == b) {
7055             SvREFCNT_dec(b);
7056         }
7057
7058         /* If the result is not to be the same variable as the original, create
7059          * a copy */
7060         if (*result != a) {
7061             *result = invlist_clone(a);
7062         }
7063     } else {
7064         SV *b_copy = invlist_clone(b);
7065         _invlist_invert(b_copy);        /* Everything not in 'b' */
7066
7067         if (*result == b) {
7068             SvREFCNT_dec(b);
7069         }
7070
7071         _invlist_intersection(a, b_copy, result);    /* Everything in 'a' not in
7072                                                        'b' */
7073         SvREFCNT_dec(b_copy);
7074     }
7075
7076     return;
7077 }
7078 #endif
7079
7080 PERL_STATIC_INLINE UV*
7081 S_get_invlist_iter_addr(pTHX_ SV* invlist)
7082 {
7083     /* Return the address of the UV that contains the current iteration
7084      * position */
7085
7086     PERL_ARGS_ASSERT_GET_INVLIST_ITER_ADDR;
7087
7088     return (UV *) (SvPVX(invlist) + (INVLIST_ITER_OFFSET * sizeof (UV)));
7089 }
7090
7091 PERL_STATIC_INLINE void
7092 S_invlist_iterinit(pTHX_ SV* invlist)   /* Initialize iterator for invlist */
7093 {
7094     PERL_ARGS_ASSERT_INVLIST_ITERINIT;
7095
7096     *get_invlist_iter_addr(invlist) = 0;
7097 }
7098
7099 STATIC bool
7100 S_invlist_iternext(pTHX_ SV* invlist, UV* start, UV* end)
7101 {
7102     /* An C<invlist_iterinit> call on <invlist> must be used to set this up.
7103      * This call sets in <*start> and <*end>, the next range in <invlist>.
7104      * Returns <TRUE> if successful and the next call will return the next
7105      * range; <FALSE> if was already at the end of the list.  If the latter,
7106      * <*start> and <*end> are unchanged, and the next call to this function
7107      * will start over at the beginning of the list */
7108
7109     UV* pos = get_invlist_iter_addr(invlist);
7110     UV len = invlist_len(invlist);
7111     UV *array;
7112
7113     PERL_ARGS_ASSERT_INVLIST_ITERNEXT;
7114
7115     if (*pos >= len) {
7116         *pos = UV_MAX;  /* Force iternit() to be required next time */
7117         return FALSE;
7118     }
7119
7120     array = invlist_array(invlist);
7121
7122     *start = array[(*pos)++];
7123
7124     if (*pos >= len) {
7125         *end = UV_MAX;
7126     }
7127     else {
7128         *end = array[(*pos)++] - 1;
7129     }
7130
7131     return TRUE;
7132 }
7133
7134 #ifndef PERL_IN_XSUB_RE
7135 SV *
7136 Perl__invlist_contents(pTHX_ SV* const invlist)
7137 {
7138     /* Get the contents of an inversion list into a string SV so that they can
7139      * be printed out.  It uses the format traditionally done for debug tracing
7140      */
7141
7142     UV start, end;
7143     SV* output = newSVpvs("\n");
7144
7145     PERL_ARGS_ASSERT__INVLIST_CONTENTS;
7146
7147     invlist_iterinit(invlist);
7148     while (invlist_iternext(invlist, &start, &end)) {
7149         if (end == UV_MAX) {
7150             Perl_sv_catpvf(aTHX_ output, "%04"UVXf"\tINFINITY\n", start);
7151         }
7152         else if (end != start) {
7153             Perl_sv_catpvf(aTHX_ output, "%04"UVXf"\t%04"UVXf"\n",
7154                     start,       end);
7155         }
7156         else {
7157             Perl_sv_catpvf(aTHX_ output, "%04"UVXf"\n", start);
7158         }
7159     }
7160
7161     return output;
7162 }
7163 #endif
7164
7165 #if 0
7166 void
7167 S_invlist_dump(pTHX_ SV* const invlist, const char * const header)
7168 {
7169     /* Dumps out the ranges in an inversion list.  The string 'header'
7170      * if present is output on a line before the first range */
7171
7172     UV start, end;
7173
7174     if (header && strlen(header)) {
7175         PerlIO_printf(Perl_debug_log, "%s\n", header);
7176     }
7177     invlist_iterinit(invlist);
7178     while (invlist_iternext(invlist, &start, &end)) {
7179         if (end == UV_MAX) {
7180             PerlIO_printf(Perl_debug_log, "0x%04"UVXf" .. INFINITY\n", start);
7181         }
7182         else {
7183             PerlIO_printf(Perl_debug_log, "0x%04"UVXf" .. 0x%04"UVXf"\n", start, end);
7184         }
7185     }
7186 }
7187 #endif
7188
7189 #undef HEADER_LENGTH
7190 #undef INVLIST_INITIAL_LENGTH
7191 #undef TO_INTERNAL_SIZE
7192 #undef FROM_INTERNAL_SIZE
7193 #undef INVLIST_LEN_OFFSET
7194 #undef INVLIST_ZERO_OFFSET
7195 #undef INVLIST_ITER_OFFSET
7196
7197 /* End of inversion list object */
7198
7199 /*
7200  - reg - regular expression, i.e. main body or parenthesized thing
7201  *
7202  * Caller must absorb opening parenthesis.
7203  *
7204  * Combining parenthesis handling with the base level of regular expression
7205  * is a trifle forced, but the need to tie the tails of the branches to what
7206  * follows makes it hard to avoid.
7207  */
7208 #define REGTAIL(x,y,z) regtail((x),(y),(z),depth+1)
7209 #ifdef DEBUGGING
7210 #define REGTAIL_STUDY(x,y,z) regtail_study((x),(y),(z),depth+1)
7211 #else
7212 #define REGTAIL_STUDY(x,y,z) regtail((x),(y),(z),depth+1)
7213 #endif
7214
7215 STATIC regnode *
7216 S_reg(pTHX_ RExC_state_t *pRExC_state, I32 paren, I32 *flagp,U32 depth)
7217     /* paren: Parenthesized? 0=top, 1=(, inside: changed to letter. */
7218 {
7219     dVAR;
7220     register regnode *ret;              /* Will be the head of the group. */
7221     register regnode *br;
7222     register regnode *lastbr;
7223     register regnode *ender = NULL;
7224     register I32 parno = 0;
7225     I32 flags;
7226     U32 oregflags = RExC_flags;
7227     bool have_branch = 0;
7228     bool is_open = 0;
7229     I32 freeze_paren = 0;
7230     I32 after_freeze = 0;
7231
7232     /* for (?g), (?gc), and (?o) warnings; warning
7233        about (?c) will warn about (?g) -- japhy    */
7234
7235 #define WASTED_O  0x01
7236 #define WASTED_G  0x02
7237 #define WASTED_C  0x04
7238 #define WASTED_GC (0x02|0x04)
7239     I32 wastedflags = 0x00;
7240
7241     char * parse_start = RExC_parse; /* MJD */
7242     char * const oregcomp_parse = RExC_parse;
7243
7244     GET_RE_DEBUG_FLAGS_DECL;
7245
7246     PERL_ARGS_ASSERT_REG;
7247     DEBUG_PARSE("reg ");
7248
7249     *flagp = 0;                         /* Tentatively. */
7250
7251
7252     /* Make an OPEN node, if parenthesized. */
7253     if (paren) {
7254         if ( *RExC_parse == '*') { /* (*VERB:ARG) */
7255             char *start_verb = RExC_parse;
7256             STRLEN verb_len = 0;
7257             char *start_arg = NULL;
7258             unsigned char op = 0;
7259             int argok = 1;
7260             int internal_argval = 0; /* internal_argval is only useful if !argok */
7261             while ( *RExC_parse && *RExC_parse != ')' ) {
7262                 if ( *RExC_parse == ':' ) {
7263                     start_arg = RExC_parse + 1;
7264                     break;
7265                 }
7266                 RExC_parse++;
7267             }
7268             ++start_verb;
7269             verb_len = RExC_parse - start_verb;
7270             if ( start_arg ) {
7271                 RExC_parse++;
7272                 while ( *RExC_parse && *RExC_parse != ')' ) 
7273                     RExC_parse++;
7274                 if ( *RExC_parse != ')' ) 
7275                     vFAIL("Unterminated verb pattern argument");
7276                 if ( RExC_parse == start_arg )
7277                     start_arg = NULL;
7278             } else {
7279                 if ( *RExC_parse != ')' )
7280                     vFAIL("Unterminated verb pattern");
7281             }
7282             
7283             switch ( *start_verb ) {
7284             case 'A':  /* (*ACCEPT) */
7285                 if ( memEQs(start_verb,verb_len,"ACCEPT") ) {
7286                     op = ACCEPT;
7287                     internal_argval = RExC_nestroot;
7288                 }
7289                 break;
7290             case 'C':  /* (*COMMIT) */
7291                 if ( memEQs(start_verb,verb_len,"COMMIT") )
7292                     op = COMMIT;
7293                 break;
7294             case 'F':  /* (*FAIL) */
7295                 if ( verb_len==1 || memEQs(start_verb,verb_len,"FAIL") ) {
7296                     op = OPFAIL;
7297                     argok = 0;
7298                 }
7299                 break;
7300             case ':':  /* (*:NAME) */
7301             case 'M':  /* (*MARK:NAME) */
7302                 if ( verb_len==0 || memEQs(start_verb,verb_len,"MARK") ) {
7303                     op = MARKPOINT;
7304                     argok = -1;
7305                 }
7306                 break;
7307             case 'P':  /* (*PRUNE) */
7308                 if ( memEQs(start_verb,verb_len,"PRUNE") )
7309                     op = PRUNE;
7310                 break;
7311             case 'S':   /* (*SKIP) */  
7312                 if ( memEQs(start_verb,verb_len,"SKIP") ) 
7313                     op = SKIP;
7314                 break;
7315             case 'T':  /* (*THEN) */
7316                 /* [19:06] <TimToady> :: is then */
7317                 if ( memEQs(start_verb,verb_len,"THEN") ) {
7318                     op = CUTGROUP;
7319                     RExC_seen |= REG_SEEN_CUTGROUP;
7320                 }
7321                 break;
7322             }
7323             if ( ! op ) {
7324                 RExC_parse++;
7325                 vFAIL3("Unknown verb pattern '%.*s'",
7326                     verb_len, start_verb);
7327             }
7328             if ( argok ) {
7329                 if ( start_arg && internal_argval ) {
7330                     vFAIL3("Verb pattern '%.*s' may not have an argument",
7331                         verb_len, start_verb); 
7332                 } else if ( argok < 0 && !start_arg ) {
7333                     vFAIL3("Verb pattern '%.*s' has a mandatory argument",
7334                         verb_len, start_verb);    
7335                 } else {
7336                     ret = reganode(pRExC_state, op, internal_argval);
7337                     if ( ! internal_argval && ! SIZE_ONLY ) {
7338                         if (start_arg) {
7339                             SV *sv = newSVpvn( start_arg, RExC_parse - start_arg);
7340                             ARG(ret) = add_data( pRExC_state, 1, "S" );
7341                             RExC_rxi->data->data[ARG(ret)]=(void*)sv;
7342                             ret->flags = 0;
7343                         } else {
7344                             ret->flags = 1; 
7345                         }
7346                     }               
7347                 }
7348                 if (!internal_argval)
7349                     RExC_seen |= REG_SEEN_VERBARG;
7350             } else if ( start_arg ) {
7351                 vFAIL3("Verb pattern '%.*s' may not have an argument",
7352                         verb_len, start_verb);    
7353             } else {
7354                 ret = reg_node(pRExC_state, op);
7355             }
7356             nextchar(pRExC_state);
7357             return ret;
7358         } else 
7359         if (*RExC_parse == '?') { /* (?...) */
7360             bool is_logical = 0;
7361             const char * const seqstart = RExC_parse;
7362             bool has_use_defaults = FALSE;
7363
7364             RExC_parse++;
7365             paren = *RExC_parse++;
7366             ret = NULL;                 /* For look-ahead/behind. */
7367             switch (paren) {
7368
7369             case 'P':   /* (?P...) variants for those used to PCRE/Python */
7370                 paren = *RExC_parse++;
7371                 if ( paren == '<')         /* (?P<...>) named capture */
7372                     goto named_capture;
7373                 else if (paren == '>') {   /* (?P>name) named recursion */
7374                     goto named_recursion;
7375                 }
7376                 else if (paren == '=') {   /* (?P=...)  named backref */
7377                     /* this pretty much dupes the code for \k<NAME> in regatom(), if
7378                        you change this make sure you change that */
7379                     char* name_start = RExC_parse;
7380                     U32 num = 0;
7381                     SV *sv_dat = reg_scan_name(pRExC_state,
7382                         SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
7383                     if (RExC_parse == name_start || *RExC_parse != ')')
7384                         vFAIL2("Sequence %.3s... not terminated",parse_start);
7385
7386                     if (!SIZE_ONLY) {
7387                         num = add_data( pRExC_state, 1, "S" );
7388                         RExC_rxi->data->data[num]=(void*)sv_dat;
7389                         SvREFCNT_inc_simple_void(sv_dat);
7390                     }
7391                     RExC_sawback = 1;
7392                     ret = reganode(pRExC_state,
7393                                    ((! FOLD)
7394                                      ? NREF
7395                                      : (MORE_ASCII_RESTRICTED)
7396                                        ? NREFFA
7397                                        : (AT_LEAST_UNI_SEMANTICS)
7398                                          ? NREFFU
7399                                          : (LOC)
7400                                            ? NREFFL
7401                                            : NREFF),
7402                                     num);
7403                     *flagp |= HASWIDTH;
7404
7405                     Set_Node_Offset(ret, parse_start+1);
7406                     Set_Node_Cur_Length(ret); /* MJD */
7407
7408                     nextchar(pRExC_state);
7409                     return ret;
7410                 }
7411                 RExC_parse++;
7412                 vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
7413                 /*NOTREACHED*/
7414             case '<':           /* (?<...) */
7415                 if (*RExC_parse == '!')
7416                     paren = ',';
7417                 else if (*RExC_parse != '=') 
7418               named_capture:
7419                 {               /* (?<...>) */
7420                     char *name_start;
7421                     SV *svname;
7422                     paren= '>';
7423             case '\'':          /* (?'...') */
7424                     name_start= RExC_parse;
7425                     svname = reg_scan_name(pRExC_state,
7426                         SIZE_ONLY ?  /* reverse test from the others */
7427                         REG_RSN_RETURN_NAME : 
7428                         REG_RSN_RETURN_NULL);
7429                     if (RExC_parse == name_start) {
7430                         RExC_parse++;
7431                         vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
7432                         /*NOTREACHED*/
7433                     }
7434                     if (*RExC_parse != paren)
7435                         vFAIL2("Sequence (?%c... not terminated",
7436                             paren=='>' ? '<' : paren);
7437                     if (SIZE_ONLY) {
7438                         HE *he_str;
7439                         SV *sv_dat = NULL;
7440                         if (!svname) /* shouldn't happen */
7441                             Perl_croak(aTHX_
7442                                 "panic: reg_scan_name returned NULL");
7443                         if (!RExC_paren_names) {
7444                             RExC_paren_names= newHV();
7445                             sv_2mortal(MUTABLE_SV(RExC_paren_names));
7446 #ifdef DEBUGGING
7447                             RExC_paren_name_list= newAV();
7448                             sv_2mortal(MUTABLE_SV(RExC_paren_name_list));
7449 #endif
7450                         }
7451                         he_str = hv_fetch_ent( RExC_paren_names, svname, 1, 0 );
7452                         if ( he_str )
7453                             sv_dat = HeVAL(he_str);
7454                         if ( ! sv_dat ) {
7455                             /* croak baby croak */
7456                             Perl_croak(aTHX_
7457                                 "panic: paren_name hash element allocation failed");
7458                         } else if ( SvPOK(sv_dat) ) {
7459                             /* (?|...) can mean we have dupes so scan to check
7460                                its already been stored. Maybe a flag indicating
7461                                we are inside such a construct would be useful,
7462                                but the arrays are likely to be quite small, so
7463                                for now we punt -- dmq */
7464                             IV count = SvIV(sv_dat);
7465                             I32 *pv = (I32*)SvPVX(sv_dat);
7466                             IV i;
7467                             for ( i = 0 ; i < count ; i++ ) {
7468                                 if ( pv[i] == RExC_npar ) {
7469                                     count = 0;
7470                                     break;
7471                                 }
7472                             }
7473                             if ( count ) {
7474                                 pv = (I32*)SvGROW(sv_dat, SvCUR(sv_dat) + sizeof(I32)+1);
7475                                 SvCUR_set(sv_dat, SvCUR(sv_dat) + sizeof(I32));
7476                                 pv[count] = RExC_npar;
7477                                 SvIV_set(sv_dat, SvIVX(sv_dat) + 1);
7478                             }
7479                         } else {
7480                             (void)SvUPGRADE(sv_dat,SVt_PVNV);
7481                             sv_setpvn(sv_dat, (char *)&(RExC_npar), sizeof(I32));
7482                             SvIOK_on(sv_dat);
7483                             SvIV_set(sv_dat, 1);
7484                         }
7485 #ifdef DEBUGGING
7486                         /* Yes this does cause a memory leak in debugging Perls */
7487                         if (!av_store(RExC_paren_name_list, RExC_npar, SvREFCNT_inc(svname)))
7488                             SvREFCNT_dec(svname);
7489 #endif
7490
7491                         /*sv_dump(sv_dat);*/
7492                     }
7493                     nextchar(pRExC_state);
7494                     paren = 1;
7495                     goto capturing_parens;
7496                 }
7497                 RExC_seen |= REG_SEEN_LOOKBEHIND;
7498                 RExC_in_lookbehind++;
7499                 RExC_parse++;
7500             case '=':           /* (?=...) */
7501                 RExC_seen_zerolen++;
7502                 break;
7503             case '!':           /* (?!...) */
7504                 RExC_seen_zerolen++;
7505                 if (*RExC_parse == ')') {
7506                     ret=reg_node(pRExC_state, OPFAIL);
7507                     nextchar(pRExC_state);
7508                     return ret;
7509                 }
7510                 break;
7511             case '|':           /* (?|...) */
7512                 /* branch reset, behave like a (?:...) except that
7513                    buffers in alternations share the same numbers */
7514                 paren = ':'; 
7515                 after_freeze = freeze_paren = RExC_npar;
7516                 break;
7517             case ':':           /* (?:...) */
7518             case '>':           /* (?>...) */
7519                 break;
7520             case '$':           /* (?$...) */
7521             case '@':           /* (?@...) */
7522                 vFAIL2("Sequence (?%c...) not implemented", (int)paren);
7523                 break;
7524             case '#':           /* (?#...) */
7525                 while (*RExC_parse && *RExC_parse != ')')
7526                     RExC_parse++;
7527                 if (*RExC_parse != ')')
7528                     FAIL("Sequence (?#... not terminated");
7529                 nextchar(pRExC_state);
7530                 *flagp = TRYAGAIN;
7531                 return NULL;
7532             case '0' :           /* (?0) */
7533             case 'R' :           /* (?R) */
7534                 if (*RExC_parse != ')')
7535                     FAIL("Sequence (?R) not terminated");
7536                 ret = reg_node(pRExC_state, GOSTART);
7537                 *flagp |= POSTPONED;
7538                 nextchar(pRExC_state);
7539                 return ret;
7540                 /*notreached*/
7541             { /* named and numeric backreferences */
7542                 I32 num;
7543             case '&':            /* (?&NAME) */
7544                 parse_start = RExC_parse - 1;
7545               named_recursion:
7546                 {
7547                     SV *sv_dat = reg_scan_name(pRExC_state,
7548                         SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
7549                      num = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
7550                 }
7551                 goto gen_recurse_regop;
7552                 /* NOT REACHED */
7553             case '+':
7554                 if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
7555                     RExC_parse++;
7556                     vFAIL("Illegal pattern");
7557                 }
7558                 goto parse_recursion;
7559                 /* NOT REACHED*/
7560             case '-': /* (?-1) */
7561                 if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
7562                     RExC_parse--; /* rewind to let it be handled later */
7563                     goto parse_flags;
7564                 } 
7565                 /*FALLTHROUGH */
7566             case '1': case '2': case '3': case '4': /* (?1) */
7567             case '5': case '6': case '7': case '8': case '9':
7568                 RExC_parse--;
7569               parse_recursion:
7570                 num = atoi(RExC_parse);
7571                 parse_start = RExC_parse - 1; /* MJD */
7572                 if (*RExC_parse == '-')
7573                     RExC_parse++;
7574                 while (isDIGIT(*RExC_parse))
7575                         RExC_parse++;
7576                 if (*RExC_parse!=')') 
7577                     vFAIL("Expecting close bracket");
7578
7579               gen_recurse_regop:
7580                 if ( paren == '-' ) {
7581                     /*
7582                     Diagram of capture buffer numbering.
7583                     Top line is the normal capture buffer numbers
7584                     Bottom line is the negative indexing as from
7585                     the X (the (?-2))
7586
7587                     +   1 2    3 4 5 X          6 7
7588                        /(a(x)y)(a(b(c(?-2)d)e)f)(g(h))/
7589                     -   5 4    3 2 1 X          x x
7590
7591                     */
7592                     num = RExC_npar + num;
7593                     if (num < 1)  {
7594                         RExC_parse++;
7595                         vFAIL("Reference to nonexistent group");
7596                     }
7597                 } else if ( paren == '+' ) {
7598                     num = RExC_npar + num - 1;
7599                 }
7600
7601                 ret = reganode(pRExC_state, GOSUB, num);
7602                 if (!SIZE_ONLY) {
7603                     if (num > (I32)RExC_rx->nparens) {
7604                         RExC_parse++;
7605                         vFAIL("Reference to nonexistent group");
7606                     }
7607                     ARG2L_SET( ret, RExC_recurse_count++);
7608                     RExC_emit++;
7609                     DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
7610                         "Recurse #%"UVuf" to %"IVdf"\n", (UV)ARG(ret), (IV)ARG2L(ret)));
7611                 } else {
7612                     RExC_size++;
7613                 }
7614                 RExC_seen |= REG_SEEN_RECURSE;
7615                 Set_Node_Length(ret, 1 + regarglen[OP(ret)]); /* MJD */
7616                 Set_Node_Offset(ret, parse_start); /* MJD */
7617
7618                 *flagp |= POSTPONED;
7619                 nextchar(pRExC_state);
7620                 return ret;
7621             } /* named and numeric backreferences */
7622             /* NOT REACHED */
7623
7624             case '?':           /* (??...) */
7625                 is_logical = 1;
7626                 if (*RExC_parse != '{') {
7627                     RExC_parse++;
7628                     vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
7629                     /*NOTREACHED*/
7630                 }
7631                 *flagp |= POSTPONED;
7632                 paren = *RExC_parse++;
7633                 /* FALL THROUGH */
7634             case '{':           /* (?{...}) */
7635             {
7636                 I32 count = 1;
7637                 U32 n = 0;
7638                 char c;
7639                 char *s = RExC_parse;
7640
7641                 RExC_seen_zerolen++;
7642                 RExC_seen |= REG_SEEN_EVAL;
7643                 while (count && (c = *RExC_parse)) {
7644                     if (c == '\\') {
7645                         if (RExC_parse[1])
7646                             RExC_parse++;
7647                     }
7648                     else if (c == '{')
7649                         count++;
7650                     else if (c == '}')
7651                         count--;
7652                     RExC_parse++;
7653                 }
7654                 if (*RExC_parse != ')') {
7655                     RExC_parse = s;
7656                     vFAIL("Sequence (?{...}) not terminated or not {}-balanced");
7657                 }
7658                 if (!SIZE_ONLY) {
7659                     PAD *pad;
7660                     OP_4tree *sop, *rop;
7661                     SV * const sv = newSVpvn(s, RExC_parse - 1 - s);
7662
7663                     ENTER;
7664                     Perl_save_re_context(aTHX);
7665                     rop = Perl_sv_compile_2op_is_broken(aTHX_ sv, &sop, "re", &pad);
7666                     sop->op_private |= OPpREFCOUNTED;
7667                     /* re_dup will OpREFCNT_inc */
7668                     OpREFCNT_set(sop, 1);
7669                     LEAVE;
7670
7671                     n = add_data(pRExC_state, 3, "nop");
7672                     RExC_rxi->data->data[n] = (void*)rop;
7673                     RExC_rxi->data->data[n+1] = (void*)sop;
7674                     RExC_rxi->data->data[n+2] = (void*)pad;
7675                     SvREFCNT_dec(sv);
7676                 }
7677                 else {                                          /* First pass */
7678                     if (PL_reginterp_cnt < ++RExC_seen_evals
7679                         && IN_PERL_RUNTIME)
7680                         /* No compiled RE interpolated, has runtime
7681                            components ===> unsafe.  */
7682                         FAIL("Eval-group not allowed at runtime, use re 'eval'");
7683                     if (PL_tainting && PL_tainted)
7684                         FAIL("Eval-group in insecure regular expression");
7685 #if PERL_VERSION > 8
7686                     if (IN_PERL_COMPILETIME)
7687                         PL_cv_has_eval = 1;
7688 #endif
7689                 }
7690
7691                 nextchar(pRExC_state);
7692                 if (is_logical) {
7693                     ret = reg_node(pRExC_state, LOGICAL);
7694                     if (!SIZE_ONLY)
7695                         ret->flags = 2;
7696                     REGTAIL(pRExC_state, ret, reganode(pRExC_state, EVAL, n));
7697                     /* deal with the length of this later - MJD */
7698                     return ret;
7699                 }
7700                 ret = reganode(pRExC_state, EVAL, n);
7701                 Set_Node_Length(ret, RExC_parse - parse_start + 1);
7702                 Set_Node_Offset(ret, parse_start);
7703                 return ret;
7704             }
7705             case '(':           /* (?(?{...})...) and (?(?=...)...) */
7706             {
7707                 int is_define= 0;
7708                 if (RExC_parse[0] == '?') {        /* (?(?...)) */
7709                     if (RExC_parse[1] == '=' || RExC_parse[1] == '!'
7710                         || RExC_parse[1] == '<'
7711                         || RExC_parse[1] == '{') { /* Lookahead or eval. */
7712                         I32 flag;
7713
7714                         ret = reg_node(pRExC_state, LOGICAL);
7715                         if (!SIZE_ONLY)
7716                             ret->flags = 1;
7717                         REGTAIL(pRExC_state, ret, reg(pRExC_state, 1, &flag,depth+1));
7718                         goto insert_if;
7719                     }
7720                 }
7721                 else if ( RExC_parse[0] == '<'     /* (?(<NAME>)...) */
7722                          || RExC_parse[0] == '\'' ) /* (?('NAME')...) */
7723                 {
7724                     char ch = RExC_parse[0] == '<' ? '>' : '\'';
7725                     char *name_start= RExC_parse++;
7726                     U32 num = 0;
7727                     SV *sv_dat=reg_scan_name(pRExC_state,
7728                         SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
7729                     if (RExC_parse == name_start || *RExC_parse != ch)
7730                         vFAIL2("Sequence (?(%c... not terminated",
7731                             (ch == '>' ? '<' : ch));
7732                     RExC_parse++;
7733                     if (!SIZE_ONLY) {
7734                         num = add_data( pRExC_state, 1, "S" );
7735                         RExC_rxi->data->data[num]=(void*)sv_dat;
7736                         SvREFCNT_inc_simple_void(sv_dat);
7737                     }
7738                     ret = reganode(pRExC_state,NGROUPP,num);
7739                     goto insert_if_check_paren;
7740                 }
7741                 else if (RExC_parse[0] == 'D' &&
7742                          RExC_parse[1] == 'E' &&
7743                          RExC_parse[2] == 'F' &&
7744                          RExC_parse[3] == 'I' &&
7745                          RExC_parse[4] == 'N' &&
7746                          RExC_parse[5] == 'E')
7747                 {
7748                     ret = reganode(pRExC_state,DEFINEP,0);
7749                     RExC_parse +=6 ;
7750                     is_define = 1;
7751                     goto insert_if_check_paren;
7752                 }
7753                 else if (RExC_parse[0] == 'R') {
7754                     RExC_parse++;
7755                     parno = 0;
7756                     if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
7757                         parno = atoi(RExC_parse++);
7758                         while (isDIGIT(*RExC_parse))
7759                             RExC_parse++;
7760                     } else if (RExC_parse[0] == '&') {
7761                         SV *sv_dat;
7762                         RExC_parse++;
7763                         sv_dat = reg_scan_name(pRExC_state,
7764                             SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
7765                         parno = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
7766                     }
7767                     ret = reganode(pRExC_state,INSUBP,parno); 
7768                     goto insert_if_check_paren;
7769                 }
7770                 else if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
7771                     /* (?(1)...) */
7772                     char c;
7773                     parno = atoi(RExC_parse++);
7774
7775                     while (isDIGIT(*RExC_parse))
7776                         RExC_parse++;
7777                     ret = reganode(pRExC_state, GROUPP, parno);
7778
7779                  insert_if_check_paren:
7780                     if ((c = *nextchar(pRExC_state)) != ')')
7781                         vFAIL("Switch condition not recognized");
7782                   insert_if:
7783                     REGTAIL(pRExC_state, ret, reganode(pRExC_state, IFTHEN, 0));
7784                     br = regbranch(pRExC_state, &flags, 1,depth+1);
7785                     if (br == NULL)
7786                         br = reganode(pRExC_state, LONGJMP, 0);
7787                     else
7788                         REGTAIL(pRExC_state, br, reganode(pRExC_state, LONGJMP, 0));
7789                     c = *nextchar(pRExC_state);
7790                     if (flags&HASWIDTH)
7791                         *flagp |= HASWIDTH;
7792                     if (c == '|') {
7793                         if (is_define) 
7794                             vFAIL("(?(DEFINE)....) does not allow branches");
7795                         lastbr = reganode(pRExC_state, IFTHEN, 0); /* Fake one for optimizer. */
7796                         regbranch(pRExC_state, &flags, 1,depth+1);
7797                         REGTAIL(pRExC_state, ret, lastbr);
7798                         if (flags&HASWIDTH)
7799                             *flagp |= HASWIDTH;
7800                         c = *nextchar(pRExC_state);
7801                     }
7802                     else
7803                         lastbr = NULL;
7804                     if (c != ')')
7805                         vFAIL("Switch (?(condition)... contains too many branches");
7806                     ender = reg_node(pRExC_state, TAIL);
7807                     REGTAIL(pRExC_state, br, ender);
7808                     if (lastbr) {
7809                         REGTAIL(pRExC_state, lastbr, ender);
7810                         REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender);
7811                     }
7812                     else
7813                         REGTAIL(pRExC_state, ret, ender);
7814                     RExC_size++; /* XXX WHY do we need this?!!
7815                                     For large programs it seems to be required
7816                                     but I can't figure out why. -- dmq*/
7817                     return ret;
7818                 }
7819                 else {
7820                     vFAIL2("Unknown switch condition (?(%.2s", RExC_parse);
7821                 }
7822             }
7823             case 0:
7824                 RExC_parse--; /* for vFAIL to print correctly */
7825                 vFAIL("Sequence (? incomplete");
7826                 break;
7827             case DEFAULT_PAT_MOD:   /* Use default flags with the exceptions
7828                                        that follow */
7829                 has_use_defaults = TRUE;
7830                 STD_PMMOD_FLAGS_CLEAR(&RExC_flags);
7831                 set_regex_charset(&RExC_flags, (RExC_utf8 || RExC_uni_semantics)
7832                                                 ? REGEX_UNICODE_CHARSET
7833                                                 : REGEX_DEPENDS_CHARSET);
7834                 goto parse_flags;
7835             default:
7836                 --RExC_parse;
7837                 parse_flags:      /* (?i) */  
7838             {
7839                 U32 posflags = 0, negflags = 0;
7840                 U32 *flagsp = &posflags;
7841                 char has_charset_modifier = '\0';
7842                 regex_charset cs = (RExC_utf8 || RExC_uni_semantics)
7843                                     ? REGEX_UNICODE_CHARSET
7844                                     : REGEX_DEPENDS_CHARSET;
7845
7846                 while (*RExC_parse) {
7847                     /* && strchr("iogcmsx", *RExC_parse) */
7848                     /* (?g), (?gc) and (?o) are useless here
7849                        and must be globally applied -- japhy */
7850                     switch (*RExC_parse) {
7851                     CASE_STD_PMMOD_FLAGS_PARSE_SET(flagsp);
7852                     case LOCALE_PAT_MOD:
7853                         if (has_charset_modifier) {
7854                             goto excess_modifier;
7855                         }
7856                         else if (flagsp == &negflags) {
7857                             goto neg_modifier;
7858                         }
7859                         cs = REGEX_LOCALE_CHARSET;
7860                         has_charset_modifier = LOCALE_PAT_MOD;
7861                         RExC_contains_locale = 1;
7862                         break;
7863                     case UNICODE_PAT_MOD:
7864                         if (has_charset_modifier) {
7865                             goto excess_modifier;
7866                         }
7867                         else if (flagsp == &negflags) {
7868                             goto neg_modifier;
7869                         }
7870                         cs = REGEX_UNICODE_CHARSET;
7871                         has_charset_modifier = UNICODE_PAT_MOD;
7872                         break;
7873                     case ASCII_RESTRICT_PAT_MOD:
7874                         if (flagsp == &negflags) {
7875                             goto neg_modifier;
7876                         }
7877                         if (has_charset_modifier) {
7878                             if (cs != REGEX_ASCII_RESTRICTED_CHARSET) {
7879                                 goto excess_modifier;
7880                             }
7881                             /* Doubled modifier implies more restricted */
7882                             cs = REGEX_ASCII_MORE_RESTRICTED_CHARSET;
7883                         }
7884                         else {
7885                             cs = REGEX_ASCII_RESTRICTED_CHARSET;
7886                         }
7887                         has_charset_modifier = ASCII_RESTRICT_PAT_MOD;
7888                         break;
7889                     case DEPENDS_PAT_MOD:
7890                         if (has_use_defaults) {
7891                             goto fail_modifiers;
7892                         }
7893                         else if (flagsp == &negflags) {
7894                             goto neg_modifier;
7895                         }
7896                         else if (has_charset_modifier) {
7897                             goto excess_modifier;
7898                         }
7899
7900                         /* The dual charset means unicode semantics if the
7901                          * pattern (or target, not known until runtime) are
7902                          * utf8, or something in the pattern indicates unicode
7903                          * semantics */
7904                         cs = (RExC_utf8 || RExC_uni_semantics)
7905                              ? REGEX_UNICODE_CHARSET
7906                              : REGEX_DEPENDS_CHARSET;
7907                         has_charset_modifier = DEPENDS_PAT_MOD;
7908                         break;
7909                     excess_modifier:
7910                         RExC_parse++;
7911                         if (has_charset_modifier == ASCII_RESTRICT_PAT_MOD) {
7912                             vFAIL2("Regexp modifier \"%c\" may appear a maximum of twice", ASCII_RESTRICT_PAT_MOD);
7913                         }
7914                         else if (has_charset_modifier == *(RExC_parse - 1)) {
7915                             vFAIL2("Regexp modifier \"%c\" may not appear twice", *(RExC_parse - 1));
7916                         }
7917                         else {
7918                             vFAIL3("Regexp modifiers \"%c\" and \"%c\" are mutually exclusive", has_charset_modifier, *(RExC_parse - 1));
7919                         }
7920                         /*NOTREACHED*/
7921                     neg_modifier:
7922                         RExC_parse++;
7923                         vFAIL2("Regexp modifier \"%c\" may not appear after the \"-\"", *(RExC_parse - 1));
7924                         /*NOTREACHED*/
7925                     case ONCE_PAT_MOD: /* 'o' */
7926                     case GLOBAL_PAT_MOD: /* 'g' */
7927                         if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
7928                             const I32 wflagbit = *RExC_parse == 'o' ? WASTED_O : WASTED_G;
7929                             if (! (wastedflags & wflagbit) ) {
7930                                 wastedflags |= wflagbit;
7931                                 vWARN5(
7932                                     RExC_parse + 1,
7933                                     "Useless (%s%c) - %suse /%c modifier",
7934                                     flagsp == &negflags ? "?-" : "?",
7935                                     *RExC_parse,
7936                                     flagsp == &negflags ? "don't " : "",
7937                                     *RExC_parse
7938                                 );
7939                             }
7940                         }
7941                         break;
7942                         
7943                     case CONTINUE_PAT_MOD: /* 'c' */
7944                         if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
7945                             if (! (wastedflags & WASTED_C) ) {
7946                                 wastedflags |= WASTED_GC;
7947                                 vWARN3(
7948                                     RExC_parse + 1,
7949                                     "Useless (%sc) - %suse /gc modifier",
7950                                     flagsp == &negflags ? "?-" : "?",
7951                                     flagsp == &negflags ? "don't " : ""
7952                                 );
7953                             }
7954                         }
7955                         break;
7956                     case KEEPCOPY_PAT_MOD: /* 'p' */
7957                         if (flagsp == &negflags) {
7958                             if (SIZE_ONLY)
7959                                 ckWARNreg(RExC_parse + 1,"Useless use of (?-p)");
7960                         } else {
7961                             *flagsp |= RXf_PMf_KEEPCOPY;
7962                         }
7963                         break;
7964                     case '-':
7965                         /* A flag is a default iff it is following a minus, so
7966                          * if there is a minus, it means will be trying to
7967                          * re-specify a default which is an error */
7968                         if (has_use_defaults || flagsp == &negflags) {
7969             fail_modifiers:
7970                             RExC_parse++;
7971                             vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
7972                             /*NOTREACHED*/
7973                         }
7974                         flagsp = &negflags;
7975                         wastedflags = 0;  /* reset so (?g-c) warns twice */
7976                         break;
7977                     case ':':
7978                         paren = ':';
7979                         /*FALLTHROUGH*/
7980                     case ')':
7981                         RExC_flags |= posflags;
7982                         RExC_flags &= ~negflags;
7983                         set_regex_charset(&RExC_flags, cs);
7984                         if (paren != ':') {
7985                             oregflags |= posflags;
7986                             oregflags &= ~negflags;
7987                             set_regex_charset(&oregflags, cs);
7988                         }
7989                         nextchar(pRExC_state);
7990                         if (paren != ':') {
7991                             *flagp = TRYAGAIN;
7992                             return NULL;
7993                         } else {
7994                             ret = NULL;
7995                             goto parse_rest;
7996                         }
7997                         /*NOTREACHED*/
7998                     default:
7999                         RExC_parse++;
8000                         vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
8001                         /*NOTREACHED*/
8002                     }                           
8003                     ++RExC_parse;
8004                 }
8005             }} /* one for the default block, one for the switch */
8006         }
8007         else {                  /* (...) */
8008           capturing_parens:
8009             parno = RExC_npar;
8010             RExC_npar++;
8011             
8012             ret = reganode(pRExC_state, OPEN, parno);
8013             if (!SIZE_ONLY ){
8014                 if (!RExC_nestroot) 
8015                     RExC_nestroot = parno;
8016                 if (RExC_seen & REG_SEEN_RECURSE
8017                     && !RExC_open_parens[parno-1])
8018                 {
8019                     DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
8020                         "Setting open paren #%"IVdf" to %d\n", 
8021                         (IV)parno, REG_NODE_NUM(ret)));
8022                     RExC_open_parens[parno-1]= ret;
8023                 }
8024             }
8025             Set_Node_Length(ret, 1); /* MJD */
8026             Set_Node_Offset(ret, RExC_parse); /* MJD */
8027             is_open = 1;
8028         }
8029     }
8030     else                        /* ! paren */
8031         ret = NULL;
8032    
8033    parse_rest:
8034     /* Pick up the branches, linking them together. */
8035     parse_start = RExC_parse;   /* MJD */
8036     br = regbranch(pRExC_state, &flags, 1,depth+1);
8037
8038     /*     branch_len = (paren != 0); */
8039
8040     if (br == NULL)
8041         return(NULL);
8042     if (*RExC_parse == '|') {
8043         if (!SIZE_ONLY && RExC_extralen) {
8044             reginsert(pRExC_state, BRANCHJ, br, depth+1);
8045         }
8046         else {                  /* MJD */
8047             reginsert(pRExC_state, BRANCH, br, depth+1);
8048             Set_Node_Length(br, paren != 0);
8049             Set_Node_Offset_To_R(br-RExC_emit_start, parse_start-RExC_start);
8050         }
8051         have_branch = 1;
8052         if (SIZE_ONLY)
8053             RExC_extralen += 1;         /* For BRANCHJ-BRANCH. */
8054     }
8055     else if (paren == ':') {
8056         *flagp |= flags&SIMPLE;
8057     }
8058     if (is_open) {                              /* Starts with OPEN. */
8059         REGTAIL(pRExC_state, ret, br);          /* OPEN -> first. */
8060     }
8061     else if (paren != '?')              /* Not Conditional */
8062         ret = br;
8063     *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
8064     lastbr = br;
8065     while (*RExC_parse == '|') {
8066         if (!SIZE_ONLY && RExC_extralen) {
8067             ender = reganode(pRExC_state, LONGJMP,0);
8068             REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender); /* Append to the previous. */
8069         }
8070         if (SIZE_ONLY)
8071             RExC_extralen += 2;         /* Account for LONGJMP. */
8072         nextchar(pRExC_state);
8073         if (freeze_paren) {
8074             if (RExC_npar > after_freeze)
8075                 after_freeze = RExC_npar;
8076             RExC_npar = freeze_paren;       
8077         }
8078         br = regbranch(pRExC_state, &flags, 0, depth+1);
8079
8080         if (br == NULL)
8081             return(NULL);
8082         REGTAIL(pRExC_state, lastbr, br);               /* BRANCH -> BRANCH. */
8083         lastbr = br;
8084         *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
8085     }
8086
8087     if (have_branch || paren != ':') {
8088         /* Make a closing node, and hook it on the end. */
8089         switch (paren) {
8090         case ':':
8091             ender = reg_node(pRExC_state, TAIL);
8092             break;
8093         case 1:
8094             ender = reganode(pRExC_state, CLOSE, parno);
8095             if (!SIZE_ONLY && RExC_seen & REG_SEEN_RECURSE) {
8096                 DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
8097                         "Setting close paren #%"IVdf" to %d\n", 
8098                         (IV)parno, REG_NODE_NUM(ender)));
8099                 RExC_close_parens[parno-1]= ender;
8100                 if (RExC_nestroot == parno) 
8101                     RExC_nestroot = 0;
8102             }       
8103             Set_Node_Offset(ender,RExC_parse+1); /* MJD */
8104             Set_Node_Length(ender,1); /* MJD */
8105             break;
8106         case '<':
8107         case ',':
8108         case '=':
8109         case '!':
8110             *flagp &= ~HASWIDTH;
8111             /* FALL THROUGH */
8112         case '>':
8113             ender = reg_node(pRExC_state, SUCCEED);
8114             break;
8115         case 0:
8116             ender = reg_node(pRExC_state, END);
8117             if (!SIZE_ONLY) {
8118                 assert(!RExC_opend); /* there can only be one! */
8119                 RExC_opend = ender;
8120             }
8121             break;
8122         }
8123         REGTAIL(pRExC_state, lastbr, ender);
8124
8125         if (have_branch && !SIZE_ONLY) {
8126             if (depth==1)
8127                 RExC_seen |= REG_TOP_LEVEL_BRANCHES;
8128
8129             /* Hook the tails of the branches to the closing node. */
8130             for (br = ret; br; br = regnext(br)) {
8131                 const U8 op = PL_regkind[OP(br)];
8132                 if (op == BRANCH) {
8133                     REGTAIL_STUDY(pRExC_state, NEXTOPER(br), ender);
8134                 }
8135                 else if (op == BRANCHJ) {
8136                     REGTAIL_STUDY(pRExC_state, NEXTOPER(NEXTOPER(br)), ender);
8137                 }
8138             }
8139         }
8140     }
8141
8142     {
8143         const char *p;
8144         static const char parens[] = "=!<,>";
8145
8146         if (paren && (p = strchr(parens, paren))) {
8147             U8 node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
8148             int flag = (p - parens) > 1;
8149
8150             if (paren == '>')
8151                 node = SUSPEND, flag = 0;
8152             reginsert(pRExC_state, node,ret, depth+1);
8153             Set_Node_Cur_Length(ret);
8154             Set_Node_Offset(ret, parse_start + 1);
8155             ret->flags = flag;
8156             REGTAIL_STUDY(pRExC_state, ret, reg_node(pRExC_state, TAIL));
8157         }
8158     }
8159
8160     /* Check for proper termination. */
8161     if (paren) {
8162         RExC_flags = oregflags;
8163         if (RExC_parse >= RExC_end || *nextchar(pRExC_state) != ')') {
8164             RExC_parse = oregcomp_parse;
8165             vFAIL("Unmatched (");
8166         }
8167     }
8168     else if (!paren && RExC_parse < RExC_end) {
8169         if (*RExC_parse == ')') {
8170             RExC_parse++;
8171             vFAIL("Unmatched )");
8172         }
8173         else
8174             FAIL("Junk on end of regexp");      /* "Can't happen". */
8175         /* NOTREACHED */
8176     }
8177
8178     if (RExC_in_lookbehind) {
8179         RExC_in_lookbehind--;
8180     }
8181     if (after_freeze > RExC_npar)
8182         RExC_npar = after_freeze;
8183     return(ret);
8184 }
8185
8186 /*
8187  - regbranch - one alternative of an | operator
8188  *
8189  * Implements the concatenation operator.
8190  */
8191 STATIC regnode *
8192 S_regbranch(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, I32 first, U32 depth)
8193 {
8194     dVAR;
8195     register regnode *ret;
8196     register regnode *chain = NULL;
8197     register regnode *latest;
8198     I32 flags = 0, c = 0;
8199     GET_RE_DEBUG_FLAGS_DECL;
8200
8201     PERL_ARGS_ASSERT_REGBRANCH;
8202
8203     DEBUG_PARSE("brnc");
8204
8205     if (first)
8206         ret = NULL;
8207     else {
8208         if (!SIZE_ONLY && RExC_extralen)
8209             ret = reganode(pRExC_state, BRANCHJ,0);
8210         else {
8211             ret = reg_node(pRExC_state, BRANCH);
8212             Set_Node_Length(ret, 1);
8213         }
8214     }
8215
8216     if (!first && SIZE_ONLY)
8217         RExC_extralen += 1;                     /* BRANCHJ */
8218
8219     *flagp = WORST;                     /* Tentatively. */
8220
8221     RExC_parse--;
8222     nextchar(pRExC_state);
8223     while (RExC_parse < RExC_end && *RExC_parse != '|' && *RExC_parse != ')') {
8224         flags &= ~TRYAGAIN;
8225         latest = regpiece(pRExC_state, &flags,depth+1);
8226         if (latest == NULL) {
8227             if (flags & TRYAGAIN)
8228                 continue;
8229             return(NULL);
8230         }
8231         else if (ret == NULL)
8232             ret = latest;
8233         *flagp |= flags&(HASWIDTH|POSTPONED);
8234         if (chain == NULL)      /* First piece. */
8235             *flagp |= flags&SPSTART;
8236         else {
8237             RExC_naughty++;
8238             REGTAIL(pRExC_state, chain, latest);
8239         }
8240         chain = latest;
8241         c++;
8242     }
8243     if (chain == NULL) {        /* Loop ran zero times. */
8244         chain = reg_node(pRExC_state, NOTHING);
8245         if (ret == NULL)
8246             ret = chain;
8247     }
8248     if (c == 1) {
8249         *flagp |= flags&SIMPLE;
8250     }
8251
8252     return ret;
8253 }
8254
8255 /*
8256  - regpiece - something followed by possible [*+?]
8257  *
8258  * Note that the branching code sequences used for ? and the general cases
8259  * of * and + are somewhat optimized:  they use the same NOTHING node as
8260  * both the endmarker for their branch list and the body of the last branch.
8261  * It might seem that this node could be dispensed with entirely, but the
8262  * endmarker role is not redundant.
8263  */
8264 STATIC regnode *
8265 S_regpiece(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
8266 {
8267     dVAR;
8268     register regnode *ret;
8269     register char op;
8270     register char *next;
8271     I32 flags;
8272     const char * const origparse = RExC_parse;
8273     I32 min;
8274     I32 max = REG_INFTY;
8275 #ifdef RE_TRACK_PATTERN_OFFSETS
8276     char *parse_start;
8277 #endif
8278     const char *maxpos = NULL;
8279     GET_RE_DEBUG_FLAGS_DECL;
8280
8281     PERL_ARGS_ASSERT_REGPIECE;
8282
8283     DEBUG_PARSE("piec");
8284
8285     ret = regatom(pRExC_state, &flags,depth+1);
8286     if (ret == NULL) {
8287         if (flags & TRYAGAIN)
8288             *flagp |= TRYAGAIN;
8289         return(NULL);
8290     }
8291
8292     op = *RExC_parse;
8293
8294     if (op == '{' && regcurly(RExC_parse)) {
8295         maxpos = NULL;
8296 #ifdef RE_TRACK_PATTERN_OFFSETS
8297         parse_start = RExC_parse; /* MJD */
8298 #endif
8299         next = RExC_parse + 1;
8300         while (isDIGIT(*next) || *next == ',') {
8301             if (*next == ',') {
8302                 if (maxpos)
8303                     break;
8304                 else
8305                     maxpos = next;
8306             }
8307             next++;
8308         }
8309         if (*next == '}') {             /* got one */
8310             if (!maxpos)
8311                 maxpos = next;
8312             RExC_parse++;
8313             min = atoi(RExC_parse);
8314             if (*maxpos == ',')
8315                 maxpos++;
8316             else
8317                 maxpos = RExC_parse;
8318             max = atoi(maxpos);
8319             if (!max && *maxpos != '0')
8320                 max = REG_INFTY;                /* meaning "infinity" */
8321             else if (max >= REG_INFTY)
8322                 vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
8323             RExC_parse = next;
8324             nextchar(pRExC_state);
8325
8326         do_curly:
8327             if ((flags&SIMPLE)) {
8328                 RExC_naughty += 2 + RExC_naughty / 2;
8329                 reginsert(pRExC_state, CURLY, ret, depth+1);
8330                 Set_Node_Offset(ret, parse_start+1); /* MJD */
8331                 Set_Node_Cur_Length(ret);
8332             }
8333             else {
8334                 regnode * const w = reg_node(pRExC_state, WHILEM);
8335
8336                 w->flags = 0;
8337                 REGTAIL(pRExC_state, ret, w);
8338                 if (!SIZE_ONLY && RExC_extralen) {
8339                     reginsert(pRExC_state, LONGJMP,ret, depth+1);
8340                     reginsert(pRExC_state, NOTHING,ret, depth+1);
8341                     NEXT_OFF(ret) = 3;  /* Go over LONGJMP. */
8342                 }
8343                 reginsert(pRExC_state, CURLYX,ret, depth+1);
8344                                 /* MJD hk */
8345                 Set_Node_Offset(ret, parse_start+1);
8346                 Set_Node_Length(ret,
8347                                 op == '{' ? (RExC_parse - parse_start) : 1);
8348
8349                 if (!SIZE_ONLY && RExC_extralen)
8350                     NEXT_OFF(ret) = 3;  /* Go over NOTHING to LONGJMP. */
8351                 REGTAIL(pRExC_state, ret, reg_node(pRExC_state, NOTHING));
8352                 if (SIZE_ONLY)
8353                     RExC_whilem_seen++, RExC_extralen += 3;
8354                 RExC_naughty += 4 + RExC_naughty;       /* compound interest */
8355             }
8356             ret->flags = 0;
8357
8358             if (min > 0)
8359                 *flagp = WORST;
8360             if (max > 0)
8361                 *flagp |= HASWIDTH;
8362             if (max < min)
8363                 vFAIL("Can't do {n,m} with n > m");
8364             if (!SIZE_ONLY) {
8365                 ARG1_SET(ret, (U16)min);
8366                 ARG2_SET(ret, (U16)max);
8367             }
8368
8369             goto nest_check;
8370         }
8371     }
8372
8373     if (!ISMULT1(op)) {
8374         *flagp = flags;
8375         return(ret);
8376     }
8377
8378 #if 0                           /* Now runtime fix should be reliable. */
8379
8380     /* if this is reinstated, don't forget to put this back into perldiag:
8381
8382             =item Regexp *+ operand could be empty at {#} in regex m/%s/
8383
8384            (F) The part of the regexp subject to either the * or + quantifier
8385            could match an empty string. The {#} shows in the regular
8386            expression about where the problem was discovered.
8387
8388     */
8389
8390     if (!(flags&HASWIDTH) && op != '?')
8391       vFAIL("Regexp *+ operand could be empty");
8392 #endif
8393
8394 #ifdef RE_TRACK_PATTERN_OFFSETS
8395     parse_start = RExC_parse;
8396 #endif
8397     nextchar(pRExC_state);
8398
8399     *flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
8400
8401     if (op == '*' && (flags&SIMPLE)) {
8402         reginsert(pRExC_state, STAR, ret, depth+1);
8403         ret->flags = 0;
8404         RExC_naughty += 4;
8405     }
8406     else if (op == '*') {
8407         min = 0;
8408         goto do_curly;
8409     }
8410     else if (op == '+' && (flags&SIMPLE)) {
8411         reginsert(pRExC_state, PLUS, ret, depth+1);
8412         ret->flags = 0;
8413         RExC_naughty += 3;
8414     }
8415     else if (op == '+') {
8416         min = 1;
8417         goto do_curly;
8418     }
8419     else if (op == '?') {
8420         min = 0; max = 1;
8421         goto do_curly;
8422     }
8423   nest_check:
8424     if (!SIZE_ONLY && !(flags&(HASWIDTH|POSTPONED)) && max > REG_INFTY/3) {
8425         ckWARN3reg(RExC_parse,
8426                    "%.*s matches null string many times",
8427                    (int)(RExC_parse >= origparse ? RExC_parse - origparse : 0),
8428                    origparse);
8429     }
8430
8431     if (RExC_parse < RExC_end && *RExC_parse == '?') {
8432         nextchar(pRExC_state);
8433         reginsert(pRExC_state, MINMOD, ret, depth+1);
8434         REGTAIL(pRExC_state, ret, ret + NODE_STEP_REGNODE);
8435     }
8436 #ifndef REG_ALLOW_MINMOD_SUSPEND
8437     else
8438 #endif
8439     if (RExC_parse < RExC_end && *RExC_parse == '+') {
8440         regnode *ender;
8441         nextchar(pRExC_state);
8442         ender = reg_node(pRExC_state, SUCCEED);
8443         REGTAIL(pRExC_state, ret, ender);
8444         reginsert(pRExC_state, SUSPEND, ret, depth+1);
8445         ret->flags = 0;
8446         ender = reg_node(pRExC_state, TAIL);
8447         REGTAIL(pRExC_state, ret, ender);
8448         /*ret= ender;*/
8449     }
8450
8451     if (RExC_parse < RExC_end && ISMULT2(RExC_parse)) {
8452         RExC_parse++;
8453         vFAIL("Nested quantifiers");
8454     }
8455
8456     return(ret);
8457 }
8458
8459
8460 /* reg_namedseq(pRExC_state,UVp, UV depth)
8461    
8462    This is expected to be called by a parser routine that has 
8463    recognized '\N' and needs to handle the rest. RExC_parse is
8464    expected to point at the first char following the N at the time
8465    of the call.
8466
8467    The \N may be inside (indicated by valuep not being NULL) or outside a
8468    character class.
8469
8470    \N may begin either a named sequence, or if outside a character class, mean
8471    to match a non-newline.  For non single-quoted regexes, the tokenizer has
8472    attempted to decide which, and in the case of a named sequence converted it
8473    into one of the forms: \N{} (if the sequence is null), or \N{U+c1.c2...},
8474    where c1... are the characters in the sequence.  For single-quoted regexes,
8475    the tokenizer passes the \N sequence through unchanged; this code will not
8476    attempt to determine this nor expand those.  The net effect is that if the
8477    beginning of the passed-in pattern isn't '{U+' or there is no '}', it
8478    signals that this \N occurrence means to match a non-newline.
8479    
8480    Only the \N{U+...} form should occur in a character class, for the same
8481    reason that '.' inside a character class means to just match a period: it
8482    just doesn't make sense.
8483    
8484    If valuep is non-null then it is assumed that we are parsing inside 
8485    of a charclass definition and the first codepoint in the resolved
8486    string is returned via *valuep and the routine will return NULL. 
8487    In this mode if a multichar string is returned from the charnames 
8488    handler, a warning will be issued, and only the first char in the 
8489    sequence will be examined. If the string returned is zero length
8490    then the value of *valuep is undefined and NON-NULL will 
8491    be returned to indicate failure. (This will NOT be a valid pointer 
8492    to a regnode.)
8493    
8494    If valuep is null then it is assumed that we are parsing normal text and a
8495    new EXACT node is inserted into the program containing the resolved string,
8496    and a pointer to the new node is returned.  But if the string is zero length
8497    a NOTHING node is emitted instead.
8498
8499    On success RExC_parse is set to the char following the endbrace.
8500    Parsing failures will generate a fatal error via vFAIL(...)
8501  */
8502 STATIC regnode *
8503 S_reg_namedseq(pTHX_ RExC_state_t *pRExC_state, UV *valuep, I32 *flagp, U32 depth)
8504 {
8505     char * endbrace;    /* '}' following the name */
8506     regnode *ret = NULL;
8507     char* p;
8508
8509     GET_RE_DEBUG_FLAGS_DECL;
8510  
8511     PERL_ARGS_ASSERT_REG_NAMEDSEQ;
8512
8513     GET_RE_DEBUG_FLAGS;
8514
8515     /* The [^\n] meaning of \N ignores spaces and comments under the /x
8516      * modifier.  The other meaning does not */
8517     p = (RExC_flags & RXf_PMf_EXTENDED)
8518         ? regwhite( pRExC_state, RExC_parse )
8519         : RExC_parse;
8520    
8521     /* Disambiguate between \N meaning a named character versus \N meaning
8522      * [^\n].  The former is assumed when it can't be the latter. */
8523     if (*p != '{' || regcurly(p)) {
8524         RExC_parse = p;
8525         if (valuep) {
8526             /* no bare \N in a charclass */
8527             vFAIL("\\N in a character class must be a named character: \\N{...}");
8528         }
8529         nextchar(pRExC_state);
8530         ret = reg_node(pRExC_state, REG_ANY);
8531         *flagp |= HASWIDTH|SIMPLE;
8532         RExC_naughty++;
8533         RExC_parse--;
8534         Set_Node_Length(ret, 1); /* MJD */
8535         return ret;
8536     }
8537
8538     /* Here, we have decided it should be a named sequence */
8539
8540     /* The test above made sure that the next real character is a '{', but
8541      * under the /x modifier, it could be separated by space (or a comment and
8542      * \n) and this is not allowed (for consistency with \x{...} and the
8543      * tokenizer handling of \N{NAME}). */
8544     if (*RExC_parse != '{') {
8545         vFAIL("Missing braces on \\N{}");
8546     }
8547
8548     RExC_parse++;       /* Skip past the '{' */
8549
8550     if (! (endbrace = strchr(RExC_parse, '}')) /* no trailing brace */
8551         || ! (endbrace == RExC_parse            /* nothing between the {} */
8552               || (endbrace - RExC_parse >= 2    /* U+ (bad hex is checked below */
8553                   && strnEQ(RExC_parse, "U+", 2)))) /* for a better error msg) */
8554     {
8555         if (endbrace) RExC_parse = endbrace;    /* position msg's '<--HERE' */
8556         vFAIL("\\N{NAME} must be resolved by the lexer");
8557     }
8558
8559     if (endbrace == RExC_parse) {   /* empty: \N{} */
8560         if (! valuep) {
8561             RExC_parse = endbrace + 1;  
8562             return reg_node(pRExC_state,NOTHING);
8563         }
8564
8565         if (SIZE_ONLY) {
8566             ckWARNreg(RExC_parse,
8567                     "Ignoring zero length \\N{} in character class"
8568             );
8569             RExC_parse = endbrace + 1;  
8570         }
8571         *valuep = 0;
8572         return (regnode *) &RExC_parse; /* Invalid regnode pointer */
8573     }
8574
8575     REQUIRE_UTF8;       /* named sequences imply Unicode semantics */
8576     RExC_parse += 2;    /* Skip past the 'U+' */
8577
8578     if (valuep) {   /* In a bracketed char class */
8579         /* We only pay attention to the first char of 
8580         multichar strings being returned. I kinda wonder
8581         if this makes sense as it does change the behaviour
8582         from earlier versions, OTOH that behaviour was broken
8583         as well. XXX Solution is to recharacterize as
8584         [rest-of-class]|multi1|multi2... */
8585
8586         STRLEN length_of_hex;
8587         I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
8588             | PERL_SCAN_DISALLOW_PREFIX
8589             | (SIZE_ONLY ? PERL_SCAN_SILENT_ILLDIGIT : 0);
8590     
8591         char * endchar = RExC_parse + strcspn(RExC_parse, ".}");
8592         if (endchar < endbrace) {
8593             ckWARNreg(endchar, "Using just the first character returned by \\N{} in character class");
8594         }
8595
8596         length_of_hex = (STRLEN)(endchar - RExC_parse);
8597         *valuep = grok_hex(RExC_parse, &length_of_hex, &flags, NULL);
8598
8599         /* The tokenizer should have guaranteed validity, but it's possible to
8600          * bypass it by using single quoting, so check */
8601         if (length_of_hex == 0
8602             || length_of_hex != (STRLEN)(endchar - RExC_parse) )
8603         {
8604             RExC_parse += length_of_hex;        /* Includes all the valid */
8605             RExC_parse += (RExC_orig_utf8)      /* point to after 1st invalid */
8606                             ? UTF8SKIP(RExC_parse)
8607                             : 1;
8608             /* Guard against malformed utf8 */
8609             if (RExC_parse >= endchar) RExC_parse = endchar;
8610             vFAIL("Invalid hexadecimal number in \\N{U+...}");
8611         }    
8612
8613         RExC_parse = endbrace + 1;
8614         if (endchar == endbrace) return NULL;
8615
8616         ret = (regnode *) &RExC_parse;  /* Invalid regnode pointer */
8617     }
8618     else {      /* Not a char class */
8619
8620         /* What is done here is to convert this to a sub-pattern of the form
8621          * (?:\x{char1}\x{char2}...)
8622          * and then call reg recursively.  That way, it retains its atomicness,
8623          * while not having to worry about special handling that some code
8624          * points may have.  toke.c has converted the original Unicode values
8625          * to native, so that we can just pass on the hex values unchanged.  We
8626          * do have to set a flag to keep recoding from happening in the
8627          * recursion */
8628
8629         SV * substitute_parse = newSVpvn_flags("?:", 2, SVf_UTF8|SVs_TEMP);
8630         STRLEN len;
8631         char *endchar;      /* Points to '.' or '}' ending cur char in the input
8632                                stream */
8633         char *orig_end = RExC_end;
8634
8635         while (RExC_parse < endbrace) {
8636
8637             /* Code points are separated by dots.  If none, there is only one
8638              * code point, and is terminated by the brace */
8639             endchar = RExC_parse + strcspn(RExC_parse, ".}");
8640
8641             /* Convert to notation the rest of the code understands */
8642             sv_catpv(substitute_parse, "\\x{");
8643             sv_catpvn(substitute_parse, RExC_parse, endchar - RExC_parse);
8644             sv_catpv(substitute_parse, "}");
8645
8646             /* Point to the beginning of the next character in the sequence. */
8647             RExC_parse = endchar + 1;
8648         }
8649         sv_catpv(substitute_parse, ")");
8650
8651         RExC_parse = SvPV(substitute_parse, len);
8652
8653         /* Don't allow empty number */
8654         if (len < 8) {
8655             vFAIL("Invalid hexadecimal number in \\N{U+...}");
8656         }
8657         RExC_end = RExC_parse + len;
8658
8659         /* The values are Unicode, and therefore not subject to recoding */
8660         RExC_override_recoding = 1;
8661
8662         ret = reg(pRExC_state, 1, flagp, depth+1);
8663
8664         RExC_parse = endbrace;
8665         RExC_end = orig_end;
8666         RExC_override_recoding = 0;
8667
8668         nextchar(pRExC_state);
8669     }
8670
8671     return ret;
8672 }
8673
8674
8675 /*
8676  * reg_recode
8677  *
8678  * It returns the code point in utf8 for the value in *encp.
8679  *    value: a code value in the source encoding
8680  *    encp:  a pointer to an Encode object
8681  *
8682  * If the result from Encode is not a single character,
8683  * it returns U+FFFD (Replacement character) and sets *encp to NULL.
8684  */
8685 STATIC UV
8686 S_reg_recode(pTHX_ const char value, SV **encp)
8687 {
8688     STRLEN numlen = 1;
8689     SV * const sv = newSVpvn_flags(&value, numlen, SVs_TEMP);
8690     const char * const s = *encp ? sv_recode_to_utf8(sv, *encp) : SvPVX(sv);
8691     const STRLEN newlen = SvCUR(sv);
8692     UV uv = UNICODE_REPLACEMENT;
8693
8694     PERL_ARGS_ASSERT_REG_RECODE;
8695
8696     if (newlen)
8697         uv = SvUTF8(sv)
8698              ? utf8n_to_uvchr((U8*)s, newlen, &numlen, UTF8_ALLOW_DEFAULT)
8699              : *(U8*)s;
8700
8701     if (!newlen || numlen != newlen) {
8702         uv = UNICODE_REPLACEMENT;
8703         *encp = NULL;
8704     }
8705     return uv;
8706 }
8707
8708
8709 /*
8710  - regatom - the lowest level
8711
8712    Try to identify anything special at the start of the pattern. If there
8713    is, then handle it as required. This may involve generating a single regop,
8714    such as for an assertion; or it may involve recursing, such as to
8715    handle a () structure.
8716
8717    If the string doesn't start with something special then we gobble up
8718    as much literal text as we can.
8719
8720    Once we have been able to handle whatever type of thing started the
8721    sequence, we return.
8722
8723    Note: we have to be careful with escapes, as they can be both literal
8724    and special, and in the case of \10 and friends can either, depending
8725    on context. Specifically there are two separate switches for handling
8726    escape sequences, with the one for handling literal escapes requiring
8727    a dummy entry for all of the special escapes that are actually handled
8728    by the other.
8729 */
8730
8731 STATIC regnode *
8732 S_regatom(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
8733 {
8734     dVAR;
8735     register regnode *ret = NULL;
8736     I32 flags;
8737     char *parse_start = RExC_parse;
8738     U8 op;
8739     GET_RE_DEBUG_FLAGS_DECL;
8740     DEBUG_PARSE("atom");
8741     *flagp = WORST;             /* Tentatively. */
8742
8743     PERL_ARGS_ASSERT_REGATOM;
8744
8745 tryagain:
8746     switch ((U8)*RExC_parse) {
8747     case '^':
8748         RExC_seen_zerolen++;
8749         nextchar(pRExC_state);
8750         if (RExC_flags & RXf_PMf_MULTILINE)
8751             ret = reg_node(pRExC_state, MBOL);
8752         else if (RExC_flags & RXf_PMf_SINGLELINE)
8753             ret = reg_node(pRExC_state, SBOL);
8754         else
8755             ret = reg_node(pRExC_state, BOL);
8756         Set_Node_Length(ret, 1); /* MJD */
8757         break;
8758     case '$':
8759         nextchar(pRExC_state);
8760         if (*RExC_parse)
8761             RExC_seen_zerolen++;
8762         if (RExC_flags & RXf_PMf_MULTILINE)
8763             ret = reg_node(pRExC_state, MEOL);
8764         else if (RExC_flags & RXf_PMf_SINGLELINE)
8765             ret = reg_node(pRExC_state, SEOL);
8766         else
8767             ret = reg_node(pRExC_state, EOL);
8768         Set_Node_Length(ret, 1); /* MJD */
8769         break;
8770     case '.':
8771         nextchar(pRExC_state);
8772         if (RExC_flags & RXf_PMf_SINGLELINE)
8773             ret = reg_node(pRExC_state, SANY);
8774         else
8775             ret = reg_node(pRExC_state, REG_ANY);
8776         *flagp |= HASWIDTH|SIMPLE;
8777         RExC_naughty++;
8778         Set_Node_Length(ret, 1); /* MJD */
8779         break;
8780     case '[':
8781     {
8782         char * const oregcomp_parse = ++RExC_parse;
8783         ret = regclass(pRExC_state,depth+1);
8784         if (*RExC_parse != ']') {
8785             RExC_parse = oregcomp_parse;
8786             vFAIL("Unmatched [");
8787         }
8788         nextchar(pRExC_state);
8789         *flagp |= HASWIDTH|SIMPLE;
8790         Set_Node_Length(ret, RExC_parse - oregcomp_parse + 1); /* MJD */
8791         break;
8792     }
8793     case '(':
8794         nextchar(pRExC_state);
8795         ret = reg(pRExC_state, 1, &flags,depth+1);
8796         if (ret == NULL) {
8797                 if (flags & TRYAGAIN) {
8798                     if (RExC_parse == RExC_end) {
8799                          /* Make parent create an empty node if needed. */
8800                         *flagp |= TRYAGAIN;
8801                         return(NULL);
8802                     }
8803                     goto tryagain;
8804                 }
8805                 return(NULL);
8806         }
8807         *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
8808         break;
8809     case '|':
8810     case ')':
8811         if (flags & TRYAGAIN) {
8812             *flagp |= TRYAGAIN;
8813             return NULL;
8814         }
8815         vFAIL("Internal urp");
8816                                 /* Supposed to be caught earlier. */
8817         break;
8818     case '{':
8819         if (!regcurly(RExC_parse)) {
8820             RExC_parse++;
8821             goto defchar;
8822         }
8823         /* FALL THROUGH */
8824     case '?':
8825     case '+':
8826     case '*':
8827         RExC_parse++;
8828         vFAIL("Quantifier follows nothing");
8829         break;
8830     case '\\':
8831         /* Special Escapes
8832
8833            This switch handles escape sequences that resolve to some kind
8834            of special regop and not to literal text. Escape sequnces that
8835            resolve to literal text are handled below in the switch marked
8836            "Literal Escapes".
8837
8838            Every entry in this switch *must* have a corresponding entry
8839            in the literal escape switch. However, the opposite is not
8840            required, as the default for this switch is to jump to the
8841            literal text handling code.
8842         */
8843         switch ((U8)*++RExC_parse) {
8844         /* Special Escapes */
8845         case 'A':
8846             RExC_seen_zerolen++;
8847             ret = reg_node(pRExC_state, SBOL);
8848             *flagp |= SIMPLE;
8849             goto finish_meta_pat;
8850         case 'G':
8851             ret = reg_node(pRExC_state, GPOS);
8852             RExC_seen |= REG_SEEN_GPOS;
8853             *flagp |= SIMPLE;
8854             goto finish_meta_pat;
8855         case 'K':
8856             RExC_seen_zerolen++;
8857             ret = reg_node(pRExC_state, KEEPS);
8858             *flagp |= SIMPLE;
8859             /* XXX:dmq : disabling in-place substitution seems to
8860              * be necessary here to avoid cases of memory corruption, as
8861              * with: C<$_="x" x 80; s/x\K/y/> -- rgs
8862              */
8863             RExC_seen |= REG_SEEN_LOOKBEHIND;
8864             goto finish_meta_pat;
8865         case 'Z':
8866             ret = reg_node(pRExC_state, SEOL);
8867             *flagp |= SIMPLE;
8868             RExC_seen_zerolen++;                /* Do not optimize RE away */
8869             goto finish_meta_pat;
8870         case 'z':
8871             ret = reg_node(pRExC_state, EOS);
8872             *flagp |= SIMPLE;
8873             RExC_seen_zerolen++;                /* Do not optimize RE away */
8874             goto finish_meta_pat;
8875         case 'C':
8876             ret = reg_node(pRExC_state, CANY);
8877             RExC_seen |= REG_SEEN_CANY;
8878             *flagp |= HASWIDTH|SIMPLE;
8879             goto finish_meta_pat;
8880         case 'X':
8881             ret = reg_node(pRExC_state, CLUMP);
8882             *flagp |= HASWIDTH;
8883             goto finish_meta_pat;
8884         case 'w':
8885             switch (get_regex_charset(RExC_flags)) {
8886                 case REGEX_LOCALE_CHARSET:
8887                     op = ALNUML;
8888                     break;
8889                 case REGEX_UNICODE_CHARSET:
8890                     op = ALNUMU;
8891                     break;
8892                 case REGEX_ASCII_RESTRICTED_CHARSET:
8893                 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
8894                     op = ALNUMA;
8895                     break;
8896                 case REGEX_DEPENDS_CHARSET:
8897                     op = ALNUM;
8898                     break;
8899                 default:
8900                     goto bad_charset;
8901             }
8902             ret = reg_node(pRExC_state, op);
8903             *flagp |= HASWIDTH|SIMPLE;
8904             goto finish_meta_pat;
8905         case 'W':
8906             switch (get_regex_charset(RExC_flags)) {
8907                 case REGEX_LOCALE_CHARSET:
8908                     op = NALNUML;
8909                     break;
8910                 case REGEX_UNICODE_CHARSET:
8911                     op = NALNUMU;
8912                     break;
8913                 case REGEX_ASCII_RESTRICTED_CHARSET:
8914                 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
8915                     op = NALNUMA;
8916                     break;
8917                 case REGEX_DEPENDS_CHARSET:
8918                     op = NALNUM;
8919                     break;
8920                 default:
8921                     goto bad_charset;
8922             }
8923             ret = reg_node(pRExC_state, op);
8924             *flagp |= HASWIDTH|SIMPLE;
8925             goto finish_meta_pat;
8926         case 'b':
8927             RExC_seen_zerolen++;
8928             RExC_seen |= REG_SEEN_LOOKBEHIND;
8929             switch (get_regex_charset(RExC_flags)) {
8930                 case REGEX_LOCALE_CHARSET:
8931                     op = BOUNDL;
8932                     break;
8933                 case REGEX_UNICODE_CHARSET:
8934                     op = BOUNDU;
8935                     break;
8936                 case REGEX_ASCII_RESTRICTED_CHARSET:
8937                 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
8938                     op = BOUNDA;
8939                     break;
8940                 case REGEX_DEPENDS_CHARSET:
8941                     op = BOUND;
8942                     break;
8943                 default:
8944                     goto bad_charset;
8945             }
8946             ret = reg_node(pRExC_state, op);
8947             FLAGS(ret) = get_regex_charset(RExC_flags);
8948             *flagp |= SIMPLE;
8949             if (! SIZE_ONLY && (U8) *(RExC_parse + 1) == '{') {
8950                 ckWARNregdep(RExC_parse, "\"\\b{\" is deprecated; use \"\\b\\{\" instead");
8951             }
8952             goto finish_meta_pat;
8953         case 'B':
8954             RExC_seen_zerolen++;
8955             RExC_seen |= REG_SEEN_LOOKBEHIND;
8956             switch (get_regex_charset(RExC_flags)) {
8957                 case REGEX_LOCALE_CHARSET:
8958                     op = NBOUNDL;
8959                     break;
8960                 case REGEX_UNICODE_CHARSET:
8961                     op = NBOUNDU;
8962                     break;
8963                 case REGEX_ASCII_RESTRICTED_CHARSET:
8964                 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
8965                     op = NBOUNDA;
8966                     break;
8967                 case REGEX_DEPENDS_CHARSET:
8968                     op = NBOUND;
8969                     break;
8970                 default:
8971                     goto bad_charset;
8972             }
8973             ret = reg_node(pRExC_state, op);
8974             FLAGS(ret) = get_regex_charset(RExC_flags);
8975             *flagp |= SIMPLE;
8976             if (! SIZE_ONLY && (U8) *(RExC_parse + 1) == '{') {
8977                 ckWARNregdep(RExC_parse, "\"\\B{\" is deprecated; use \"\\B\\{\" instead");
8978             }
8979             goto finish_meta_pat;
8980         case 's':
8981             switch (get_regex_charset(RExC_flags)) {
8982                 case REGEX_LOCALE_CHARSET:
8983                     op = SPACEL;
8984                     break;
8985                 case REGEX_UNICODE_CHARSET:
8986                     op = SPACEU;
8987                     break;
8988                 case REGEX_ASCII_RESTRICTED_CHARSET:
8989                 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
8990                     op = SPACEA;
8991                     break;
8992                 case REGEX_DEPENDS_CHARSET:
8993                     op = SPACE;
8994                     break;
8995                 default:
8996                     goto bad_charset;
8997             }
8998             ret = reg_node(pRExC_state, op);
8999             *flagp |= HASWIDTH|SIMPLE;
9000             goto finish_meta_pat;
9001         case 'S':
9002             switch (get_regex_charset(RExC_flags)) {
9003                 case REGEX_LOCALE_CHARSET:
9004                     op = NSPACEL;
9005                     break;
9006                 case REGEX_UNICODE_CHARSET:
9007                     op = NSPACEU;
9008                     break;
9009                 case REGEX_ASCII_RESTRICTED_CHARSET:
9010                 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
9011                     op = NSPACEA;
9012                     break;
9013                 case REGEX_DEPENDS_CHARSET:
9014                     op = NSPACE;
9015                     break;
9016                 default:
9017                     goto bad_charset;
9018             }
9019             ret = reg_node(pRExC_state, op);
9020             *flagp |= HASWIDTH|SIMPLE;
9021             goto finish_meta_pat;
9022         case 'd':
9023             switch (get_regex_charset(RExC_flags)) {
9024                 case REGEX_LOCALE_CHARSET:
9025                     op = DIGITL;
9026                     break;
9027                 case REGEX_ASCII_RESTRICTED_CHARSET:
9028                 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
9029                     op = DIGITA;
9030                     break;
9031                 case REGEX_DEPENDS_CHARSET: /* No difference between these */
9032                 case REGEX_UNICODE_CHARSET:
9033                     op = DIGIT;
9034                     break;
9035                 default:
9036                     goto bad_charset;
9037             }
9038             ret = reg_node(pRExC_state, op);
9039             *flagp |= HASWIDTH|SIMPLE;
9040             goto finish_meta_pat;
9041         case 'D':
9042             switch (get_regex_charset(RExC_flags)) {
9043                 case REGEX_LOCALE_CHARSET:
9044                     op = NDIGITL;
9045                     break;
9046                 case REGEX_ASCII_RESTRICTED_CHARSET:
9047                 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
9048                     op = NDIGITA;
9049                     break;
9050                 case REGEX_DEPENDS_CHARSET: /* No difference between these */
9051                 case REGEX_UNICODE_CHARSET:
9052                     op = NDIGIT;
9053                     break;
9054                 default:
9055                     goto bad_charset;
9056             }
9057             ret = reg_node(pRExC_state, op);
9058             *flagp |= HASWIDTH|SIMPLE;
9059             goto finish_meta_pat;
9060         case 'R':
9061             ret = reg_node(pRExC_state, LNBREAK);
9062             *flagp |= HASWIDTH|SIMPLE;
9063             goto finish_meta_pat;
9064         case 'h':
9065             ret = reg_node(pRExC_state, HORIZWS);
9066             *flagp |= HASWIDTH|SIMPLE;
9067             goto finish_meta_pat;
9068         case 'H':
9069             ret = reg_node(pRExC_state, NHORIZWS);
9070             *flagp |= HASWIDTH|SIMPLE;
9071             goto finish_meta_pat;
9072         case 'v':
9073             ret = reg_node(pRExC_state, VERTWS);
9074             *flagp |= HASWIDTH|SIMPLE;
9075             goto finish_meta_pat;
9076         case 'V':
9077             ret = reg_node(pRExC_state, NVERTWS);
9078             *flagp |= HASWIDTH|SIMPLE;
9079          finish_meta_pat:           
9080             nextchar(pRExC_state);
9081             Set_Node_Length(ret, 2); /* MJD */
9082             break;          
9083         case 'p':
9084         case 'P':
9085             {
9086                 char* const oldregxend = RExC_end;
9087 #ifdef DEBUGGING
9088                 char* parse_start = RExC_parse - 2;
9089 #endif
9090
9091                 if (RExC_parse[1] == '{') {
9092                   /* a lovely hack--pretend we saw [\pX] instead */
9093                     RExC_end = strchr(RExC_parse, '}');
9094                     if (!RExC_end) {
9095                         const U8 c = (U8)*RExC_parse;
9096                         RExC_parse += 2;
9097                         RExC_end = oldregxend;
9098                         vFAIL2("Missing right brace on \\%c{}", c);
9099                     }
9100                     RExC_end++;
9101                 }
9102                 else {
9103                     RExC_end = RExC_parse + 2;
9104                     if (RExC_end > oldregxend)
9105                         RExC_end = oldregxend;
9106                 }
9107                 RExC_parse--;
9108
9109                 ret = regclass(pRExC_state,depth+1);
9110
9111                 RExC_end = oldregxend;
9112                 RExC_parse--;
9113
9114                 Set_Node_Offset(ret, parse_start + 2);
9115                 Set_Node_Cur_Length(ret);
9116                 nextchar(pRExC_state);
9117                 *flagp |= HASWIDTH|SIMPLE;
9118             }
9119             break;
9120         case 'N': 
9121             /* Handle \N and \N{NAME} here and not below because it can be
9122             multicharacter. join_exact() will join them up later on. 
9123             Also this makes sure that things like /\N{BLAH}+/ and 
9124             \N{BLAH} being multi char Just Happen. dmq*/
9125             ++RExC_parse;
9126             ret= reg_namedseq(pRExC_state, NULL, flagp, depth);
9127             break;
9128         case 'k':    /* Handle \k<NAME> and \k'NAME' */
9129         parse_named_seq:
9130         {   
9131             char ch= RExC_parse[1];         
9132             if (ch != '<' && ch != '\'' && ch != '{') {
9133                 RExC_parse++;
9134                 vFAIL2("Sequence %.2s... not terminated",parse_start);
9135             } else {
9136                 /* this pretty much dupes the code for (?P=...) in reg(), if
9137                    you change this make sure you change that */
9138                 char* name_start = (RExC_parse += 2);
9139                 U32 num = 0;
9140                 SV *sv_dat = reg_scan_name(pRExC_state,
9141                     SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
9142                 ch= (ch == '<') ? '>' : (ch == '{') ? '}' : '\'';
9143                 if (RExC_parse == name_start || *RExC_parse != ch)
9144                     vFAIL2("Sequence %.3s... not terminated",parse_start);
9145
9146                 if (!SIZE_ONLY) {
9147                     num = add_data( pRExC_state, 1, "S" );
9148                     RExC_rxi->data->data[num]=(void*)sv_dat;
9149                     SvREFCNT_inc_simple_void(sv_dat);
9150                 }
9151
9152                 RExC_sawback = 1;
9153                 ret = reganode(pRExC_state,
9154                                ((! FOLD)
9155                                  ? NREF
9156                                  : (MORE_ASCII_RESTRICTED)
9157                                    ? NREFFA
9158                                    : (AT_LEAST_UNI_SEMANTICS)
9159                                      ? NREFFU
9160                                      : (LOC)
9161                                        ? NREFFL
9162                                        : NREFF),
9163                                 num);
9164                 *flagp |= HASWIDTH;
9165
9166                 /* override incorrect value set in reganode MJD */
9167                 Set_Node_Offset(ret, parse_start+1);
9168                 Set_Node_Cur_Length(ret); /* MJD */
9169                 nextchar(pRExC_state);
9170
9171             }
9172             break;
9173         }
9174         case 'g': 
9175         case '1': case '2': case '3': case '4':
9176         case '5': case '6': case '7': case '8': case '9':
9177             {
9178                 I32 num;
9179                 bool isg = *RExC_parse == 'g';
9180                 bool isrel = 0; 
9181                 bool hasbrace = 0;
9182                 if (isg) {
9183                     RExC_parse++;
9184                     if (*RExC_parse == '{') {
9185                         RExC_parse++;
9186                         hasbrace = 1;
9187                     }
9188                     if (*RExC_parse == '-') {
9189                         RExC_parse++;
9190                         isrel = 1;
9191                     }
9192                     if (hasbrace && !isDIGIT(*RExC_parse)) {
9193                         if (isrel) RExC_parse--;
9194                         RExC_parse -= 2;                            
9195                         goto parse_named_seq;
9196                 }   }
9197                 num = atoi(RExC_parse);
9198                 if (isg && num == 0)
9199                     vFAIL("Reference to invalid group 0");
9200                 if (isrel) {
9201                     num = RExC_npar - num;
9202                     if (num < 1)
9203                         vFAIL("Reference to nonexistent or unclosed group");
9204                 }
9205                 if (!isg && num > 9 && num >= RExC_npar)
9206                     goto defchar;
9207                 else {
9208                     char * const parse_start = RExC_parse - 1; /* MJD */
9209                     while (isDIGIT(*RExC_parse))
9210                         RExC_parse++;
9211                     if (parse_start == RExC_parse - 1) 
9212                         vFAIL("Unterminated \\g... pattern");
9213                     if (hasbrace) {
9214                         if (*RExC_parse != '}') 
9215                             vFAIL("Unterminated \\g{...} pattern");
9216                         RExC_parse++;
9217                     }    
9218                     if (!SIZE_ONLY) {
9219                         if (num > (I32)RExC_rx->nparens)
9220                             vFAIL("Reference to nonexistent group");
9221                     }
9222                     RExC_sawback = 1;
9223                     ret = reganode(pRExC_state,
9224                                    ((! FOLD)
9225                                      ? REF
9226                                      : (MORE_ASCII_RESTRICTED)
9227                                        ? REFFA
9228                                        : (AT_LEAST_UNI_SEMANTICS)
9229                                          ? REFFU
9230                                          : (LOC)
9231                                            ? REFFL
9232                                            : REFF),
9233                                     num);
9234                     *flagp |= HASWIDTH;
9235
9236                     /* override incorrect value set in reganode MJD */
9237                     Set_Node_Offset(ret, parse_start+1);
9238                     Set_Node_Cur_Length(ret); /* MJD */
9239                     RExC_parse--;
9240                     nextchar(pRExC_state);
9241                 }
9242             }
9243             break;
9244         case '\0':
9245             if (RExC_parse >= RExC_end)
9246                 FAIL("Trailing \\");
9247             /* FALL THROUGH */
9248         default:
9249             /* Do not generate "unrecognized" warnings here, we fall
9250                back into the quick-grab loop below */
9251             parse_start--;
9252             goto defchar;
9253         }
9254         break;
9255
9256     case '#':
9257         if (RExC_flags & RXf_PMf_EXTENDED) {
9258             if ( reg_skipcomment( pRExC_state ) )
9259                 goto tryagain;
9260         }
9261         /* FALL THROUGH */
9262
9263     default:
9264
9265             parse_start = RExC_parse - 1;
9266
9267             RExC_parse++;
9268
9269         defchar: {
9270             register STRLEN len;
9271             register UV ender;
9272             register char *p;
9273             char *s;
9274             STRLEN foldlen;
9275             U8 tmpbuf[UTF8_MAXBYTES_CASE+1], *foldbuf;
9276             regnode * orig_emit;
9277             U8 node_type;
9278
9279             /* Is this a LATIN LOWER CASE SHARP S in an EXACTFU node?  If so,
9280              * it is folded to 'ss' even if not utf8 */
9281             bool is_exactfu_sharp_s;
9282
9283             ender = 0;
9284             orig_emit = RExC_emit; /* Save the original output node position in
9285                                       case we need to output a different node
9286                                       type */
9287             node_type = ((! FOLD) ? EXACT
9288                         : (LOC)
9289                           ? EXACTFL
9290                           : (MORE_ASCII_RESTRICTED)
9291                             ? EXACTFA
9292                             : (AT_LEAST_UNI_SEMANTICS)
9293                               ? EXACTFU
9294                               : EXACTF);
9295             ret = reg_node(pRExC_state, node_type);
9296             s = STRING(ret);
9297
9298             /* XXX The node can hold up to 255 bytes, yet this only goes to
9299              * 127.  I (khw) do not know why.  Keeping it somewhat less than
9300              * 255 allows us to not have to worry about overflow due to
9301              * converting to utf8 and fold expansion, but that value is
9302              * 255-UTF8_MAXBYTES_CASE.  join_exact() may join adjacent nodes
9303              * split up by this limit into a single one using the real max of
9304              * 255.  Even at 127, this breaks under rare circumstances.  If
9305              * folding, we do not want to split a node at a character that is a
9306              * non-final in a multi-char fold, as an input string could just
9307              * happen to want to match across the node boundary.  The join
9308              * would solve that problem if the join actually happens.  But a
9309              * series of more than two nodes in a row each of 127 would cause
9310              * the first join to succeed to get to 254, but then there wouldn't
9311              * be room for the next one, which could at be one of those split
9312              * multi-char folds.  I don't know of any fool-proof solution.  One
9313              * could back off to end with only a code point that isn't such a
9314              * non-final, but it is possible for there not to be any in the
9315              * entire node. */
9316             for (len = 0, p = RExC_parse - 1;
9317                  len < 127 && p < RExC_end;
9318                  len++)
9319             {
9320                 char * const oldp = p;
9321
9322                 if (RExC_flags & RXf_PMf_EXTENDED)
9323                     p = regwhite( pRExC_state, p );
9324                 switch ((U8)*p) {
9325                 case '^':
9326                 case '$':
9327                 case '.':
9328                 case '[':
9329                 case '(':
9330                 case ')':
9331                 case '|':
9332                     goto loopdone;
9333                 case '\\':
9334                     /* Literal Escapes Switch
9335
9336                        This switch is meant to handle escape sequences that
9337                        resolve to a literal character.
9338
9339                        Every escape sequence that represents something
9340                        else, like an assertion or a char class, is handled
9341                        in the switch marked 'Special Escapes' above in this
9342                        routine, but also has an entry here as anything that
9343                        isn't explicitly mentioned here will be treated as
9344                        an unescaped equivalent literal.
9345                     */
9346
9347                     switch ((U8)*++p) {
9348                     /* These are all the special escapes. */
9349                     case 'A':             /* Start assertion */
9350                     case 'b': case 'B':   /* Word-boundary assertion*/
9351                     case 'C':             /* Single char !DANGEROUS! */
9352                     case 'd': case 'D':   /* digit class */
9353                     case 'g': case 'G':   /* generic-backref, pos assertion */
9354                     case 'h': case 'H':   /* HORIZWS */
9355                     case 'k': case 'K':   /* named backref, keep marker */
9356                     case 'N':             /* named char sequence */
9357                     case 'p': case 'P':   /* Unicode property */
9358                               case 'R':   /* LNBREAK */
9359                     case 's': case 'S':   /* space class */
9360                     case 'v': case 'V':   /* VERTWS */
9361                     case 'w': case 'W':   /* word class */
9362                     case 'X':             /* eXtended Unicode "combining character sequence" */
9363                     case 'z': case 'Z':   /* End of line/string assertion */
9364                         --p;
9365                         goto loopdone;
9366
9367                     /* Anything after here is an escape that resolves to a
9368                        literal. (Except digits, which may or may not)
9369                      */
9370                     case 'n':
9371                         ender = '\n';
9372                         p++;
9373                         break;
9374                     case 'r':
9375                         ender = '\r';
9376                         p++;
9377                         break;
9378                     case 't':
9379                         ender = '\t';
9380                         p++;
9381                         break;
9382                     case 'f':
9383                         ender = '\f';
9384                         p++;
9385                         break;
9386                     case 'e':
9387                           ender = ASCII_TO_NATIVE('\033');
9388                         p++;
9389                         break;
9390                     case 'a':
9391                           ender = ASCII_TO_NATIVE('\007');
9392                         p++;
9393                         break;
9394                     case 'o':
9395                         {
9396                             STRLEN brace_len = len;
9397                             UV result;
9398                             const char* error_msg;
9399
9400                             bool valid = grok_bslash_o(p,
9401                                                        &result,
9402                                                        &brace_len,
9403                                                        &error_msg,
9404                                                        1);
9405                             p += brace_len;
9406                             if (! valid) {
9407                                 RExC_parse = p; /* going to die anyway; point
9408                                                    to exact spot of failure */
9409                                 vFAIL(error_msg);
9410                             }
9411                             else
9412                             {
9413                                 ender = result;
9414                             }
9415                             if (PL_encoding && ender < 0x100) {
9416                                 goto recode_encoding;
9417                             }
9418                             if (ender > 0xff) {
9419                                 REQUIRE_UTF8;
9420                             }
9421                             break;
9422                         }
9423                     case 'x':
9424                         if (*++p == '{') {
9425                             char* const e = strchr(p, '}');
9426
9427                             if (!e) {
9428                                 RExC_parse = p + 1;
9429                                 vFAIL("Missing right brace on \\x{}");
9430                             }
9431                             else {
9432                                 I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
9433                                     | PERL_SCAN_DISALLOW_PREFIX;
9434                                 STRLEN numlen = e - p - 1;
9435                                 ender = grok_hex(p + 1, &numlen, &flags, NULL);
9436                                 if (ender > 0xff)
9437                                     REQUIRE_UTF8;
9438                                 p = e + 1;
9439                             }
9440                         }
9441                         else {
9442                             I32 flags = PERL_SCAN_DISALLOW_PREFIX;
9443                             STRLEN numlen = 2;
9444                             ender = grok_hex(p, &numlen, &flags, NULL);
9445                             p += numlen;
9446                         }
9447                         if (PL_encoding && ender < 0x100)
9448                             goto recode_encoding;
9449                         break;
9450                     case 'c':
9451                         p++;
9452                         ender = grok_bslash_c(*p++, UTF, SIZE_ONLY);
9453                         break;
9454                     case '0': case '1': case '2': case '3':case '4':
9455                     case '5': case '6': case '7': case '8':case '9':
9456                         if (*p == '0' ||
9457                             (isDIGIT(p[1]) && atoi(p) >= RExC_npar))
9458                         {
9459                             I32 flags = PERL_SCAN_SILENT_ILLDIGIT;
9460                             STRLEN numlen = 3;
9461                             ender = grok_oct(p, &numlen, &flags, NULL);
9462                             if (ender > 0xff) {
9463                                 REQUIRE_UTF8;
9464                             }
9465                             p += numlen;
9466                         }
9467                         else {
9468                             --p;
9469                             goto loopdone;
9470                         }
9471                         if (PL_encoding && ender < 0x100)
9472                             goto recode_encoding;
9473                         break;
9474                     recode_encoding:
9475                         if (! RExC_override_recoding) {
9476                             SV* enc = PL_encoding;
9477                             ender = reg_recode((const char)(U8)ender, &enc);
9478                             if (!enc && SIZE_ONLY)
9479                                 ckWARNreg(p, "Invalid escape in the specified encoding");
9480                             REQUIRE_UTF8;
9481                         }
9482                         break;
9483                     case '\0':
9484                         if (p >= RExC_end)
9485                             FAIL("Trailing \\");
9486                         /* FALL THROUGH */
9487                     default:
9488                         if (!SIZE_ONLY&& isALPHA(*p)) {
9489                             /* Include any { following the alpha to emphasize
9490                              * that it could be part of an escape at some point
9491                              * in the future */
9492                             int len = (*(p + 1) == '{') ? 2 : 1;
9493                             ckWARN3reg(p + len, "Unrecognized escape \\%.*s passed through", len, p);
9494                         }
9495                         goto normal_default;
9496                     }
9497                     break;
9498                 default:
9499                   normal_default:
9500                     if (UTF8_IS_START(*p) && UTF) {
9501                         STRLEN numlen;
9502                         ender = utf8n_to_uvchr((U8*)p, RExC_end - p,
9503                                                &numlen, UTF8_ALLOW_DEFAULT);
9504                         p += numlen;
9505                     }
9506                     else
9507                         ender = (U8) *p++;
9508                     break;
9509                 } /* End of switch on the literal */
9510
9511                 is_exactfu_sharp_s = (node_type == EXACTFU
9512                                       && ender == LATIN_SMALL_LETTER_SHARP_S);
9513                 if ( RExC_flags & RXf_PMf_EXTENDED)
9514                     p = regwhite( pRExC_state, p );
9515                 if ((UTF && FOLD) || is_exactfu_sharp_s) {
9516                     /* Prime the casefolded buffer.  Locale rules, which apply
9517                      * only to code points < 256, aren't known until execution,
9518                      * so for them, just output the original character using
9519                      * utf8.  If we start to fold non-UTF patterns, be sure to
9520                      * update join_exact() */
9521                     if (LOC && ender < 256) {
9522                         if (UNI_IS_INVARIANT(ender)) {
9523                             *tmpbuf = (U8) ender;
9524                             foldlen = 1;
9525                         } else {
9526                             *tmpbuf = UTF8_TWO_BYTE_HI(ender);
9527                             *(tmpbuf + 1) = UTF8_TWO_BYTE_LO(ender);
9528                             foldlen = 2;
9529                         }
9530                     }
9531                     else if (isASCII(ender)) {  /* Note: Here can't also be LOC
9532                                                  */
9533                         ender = toLOWER(ender);
9534                         *tmpbuf = (U8) ender;
9535                         foldlen = 1;
9536                     }
9537                     else if (! MORE_ASCII_RESTRICTED && ! LOC) {
9538
9539                         /* Locale and /aa require more selectivity about the
9540                          * fold, so are handled below.  Otherwise, here, just
9541                          * use the fold */
9542                         ender = toFOLD_uni(ender, tmpbuf, &foldlen);
9543                     }
9544                     else {
9545                         /* Under locale rules or /aa we are not to mix,
9546                          * respectively, ords < 256 or ASCII with non-.  So
9547                          * reject folds that mix them, using only the
9548                          * non-folded code point.  So do the fold to a
9549                          * temporary, and inspect each character in it. */
9550                         U8 trialbuf[UTF8_MAXBYTES_CASE+1];
9551                         U8* s = trialbuf;
9552                         UV tmpender = toFOLD_uni(ender, trialbuf, &foldlen);
9553                         U8* e = s + foldlen;
9554                         bool fold_ok = TRUE;
9555
9556                         while (s < e) {
9557                             if (isASCII(*s)
9558                                 || (LOC && (UTF8_IS_INVARIANT(*s)
9559                                            || UTF8_IS_DOWNGRADEABLE_START(*s))))
9560                             {
9561                                 fold_ok = FALSE;
9562                                 break;
9563                             }
9564                             s += UTF8SKIP(s);
9565                         }
9566                         if (fold_ok) {
9567                             Copy(trialbuf, tmpbuf, foldlen, U8);
9568                             ender = tmpender;
9569                         }
9570                         else {
9571                             uvuni_to_utf8(tmpbuf, ender);
9572                             foldlen = UNISKIP(ender);
9573                         }
9574                     }
9575                 }
9576                 if (p < RExC_end && ISMULT2(p)) { /* Back off on ?+*. */
9577                     if (len)
9578                         p = oldp;
9579                     else if (UTF || is_exactfu_sharp_s) {
9580                          if (FOLD) {
9581                               /* Emit all the Unicode characters. */
9582                               STRLEN numlen;
9583                               for (foldbuf = tmpbuf;
9584                                    foldlen;
9585                                    foldlen -= numlen) {
9586                                    ender = utf8_to_uvchr(foldbuf, &numlen);
9587                                    if (numlen > 0) {
9588                                         const STRLEN unilen = reguni(pRExC_state, ender, s);
9589                                         s       += unilen;
9590                                         len     += unilen;
9591                                         /* In EBCDIC the numlen
9592                                          * and unilen can differ. */
9593                                         foldbuf += numlen;
9594                                         if (numlen >= foldlen)
9595                                              break;
9596                                    }
9597                                    else
9598                                         break; /* "Can't happen." */
9599                               }
9600                          }
9601                          else {
9602                               const STRLEN unilen = reguni(pRExC_state, ender, s);
9603                               if (unilen > 0) {
9604                                    s   += unilen;
9605                                    len += unilen;
9606                               }
9607                          }
9608                     }
9609                     else {
9610                         len++;
9611                         REGC((char)ender, s++);
9612                     }
9613                     break;
9614                 }
9615                 if (UTF || is_exactfu_sharp_s) {
9616                      if (FOLD) {
9617                           /* Emit all the Unicode characters. */
9618                           STRLEN numlen;
9619                           for (foldbuf = tmpbuf;
9620                                foldlen;
9621                                foldlen -= numlen) {
9622                                ender = utf8_to_uvchr(foldbuf, &numlen);
9623                                if (numlen > 0) {
9624                                     const STRLEN unilen = reguni(pRExC_state, ender, s);
9625                                     len     += unilen;
9626                                     s       += unilen;
9627                                     /* In EBCDIC the numlen
9628                                      * and unilen can differ. */
9629                                     foldbuf += numlen;
9630                                     if (numlen >= foldlen)
9631                                          break;
9632                                }
9633                                else
9634                                     break;
9635                           }
9636                      }
9637                      else {
9638                           const STRLEN unilen = reguni(pRExC_state, ender, s);
9639                           if (unilen > 0) {
9640                                s   += unilen;
9641                                len += unilen;
9642                           }
9643                      }
9644                      len--;
9645                 }
9646                 else {
9647                     REGC((char)ender, s++);
9648                 }
9649             }
9650         loopdone:   /* Jumped to when encounters something that shouldn't be in
9651                        the node */
9652             RExC_parse = p - 1;
9653             Set_Node_Cur_Length(ret); /* MJD */
9654             nextchar(pRExC_state);
9655             {
9656                 /* len is STRLEN which is unsigned, need to copy to signed */
9657                 IV iv = len;
9658                 if (iv < 0)
9659                     vFAIL("Internal disaster");
9660             }
9661             if (len > 0)
9662                 *flagp |= HASWIDTH;
9663             if (len == 1 && UNI_IS_INVARIANT(ender))
9664                 *flagp |= SIMPLE;
9665
9666             if (SIZE_ONLY)
9667                 RExC_size += STR_SZ(len);
9668             else {
9669                 STR_LEN(ret) = len;
9670                 RExC_emit += STR_SZ(len);
9671             }
9672         }
9673         break;
9674     }
9675
9676     return(ret);
9677
9678 /* Jumped to when an unrecognized character set is encountered */
9679 bad_charset:
9680     Perl_croak(aTHX_ "panic: Unknown regex character set encoding: %u", get_regex_charset(RExC_flags));
9681     return(NULL);
9682 }
9683
9684 STATIC char *
9685 S_regwhite( RExC_state_t *pRExC_state, char *p )
9686 {
9687     const char *e = RExC_end;
9688
9689     PERL_ARGS_ASSERT_REGWHITE;
9690
9691     while (p < e) {
9692         if (isSPACE(*p))
9693             ++p;
9694         else if (*p == '#') {
9695             bool ended = 0;
9696             do {
9697                 if (*p++ == '\n') {
9698                     ended = 1;
9699                     break;
9700                 }
9701             } while (p < e);
9702             if (!ended)
9703                 RExC_seen |= REG_SEEN_RUN_ON_COMMENT;
9704         }
9705         else
9706             break;
9707     }
9708     return p;
9709 }
9710
9711 /* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
9712    Character classes ([:foo:]) can also be negated ([:^foo:]).
9713    Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
9714    Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
9715    but trigger failures because they are currently unimplemented. */
9716
9717 #define POSIXCC_DONE(c)   ((c) == ':')
9718 #define POSIXCC_NOTYET(c) ((c) == '=' || (c) == '.')
9719 #define POSIXCC(c) (POSIXCC_DONE(c) || POSIXCC_NOTYET(c))
9720
9721 STATIC I32
9722 S_regpposixcc(pTHX_ RExC_state_t *pRExC_state, I32 value)
9723 {
9724     dVAR;
9725     I32 namedclass = OOB_NAMEDCLASS;
9726
9727     PERL_ARGS_ASSERT_REGPPOSIXCC;
9728
9729     if (value == '[' && RExC_parse + 1 < RExC_end &&
9730         /* I smell either [: or [= or [. -- POSIX has been here, right? */
9731         POSIXCC(UCHARAT(RExC_parse))) {
9732         const char c = UCHARAT(RExC_parse);
9733         char* const s = RExC_parse++;
9734
9735         while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != c)
9736             RExC_parse++;
9737         if (RExC_parse == RExC_end)
9738             /* Grandfather lone [:, [=, [. */
9739             RExC_parse = s;
9740         else {
9741             const char* const t = RExC_parse++; /* skip over the c */
9742             assert(*t == c);
9743
9744             if (UCHARAT(RExC_parse) == ']') {
9745                 const char *posixcc = s + 1;
9746                 RExC_parse++; /* skip over the ending ] */
9747
9748                 if (*s == ':') {
9749                     const I32 complement = *posixcc == '^' ? *posixcc++ : 0;
9750                     const I32 skip = t - posixcc;
9751
9752                     /* Initially switch on the length of the name.  */
9753                     switch (skip) {
9754                     case 4:
9755                         if (memEQ(posixcc, "word", 4)) /* this is not POSIX, this is the Perl \w */
9756                             namedclass = complement ? ANYOF_NALNUM : ANYOF_ALNUM;
9757                         break;
9758                     case 5:
9759                         /* Names all of length 5.  */
9760                         /* alnum alpha ascii blank cntrl digit graph lower
9761                            print punct space upper  */
9762                         /* Offset 4 gives the best switch position.  */
9763                         switch (posixcc[4]) {
9764                         case 'a':
9765                             if (memEQ(posixcc, "alph", 4)) /* alpha */
9766                                 namedclass = complement ? ANYOF_NALPHA : ANYOF_ALPHA;
9767                             break;
9768                         case 'e':
9769                             if (memEQ(posixcc, "spac", 4)) /* space */
9770                                 namedclass = complement ? ANYOF_NPSXSPC : ANYOF_PSXSPC;
9771                             break;
9772                         case 'h':
9773                             if (memEQ(posixcc, "grap", 4)) /* graph */
9774                                 namedclass = complement ? ANYOF_NGRAPH : ANYOF_GRAPH;
9775                             break;
9776                         case 'i':
9777                             if (memEQ(posixcc, "asci", 4)) /* ascii */
9778                                 namedclass = complement ? ANYOF_NASCII : ANYOF_ASCII;
9779                             break;
9780                         case 'k':
9781                             if (memEQ(posixcc, "blan", 4)) /* blank */
9782                                 namedclass = complement ? ANYOF_NBLANK : ANYOF_BLANK;
9783                             break;
9784                         case 'l':
9785                             if (memEQ(posixcc, "cntr", 4)) /* cntrl */
9786                                 namedclass = complement ? ANYOF_NCNTRL : ANYOF_CNTRL;
9787                             break;
9788                         case 'm':
9789                             if (memEQ(posixcc, "alnu", 4)) /* alnum */
9790                                 namedclass = complement ? ANYOF_NALNUMC : ANYOF_ALNUMC;
9791                             break;
9792                         case 'r':
9793                             if (memEQ(posixcc, "lowe", 4)) /* lower */
9794                                 namedclass = complement ? ANYOF_NLOWER : ANYOF_LOWER;
9795                             else if (memEQ(posixcc, "uppe", 4)) /* upper */
9796                                 namedclass = complement ? ANYOF_NUPPER : ANYOF_UPPER;
9797                             break;
9798                         case 't':
9799                             if (memEQ(posixcc, "digi", 4)) /* digit */
9800                                 namedclass = complement ? ANYOF_NDIGIT : ANYOF_DIGIT;
9801                             else if (memEQ(posixcc, "prin", 4)) /* print */
9802                                 namedclass = complement ? ANYOF_NPRINT : ANYOF_PRINT;
9803                             else if (memEQ(posixcc, "punc", 4)) /* punct */
9804                                 namedclass = complement ? ANYOF_NPUNCT : ANYOF_PUNCT;
9805                             break;
9806                         }
9807                         break;
9808                     case 6:
9809                         if (memEQ(posixcc, "xdigit", 6))
9810                             namedclass = complement ? ANYOF_NXDIGIT : ANYOF_XDIGIT;
9811                         break;
9812                     }
9813
9814                     if (namedclass == OOB_NAMEDCLASS)
9815                         Simple_vFAIL3("POSIX class [:%.*s:] unknown",
9816                                       t - s - 1, s + 1);
9817                     assert (posixcc[skip] == ':');
9818                     assert (posixcc[skip+1] == ']');
9819                 } else if (!SIZE_ONLY) {
9820                     /* [[=foo=]] and [[.foo.]] are still future. */
9821
9822                     /* adjust RExC_parse so the warning shows after
9823                        the class closes */
9824                     while (UCHARAT(RExC_parse) && UCHARAT(RExC_parse) != ']')
9825                         RExC_parse++;
9826                     Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
9827                 }
9828             } else {
9829                 /* Maternal grandfather:
9830                  * "[:" ending in ":" but not in ":]" */
9831                 RExC_parse = s;
9832             }
9833         }
9834     }
9835
9836     return namedclass;
9837 }
9838
9839 STATIC void
9840 S_checkposixcc(pTHX_ RExC_state_t *pRExC_state)
9841 {
9842     dVAR;
9843
9844     PERL_ARGS_ASSERT_CHECKPOSIXCC;
9845
9846     if (POSIXCC(UCHARAT(RExC_parse))) {
9847         const char *s = RExC_parse;
9848         const char  c = *s++;
9849
9850         while (isALNUM(*s))
9851             s++;
9852         if (*s && c == *s && s[1] == ']') {
9853             ckWARN3reg(s+2,
9854                        "POSIX syntax [%c %c] belongs inside character classes",
9855                        c, c);
9856
9857             /* [[=foo=]] and [[.foo.]] are still future. */
9858             if (POSIXCC_NOTYET(c)) {
9859                 /* adjust RExC_parse so the error shows after
9860                    the class closes */
9861                 while (UCHARAT(RExC_parse) && UCHARAT(RExC_parse++) != ']')
9862                     NOOP;
9863                 Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
9864             }
9865         }
9866     }
9867 }
9868
9869 /* No locale test, and always Unicode semantics, no ignore-case differences */
9870 #define _C_C_T_NOLOC_(NAME,TEST,WORD)                                          \
9871 ANYOF_##NAME:                                                                  \
9872         for (value = 0; value < 256; value++)                                  \
9873             if (TEST)                                                          \
9874             stored += set_regclass_bit(pRExC_state, ret, (U8) value, &l1_fold_invlist, &unicode_alternate);  \
9875     yesno = '+';                                                               \
9876     what = WORD;                                                               \
9877     break;                                                                     \
9878 case ANYOF_N##NAME:                                                            \
9879         for (value = 0; value < 256; value++)                                  \
9880             if (!TEST)                                                         \
9881             stored += set_regclass_bit(pRExC_state, ret, (U8) value, &l1_fold_invlist, &unicode_alternate);  \
9882     yesno = '!';                                                               \
9883     what = WORD;                                                               \
9884     break
9885
9886 /* Like the above, but there are differences if we are in uni-8-bit or not, so
9887  * there are two tests passed in, to use depending on that. There aren't any
9888  * cases where the label is different from the name, so no need for that
9889  * parameter.
9890  * Sets 'what' to WORD which is the property name for non-bitmap code points;
9891  * But, uses FOLD_WORD instead if /i has been selected, to allow a different
9892  * property name */
9893 #define _C_C_T_(NAME, TEST_8, TEST_7, WORD, FOLD_WORD)                         \
9894 ANYOF_##NAME:                                                                  \
9895     if (LOC) ANYOF_CLASS_SET(ret, ANYOF_##NAME);                               \
9896     else if (UNI_SEMANTICS) {                                                  \
9897         for (value = 0; value < 256; value++) {                                \
9898             if (TEST_8(value)) stored +=                                       \
9899                       set_regclass_bit(pRExC_state, ret, (U8) value, &l1_fold_invlist, &unicode_alternate);  \
9900         }                                                                      \
9901     }                                                                          \
9902     else {                                                                     \
9903         for (value = 0; value < 128; value++) {                                \
9904             if (TEST_7(UNI_TO_NATIVE(value))) stored +=                        \
9905                 set_regclass_bit(pRExC_state, ret,                     \
9906                                    (U8) UNI_TO_NATIVE(value), &l1_fold_invlist, &unicode_alternate);                 \
9907         }                                                                      \
9908     }                                                                          \
9909     yesno = '+';                                                               \
9910     if (FOLD) {                                                                \
9911         what = FOLD_WORD;                                                      \
9912     }                                                                          \
9913     else {                                                                     \
9914         what = WORD;                                                           \
9915     }                                                                          \
9916     break;                                                                     \
9917 case ANYOF_N##NAME:                                                            \
9918     if (LOC) ANYOF_CLASS_SET(ret, ANYOF_N##NAME);                              \
9919     else if (UNI_SEMANTICS) {                                                  \
9920         for (value = 0; value < 256; value++) {                                \
9921             if (! TEST_8(value)) stored +=                                     \
9922                     set_regclass_bit(pRExC_state, ret, (U8) value, &l1_fold_invlist, &unicode_alternate);    \
9923         }                                                                      \
9924     }                                                                          \
9925     else {                                                                     \
9926         for (value = 0; value < 128; value++) {                                \
9927             if (! TEST_7(UNI_TO_NATIVE(value))) stored += set_regclass_bit(  \
9928                         pRExC_state, ret, (U8) UNI_TO_NATIVE(value), &l1_fold_invlist, &unicode_alternate);    \
9929         }                                                                      \
9930         if (AT_LEAST_ASCII_RESTRICTED) {                                       \
9931             for (value = 128; value < 256; value++) {                          \
9932              stored += set_regclass_bit(                                     \
9933                            pRExC_state, ret, (U8) UNI_TO_NATIVE(value), &l1_fold_invlist, &unicode_alternate); \
9934             }                                                                  \
9935             ANYOF_FLAGS(ret) |= ANYOF_UNICODE_ALL;                             \
9936         }                                                                      \
9937         else {                                                                 \
9938             /* For a non-ut8 target string with DEPENDS semantics, all above   \
9939              * ASCII Latin1 code points match the complement of any of the     \
9940              * classes.  But in utf8, they have their Unicode semantics, so    \
9941              * can't just set them in the bitmap, or else regexec.c will think \
9942              * they matched when they shouldn't. */                            \
9943             ANYOF_FLAGS(ret) |= ANYOF_NON_UTF8_LATIN1_ALL;                     \
9944         }                                                                      \
9945     }                                                                          \
9946     yesno = '!';                                                               \
9947     if (FOLD) {                                                                \
9948         what = FOLD_WORD;                                                      \
9949     }                                                                          \
9950     else {                                                                     \
9951         what = WORD;                                                           \
9952     }                                                                          \
9953     break
9954
9955 STATIC U8
9956 S_set_regclass_bit_fold(pTHX_ RExC_state_t *pRExC_state, regnode* node, const U8 value, SV** invlist_ptr, AV** alternate_ptr)
9957 {
9958
9959     /* Handle the setting of folds in the bitmap for non-locale ANYOF nodes.
9960      * Locale folding is done at run-time, so this function should not be
9961      * called for nodes that are for locales.
9962      *
9963      * This function sets the bit corresponding to the fold of the input
9964      * 'value', if not already set.  The fold of 'f' is 'F', and the fold of
9965      * 'F' is 'f'.
9966      *
9967      * It also knows about the characters that are in the bitmap that have
9968      * folds that are matchable only outside it, and sets the appropriate lists
9969      * and flags.
9970      *
9971      * It returns the number of bits that actually changed from 0 to 1 */
9972
9973     U8 stored = 0;
9974     U8 fold;
9975
9976     PERL_ARGS_ASSERT_SET_REGCLASS_BIT_FOLD;
9977
9978     fold = (AT_LEAST_UNI_SEMANTICS) ? PL_fold_latin1[value]
9979                                     : PL_fold[value];
9980
9981     /* It assumes the bit for 'value' has already been set */
9982     if (fold != value && ! ANYOF_BITMAP_TEST(node, fold)) {
9983         ANYOF_BITMAP_SET(node, fold);
9984         stored++;
9985     }
9986     if (_HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(value) && (! isASCII(value) || ! MORE_ASCII_RESTRICTED)) {
9987         /* Certain Latin1 characters have matches outside the bitmap.  To get
9988          * here, 'value' is one of those characters.   None of these matches is
9989          * valid for ASCII characters under /aa, which have been excluded by
9990          * the 'if' above.  The matches fall into three categories:
9991          * 1) They are singly folded-to or -from an above 255 character, as
9992          *    LATIN SMALL LETTER Y WITH DIAERESIS and LATIN CAPITAL LETTER Y
9993          *    WITH DIAERESIS;
9994          * 2) They are part of a multi-char fold with another character in the
9995          *    bitmap, only LATIN SMALL LETTER SHARP S => "ss" fits that bill;
9996          * 3) They are part of a multi-char fold with a character not in the
9997          *    bitmap, such as various ligatures.
9998          * We aren't dealing fully with multi-char folds, except we do deal
9999          * with the pattern containing a character that has a multi-char fold
10000          * (not so much the inverse).
10001          * For types 1) and 3), the matches only happen when the target string
10002          * is utf8; that's not true for 2), and we set a flag for it.
10003          *
10004          * The code below adds to the passed in inversion list the single fold
10005          * closures for 'value'.  The values are hard-coded here so that an
10006          * innocent-looking character class, like /[ks]/i won't have to go out
10007          * to disk to find the possible matches.  XXX It would be better to
10008          * generate these via regen, in case a new version of the Unicode
10009          * standard adds new mappings, though that is not really likely. */
10010         switch (value) {
10011             case 'k':
10012             case 'K':
10013                 /* KELVIN SIGN */
10014                 *invlist_ptr = add_cp_to_invlist(*invlist_ptr, 0x212A);
10015                 break;
10016             case 's':
10017             case 'S':
10018                 /* LATIN SMALL LETTER LONG S */
10019                 *invlist_ptr = add_cp_to_invlist(*invlist_ptr, 0x017F);
10020                 break;
10021             case MICRO_SIGN:
10022                 *invlist_ptr = add_cp_to_invlist(*invlist_ptr,
10023                                                  GREEK_SMALL_LETTER_MU);
10024                 *invlist_ptr = add_cp_to_invlist(*invlist_ptr,
10025                                                  GREEK_CAPITAL_LETTER_MU);
10026                 break;
10027             case LATIN_CAPITAL_LETTER_A_WITH_RING_ABOVE:
10028             case LATIN_SMALL_LETTER_A_WITH_RING_ABOVE:
10029                 /* ANGSTROM SIGN */
10030                 *invlist_ptr = add_cp_to_invlist(*invlist_ptr, 0x212B);
10031                 if (DEPENDS_SEMANTICS) {    /* See DEPENDS comment below */
10032                     *invlist_ptr = add_cp_to_invlist(*invlist_ptr,
10033                                                      PL_fold_latin1[value]);
10034                 }
10035                 break;
10036             case LATIN_SMALL_LETTER_Y_WITH_DIAERESIS:
10037                 *invlist_ptr = add_cp_to_invlist(*invlist_ptr,
10038                                         LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS);
10039                 break;
10040             case LATIN_SMALL_LETTER_SHARP_S:
10041                 *invlist_ptr = add_cp_to_invlist(*invlist_ptr,
10042                                         LATIN_CAPITAL_LETTER_SHARP_S);
10043
10044                 /* Under /a, /d, and /u, this can match the two chars "ss" */
10045                 if (! MORE_ASCII_RESTRICTED) {
10046                     add_alternate(alternate_ptr, (U8 *) "ss", 2);
10047
10048                     /* And under /u or /a, it can match even if the target is
10049                      * not utf8 */
10050                     if (AT_LEAST_UNI_SEMANTICS) {
10051                         ANYOF_FLAGS(node) |= ANYOF_NONBITMAP_NON_UTF8;
10052                     }
10053                 }
10054                 break;
10055             case 'F': case 'f':
10056             case 'I': case 'i':
10057             case 'L': case 'l':
10058             case 'T': case 't':
10059             case 'A': case 'a':
10060             case 'H': case 'h':
10061             case 'J': case 'j':
10062             case 'N': case 'n':
10063             case 'W': case 'w':
10064             case 'Y': case 'y':
10065                 /* These all are targets of multi-character folds from code
10066                  * points that require UTF8 to express, so they can't match
10067                  * unless the target string is in UTF-8, so no action here is
10068                  * necessary, as regexec.c properly handles the general case
10069                  * for UTF-8 matching */
10070                 break;
10071             default:
10072                 /* Use deprecated warning to increase the chances of this
10073                  * being output */
10074                 ckWARN2regdep(RExC_parse, "Perl folding rules are not up-to-date for 0x%x; please use the perlbug utility to report;", value);
10075                 break;
10076         }
10077     }
10078     else if (DEPENDS_SEMANTICS
10079             && ! isASCII(value)
10080             && PL_fold_latin1[value] != value)
10081     {
10082            /* Under DEPENDS rules, non-ASCII Latin1 characters match their
10083             * folds only when the target string is in UTF-8.  We add the fold
10084             * here to the list of things to match outside the bitmap, which
10085             * won't be looked at unless it is UTF8 (or else if something else
10086             * says to look even if not utf8, but those things better not happen
10087             * under DEPENDS semantics. */
10088         *invlist_ptr = add_cp_to_invlist(*invlist_ptr, PL_fold_latin1[value]);
10089     }
10090
10091     return stored;
10092 }
10093
10094
10095 PERL_STATIC_INLINE U8
10096 S_set_regclass_bit(pTHX_ RExC_state_t *pRExC_state, regnode* node, const U8 value, SV** invlist_ptr, AV** alternate_ptr)
10097 {
10098     /* This inline function sets a bit in the bitmap if not already set, and if
10099      * appropriate, its fold, returning the number of bits that actually
10100      * changed from 0 to 1 */
10101
10102     U8 stored;
10103
10104     PERL_ARGS_ASSERT_SET_REGCLASS_BIT;
10105
10106     if (ANYOF_BITMAP_TEST(node, value)) {   /* Already set */
10107         return 0;
10108     }
10109
10110     ANYOF_BITMAP_SET(node, value);
10111     stored = 1;
10112
10113     if (FOLD && ! LOC) {        /* Locale folds aren't known until runtime */
10114         stored += set_regclass_bit_fold(pRExC_state, node, value, invlist_ptr, alternate_ptr);
10115     }
10116
10117     return stored;
10118 }
10119
10120 STATIC void
10121 S_add_alternate(pTHX_ AV** alternate_ptr, U8* string, STRLEN len)
10122 {
10123     /* Adds input 'string' with length 'len' to the ANYOF node's unicode
10124      * alternate list, pointed to by 'alternate_ptr'.  This is an array of
10125      * the multi-character folds of characters in the node */
10126     SV *sv;
10127
10128     PERL_ARGS_ASSERT_ADD_ALTERNATE;
10129
10130     if (! *alternate_ptr) {
10131         *alternate_ptr = newAV();
10132     }
10133     sv = newSVpvn_utf8((char*)string, len, TRUE);
10134     av_push(*alternate_ptr, sv);
10135     return;
10136 }
10137
10138 /*
10139    parse a class specification and produce either an ANYOF node that
10140    matches the pattern or perhaps will be optimized into an EXACTish node
10141    instead. The node contains a bit map for the first 256 characters, with the
10142    corresponding bit set if that character is in the list.  For characters
10143    above 255, a range list is used */
10144
10145 STATIC regnode *
10146 S_regclass(pTHX_ RExC_state_t *pRExC_state, U32 depth)
10147 {
10148     dVAR;
10149     register UV nextvalue;
10150     register IV prevvalue = OOB_UNICODE;
10151     register IV range = 0;
10152     UV value = 0; /* XXX:dmq: needs to be referenceable (unfortunately) */
10153     register regnode *ret;
10154     STRLEN numlen;
10155     IV namedclass;
10156     char *rangebegin = NULL;
10157     bool need_class = 0;
10158     bool allow_full_fold = TRUE;   /* Assume wants multi-char folding */
10159     SV *listsv = NULL;
10160     STRLEN initial_listsv_len = 0; /* Kind of a kludge to see if it is more
10161                                       than just initialized.  */
10162     SV* properties = NULL;    /* Code points that match \p{} \P{} */
10163     UV element_count = 0;   /* Number of distinct elements in the class.
10164                                Optimizations may be possible if this is tiny */
10165     UV n;
10166
10167     /* Unicode properties are stored in a swash; this holds the current one
10168      * being parsed.  If this swash is the only above-latin1 component of the
10169      * character class, an optimization is to pass it directly on to the
10170      * execution engine.  Otherwise, it is set to NULL to indicate that there
10171      * are other things in the class that have to be dealt with at execution
10172      * time */
10173     SV* swash = NULL;           /* Code points that match \p{} \P{} */
10174
10175     /* Set if a component of this character class is user-defined; just passed
10176      * on to the engine */
10177     UV has_user_defined_property = 0;
10178
10179     /* code points this node matches that can't be stored in the bitmap */
10180     SV* nonbitmap = NULL;
10181
10182     /* The items that are to match that aren't stored in the bitmap, but are a
10183      * result of things that are stored there.  This is the fold closure of
10184      * such a character, either because it has DEPENDS semantics and shouldn't
10185      * be matched unless the target string is utf8, or is a code point that is
10186      * too large for the bit map, as for example, the fold of the MICRO SIGN is
10187      * above 255.  This all is solely for performance reasons.  By having this
10188      * code know the outside-the-bitmap folds that the bitmapped characters are
10189      * involved with, we don't have to go out to disk to find the list of
10190      * matches, unless the character class includes code points that aren't
10191      * storable in the bit map.  That means that a character class with an 's'
10192      * in it, for example, doesn't need to go out to disk to find everything
10193      * that matches.  A 2nd list is used so that the 'nonbitmap' list is kept
10194      * empty unless there is something whose fold we don't know about, and will
10195      * have to go out to the disk to find. */
10196     SV* l1_fold_invlist = NULL;
10197
10198     /* List of multi-character folds that are matched by this node */
10199     AV* unicode_alternate  = NULL;
10200 #ifdef EBCDIC
10201     UV literal_endpoint = 0;
10202 #endif
10203     UV stored = 0;  /* how many chars stored in the bitmap */
10204
10205     regnode * const orig_emit = RExC_emit; /* Save the original RExC_emit in
10206         case we need to change the emitted regop to an EXACT. */
10207     const char * orig_parse = RExC_parse;
10208     GET_RE_DEBUG_FLAGS_DECL;
10209
10210     PERL_ARGS_ASSERT_REGCLASS;
10211 #ifndef DEBUGGING
10212     PERL_UNUSED_ARG(depth);
10213 #endif
10214
10215     DEBUG_PARSE("clas");
10216
10217     /* Assume we are going to generate an ANYOF node. */
10218     ret = reganode(pRExC_state, ANYOF, 0);
10219
10220
10221     if (!SIZE_ONLY) {
10222         ANYOF_FLAGS(ret) = 0;
10223     }
10224
10225     if (UCHARAT(RExC_parse) == '^') {   /* Complement of range. */
10226         RExC_naughty++;
10227         RExC_parse++;
10228         if (!SIZE_ONLY)
10229             ANYOF_FLAGS(ret) |= ANYOF_INVERT;
10230
10231         /* We have decided to not allow multi-char folds in inverted character
10232          * classes, due to the confusion that can happen, especially with
10233          * classes that are designed for a non-Unicode world:  You have the
10234          * peculiar case that:
10235             "s s" =~ /^[^\xDF]+$/i => Y
10236             "ss"  =~ /^[^\xDF]+$/i => N
10237          *
10238          * See [perl #89750] */
10239         allow_full_fold = FALSE;
10240     }
10241
10242     if (SIZE_ONLY) {
10243         RExC_size += ANYOF_SKIP;
10244         listsv = &PL_sv_undef; /* For code scanners: listsv always non-NULL. */
10245     }
10246     else {
10247         RExC_emit += ANYOF_SKIP;
10248         if (LOC) {
10249             ANYOF_FLAGS(ret) |= ANYOF_LOCALE;
10250         }
10251         ANYOF_BITMAP_ZERO(ret);
10252         listsv = newSVpvs("# comment\n");
10253         initial_listsv_len = SvCUR(listsv);
10254     }
10255
10256     nextvalue = RExC_parse < RExC_end ? UCHARAT(RExC_parse) : 0;
10257
10258     if (!SIZE_ONLY && POSIXCC(nextvalue))
10259         checkposixcc(pRExC_state);
10260
10261     /* allow 1st char to be ] (allowing it to be - is dealt with later) */
10262     if (UCHARAT(RExC_parse) == ']')
10263         goto charclassloop;
10264
10265 parseit:
10266     while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != ']') {
10267
10268     charclassloop:
10269
10270         namedclass = OOB_NAMEDCLASS; /* initialize as illegal */
10271
10272         if (!range) {
10273             rangebegin = RExC_parse;
10274             element_count++;
10275         }
10276         if (UTF) {
10277             value = utf8n_to_uvchr((U8*)RExC_parse,
10278                                    RExC_end - RExC_parse,
10279                                    &numlen, UTF8_ALLOW_DEFAULT);
10280             RExC_parse += numlen;
10281         }
10282         else
10283             value = UCHARAT(RExC_parse++);
10284
10285         nextvalue = RExC_parse < RExC_end ? UCHARAT(RExC_parse) : 0;
10286         if (value == '[' && POSIXCC(nextvalue))
10287             namedclass = regpposixcc(pRExC_state, value);
10288         else if (value == '\\') {
10289             if (UTF) {
10290                 value = utf8n_to_uvchr((U8*)RExC_parse,
10291                                    RExC_end - RExC_parse,
10292                                    &numlen, UTF8_ALLOW_DEFAULT);
10293                 RExC_parse += numlen;
10294             }
10295             else
10296                 value = UCHARAT(RExC_parse++);
10297             /* Some compilers cannot handle switching on 64-bit integer
10298              * values, therefore value cannot be an UV.  Yes, this will
10299              * be a problem later if we want switch on Unicode.
10300              * A similar issue a little bit later when switching on
10301              * namedclass. --jhi */
10302             switch ((I32)value) {
10303             case 'w':   namedclass = ANYOF_ALNUM;       break;
10304             case 'W':   namedclass = ANYOF_NALNUM;      break;
10305             case 's':   namedclass = ANYOF_SPACE;       break;
10306             case 'S':   namedclass = ANYOF_NSPACE;      break;
10307             case 'd':   namedclass = ANYOF_DIGIT;       break;
10308             case 'D':   namedclass = ANYOF_NDIGIT;      break;
10309             case 'v':   namedclass = ANYOF_VERTWS;      break;
10310             case 'V':   namedclass = ANYOF_NVERTWS;     break;
10311             case 'h':   namedclass = ANYOF_HORIZWS;     break;
10312             case 'H':   namedclass = ANYOF_NHORIZWS;    break;
10313             case 'N':  /* Handle \N{NAME} in class */
10314                 {
10315                     /* We only pay attention to the first char of 
10316                     multichar strings being returned. I kinda wonder
10317                     if this makes sense as it does change the behaviour
10318                     from earlier versions, OTOH that behaviour was broken
10319                     as well. */
10320                     UV v; /* value is register so we cant & it /grrr */
10321                     if (reg_namedseq(pRExC_state, &v, NULL, depth)) {
10322                         goto parseit;
10323                     }
10324                     value= v; 
10325                 }
10326                 break;
10327             case 'p':
10328             case 'P':
10329                 {
10330                 char *e;
10331                 if (RExC_parse >= RExC_end)
10332                     vFAIL2("Empty \\%c{}", (U8)value);
10333                 if (*RExC_parse == '{') {
10334                     const U8 c = (U8)value;
10335                     e = strchr(RExC_parse++, '}');
10336                     if (!e)
10337                         vFAIL2("Missing right brace on \\%c{}", c);
10338                     while (isSPACE(UCHARAT(RExC_parse)))
10339                         RExC_parse++;
10340                     if (e == RExC_parse)
10341                         vFAIL2("Empty \\%c{}", c);
10342                     n = e - RExC_parse;
10343                     while (isSPACE(UCHARAT(RExC_parse + n - 1)))
10344                         n--;
10345                 }
10346                 else {
10347                     e = RExC_parse;
10348                     n = 1;
10349                 }
10350                 if (!SIZE_ONLY) {
10351                     SV** invlistsvp;
10352                     SV* invlist;
10353                     char* name;
10354                     if (UCHARAT(RExC_parse) == '^') {
10355                          RExC_parse++;
10356                          n--;
10357                          value = value == 'p' ? 'P' : 'p'; /* toggle */
10358                          while (isSPACE(UCHARAT(RExC_parse))) {
10359                               RExC_parse++;
10360                               n--;
10361                          }
10362                     }
10363                     /* Try to get the definition of the property into
10364                      * <invlist>.  If /i is in effect, the effective property
10365                      * will have its name be <__NAME_i>.  The design is
10366                      * discussed in commit
10367                      * 2f833f5208e26b208886e51e09e2c072b5eabb46 */
10368                     Newx(name, n + sizeof("_i__\n"), char);
10369
10370                     sprintf(name, "%s%.*s%s\n",
10371                                     (FOLD) ? "__" : "",
10372                                     (int)n,
10373                                     RExC_parse,
10374                                     (FOLD) ? "_i" : ""
10375                     );
10376
10377                     /* Look up the property name, and get its swash and
10378                      * inversion list, if the property is found  */
10379                     if (swash) {
10380                         SvREFCNT_dec(swash);
10381                     }
10382                     swash = _core_swash_init("utf8", name, &PL_sv_undef,
10383                                              1, /* binary */
10384                                              0, /* not tr/// */
10385                                              TRUE, /* this routine will handle
10386                                                       undefined properties */
10387                                              NULL, FALSE /* No inversion list */
10388                                             );
10389                     if (   ! swash
10390                         || ! SvROK(swash)
10391                         || ! SvTYPE(SvRV(swash)) == SVt_PVHV
10392                         || ! (invlistsvp =
10393                                 hv_fetchs(MUTABLE_HV(SvRV(swash)),
10394                                 "INVLIST", FALSE))
10395                         || ! (invlist = *invlistsvp))
10396                     {
10397                         if (swash) {
10398                             SvREFCNT_dec(swash);
10399                             swash = NULL;
10400                         }
10401
10402                         /* Here didn't find it.  It could be a user-defined
10403                          * property that will be available at run-time.  Add it
10404                          * to the list to look up then */
10405                         Perl_sv_catpvf(aTHX_ listsv, "%cutf8::%s\n",
10406                                         (value == 'p' ? '+' : '!'),
10407                                         name);
10408                         has_user_defined_property = 1;
10409
10410                         /* We don't know yet, so have to assume that the
10411                          * property could match something in the Latin1 range,
10412                          * hence something that isn't utf8 */
10413                         ANYOF_FLAGS(ret) |= ANYOF_NONBITMAP_NON_UTF8;
10414                     }
10415                     else {
10416
10417                         /* Here, did get the swash and its inversion list.  If
10418                          * the swash is from a user-defined property, then this
10419                          * whole character class should be regarded as such */
10420                         SV** user_defined_svp =
10421                                             hv_fetchs(MUTABLE_HV(SvRV(swash)),
10422                                                         "USER_DEFINED", FALSE);
10423                         if (user_defined_svp) {
10424                             has_user_defined_property
10425                                                     |= SvUV(*user_defined_svp);
10426                         }
10427
10428                         /* Invert if asking for the complement */
10429                         if (value == 'P') {
10430
10431                             /* Add to any existing list */
10432                             if (! properties) {
10433                                 properties = invlist_clone(invlist);
10434                                 _invlist_invert(properties);
10435                             }
10436                             else {
10437                                 invlist = invlist_clone(invlist);
10438                                 _invlist_invert(invlist);
10439                                 _invlist_union(properties, invlist, &properties);
10440                                 SvREFCNT_dec(invlist);
10441                             }
10442
10443                             /* The swash can't be used as-is, because we've
10444                              * inverted things; delay removing it to here after
10445                              * have copied its invlist above */
10446                             SvREFCNT_dec(swash);
10447                             swash = NULL;
10448                         }
10449                         else {
10450                             if (! properties) {
10451                                 properties = invlist_clone(invlist);
10452                             }
10453                             else {
10454                                 _invlist_union(properties, invlist, &properties);
10455                             }
10456                         }
10457                     }
10458                     Safefree(name);
10459                 }
10460                 RExC_parse = e + 1;
10461                 namedclass = ANYOF_MAX;  /* no official name, but it's named */
10462
10463                 /* \p means they want Unicode semantics */
10464                 RExC_uni_semantics = 1;
10465                 }
10466                 break;
10467             case 'n':   value = '\n';                   break;
10468             case 'r':   value = '\r';                   break;
10469             case 't':   value = '\t';                   break;
10470             case 'f':   value = '\f';                   break;
10471             case 'b':   value = '\b';                   break;
10472             case 'e':   value = ASCII_TO_NATIVE('\033');break;
10473             case 'a':   value = ASCII_TO_NATIVE('\007');break;
10474             case 'o':
10475                 RExC_parse--;   /* function expects to be pointed at the 'o' */
10476                 {
10477                     const char* error_msg;
10478                     bool valid = grok_bslash_o(RExC_parse,
10479                                                &value,
10480                                                &numlen,
10481                                                &error_msg,
10482                                                SIZE_ONLY);
10483                     RExC_parse += numlen;
10484                     if (! valid) {
10485                         vFAIL(error_msg);
10486                     }
10487                 }
10488                 if (PL_encoding && value < 0x100) {
10489                     goto recode_encoding;
10490                 }
10491                 break;
10492             case 'x':
10493                 if (*RExC_parse == '{') {
10494                     I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
10495                         | PERL_SCAN_DISALLOW_PREFIX;
10496                     char * const e = strchr(RExC_parse++, '}');
10497                     if (!e)
10498                         vFAIL("Missing right brace on \\x{}");
10499
10500                     numlen = e - RExC_parse;
10501                     value = grok_hex(RExC_parse, &numlen, &flags, NULL);
10502                     RExC_parse = e + 1;
10503                 }
10504                 else {
10505                     I32 flags = PERL_SCAN_DISALLOW_PREFIX;
10506                     numlen = 2;
10507                     value = grok_hex(RExC_parse, &numlen, &flags, NULL);
10508                     RExC_parse += numlen;
10509                 }
10510                 if (PL_encoding && value < 0x100)
10511                     goto recode_encoding;
10512                 break;
10513             case 'c':
10514                 value = grok_bslash_c(*RExC_parse++, UTF, SIZE_ONLY);
10515                 break;
10516             case '0': case '1': case '2': case '3': case '4':
10517             case '5': case '6': case '7':
10518                 {
10519                     /* Take 1-3 octal digits */
10520                     I32 flags = PERL_SCAN_SILENT_ILLDIGIT;
10521                     numlen = 3;
10522                     value = grok_oct(--RExC_parse, &numlen, &flags, NULL);
10523                     RExC_parse += numlen;
10524                     if (PL_encoding && value < 0x100)
10525                         goto recode_encoding;
10526                     break;
10527                 }
10528             recode_encoding:
10529                 if (! RExC_override_recoding) {
10530                     SV* enc = PL_encoding;
10531                     value = reg_recode((const char)(U8)value, &enc);
10532                     if (!enc && SIZE_ONLY)
10533                         ckWARNreg(RExC_parse,
10534                                   "Invalid escape in the specified encoding");
10535                     break;
10536                 }
10537             default:
10538                 /* Allow \_ to not give an error */
10539                 if (!SIZE_ONLY && isALNUM(value) && value != '_') {
10540                     ckWARN2reg(RExC_parse,
10541                                "Unrecognized escape \\%c in character class passed through",
10542                                (int)value);
10543                 }
10544                 break;
10545             }
10546         } /* end of \blah */
10547 #ifdef EBCDIC
10548         else
10549             literal_endpoint++;
10550 #endif
10551
10552         if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */
10553
10554             /* What matches in a locale is not known until runtime, so need to
10555              * (one time per class) allocate extra space to pass to regexec.
10556              * The space will contain a bit for each named class that is to be
10557              * matched against.  This isn't needed for \p{} and pseudo-classes,
10558              * as they are not affected by locale, and hence are dealt with
10559              * separately */
10560             if (LOC && namedclass < ANYOF_MAX && ! need_class) {
10561                 need_class = 1;
10562                 if (SIZE_ONLY) {
10563                     RExC_size += ANYOF_CLASS_SKIP - ANYOF_SKIP;
10564                 }
10565                 else {
10566                     RExC_emit += ANYOF_CLASS_SKIP - ANYOF_SKIP;
10567                     ANYOF_CLASS_ZERO(ret);
10568                 }
10569                 ANYOF_FLAGS(ret) |= ANYOF_CLASS;
10570             }
10571
10572             /* a bad range like a-\d, a-[:digit:].  The '-' is taken as a
10573              * literal, as is the character that began the false range, i.e.
10574              * the 'a' in the examples */
10575             if (range) {
10576                 if (!SIZE_ONLY) {
10577                     const int w =
10578                         RExC_parse >= rangebegin ?
10579                         RExC_parse - rangebegin : 0;
10580                     ckWARN4reg(RExC_parse,
10581                                "False [] range \"%*.*s\"",
10582                                w, w, rangebegin);
10583
10584                     stored +=
10585                          set_regclass_bit(pRExC_state, ret, '-', &l1_fold_invlist, &unicode_alternate);
10586                     if (prevvalue < 256) {
10587                         stored +=
10588                          set_regclass_bit(pRExC_state, ret, (U8) prevvalue, &l1_fold_invlist, &unicode_alternate);
10589                     }
10590                     else {
10591                         nonbitmap = add_cp_to_invlist(nonbitmap, prevvalue);
10592                     }
10593                 }
10594
10595                 range = 0; /* this was not a true range */
10596             }
10597
10598             if (!SIZE_ONLY) {
10599                 const char *what = NULL;
10600                 char yesno = 0;
10601
10602                 /* Possible truncation here but in some 64-bit environments
10603                  * the compiler gets heartburn about switch on 64-bit values.
10604                  * A similar issue a little earlier when switching on value.
10605                  * --jhi */
10606                 switch ((I32)namedclass) {
10607                 
10608                 case _C_C_T_(ALNUMC, isALNUMC_L1, isALNUMC, "XPosixAlnum", "XPosixAlnum");
10609                 case _C_C_T_(ALPHA, isALPHA_L1, isALPHA, "XPosixAlpha", "XPosixAlpha");
10610                 case _C_C_T_(BLANK, isBLANK_L1, isBLANK, "XPosixBlank", "XPosixBlank");
10611                 case _C_C_T_(CNTRL, isCNTRL_L1, isCNTRL, "XPosixCntrl", "XPosixCntrl");
10612                 case _C_C_T_(GRAPH, isGRAPH_L1, isGRAPH, "XPosixGraph", "XPosixGraph");
10613                 case _C_C_T_(LOWER, isLOWER_L1, isLOWER, "XPosixLower", "__XPosixLower_i");
10614                 case _C_C_T_(PRINT, isPRINT_L1, isPRINT, "XPosixPrint", "XPosixPrint");
10615                 case _C_C_T_(PSXSPC, isPSXSPC_L1, isPSXSPC, "XPosixSpace", "XPosixSpace");
10616                 case _C_C_T_(PUNCT, isPUNCT_L1, isPUNCT, "XPosixPunct", "XPosixPunct");
10617                 case _C_C_T_(UPPER, isUPPER_L1, isUPPER, "XPosixUpper", "__XPosixUpper_i");
10618                 /* \s, \w match all unicode if utf8. */
10619                 case _C_C_T_(SPACE, isSPACE_L1, isSPACE, "SpacePerl", "SpacePerl");
10620                 case _C_C_T_(ALNUM, isWORDCHAR_L1, isALNUM, "Word", "Word");
10621                 case _C_C_T_(XDIGIT, isXDIGIT_L1, isXDIGIT, "XPosixXDigit", "XPosixXDigit");
10622                 case _C_C_T_NOLOC_(VERTWS, is_VERTWS_latin1(&value), "VertSpace");
10623                 case _C_C_T_NOLOC_(HORIZWS, is_HORIZWS_latin1(&value), "HorizSpace");
10624                 case ANYOF_ASCII:
10625                     if (LOC)
10626                         ANYOF_CLASS_SET(ret, ANYOF_ASCII);
10627                     else {
10628                         for (value = 0; value < 128; value++)
10629                             stored +=
10630                               set_regclass_bit(pRExC_state, ret, (U8) ASCII_TO_NATIVE(value), &l1_fold_invlist, &unicode_alternate);
10631                     }
10632                     yesno = '+';
10633                     what = NULL;        /* Doesn't match outside ascii, so
10634                                            don't want to add +utf8:: */
10635                     break;
10636                 case ANYOF_NASCII:
10637                     if (LOC)
10638                         ANYOF_CLASS_SET(ret, ANYOF_NASCII);
10639                     else {
10640                         for (value = 128; value < 256; value++)
10641                             stored +=
10642                               set_regclass_bit(pRExC_state, ret, (U8) ASCII_TO_NATIVE(value), &l1_fold_invlist, &unicode_alternate);
10643                     }
10644                     ANYOF_FLAGS(ret) |= ANYOF_UNICODE_ALL;
10645                     yesno = '!';
10646                     what = "ASCII";
10647                     break;              
10648                 case ANYOF_DIGIT:
10649                     if (LOC)
10650                         ANYOF_CLASS_SET(ret, ANYOF_DIGIT);
10651                     else {
10652                         /* consecutive digits assumed */
10653                         for (value = '0'; value <= '9'; value++)
10654                             stored +=
10655                               set_regclass_bit(pRExC_state, ret, (U8) value, &l1_fold_invlist, &unicode_alternate);
10656                     }
10657                     yesno = '+';
10658                     what = "Digit";
10659                     break;
10660                 case ANYOF_NDIGIT:
10661                     if (LOC)
10662                         ANYOF_CLASS_SET(ret, ANYOF_NDIGIT);
10663                     else {
10664                         /* consecutive digits assumed */
10665                         for (value = 0; value < '0'; value++)
10666                             stored +=
10667                               set_regclass_bit(pRExC_state, ret, (U8) value, &l1_fold_invlist, &unicode_alternate);
10668                         for (value = '9' + 1; value < 256; value++)
10669                             stored +=
10670                               set_regclass_bit(pRExC_state, ret, (U8) value, &l1_fold_invlist, &unicode_alternate);
10671                     }
10672                     yesno = '!';
10673                     what = "Digit";
10674                     if (AT_LEAST_ASCII_RESTRICTED ) {
10675                         ANYOF_FLAGS(ret) |= ANYOF_UNICODE_ALL;
10676                     }
10677                     break;              
10678                 case ANYOF_MAX:
10679                     /* this is to handle \p and \P */
10680                     break;
10681                 default:
10682                     vFAIL("Invalid [::] class");
10683                     break;
10684                 }
10685                 if (what && ! (AT_LEAST_ASCII_RESTRICTED)) {
10686                     /* Strings such as "+utf8::isWord\n" */
10687                     Perl_sv_catpvf(aTHX_ listsv, "%cutf8::%s\n", yesno, what);
10688                 }
10689
10690                 continue;
10691             }
10692         } /* end of namedclass \blah */
10693
10694         if (range) {
10695             if (prevvalue > (IV)value) /* b-a */ {
10696                 const int w = RExC_parse - rangebegin;
10697                 Simple_vFAIL4("Invalid [] range \"%*.*s\"", w, w, rangebegin);
10698                 range = 0; /* not a valid range */
10699             }
10700         }
10701         else {
10702             prevvalue = value; /* save the beginning of the range */
10703             if (RExC_parse+1 < RExC_end
10704                 && *RExC_parse == '-'
10705                 && RExC_parse[1] != ']')
10706             {
10707                 RExC_parse++;
10708
10709                 /* a bad range like \w-, [:word:]- ? */
10710                 if (namedclass > OOB_NAMEDCLASS) {
10711                     if (ckWARN(WARN_REGEXP)) {
10712                         const int w =
10713                             RExC_parse >= rangebegin ?
10714                             RExC_parse - rangebegin : 0;
10715                         vWARN4(RExC_parse,
10716                                "False [] range \"%*.*s\"",
10717                                w, w, rangebegin);
10718                     }
10719                     if (!SIZE_ONLY)
10720                         stored +=
10721                             set_regclass_bit(pRExC_state, ret, '-', &l1_fold_invlist, &unicode_alternate);
10722                 } else
10723                     range = 1;  /* yeah, it's a range! */
10724                 continue;       /* but do it the next time */
10725             }
10726         }
10727
10728         /* non-Latin1 code point implies unicode semantics.  Must be set in
10729          * pass1 so is there for the whole of pass 2 */
10730         if (value > 255) {
10731             RExC_uni_semantics = 1;
10732         }
10733
10734         /* now is the next time */
10735         if (!SIZE_ONLY) {
10736             if (prevvalue < 256) {
10737                 const IV ceilvalue = value < 256 ? value : 255;
10738                 IV i;
10739 #ifdef EBCDIC
10740                 /* In EBCDIC [\x89-\x91] should include
10741                  * the \x8e but [i-j] should not. */
10742                 if (literal_endpoint == 2 &&
10743                     ((isLOWER(prevvalue) && isLOWER(ceilvalue)) ||
10744                      (isUPPER(prevvalue) && isUPPER(ceilvalue))))
10745                 {
10746                     if (isLOWER(prevvalue)) {
10747                         for (i = prevvalue; i <= ceilvalue; i++)
10748                             if (isLOWER(i) && !ANYOF_BITMAP_TEST(ret,i)) {
10749                                 stored +=
10750                                   set_regclass_bit(pRExC_state, ret, (U8) i, &l1_fold_invlist, &unicode_alternate);
10751                             }
10752                     } else {
10753                         for (i = prevvalue; i <= ceilvalue; i++)
10754                             if (isUPPER(i) && !ANYOF_BITMAP_TEST(ret,i)) {
10755                                 stored +=
10756                                   set_regclass_bit(pRExC_state, ret, (U8) i, &l1_fold_invlist, &unicode_alternate);
10757                             }
10758                     }
10759                 }
10760                 else
10761 #endif
10762                       for (i = prevvalue; i <= ceilvalue; i++) {
10763                         stored += set_regclass_bit(pRExC_state, ret, (U8) i, &l1_fold_invlist, &unicode_alternate);
10764                       }
10765           }
10766           if (value > 255) {
10767             const UV prevnatvalue  = NATIVE_TO_UNI(prevvalue);
10768             const UV natvalue      = NATIVE_TO_UNI(value);
10769             nonbitmap = add_range_to_invlist(nonbitmap, prevnatvalue, natvalue);
10770         }
10771 #ifdef EBCDIC
10772             literal_endpoint = 0;
10773 #endif
10774         }
10775
10776         range = 0; /* this range (if it was one) is done now */
10777     }
10778
10779
10780
10781     if (SIZE_ONLY)
10782         return ret;
10783     /****** !SIZE_ONLY AFTER HERE *********/
10784
10785     /* If folding and there are code points above 255, we calculate all
10786      * characters that could fold to or from the ones already on the list */
10787     if (FOLD && nonbitmap) {
10788         UV start, end;  /* End points of code point ranges */
10789
10790         SV* fold_intersection = NULL;
10791
10792         /* This is a list of all the characters that participate in folds
10793             * (except marks, etc in multi-char folds */
10794         if (! PL_utf8_foldable) {
10795             SV* swash = swash_init("utf8", "Cased", &PL_sv_undef, 1, 0);
10796             PL_utf8_foldable = _swash_to_invlist(swash);
10797             SvREFCNT_dec(swash);
10798         }
10799
10800         /* This is a hash that for a particular fold gives all characters
10801             * that are involved in it */
10802         if (! PL_utf8_foldclosures) {
10803
10804             /* If we were unable to find any folds, then we likely won't be
10805              * able to find the closures.  So just create an empty list.
10806              * Folding will effectively be restricted to the non-Unicode rules
10807              * hard-coded into Perl.  (This case happens legitimately during
10808              * compilation of Perl itself before the Unicode tables are
10809              * generated) */
10810             if (invlist_len(PL_utf8_foldable) == 0) {
10811                 PL_utf8_foldclosures = newHV();
10812             } else {
10813                 /* If the folds haven't been read in, call a fold function
10814                     * to force that */
10815                 if (! PL_utf8_tofold) {
10816                     U8 dummy[UTF8_MAXBYTES+1];
10817                     STRLEN dummy_len;
10818
10819                     /* This particular string is above \xff in both UTF-8 and
10820                      * UTFEBCDIC */
10821                     to_utf8_fold((U8*) "\xC8\x80", dummy, &dummy_len);
10822                     assert(PL_utf8_tofold); /* Verify that worked */
10823                 }
10824                 PL_utf8_foldclosures = _swash_inversion_hash(PL_utf8_tofold);
10825             }
10826         }
10827
10828         /* Only the characters in this class that participate in folds need be
10829          * checked.  Get the intersection of this class and all the possible
10830          * characters that are foldable.  This can quickly narrow down a large
10831          * class */
10832         _invlist_intersection(PL_utf8_foldable, nonbitmap, &fold_intersection);
10833
10834         /* Now look at the foldable characters in this class individually */
10835         invlist_iterinit(fold_intersection);
10836         while (invlist_iternext(fold_intersection, &start, &end)) {
10837             UV j;
10838
10839             /* Look at every character in the range */
10840             for (j = start; j <= end; j++) {
10841
10842                 /* Get its fold */
10843                 U8 foldbuf[UTF8_MAXBYTES_CASE+1];
10844                 STRLEN foldlen;
10845                 const UV f =
10846                     _to_uni_fold_flags(j, foldbuf, &foldlen, allow_full_fold);
10847
10848                 if (foldlen > (STRLEN)UNISKIP(f)) {
10849
10850                     /* Any multicharacter foldings (disallowed in lookbehind
10851                      * patterns) require the following transform: [ABCDEF] ->
10852                      * (?:[ABCabcDEFd]|pq|rst) where E folds into "pq" and F
10853                      * folds into "rst", all other characters fold to single
10854                      * characters.  We save away these multicharacter foldings,
10855                      * to be later saved as part of the additional "s" data. */
10856                     if (! RExC_in_lookbehind) {
10857                         U8* loc = foldbuf;
10858                         U8* e = foldbuf + foldlen;
10859
10860                         /* If any of the folded characters of this are in the
10861                          * Latin1 range, tell the regex engine that this can
10862                          * match a non-utf8 target string.  The only multi-byte
10863                          * fold whose source is in the Latin1 range (U+00DF)
10864                          * applies only when the target string is utf8, or
10865                          * under unicode rules */
10866                         if (j > 255 || AT_LEAST_UNI_SEMANTICS) {
10867                             while (loc < e) {
10868
10869                                 /* Can't mix ascii with non- under /aa */
10870                                 if (MORE_ASCII_RESTRICTED
10871                                     && (isASCII(*loc) != isASCII(j)))
10872                                 {
10873                                     goto end_multi_fold;
10874                                 }
10875                                 if (UTF8_IS_INVARIANT(*loc)
10876                                     || UTF8_IS_DOWNGRADEABLE_START(*loc))
10877                                 {
10878                                     /* Can't mix above and below 256 under LOC
10879                                      */
10880                                     if (LOC) {
10881                                         goto end_multi_fold;
10882                                     }
10883                                     ANYOF_FLAGS(ret)
10884                                             |= ANYOF_NONBITMAP_NON_UTF8;
10885                                     break;
10886                                 }
10887                                 loc += UTF8SKIP(loc);
10888                             }
10889                         }
10890
10891                         add_alternate(&unicode_alternate, foldbuf, foldlen);
10892                     end_multi_fold: ;
10893                     }
10894
10895                     /* This is special-cased, as it is the only letter which
10896                      * has both a multi-fold and single-fold in Latin1.  All
10897                      * the other chars that have single and multi-folds are
10898                      * always in utf8, and the utf8 folding algorithm catches
10899                      * them */
10900                     if (! LOC && j == LATIN_CAPITAL_LETTER_SHARP_S) {
10901                         stored += set_regclass_bit(pRExC_state,
10902                                         ret,
10903                                         LATIN_SMALL_LETTER_SHARP_S,
10904                                         &l1_fold_invlist, &unicode_alternate);
10905                     }
10906                 }
10907                 else {
10908                     /* Single character fold.  Add everything in its fold
10909                      * closure to the list that this node should match */
10910                     SV** listp;
10911
10912                     /* The fold closures data structure is a hash with the keys
10913                      * being every character that is folded to, like 'k', and
10914                      * the values each an array of everything that folds to its
10915                      * key.  e.g. [ 'k', 'K', KELVIN_SIGN ] */
10916                     if ((listp = hv_fetch(PL_utf8_foldclosures,
10917                                     (char *) foldbuf, foldlen, FALSE)))
10918                     {
10919                         AV* list = (AV*) *listp;
10920                         IV k;
10921                         for (k = 0; k <= av_len(list); k++) {
10922                             SV** c_p = av_fetch(list, k, FALSE);
10923                             UV c;
10924                             if (c_p == NULL) {
10925                                 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
10926                             }
10927                             c = SvUV(*c_p);
10928
10929                             /* /aa doesn't allow folds between ASCII and non-;
10930                              * /l doesn't allow them between above and below
10931                              * 256 */
10932                             if ((MORE_ASCII_RESTRICTED
10933                                  && (isASCII(c) != isASCII(j)))
10934                                     || (LOC && ((c < 256) != (j < 256))))
10935                             {
10936                                 continue;
10937                             }
10938
10939                             if (c < 256 && AT_LEAST_UNI_SEMANTICS) {
10940                                 stored += set_regclass_bit(pRExC_state,
10941                                         ret,
10942                                         (U8) c,
10943                                         &l1_fold_invlist, &unicode_alternate);
10944                             }
10945                                 /* It may be that the code point is already in
10946                                  * this range or already in the bitmap, in
10947                                  * which case we need do nothing */
10948                             else if ((c < start || c > end)
10949                                         && (c > 255
10950                                             || ! ANYOF_BITMAP_TEST(ret, c)))
10951                             {
10952                                 nonbitmap = add_cp_to_invlist(nonbitmap, c);
10953                             }
10954                         }
10955                     }
10956                 }
10957             }
10958         }
10959         SvREFCNT_dec(fold_intersection);
10960     }
10961
10962     /* Combine the two lists into one. */
10963     if (l1_fold_invlist) {
10964         if (nonbitmap) {
10965             _invlist_union(nonbitmap, l1_fold_invlist, &nonbitmap);
10966             SvREFCNT_dec(l1_fold_invlist);
10967         }
10968         else {
10969             nonbitmap = l1_fold_invlist;
10970         }
10971     }
10972
10973     /* And combine the result (if any) with any inversion list from properties.
10974      * The lists are kept separate up to now because we don't want to fold the
10975      * properties */
10976     if (properties) {
10977         if (nonbitmap) {
10978             _invlist_union(nonbitmap, properties, &nonbitmap);
10979             SvREFCNT_dec(properties);
10980         }
10981         else {
10982             nonbitmap = properties;
10983         }
10984     }
10985
10986     /* Here, <nonbitmap> contains all the code points we can determine at
10987      * compile time that we haven't put into the bitmap.  Go through it, and
10988      * for things that belong in the bitmap, put them there, and delete from
10989      * <nonbitmap> */
10990     if (nonbitmap) {
10991
10992         /* Above-ASCII code points in /d have to stay in <nonbitmap>, as they
10993          * possibly only should match when the target string is UTF-8 */
10994         UV max_cp_to_set = (DEPENDS_SEMANTICS) ? 127 : 255;
10995
10996         /* This gets set if we actually need to modify things */
10997         bool change_invlist = FALSE;
10998
10999         UV start, end;
11000
11001         /* Start looking through <nonbitmap> */
11002         invlist_iterinit(nonbitmap);
11003         while (invlist_iternext(nonbitmap, &start, &end)) {
11004             UV high;
11005             int i;
11006
11007             /* Quit if are above what we should change */
11008             if (start > max_cp_to_set) {
11009                 break;
11010             }
11011
11012             change_invlist = TRUE;
11013
11014             /* Set all the bits in the range, up to the max that we are doing */
11015             high = (end < max_cp_to_set) ? end : max_cp_to_set;
11016             for (i = start; i <= (int) high; i++) {
11017                 if (! ANYOF_BITMAP_TEST(ret, i)) {
11018                     ANYOF_BITMAP_SET(ret, i);
11019                     stored++;
11020                     prevvalue = value;
11021                     value = i;
11022                 }
11023             }
11024         }
11025
11026         /* Done with loop; set <nonbitmap> to not include any code points that
11027          * are in the bitmap */
11028         if (change_invlist) {
11029             SV* keep_list = _new_invlist(2);
11030             _append_range_to_invlist(keep_list, max_cp_to_set + 1, UV_MAX);
11031             _invlist_intersection(nonbitmap, keep_list, &nonbitmap);
11032             SvREFCNT_dec(keep_list);
11033         }
11034
11035         /* If have completely emptied it, remove it completely */
11036         if (invlist_len(nonbitmap) == 0) {
11037             SvREFCNT_dec(nonbitmap);
11038             nonbitmap = NULL;
11039         }
11040     }
11041
11042     /* Here, we have calculated what code points should be in the character
11043      * class.  <nonbitmap> does not overlap the bitmap except possibly in the
11044      * case of DEPENDS rules.
11045      *
11046      * Now we can see about various optimizations.  Fold calculation (which we
11047      * did above) needs to take place before inversion.  Otherwise /[^k]/i
11048      * would invert to include K, which under /i would match k, which it
11049      * shouldn't. */
11050
11051     /* Optimize inverted simple patterns (e.g. [^a-z]).  Note that we haven't
11052      * set the FOLD flag yet, so this does optimize those.  It doesn't
11053      * optimize locale.  Doing so perhaps could be done as long as there is
11054      * nothing like \w in it; some thought also would have to be given to the
11055      * interaction with above 0x100 chars */
11056     if ((ANYOF_FLAGS(ret) & ANYOF_INVERT)
11057         && ! LOC
11058         && ! unicode_alternate
11059         /* In case of /d, there are some things that should match only when in
11060          * not in the bitmap, i.e., they require UTF8 to match.  These are
11061          * listed in nonbitmap, but if ANYOF_NONBITMAP_NON_UTF8 is set in this
11062          * case, they don't require UTF8, so can invert here */
11063         && (! nonbitmap
11064             || ! DEPENDS_SEMANTICS
11065             || (ANYOF_FLAGS(ret) & ANYOF_NONBITMAP_NON_UTF8))
11066         && SvCUR(listsv) == initial_listsv_len)
11067     {
11068         int i;
11069         if (! nonbitmap) {
11070             for (i = 0; i < 256; ++i) {
11071                 if (ANYOF_BITMAP_TEST(ret, i)) {
11072                     ANYOF_BITMAP_CLEAR(ret, i);
11073                 }
11074                 else {
11075                     ANYOF_BITMAP_SET(ret, i);
11076                     prevvalue = value;
11077                     value = i;
11078                 }
11079             }
11080             /* The inversion means that everything above 255 is matched */
11081             ANYOF_FLAGS(ret) |= ANYOF_UNICODE_ALL;
11082         }
11083         else {
11084             /* Here, also has things outside the bitmap that may overlap with
11085              * the bitmap.  We have to sync them up, so that they get inverted
11086              * in both places.  Earlier, we removed all overlaps except in the
11087              * case of /d rules, so no syncing is needed except for this case
11088              */
11089             SV *remove_list = NULL;
11090
11091             if (DEPENDS_SEMANTICS) {
11092                 UV start, end;
11093
11094                 /* Set the bits that correspond to the ones that aren't in the
11095                  * bitmap.  Otherwise, when we invert, we'll miss these.
11096                  * Earlier, we removed from the nonbitmap all code points
11097                  * < 128, so there is no extra work here */
11098                 invlist_iterinit(nonbitmap);
11099                 while (invlist_iternext(nonbitmap, &start, &end)) {
11100                     if (start > 255) {  /* The bit map goes to 255 */
11101                         break;
11102                     }
11103                     if (end > 255) {
11104                         end = 255;
11105                     }
11106                     for (i = start; i <= (int) end; ++i) {
11107                         ANYOF_BITMAP_SET(ret, i);
11108                         prevvalue = value;
11109                         value = i;
11110                     }
11111                 }
11112             }
11113
11114             /* Now invert both the bitmap and the nonbitmap.  Anything in the
11115              * bitmap has to also be removed from the non-bitmap, but again,
11116              * there should not be overlap unless is /d rules. */
11117             _invlist_invert(nonbitmap);
11118
11119             for (i = 0; i < 256; ++i) {
11120                 if (ANYOF_BITMAP_TEST(ret, i)) {
11121                     ANYOF_BITMAP_CLEAR(ret, i);
11122                     if (DEPENDS_SEMANTICS) {
11123                         if (! remove_list) {
11124                             remove_list = _new_invlist(2);
11125                         }
11126                         remove_list = add_cp_to_invlist(remove_list, i);
11127                     }
11128                 }
11129                 else {
11130                     ANYOF_BITMAP_SET(ret, i);
11131                     prevvalue = value;
11132                     value = i;
11133                 }
11134             }
11135
11136             /* And do the removal */
11137             if (DEPENDS_SEMANTICS) {
11138                 if (remove_list) {
11139                     _invlist_subtract(nonbitmap, remove_list, &nonbitmap);
11140                     SvREFCNT_dec(remove_list);
11141                 }
11142             }
11143             else {
11144                 /* There is no overlap for non-/d, so just delete anything
11145                  * below 256 */
11146                 SV* keep_list = _new_invlist(2);
11147                 _append_range_to_invlist(keep_list, 256, UV_MAX);
11148                 _invlist_intersection(nonbitmap, keep_list, &nonbitmap);
11149                 SvREFCNT_dec(keep_list);
11150             }
11151         }
11152
11153         stored = 256 - stored;
11154
11155         /* Clear the invert flag since have just done it here */
11156         ANYOF_FLAGS(ret) &= ~ANYOF_INVERT;
11157     }
11158
11159     /* Folding in the bitmap is taken care of above, but not for locale (for
11160      * which we have to wait to see what folding is in effect at runtime), and
11161      * for some things not in the bitmap (only the upper latin folds in this
11162      * case, as all other single-char folding has been set above).  Set
11163      * run-time fold flag for these */
11164     if (FOLD && (LOC
11165                 || (DEPENDS_SEMANTICS
11166                     && nonbitmap
11167                     && ! (ANYOF_FLAGS(ret) & ANYOF_NONBITMAP_NON_UTF8))
11168                 || unicode_alternate))
11169     {
11170         ANYOF_FLAGS(ret) |= ANYOF_LOC_NONBITMAP_FOLD;
11171     }
11172
11173     /* A single character class can be "optimized" into an EXACTish node.
11174      * Note that since we don't currently count how many characters there are
11175      * outside the bitmap, we are XXX missing optimization possibilities for
11176      * them.  This optimization can't happen unless this is a truly single
11177      * character class, which means that it can't be an inversion into a
11178      * many-character class, and there must be no possibility of there being
11179      * things outside the bitmap.  'stored' (only) for locales doesn't include
11180      * \w, etc, so have to make a special test that they aren't present
11181      *
11182      * Similarly A 2-character class of the very special form like [bB] can be
11183      * optimized into an EXACTFish node, but only for non-locales, and for
11184      * characters which only have the two folds; so things like 'fF' and 'Ii'
11185      * wouldn't work because they are part of the fold of 'LATIN SMALL LIGATURE
11186      * FI'. */
11187     if (! nonbitmap
11188         && ! unicode_alternate
11189         && SvCUR(listsv) == initial_listsv_len
11190         && ! (ANYOF_FLAGS(ret) & (ANYOF_INVERT|ANYOF_UNICODE_ALL))
11191         && (((stored == 1 && ((! (ANYOF_FLAGS(ret) & ANYOF_LOCALE))
11192                               || (! ANYOF_CLASS_TEST_ANY_SET(ret)))))
11193             || (stored == 2 && ((! (ANYOF_FLAGS(ret) & ANYOF_LOCALE))
11194                                  && (! _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(value))
11195                                  /* If the latest code point has a fold whose
11196                                   * bit is set, it must be the only other one */
11197                                 && ((prevvalue = PL_fold_latin1[value]) != (IV)value)
11198                                  && ANYOF_BITMAP_TEST(ret, prevvalue)))))
11199     {
11200         /* Note that the information needed to decide to do this optimization
11201          * is not currently available until the 2nd pass, and that the actually
11202          * used EXACTish node takes less space than the calculated ANYOF node,
11203          * and hence the amount of space calculated in the first pass is larger
11204          * than actually used, so this optimization doesn't gain us any space.
11205          * But an EXACT node is faster than an ANYOF node, and can be combined
11206          * with any adjacent EXACT nodes later by the optimizer for further
11207          * gains.  The speed of executing an EXACTF is similar to an ANYOF
11208          * node, so the optimization advantage comes from the ability to join
11209          * it to adjacent EXACT nodes */
11210
11211         const char * cur_parse= RExC_parse;
11212         U8 op;
11213         RExC_emit = (regnode *)orig_emit;
11214         RExC_parse = (char *)orig_parse;
11215
11216         if (stored == 1) {
11217
11218             /* A locale node with one point can be folded; all the other cases
11219              * with folding will have two points, since we calculate them above
11220              */
11221             if (ANYOF_FLAGS(ret) & ANYOF_LOC_NONBITMAP_FOLD) {
11222                  op = EXACTFL;
11223             }
11224             else {
11225                 op = EXACT;
11226             }
11227         }
11228         else {   /* else 2 chars in the bit map: the folds of each other */
11229
11230             /* Use the folded value, which for the cases where we get here,
11231              * is just the lower case of the current one (which may resolve to
11232              * itself, or to the other one */
11233             value = toLOWER_LATIN1(value);
11234
11235             /* To join adjacent nodes, they must be the exact EXACTish type.
11236              * Try to use the most likely type, by using EXACTFA if possible,
11237              * then EXACTFU if the regex calls for it, or is required because
11238              * the character is non-ASCII.  (If <value> is ASCII, its fold is
11239              * also ASCII for the cases where we get here.) */
11240             if (MORE_ASCII_RESTRICTED && isASCII(value)) {
11241                 op = EXACTFA;
11242             }
11243             else if (AT_LEAST_UNI_SEMANTICS || !isASCII(value)) {
11244                 op = EXACTFU;
11245             }
11246             else {    /* Otherwise, more likely to be EXACTF type */
11247                 op = EXACTF;
11248             }
11249         }
11250
11251         ret = reg_node(pRExC_state, op);
11252         RExC_parse = (char *)cur_parse;
11253         if (UTF && ! NATIVE_IS_INVARIANT(value)) {
11254             *STRING(ret)= UTF8_EIGHT_BIT_HI((U8) value);
11255             *(STRING(ret) + 1)= UTF8_EIGHT_BIT_LO((U8) value);
11256             STR_LEN(ret)= 2;
11257             RExC_emit += STR_SZ(2);
11258         }
11259         else {
11260             *STRING(ret)= (char)value;
11261             STR_LEN(ret)= 1;
11262             RExC_emit += STR_SZ(1);
11263         }
11264         SvREFCNT_dec(listsv);
11265         return ret;
11266     }
11267
11268     /* If there is a swash and more than one element, we can't use the swash in
11269      * the optimization below. */
11270     if (swash && element_count > 1) {
11271         SvREFCNT_dec(swash);
11272         swash = NULL;
11273     }
11274     if (! nonbitmap
11275         && SvCUR(listsv) == initial_listsv_len
11276         && ! unicode_alternate)
11277     {
11278         ARG_SET(ret, ANYOF_NONBITMAP_EMPTY);
11279         SvREFCNT_dec(listsv);
11280         SvREFCNT_dec(unicode_alternate);
11281     }
11282     else {
11283         /* av[0] stores the character class description in its textual form:
11284          *       used later (regexec.c:Perl_regclass_swash()) to initialize the
11285          *       appropriate swash, and is also useful for dumping the regnode.
11286          * av[1] if NULL, is a placeholder to later contain the swash computed
11287          *       from av[0].  But if no further computation need be done, the
11288          *       swash is stored there now.
11289          * av[2] stores the multicharacter foldings, used later in
11290          *       regexec.c:S_reginclass().
11291          * av[3] stores the nonbitmap inversion list for use in addition or
11292          *       instead of av[0]; not used if av[1] isn't NULL
11293          * av[4] is set if any component of the class is from a user-defined
11294          *       property; not used if av[1] isn't NULL */
11295         AV * const av = newAV();
11296         SV *rv;
11297
11298         av_store(av, 0, (SvCUR(listsv) == initial_listsv_len)
11299                         ? &PL_sv_undef
11300                         : listsv);
11301         if (swash) {
11302             av_store(av, 1, swash);
11303             SvREFCNT_dec(nonbitmap);
11304         }
11305         else {
11306             av_store(av, 1, NULL);
11307             if (nonbitmap) {
11308                 av_store(av, 3, nonbitmap);
11309                 av_store(av, 4, newSVuv(has_user_defined_property));
11310             }
11311         }
11312
11313         /* Store any computed multi-char folds only if we are allowing
11314          * them */
11315         if (allow_full_fold) {
11316             av_store(av, 2, MUTABLE_SV(unicode_alternate));
11317             if (unicode_alternate) { /* This node is variable length */
11318                 OP(ret) = ANYOFV;
11319             }
11320         }
11321         else {
11322             av_store(av, 2, NULL);
11323         }
11324         rv = newRV_noinc(MUTABLE_SV(av));
11325         n = add_data(pRExC_state, 1, "s");
11326         RExC_rxi->data->data[n] = (void*)rv;
11327         ARG_SET(ret, n);
11328     }
11329     return ret;
11330 }
11331 #undef _C_C_T_
11332
11333
11334 /* reg_skipcomment()
11335
11336    Absorbs an /x style # comments from the input stream.
11337    Returns true if there is more text remaining in the stream.
11338    Will set the REG_SEEN_RUN_ON_COMMENT flag if the comment
11339    terminates the pattern without including a newline.
11340
11341    Note its the callers responsibility to ensure that we are
11342    actually in /x mode
11343
11344 */
11345
11346 STATIC bool
11347 S_reg_skipcomment(pTHX_ RExC_state_t *pRExC_state)
11348 {
11349     bool ended = 0;
11350
11351     PERL_ARGS_ASSERT_REG_SKIPCOMMENT;
11352
11353     while (RExC_parse < RExC_end)
11354         if (*RExC_parse++ == '\n') {
11355             ended = 1;
11356             break;
11357         }
11358     if (!ended) {
11359         /* we ran off the end of the pattern without ending
11360            the comment, so we have to add an \n when wrapping */
11361         RExC_seen |= REG_SEEN_RUN_ON_COMMENT;
11362         return 0;
11363     } else
11364         return 1;
11365 }
11366
11367 /* nextchar()
11368
11369    Advances the parse position, and optionally absorbs
11370    "whitespace" from the inputstream.
11371
11372    Without /x "whitespace" means (?#...) style comments only,
11373    with /x this means (?#...) and # comments and whitespace proper.
11374
11375    Returns the RExC_parse point from BEFORE the scan occurs.
11376
11377    This is the /x friendly way of saying RExC_parse++.
11378 */
11379
11380 STATIC char*
11381 S_nextchar(pTHX_ RExC_state_t *pRExC_state)
11382 {
11383     char* const retval = RExC_parse++;
11384
11385     PERL_ARGS_ASSERT_NEXTCHAR;
11386
11387     for (;;) {
11388         if (RExC_end - RExC_parse >= 3
11389             && *RExC_parse == '('
11390             && RExC_parse[1] == '?'
11391             && RExC_parse[2] == '#')
11392         {
11393             while (*RExC_parse != ')') {
11394                 if (RExC_parse == RExC_end)
11395                     FAIL("Sequence (?#... not terminated");
11396                 RExC_parse++;
11397             }
11398             RExC_parse++;
11399             continue;
11400         }
11401         if (RExC_flags & RXf_PMf_EXTENDED) {
11402             if (isSPACE(*RExC_parse)) {
11403                 RExC_parse++;
11404                 continue;
11405             }
11406             else if (*RExC_parse == '#') {
11407                 if ( reg_skipcomment( pRExC_state ) )
11408                     continue;
11409             }
11410         }
11411         return retval;
11412     }
11413 }
11414
11415 /*
11416 - reg_node - emit a node
11417 */
11418 STATIC regnode *                        /* Location. */
11419 S_reg_node(pTHX_ RExC_state_t *pRExC_state, U8 op)
11420 {
11421     dVAR;
11422     register regnode *ptr;
11423     regnode * const ret = RExC_emit;
11424     GET_RE_DEBUG_FLAGS_DECL;
11425
11426     PERL_ARGS_ASSERT_REG_NODE;
11427
11428     if (SIZE_ONLY) {
11429         SIZE_ALIGN(RExC_size);
11430         RExC_size += 1;
11431         return(ret);
11432     }
11433     if (RExC_emit >= RExC_emit_bound)
11434         Perl_croak(aTHX_ "panic: reg_node overrun trying to emit %d, %p>=%p",
11435                    op, RExC_emit, RExC_emit_bound);
11436
11437     NODE_ALIGN_FILL(ret);
11438     ptr = ret;
11439     FILL_ADVANCE_NODE(ptr, op);
11440     REH_CALL_COMP_NODE_HOOK(pRExC_state->rx, (ptr) - 1);
11441 #ifdef RE_TRACK_PATTERN_OFFSETS
11442     if (RExC_offsets) {         /* MJD */
11443         MJD_OFFSET_DEBUG(("%s:%d: (op %s) %s %"UVuf" (len %"UVuf") (max %"UVuf").\n", 
11444               "reg_node", __LINE__, 
11445               PL_reg_name[op],
11446               (UV)(RExC_emit - RExC_emit_start) > RExC_offsets[0] 
11447                 ? "Overwriting end of array!\n" : "OK",
11448               (UV)(RExC_emit - RExC_emit_start),
11449               (UV)(RExC_parse - RExC_start),
11450               (UV)RExC_offsets[0])); 
11451         Set_Node_Offset(RExC_emit, RExC_parse + (op == END));
11452     }
11453 #endif
11454     RExC_emit = ptr;
11455     return(ret);
11456 }
11457
11458 /*
11459 - reganode - emit a node with an argument
11460 */
11461 STATIC regnode *                        /* Location. */
11462 S_reganode(pTHX_ RExC_state_t *pRExC_state, U8 op, U32 arg)
11463 {
11464     dVAR;
11465     register regnode *ptr;
11466     regnode * const ret = RExC_emit;
11467     GET_RE_DEBUG_FLAGS_DECL;
11468
11469     PERL_ARGS_ASSERT_REGANODE;
11470
11471     if (SIZE_ONLY) {
11472         SIZE_ALIGN(RExC_size);
11473         RExC_size += 2;
11474         /* 
11475            We can't do this:
11476            
11477            assert(2==regarglen[op]+1); 
11478
11479            Anything larger than this has to allocate the extra amount.
11480            If we changed this to be:
11481            
11482            RExC_size += (1 + regarglen[op]);
11483            
11484            then it wouldn't matter. Its not clear what side effect
11485            might come from that so its not done so far.
11486            -- dmq
11487         */
11488         return(ret);
11489     }
11490     if (RExC_emit >= RExC_emit_bound)
11491         Perl_croak(aTHX_ "panic: reg_node overrun trying to emit %d, %p>=%p",
11492                    op, RExC_emit, RExC_emit_bound);
11493
11494     NODE_ALIGN_FILL(ret);
11495     ptr = ret;
11496     FILL_ADVANCE_NODE_ARG(ptr, op, arg);
11497     REH_CALL_COMP_NODE_HOOK(pRExC_state->rx, (ptr) - 2);
11498 #ifdef RE_TRACK_PATTERN_OFFSETS
11499     if (RExC_offsets) {         /* MJD */
11500         MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s %"UVuf" <- %"UVuf" (max %"UVuf").\n", 
11501               "reganode",
11502               __LINE__,
11503               PL_reg_name[op],
11504               (UV)(RExC_emit - RExC_emit_start) > RExC_offsets[0] ? 
11505               "Overwriting end of array!\n" : "OK",
11506               (UV)(RExC_emit - RExC_emit_start),
11507               (UV)(RExC_parse - RExC_start),
11508               (UV)RExC_offsets[0])); 
11509         Set_Cur_Node_Offset;
11510     }
11511 #endif            
11512     RExC_emit = ptr;
11513     return(ret);
11514 }
11515
11516 /*
11517 - reguni - emit (if appropriate) a Unicode character
11518 */
11519 STATIC STRLEN
11520 S_reguni(pTHX_ const RExC_state_t *pRExC_state, UV uv, char* s)
11521 {
11522     dVAR;
11523
11524     PERL_ARGS_ASSERT_REGUNI;
11525
11526     return SIZE_ONLY ? UNISKIP(uv) : (uvchr_to_utf8((U8*)s, uv) - (U8*)s);
11527 }
11528
11529 /*
11530 - reginsert - insert an operator in front of already-emitted operand
11531 *
11532 * Means relocating the operand.
11533 */
11534 STATIC void
11535 S_reginsert(pTHX_ RExC_state_t *pRExC_state, U8 op, regnode *opnd, U32 depth)
11536 {
11537     dVAR;
11538     register regnode *src;
11539     register regnode *dst;
11540     register regnode *place;
11541     const int offset = regarglen[(U8)op];
11542     const int size = NODE_STEP_REGNODE + offset;
11543     GET_RE_DEBUG_FLAGS_DECL;
11544
11545     PERL_ARGS_ASSERT_REGINSERT;
11546     PERL_UNUSED_ARG(depth);
11547 /* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
11548     DEBUG_PARSE_FMT("inst"," - %s",PL_reg_name[op]);
11549     if (SIZE_ONLY) {
11550         RExC_size += size;
11551         return;
11552     }
11553
11554     src = RExC_emit;
11555     RExC_emit += size;
11556     dst = RExC_emit;
11557     if (RExC_open_parens) {
11558         int paren;
11559         /*DEBUG_PARSE_FMT("inst"," - %"IVdf, (IV)RExC_npar);*/
11560         for ( paren=0 ; paren < RExC_npar ; paren++ ) {
11561             if ( RExC_open_parens[paren] >= opnd ) {
11562                 /*DEBUG_PARSE_FMT("open"," - %d",size);*/
11563                 RExC_open_parens[paren] += size;
11564             } else {
11565                 /*DEBUG_PARSE_FMT("open"," - %s","ok");*/
11566             }
11567             if ( RExC_close_parens[paren] >= opnd ) {
11568                 /*DEBUG_PARSE_FMT("close"," - %d",size);*/
11569                 RExC_close_parens[paren] += size;
11570             } else {
11571                 /*DEBUG_PARSE_FMT("close"," - %s","ok");*/
11572             }
11573         }
11574     }
11575
11576     while (src > opnd) {
11577         StructCopy(--src, --dst, regnode);
11578 #ifdef RE_TRACK_PATTERN_OFFSETS
11579         if (RExC_offsets) {     /* MJD 20010112 */
11580             MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s copy %"UVuf" -> %"UVuf" (max %"UVuf").\n",
11581                   "reg_insert",
11582                   __LINE__,
11583                   PL_reg_name[op],
11584                   (UV)(dst - RExC_emit_start) > RExC_offsets[0] 
11585                     ? "Overwriting end of array!\n" : "OK",
11586                   (UV)(src - RExC_emit_start),
11587                   (UV)(dst - RExC_emit_start),
11588                   (UV)RExC_offsets[0])); 
11589             Set_Node_Offset_To_R(dst-RExC_emit_start, Node_Offset(src));
11590             Set_Node_Length_To_R(dst-RExC_emit_start, Node_Length(src));
11591         }
11592 #endif
11593     }
11594     
11595
11596     place = opnd;               /* Op node, where operand used to be. */
11597 #ifdef RE_TRACK_PATTERN_OFFSETS
11598     if (RExC_offsets) {         /* MJD */
11599         MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s %"UVuf" <- %"UVuf" (max %"UVuf").\n", 
11600               "reginsert",
11601               __LINE__,
11602               PL_reg_name[op],
11603               (UV)(place - RExC_emit_start) > RExC_offsets[0] 
11604               ? "Overwriting end of array!\n" : "OK",
11605               (UV)(place - RExC_emit_start),
11606               (UV)(RExC_parse - RExC_start),
11607               (UV)RExC_offsets[0]));
11608         Set_Node_Offset(place, RExC_parse);
11609         Set_Node_Length(place, 1);
11610     }
11611 #endif    
11612     src = NEXTOPER(place);
11613     FILL_ADVANCE_NODE(place, op);
11614     REH_CALL_COMP_NODE_HOOK(pRExC_state->rx, (place) - 1);
11615     Zero(src, offset, regnode);
11616 }
11617
11618 /*
11619 - regtail - set the next-pointer at the end of a node chain of p to val.
11620 - SEE ALSO: regtail_study
11621 */
11622 /* TODO: All three parms should be const */
11623 STATIC void
11624 S_regtail(pTHX_ RExC_state_t *pRExC_state, regnode *p, const regnode *val,U32 depth)
11625 {
11626     dVAR;
11627     register regnode *scan;
11628     GET_RE_DEBUG_FLAGS_DECL;
11629
11630     PERL_ARGS_ASSERT_REGTAIL;
11631 #ifndef DEBUGGING
11632     PERL_UNUSED_ARG(depth);
11633 #endif
11634
11635     if (SIZE_ONLY)
11636         return;
11637
11638     /* Find last node. */
11639     scan = p;
11640     for (;;) {
11641         regnode * const temp = regnext(scan);
11642         DEBUG_PARSE_r({
11643             SV * const mysv=sv_newmortal();
11644             DEBUG_PARSE_MSG((scan==p ? "tail" : ""));
11645             regprop(RExC_rx, mysv, scan);
11646             PerlIO_printf(Perl_debug_log, "~ %s (%d) %s %s\n",
11647                 SvPV_nolen_const(mysv), REG_NODE_NUM(scan),
11648                     (temp == NULL ? "->" : ""),
11649                     (temp == NULL ? PL_reg_name[OP(val)] : "")
11650             );
11651         });
11652         if (temp == NULL)
11653             break;
11654         scan = temp;
11655     }
11656
11657     if (reg_off_by_arg[OP(scan)]) {
11658         ARG_SET(scan, val - scan);
11659     }
11660     else {
11661         NEXT_OFF(scan) = val - scan;
11662     }
11663 }
11664
11665 #ifdef DEBUGGING
11666 /*
11667 - regtail_study - set the next-pointer at the end of a node chain of p to val.
11668 - Look for optimizable sequences at the same time.
11669 - currently only looks for EXACT chains.
11670
11671 This is experimental code. The idea is to use this routine to perform 
11672 in place optimizations on branches and groups as they are constructed,
11673 with the long term intention of removing optimization from study_chunk so
11674 that it is purely analytical.
11675
11676 Currently only used when in DEBUG mode. The macro REGTAIL_STUDY() is used
11677 to control which is which.
11678
11679 */
11680 /* TODO: All four parms should be const */
11681
11682 STATIC U8
11683 S_regtail_study(pTHX_ RExC_state_t *pRExC_state, regnode *p, const regnode *val,U32 depth)
11684 {
11685     dVAR;
11686     register regnode *scan;
11687     U8 exact = PSEUDO;
11688 #ifdef EXPERIMENTAL_INPLACESCAN
11689     I32 min = 0;
11690 #endif
11691     GET_RE_DEBUG_FLAGS_DECL;
11692
11693     PERL_ARGS_ASSERT_REGTAIL_STUDY;
11694
11695
11696     if (SIZE_ONLY)
11697         return exact;
11698
11699     /* Find last node. */
11700
11701     scan = p;
11702     for (;;) {
11703         regnode * const temp = regnext(scan);
11704 #ifdef EXPERIMENTAL_INPLACESCAN
11705         if (PL_regkind[OP(scan)] == EXACT) {
11706             bool has_exactf_sharp_s;    /* Unexamined in this routine */
11707             if (join_exact(pRExC_state,scan,&min, &has_exactf_sharp_s, 1,val,depth+1))
11708                 return EXACT;
11709         }
11710 #endif
11711         if ( exact ) {
11712             switch (OP(scan)) {
11713                 case EXACT:
11714                 case EXACTF:
11715                 case EXACTFA:
11716                 case EXACTFU:
11717                 case EXACTFU_SS:
11718                 case EXACTFU_NO_TRIE:
11719                 case EXACTFL:
11720                         if( exact == PSEUDO )
11721                             exact= OP(scan);
11722                         else if ( exact != OP(scan) )
11723                             exact= 0;
11724                 case NOTHING:
11725                     break;
11726                 default:
11727                     exact= 0;
11728             }
11729         }
11730         DEBUG_PARSE_r({
11731             SV * const mysv=sv_newmortal();
11732             DEBUG_PARSE_MSG((scan==p ? "tsdy" : ""));
11733             regprop(RExC_rx, mysv, scan);
11734             PerlIO_printf(Perl_debug_log, "~ %s (%d) -> %s\n",
11735                 SvPV_nolen_const(mysv),
11736                 REG_NODE_NUM(scan),
11737                 PL_reg_name[exact]);
11738         });
11739         if (temp == NULL)
11740             break;
11741         scan = temp;
11742     }
11743     DEBUG_PARSE_r({
11744         SV * const mysv_val=sv_newmortal();
11745         DEBUG_PARSE_MSG("");
11746         regprop(RExC_rx, mysv_val, val);
11747         PerlIO_printf(Perl_debug_log, "~ attach to %s (%"IVdf") offset to %"IVdf"\n",
11748                       SvPV_nolen_const(mysv_val),
11749                       (IV)REG_NODE_NUM(val),
11750                       (IV)(val - scan)
11751         );
11752     });
11753     if (reg_off_by_arg[OP(scan)]) {
11754         ARG_SET(scan, val - scan);
11755     }
11756     else {
11757         NEXT_OFF(scan) = val - scan;
11758     }
11759
11760     return exact;
11761 }
11762 #endif
11763
11764 /*
11765  - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
11766  */
11767 #ifdef DEBUGGING
11768 static void 
11769 S_regdump_extflags(pTHX_ const char *lead, const U32 flags)
11770 {
11771     int bit;
11772     int set=0;
11773     regex_charset cs;
11774
11775     for (bit=0; bit<32; bit++) {
11776         if (flags & (1<<bit)) {
11777             if ((1<<bit) & RXf_PMf_CHARSET) {   /* Output separately, below */
11778                 continue;
11779             }
11780             if (!set++ && lead) 
11781                 PerlIO_printf(Perl_debug_log, "%s",lead);
11782             PerlIO_printf(Perl_debug_log, "%s ",PL_reg_extflags_name[bit]);
11783         }               
11784     }      
11785     if ((cs = get_regex_charset(flags)) != REGEX_DEPENDS_CHARSET) {
11786             if (!set++ && lead) {
11787                 PerlIO_printf(Perl_debug_log, "%s",lead);
11788             }
11789             switch (cs) {
11790                 case REGEX_UNICODE_CHARSET:
11791                     PerlIO_printf(Perl_debug_log, "UNICODE");
11792                     break;
11793                 case REGEX_LOCALE_CHARSET:
11794                     PerlIO_printf(Perl_debug_log, "LOCALE");
11795                     break;
11796                 case REGEX_ASCII_RESTRICTED_CHARSET:
11797                     PerlIO_printf(Perl_debug_log, "ASCII-RESTRICTED");
11798                     break;
11799                 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
11800                     PerlIO_printf(Perl_debug_log, "ASCII-MORE_RESTRICTED");
11801                     break;
11802                 default:
11803                     PerlIO_printf(Perl_debug_log, "UNKNOWN CHARACTER SET");
11804                     break;
11805             }
11806     }
11807     if (lead)  {
11808         if (set) 
11809             PerlIO_printf(Perl_debug_log, "\n");
11810         else 
11811             PerlIO_printf(Perl_debug_log, "%s[none-set]\n",lead);
11812     }            
11813 }   
11814 #endif
11815
11816 void
11817 Perl_regdump(pTHX_ const regexp *r)
11818 {
11819 #ifdef DEBUGGING
11820     dVAR;
11821     SV * const sv = sv_newmortal();
11822     SV *dsv= sv_newmortal();
11823     RXi_GET_DECL(r,ri);
11824     GET_RE_DEBUG_FLAGS_DECL;
11825
11826     PERL_ARGS_ASSERT_REGDUMP;
11827
11828     (void)dumpuntil(r, ri->program, ri->program + 1, NULL, NULL, sv, 0, 0);
11829
11830     /* Header fields of interest. */
11831     if (r->anchored_substr) {
11832         RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->anchored_substr), 
11833             RE_SV_DUMPLEN(r->anchored_substr), 30);
11834         PerlIO_printf(Perl_debug_log,
11835                       "anchored %s%s at %"IVdf" ",
11836                       s, RE_SV_TAIL(r->anchored_substr),
11837                       (IV)r->anchored_offset);
11838     } else if (r->anchored_utf8) {
11839         RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->anchored_utf8), 
11840             RE_SV_DUMPLEN(r->anchored_utf8), 30);
11841         PerlIO_printf(Perl_debug_log,
11842                       "anchored utf8 %s%s at %"IVdf" ",
11843                       s, RE_SV_TAIL(r->anchored_utf8),
11844                       (IV)r->anchored_offset);
11845     }                 
11846     if (r->float_substr) {
11847         RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->float_substr), 
11848             RE_SV_DUMPLEN(r->float_substr), 30);
11849         PerlIO_printf(Perl_debug_log,
11850                       "floating %s%s at %"IVdf"..%"UVuf" ",
11851                       s, RE_SV_TAIL(r->float_substr),
11852                       (IV)r->float_min_offset, (UV)r->float_max_offset);
11853     } else if (r->float_utf8) {
11854         RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->float_utf8), 
11855             RE_SV_DUMPLEN(r->float_utf8), 30);
11856         PerlIO_printf(Perl_debug_log,
11857                       "floating utf8 %s%s at %"IVdf"..%"UVuf" ",
11858                       s, RE_SV_TAIL(r->float_utf8),
11859                       (IV)r->float_min_offset, (UV)r->float_max_offset);
11860     }
11861     if (r->check_substr || r->check_utf8)
11862         PerlIO_printf(Perl_debug_log,
11863                       (const char *)
11864                       (r->check_substr == r->float_substr
11865                        && r->check_utf8 == r->float_utf8
11866                        ? "(checking floating" : "(checking anchored"));
11867     if (r->extflags & RXf_NOSCAN)
11868         PerlIO_printf(Perl_debug_log, " noscan");
11869     if (r->extflags & RXf_CHECK_ALL)
11870         PerlIO_printf(Perl_debug_log, " isall");
11871     if (r->check_substr || r->check_utf8)
11872         PerlIO_printf(Perl_debug_log, ") ");
11873
11874     if (ri->regstclass) {
11875         regprop(r, sv, ri->regstclass);
11876         PerlIO_printf(Perl_debug_log, "stclass %s ", SvPVX_const(sv));
11877     }
11878     if (r->extflags & RXf_ANCH) {
11879         PerlIO_printf(Perl_debug_log, "anchored");
11880         if (r->extflags & RXf_ANCH_BOL)
11881             PerlIO_printf(Perl_debug_log, "(BOL)");
11882         if (r->extflags & RXf_ANCH_MBOL)
11883             PerlIO_printf(Perl_debug_log, "(MBOL)");
11884         if (r->extflags & RXf_ANCH_SBOL)
11885             PerlIO_printf(Perl_debug_log, "(SBOL)");
11886         if (r->extflags & RXf_ANCH_GPOS)
11887             PerlIO_printf(Perl_debug_log, "(GPOS)");
11888         PerlIO_putc(Perl_debug_log, ' ');
11889     }
11890     if (r->extflags & RXf_GPOS_SEEN)
11891         PerlIO_printf(Perl_debug_log, "GPOS:%"UVuf" ", (UV)r->gofs);
11892     if (r->intflags & PREGf_SKIP)
11893         PerlIO_printf(Perl_debug_log, "plus ");
11894     if (r->intflags & PREGf_IMPLICIT)
11895         PerlIO_printf(Perl_debug_log, "implicit ");
11896     PerlIO_printf(Perl_debug_log, "minlen %"IVdf" ", (IV)r->minlen);
11897     if (r->extflags & RXf_EVAL_SEEN)
11898         PerlIO_printf(Perl_debug_log, "with eval ");
11899     PerlIO_printf(Perl_debug_log, "\n");
11900     DEBUG_FLAGS_r(regdump_extflags("r->extflags: ",r->extflags));            
11901 #else
11902     PERL_ARGS_ASSERT_REGDUMP;
11903     PERL_UNUSED_CONTEXT;
11904     PERL_UNUSED_ARG(r);
11905 #endif  /* DEBUGGING */
11906 }
11907
11908 /*
11909 - regprop - printable representation of opcode
11910 */
11911 #define EMIT_ANYOF_TEST_SEPARATOR(do_sep,sv,flags) \
11912 STMT_START { \
11913         if (do_sep) {                           \
11914             Perl_sv_catpvf(aTHX_ sv,"%s][%s",PL_colors[1],PL_colors[0]); \
11915             if (flags & ANYOF_INVERT)           \
11916                 /*make sure the invert info is in each */ \
11917                 sv_catpvs(sv, "^");             \
11918             do_sep = 0;                         \
11919         }                                       \
11920 } STMT_END
11921
11922 void
11923 Perl_regprop(pTHX_ const regexp *prog, SV *sv, const regnode *o)
11924 {
11925 #ifdef DEBUGGING
11926     dVAR;
11927     register int k;
11928     RXi_GET_DECL(prog,progi);
11929     GET_RE_DEBUG_FLAGS_DECL;
11930     
11931     PERL_ARGS_ASSERT_REGPROP;
11932
11933     sv_setpvs(sv, "");
11934
11935     if (OP(o) > REGNODE_MAX)            /* regnode.type is unsigned */
11936         /* It would be nice to FAIL() here, but this may be called from
11937            regexec.c, and it would be hard to supply pRExC_state. */
11938         Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d", (int)OP(o), (int)REGNODE_MAX);
11939     sv_catpv(sv, PL_reg_name[OP(o)]); /* Take off const! */
11940
11941     k = PL_regkind[OP(o)];
11942
11943     if (k == EXACT) {
11944         sv_catpvs(sv, " ");
11945         /* Using is_utf8_string() (via PERL_PV_UNI_DETECT) 
11946          * is a crude hack but it may be the best for now since 
11947          * we have no flag "this EXACTish node was UTF-8" 
11948          * --jhi */
11949         pv_pretty(sv, STRING(o), STR_LEN(o), 60, PL_colors[0], PL_colors[1],
11950                   PERL_PV_ESCAPE_UNI_DETECT |
11951                   PERL_PV_ESCAPE_NONASCII   |
11952                   PERL_PV_PRETTY_ELLIPSES   |
11953                   PERL_PV_PRETTY_LTGT       |
11954                   PERL_PV_PRETTY_NOCLEAR
11955                   );
11956     } else if (k == TRIE) {
11957         /* print the details of the trie in dumpuntil instead, as
11958          * progi->data isn't available here */
11959         const char op = OP(o);
11960         const U32 n = ARG(o);
11961         const reg_ac_data * const ac = IS_TRIE_AC(op) ?
11962                (reg_ac_data *)progi->data->data[n] :
11963                NULL;
11964         const reg_trie_data * const trie
11965             = (reg_trie_data*)progi->data->data[!IS_TRIE_AC(op) ? n : ac->trie];
11966         
11967         Perl_sv_catpvf(aTHX_ sv, "-%s",PL_reg_name[o->flags]);
11968         DEBUG_TRIE_COMPILE_r(
11969             Perl_sv_catpvf(aTHX_ sv,
11970                 "<S:%"UVuf"/%"IVdf" W:%"UVuf" L:%"UVuf"/%"UVuf" C:%"UVuf"/%"UVuf">",
11971                 (UV)trie->startstate,
11972                 (IV)trie->statecount-1, /* -1 because of the unused 0 element */
11973                 (UV)trie->wordcount,
11974                 (UV)trie->minlen,
11975                 (UV)trie->maxlen,
11976                 (UV)TRIE_CHARCOUNT(trie),
11977                 (UV)trie->uniquecharcount
11978             )
11979         );
11980         if ( IS_ANYOF_TRIE(op) || trie->bitmap ) {
11981             int i;
11982             int rangestart = -1;
11983             U8* bitmap = IS_ANYOF_TRIE(op) ? (U8*)ANYOF_BITMAP(o) : (U8*)TRIE_BITMAP(trie);
11984             sv_catpvs(sv, "[");
11985             for (i = 0; i <= 256; i++) {
11986                 if (i < 256 && BITMAP_TEST(bitmap,i)) {
11987                     if (rangestart == -1)
11988                         rangestart = i;
11989                 } else if (rangestart != -1) {
11990                     if (i <= rangestart + 3)
11991                         for (; rangestart < i; rangestart++)
11992                             put_byte(sv, rangestart);
11993                     else {
11994                         put_byte(sv, rangestart);
11995                         sv_catpvs(sv, "-");
11996                         put_byte(sv, i - 1);
11997                     }
11998                     rangestart = -1;
11999                 }
12000             }
12001             sv_catpvs(sv, "]");
12002         } 
12003          
12004     } else if (k == CURLY) {
12005         if (OP(o) == CURLYM || OP(o) == CURLYN || OP(o) == CURLYX)
12006             Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
12007         Perl_sv_catpvf(aTHX_ sv, " {%d,%d}", ARG1(o), ARG2(o));
12008     }
12009     else if (k == WHILEM && o->flags)                   /* Ordinal/of */
12010         Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
12011     else if (k == REF || k == OPEN || k == CLOSE || k == GROUPP || OP(o)==ACCEPT) {
12012         Perl_sv_catpvf(aTHX_ sv, "%d", (int)ARG(o));    /* Parenth number */
12013         if ( RXp_PAREN_NAMES(prog) ) {
12014             if ( k != REF || (OP(o) < NREF)) {
12015                 AV *list= MUTABLE_AV(progi->data->data[progi->name_list_idx]);
12016                 SV **name= av_fetch(list, ARG(o), 0 );
12017                 if (name)
12018                     Perl_sv_catpvf(aTHX_ sv, " '%"SVf"'", SVfARG(*name));
12019             }       
12020             else {
12021                 AV *list= MUTABLE_AV(progi->data->data[ progi->name_list_idx ]);
12022                 SV *sv_dat= MUTABLE_SV(progi->data->data[ ARG( o ) ]);
12023                 I32 *nums=(I32*)SvPVX(sv_dat);
12024                 SV **name= av_fetch(list, nums[0], 0 );
12025                 I32 n;
12026                 if (name) {
12027                     for ( n=0; n<SvIVX(sv_dat); n++ ) {
12028                         Perl_sv_catpvf(aTHX_ sv, "%s%"IVdf,
12029                                     (n ? "," : ""), (IV)nums[n]);
12030                     }
12031                     Perl_sv_catpvf(aTHX_ sv, " '%"SVf"'", SVfARG(*name));
12032                 }
12033             }
12034         }            
12035     } else if (k == GOSUB) 
12036         Perl_sv_catpvf(aTHX_ sv, "%d[%+d]", (int)ARG(o),(int)ARG2L(o)); /* Paren and offset */
12037     else if (k == VERB) {
12038         if (!o->flags) 
12039             Perl_sv_catpvf(aTHX_ sv, ":%"SVf, 
12040                            SVfARG((MUTABLE_SV(progi->data->data[ ARG( o ) ]))));
12041     } else if (k == LOGICAL)
12042         Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags);     /* 2: embedded, otherwise 1 */
12043     else if (k == ANYOF) {
12044         int i, rangestart = -1;
12045         const U8 flags = ANYOF_FLAGS(o);
12046         int do_sep = 0;
12047
12048         /* Should be synchronized with * ANYOF_ #xdefines in regcomp.h */
12049         static const char * const anyofs[] = {
12050             "\\w",
12051             "\\W",
12052             "\\s",
12053             "\\S",
12054             "\\d",
12055             "\\D",
12056             "[:alnum:]",
12057             "[:^alnum:]",
12058             "[:alpha:]",
12059             "[:^alpha:]",
12060             "[:ascii:]",
12061             "[:^ascii:]",
12062             "[:cntrl:]",
12063             "[:^cntrl:]",
12064             "[:graph:]",
12065             "[:^graph:]",
12066             "[:lower:]",
12067             "[:^lower:]",
12068             "[:print:]",
12069             "[:^print:]",
12070             "[:punct:]",
12071             "[:^punct:]",
12072             "[:upper:]",
12073             "[:^upper:]",
12074             "[:xdigit:]",
12075             "[:^xdigit:]",
12076             "[:space:]",
12077             "[:^space:]",
12078             "[:blank:]",
12079             "[:^blank:]"
12080         };
12081
12082         if (flags & ANYOF_LOCALE)
12083             sv_catpvs(sv, "{loc}");
12084         if (flags & ANYOF_LOC_NONBITMAP_FOLD)
12085             sv_catpvs(sv, "{i}");
12086         Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
12087         if (flags & ANYOF_INVERT)
12088             sv_catpvs(sv, "^");
12089
12090         /* output what the standard cp 0-255 bitmap matches */
12091         for (i = 0; i <= 256; i++) {
12092             if (i < 256 && ANYOF_BITMAP_TEST(o,i)) {
12093                 if (rangestart == -1)
12094                     rangestart = i;
12095             } else if (rangestart != -1) {
12096                 if (i <= rangestart + 3)
12097                     for (; rangestart < i; rangestart++)
12098                         put_byte(sv, rangestart);
12099                 else {
12100                     put_byte(sv, rangestart);
12101                     sv_catpvs(sv, "-");
12102                     put_byte(sv, i - 1);
12103                 }
12104                 do_sep = 1;
12105                 rangestart = -1;
12106             }
12107         }
12108         
12109         EMIT_ANYOF_TEST_SEPARATOR(do_sep,sv,flags);
12110         /* output any special charclass tests (used entirely under use locale) */
12111         if (ANYOF_CLASS_TEST_ANY_SET(o))
12112             for (i = 0; i < (int)(sizeof(anyofs)/sizeof(char*)); i++)
12113                 if (ANYOF_CLASS_TEST(o,i)) {
12114                     sv_catpv(sv, anyofs[i]);
12115                     do_sep = 1;
12116                 }
12117         
12118         EMIT_ANYOF_TEST_SEPARATOR(do_sep,sv,flags);
12119         
12120         if (flags & ANYOF_NON_UTF8_LATIN1_ALL) {
12121             sv_catpvs(sv, "{non-utf8-latin1-all}");
12122         }
12123
12124         /* output information about the unicode matching */
12125         if (flags & ANYOF_UNICODE_ALL)
12126             sv_catpvs(sv, "{unicode_all}");
12127         else if (ANYOF_NONBITMAP(o))
12128             sv_catpvs(sv, "{unicode}");
12129         if (flags & ANYOF_NONBITMAP_NON_UTF8)
12130             sv_catpvs(sv, "{outside bitmap}");
12131
12132         if (ANYOF_NONBITMAP(o)) {
12133             SV *lv; /* Set if there is something outside the bit map */
12134             SV * const sw = regclass_swash(prog, o, FALSE, &lv, 0);
12135             bool byte_output = FALSE;   /* If something in the bitmap has been
12136                                            output */
12137
12138             if (lv && lv != &PL_sv_undef) {
12139                 if (sw) {
12140                     U8 s[UTF8_MAXBYTES_CASE+1];
12141
12142                     for (i = 0; i <= 256; i++) { /* Look at chars in bitmap */
12143                         uvchr_to_utf8(s, i);
12144
12145                         if (i < 256
12146                             && ! ANYOF_BITMAP_TEST(o, i)    /* Don't duplicate
12147                                                                things already
12148                                                                output as part
12149                                                                of the bitmap */
12150                             && swash_fetch(sw, s, TRUE))
12151                         {
12152                             if (rangestart == -1)
12153                                 rangestart = i;
12154                         } else if (rangestart != -1) {
12155                             byte_output = TRUE;
12156                             if (i <= rangestart + 3)
12157                                 for (; rangestart < i; rangestart++) {
12158                                     put_byte(sv, rangestart);
12159                                 }
12160                             else {
12161                                 put_byte(sv, rangestart);
12162                                 sv_catpvs(sv, "-");
12163                                 put_byte(sv, i-1);
12164                             }
12165                             rangestart = -1;
12166                         }
12167                     }
12168                 }
12169
12170                 {
12171                     char *s = savesvpv(lv);
12172                     char * const origs = s;
12173
12174                     while (*s && *s != '\n')
12175                         s++;
12176
12177                     if (*s == '\n') {
12178                         const char * const t = ++s;
12179
12180                         if (byte_output) {
12181                             sv_catpvs(sv, " ");
12182                         }
12183
12184                         while (*s) {
12185                             if (*s == '\n') {
12186
12187                                 /* Truncate very long output */
12188                                 if (s - origs > 256) {
12189                                     Perl_sv_catpvf(aTHX_ sv,
12190                                                    "%.*s...",
12191                                                    (int) (s - origs - 1),
12192                                                    t);
12193                                     goto out_dump;
12194                                 }
12195                                 *s = ' ';
12196                             }
12197                             else if (*s == '\t') {
12198                                 *s = '-';
12199                             }
12200                             s++;
12201                         }
12202                         if (s[-1] == ' ')
12203                             s[-1] = 0;
12204
12205                         sv_catpv(sv, t);
12206                     }
12207
12208                 out_dump:
12209
12210                     Safefree(origs);
12211                 }
12212                 SvREFCNT_dec(lv);
12213             }
12214         }
12215
12216         Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
12217     }
12218     else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH))
12219         Perl_sv_catpvf(aTHX_ sv, "[%d]", -(o->flags));
12220 #else
12221     PERL_UNUSED_CONTEXT;
12222     PERL_UNUSED_ARG(sv);
12223     PERL_UNUSED_ARG(o);
12224     PERL_UNUSED_ARG(prog);
12225 #endif  /* DEBUGGING */
12226 }
12227
12228 SV *
12229 Perl_re_intuit_string(pTHX_ REGEXP * const r)
12230 {                               /* Assume that RE_INTUIT is set */
12231     dVAR;
12232     struct regexp *const prog = (struct regexp *)SvANY(r);
12233     GET_RE_DEBUG_FLAGS_DECL;
12234
12235     PERL_ARGS_ASSERT_RE_INTUIT_STRING;
12236     PERL_UNUSED_CONTEXT;
12237
12238     DEBUG_COMPILE_r(
12239         {
12240             const char * const s = SvPV_nolen_const(prog->check_substr
12241                       ? prog->check_substr : prog->check_utf8);
12242
12243             if (!PL_colorset) reginitcolors();
12244             PerlIO_printf(Perl_debug_log,
12245                       "%sUsing REx %ssubstr:%s \"%s%.60s%s%s\"\n",
12246                       PL_colors[4],
12247                       prog->check_substr ? "" : "utf8 ",
12248                       PL_colors[5],PL_colors[0],
12249                       s,
12250                       PL_colors[1],
12251                       (strlen(s) > 60 ? "..." : ""));
12252         } );
12253
12254     return prog->check_substr ? prog->check_substr : prog->check_utf8;
12255 }
12256
12257 /* 
12258    pregfree() 
12259    
12260    handles refcounting and freeing the perl core regexp structure. When 
12261    it is necessary to actually free the structure the first thing it 
12262    does is call the 'free' method of the regexp_engine associated to
12263    the regexp, allowing the handling of the void *pprivate; member 
12264    first. (This routine is not overridable by extensions, which is why 
12265    the extensions free is called first.)
12266    
12267    See regdupe and regdupe_internal if you change anything here. 
12268 */
12269 #ifndef PERL_IN_XSUB_RE
12270 void
12271 Perl_pregfree(pTHX_ REGEXP *r)
12272 {
12273     SvREFCNT_dec(r);
12274 }
12275
12276 void
12277 Perl_pregfree2(pTHX_ REGEXP *rx)
12278 {
12279     dVAR;
12280     struct regexp *const r = (struct regexp *)SvANY(rx);
12281     GET_RE_DEBUG_FLAGS_DECL;
12282
12283     PERL_ARGS_ASSERT_PREGFREE2;
12284
12285     if (r->mother_re) {
12286         ReREFCNT_dec(r->mother_re);
12287     } else {
12288         CALLREGFREE_PVT(rx); /* free the private data */
12289         SvREFCNT_dec(RXp_PAREN_NAMES(r));
12290     }        
12291     if (r->substrs) {
12292         SvREFCNT_dec(r->anchored_substr);
12293         SvREFCNT_dec(r->anchored_utf8);
12294         SvREFCNT_dec(r->float_substr);
12295         SvREFCNT_dec(r->float_utf8);
12296         Safefree(r->substrs);
12297     }
12298     RX_MATCH_COPY_FREE(rx);
12299 #ifdef PERL_OLD_COPY_ON_WRITE
12300     SvREFCNT_dec(r->saved_copy);
12301 #endif
12302     Safefree(r->offs);
12303 }
12304
12305 /*  reg_temp_copy()
12306     
12307     This is a hacky workaround to the structural issue of match results
12308     being stored in the regexp structure which is in turn stored in
12309     PL_curpm/PL_reg_curpm. The problem is that due to qr// the pattern
12310     could be PL_curpm in multiple contexts, and could require multiple
12311     result sets being associated with the pattern simultaneously, such
12312     as when doing a recursive match with (??{$qr})
12313     
12314     The solution is to make a lightweight copy of the regexp structure 
12315     when a qr// is returned from the code executed by (??{$qr}) this
12316     lightweight copy doesn't actually own any of its data except for
12317     the starp/end and the actual regexp structure itself. 
12318     
12319 */    
12320     
12321     
12322 REGEXP *
12323 Perl_reg_temp_copy (pTHX_ REGEXP *ret_x, REGEXP *rx)
12324 {
12325     struct regexp *ret;
12326     struct regexp *const r = (struct regexp *)SvANY(rx);
12327     register const I32 npar = r->nparens+1;
12328
12329     PERL_ARGS_ASSERT_REG_TEMP_COPY;
12330
12331     if (!ret_x)
12332         ret_x = (REGEXP*) newSV_type(SVt_REGEXP);
12333     ret = (struct regexp *)SvANY(ret_x);
12334     
12335     (void)ReREFCNT_inc(rx);
12336     /* We can take advantage of the existing "copied buffer" mechanism in SVs
12337        by pointing directly at the buffer, but flagging that the allocated
12338        space in the copy is zero. As we've just done a struct copy, it's now
12339        a case of zero-ing that, rather than copying the current length.  */
12340     SvPV_set(ret_x, RX_WRAPPED(rx));
12341     SvFLAGS(ret_x) |= SvFLAGS(rx) & (SVf_POK|SVp_POK|SVf_UTF8);
12342     memcpy(&(ret->xpv_cur), &(r->xpv_cur),
12343            sizeof(regexp) - STRUCT_OFFSET(regexp, xpv_cur));
12344     SvLEN_set(ret_x, 0);
12345     SvSTASH_set(ret_x, NULL);
12346     SvMAGIC_set(ret_x, NULL);
12347     Newx(ret->offs, npar, regexp_paren_pair);
12348     Copy(r->offs, ret->offs, npar, regexp_paren_pair);
12349     if (r->substrs) {
12350         Newx(ret->substrs, 1, struct reg_substr_data);
12351         StructCopy(r->substrs, ret->substrs, struct reg_substr_data);
12352
12353         SvREFCNT_inc_void(ret->anchored_substr);
12354         SvREFCNT_inc_void(ret->anchored_utf8);
12355         SvREFCNT_inc_void(ret->float_substr);
12356         SvREFCNT_inc_void(ret->float_utf8);
12357
12358         /* check_substr and check_utf8, if non-NULL, point to either their
12359            anchored or float namesakes, and don't hold a second reference.  */
12360     }
12361     RX_MATCH_COPIED_off(ret_x);
12362 #ifdef PERL_OLD_COPY_ON_WRITE
12363     ret->saved_copy = NULL;
12364 #endif
12365     ret->mother_re = rx;
12366     
12367     return ret_x;
12368 }
12369 #endif
12370
12371 /* regfree_internal() 
12372
12373    Free the private data in a regexp. This is overloadable by 
12374    extensions. Perl takes care of the regexp structure in pregfree(), 
12375    this covers the *pprivate pointer which technically perl doesn't 
12376    know about, however of course we have to handle the 
12377    regexp_internal structure when no extension is in use. 
12378    
12379    Note this is called before freeing anything in the regexp 
12380    structure. 
12381  */
12382  
12383 void
12384 Perl_regfree_internal(pTHX_ REGEXP * const rx)
12385 {
12386     dVAR;
12387     struct regexp *const r = (struct regexp *)SvANY(rx);
12388     RXi_GET_DECL(r,ri);
12389     GET_RE_DEBUG_FLAGS_DECL;
12390
12391     PERL_ARGS_ASSERT_REGFREE_INTERNAL;
12392
12393     DEBUG_COMPILE_r({
12394         if (!PL_colorset)
12395             reginitcolors();
12396         {
12397             SV *dsv= sv_newmortal();
12398             RE_PV_QUOTED_DECL(s, RX_UTF8(rx),
12399                 dsv, RX_PRECOMP(rx), RX_PRELEN(rx), 60);
12400             PerlIO_printf(Perl_debug_log,"%sFreeing REx:%s %s\n", 
12401                 PL_colors[4],PL_colors[5],s);
12402         }
12403     });
12404 #ifdef RE_TRACK_PATTERN_OFFSETS
12405     if (ri->u.offsets)
12406         Safefree(ri->u.offsets);             /* 20010421 MJD */
12407 #endif
12408     if (ri->data) {
12409         int n = ri->data->count;
12410         PAD* new_comppad = NULL;
12411         PAD* old_comppad;
12412         PADOFFSET refcnt;
12413
12414         while (--n >= 0) {
12415           /* If you add a ->what type here, update the comment in regcomp.h */
12416             switch (ri->data->what[n]) {
12417             case 'a':
12418             case 's':
12419             case 'S':
12420             case 'u':
12421                 SvREFCNT_dec(MUTABLE_SV(ri->data->data[n]));
12422                 break;
12423             case 'f':
12424                 Safefree(ri->data->data[n]);
12425                 break;
12426             case 'p':
12427                 new_comppad = MUTABLE_AV(ri->data->data[n]);
12428                 break;
12429             case 'o':
12430                 if (new_comppad == NULL)
12431                     Perl_croak(aTHX_ "panic: pregfree comppad");
12432                 PAD_SAVE_LOCAL(old_comppad,
12433                     /* Watch out for global destruction's random ordering. */
12434                     (SvTYPE(new_comppad) == SVt_PVAV) ? new_comppad : NULL
12435                 );
12436                 OP_REFCNT_LOCK;
12437                 refcnt = OpREFCNT_dec((OP_4tree*)ri->data->data[n]);
12438                 OP_REFCNT_UNLOCK;
12439                 if (!refcnt)
12440                     op_free((OP_4tree*)ri->data->data[n]);
12441
12442                 PAD_RESTORE_LOCAL(old_comppad);
12443                 SvREFCNT_dec(MUTABLE_SV(new_comppad));
12444                 new_comppad = NULL;
12445                 break;
12446             case 'n':
12447                 break;
12448             case 'T':           
12449                 { /* Aho Corasick add-on structure for a trie node.
12450                      Used in stclass optimization only */
12451                     U32 refcount;
12452                     reg_ac_data *aho=(reg_ac_data*)ri->data->data[n];
12453                     OP_REFCNT_LOCK;
12454                     refcount = --aho->refcount;
12455                     OP_REFCNT_UNLOCK;
12456                     if ( !refcount ) {
12457                         PerlMemShared_free(aho->states);
12458                         PerlMemShared_free(aho->fail);
12459                          /* do this last!!!! */
12460                         PerlMemShared_free(ri->data->data[n]);
12461                         PerlMemShared_free(ri->regstclass);
12462                     }
12463                 }
12464                 break;
12465             case 't':
12466                 {
12467                     /* trie structure. */
12468                     U32 refcount;
12469                     reg_trie_data *trie=(reg_trie_data*)ri->data->data[n];
12470                     OP_REFCNT_LOCK;
12471                     refcount = --trie->refcount;
12472                     OP_REFCNT_UNLOCK;
12473                     if ( !refcount ) {
12474                         PerlMemShared_free(trie->charmap);
12475                         PerlMemShared_free(trie->states);
12476                         PerlMemShared_free(trie->trans);
12477                         if (trie->bitmap)
12478                             PerlMemShared_free(trie->bitmap);
12479                         if (trie->jump)
12480                             PerlMemShared_free(trie->jump);
12481                         PerlMemShared_free(trie->wordinfo);
12482                         /* do this last!!!! */
12483                         PerlMemShared_free(ri->data->data[n]);
12484                     }
12485                 }
12486                 break;
12487             default:
12488                 Perl_croak(aTHX_ "panic: regfree data code '%c'", ri->data->what[n]);
12489             }
12490         }
12491         Safefree(ri->data->what);
12492         Safefree(ri->data);
12493     }
12494
12495     Safefree(ri);
12496 }
12497
12498 #define av_dup_inc(s,t) MUTABLE_AV(sv_dup_inc((const SV *)s,t))
12499 #define hv_dup_inc(s,t) MUTABLE_HV(sv_dup_inc((const SV *)s,t))
12500 #define SAVEPVN(p,n)    ((p) ? savepvn(p,n) : NULL)
12501
12502 /* 
12503    re_dup - duplicate a regexp. 
12504    
12505    This routine is expected to clone a given regexp structure. It is only
12506    compiled under USE_ITHREADS.
12507
12508    After all of the core data stored in struct regexp is duplicated
12509    the regexp_engine.dupe method is used to copy any private data
12510    stored in the *pprivate pointer. This allows extensions to handle
12511    any duplication it needs to do.
12512
12513    See pregfree() and regfree_internal() if you change anything here. 
12514 */
12515 #if defined(USE_ITHREADS)
12516 #ifndef PERL_IN_XSUB_RE
12517 void
12518 Perl_re_dup_guts(pTHX_ const REGEXP *sstr, REGEXP *dstr, CLONE_PARAMS *param)
12519 {
12520     dVAR;
12521     I32 npar;
12522     const struct regexp *r = (const struct regexp *)SvANY(sstr);
12523     struct regexp *ret = (struct regexp *)SvANY(dstr);
12524     
12525     PERL_ARGS_ASSERT_RE_DUP_GUTS;
12526
12527     npar = r->nparens+1;
12528     Newx(ret->offs, npar, regexp_paren_pair);
12529     Copy(r->offs, ret->offs, npar, regexp_paren_pair);
12530     if(ret->swap) {
12531         /* no need to copy these */
12532         Newx(ret->swap, npar, regexp_paren_pair);
12533     }
12534
12535     if (ret->substrs) {
12536         /* Do it this way to avoid reading from *r after the StructCopy().
12537            That way, if any of the sv_dup_inc()s dislodge *r from the L1
12538            cache, it doesn't matter.  */
12539         const bool anchored = r->check_substr
12540             ? r->check_substr == r->anchored_substr
12541             : r->check_utf8 == r->anchored_utf8;
12542         Newx(ret->substrs, 1, struct reg_substr_data);
12543         StructCopy(r->substrs, ret->substrs, struct reg_substr_data);
12544
12545         ret->anchored_substr = sv_dup_inc(ret->anchored_substr, param);
12546         ret->anchored_utf8 = sv_dup_inc(ret->anchored_utf8, param);
12547         ret->float_substr = sv_dup_inc(ret->float_substr, param);
12548         ret->float_utf8 = sv_dup_inc(ret->float_utf8, param);
12549
12550         /* check_substr and check_utf8, if non-NULL, point to either their
12551            anchored or float namesakes, and don't hold a second reference.  */
12552
12553         if (ret->check_substr) {
12554             if (anchored) {
12555                 assert(r->check_utf8 == r->anchored_utf8);
12556                 ret->check_substr = ret->anchored_substr;
12557                 ret->check_utf8 = ret->anchored_utf8;
12558             } else {
12559                 assert(r->check_substr == r->float_substr);
12560                 assert(r->check_utf8 == r->float_utf8);
12561                 ret->check_substr = ret->float_substr;
12562                 ret->check_utf8 = ret->float_utf8;
12563             }
12564         } else if (ret->check_utf8) {
12565             if (anchored) {
12566                 ret->check_utf8 = ret->anchored_utf8;
12567             } else {
12568                 ret->check_utf8 = ret->float_utf8;
12569             }
12570         }
12571     }
12572
12573     RXp_PAREN_NAMES(ret) = hv_dup_inc(RXp_PAREN_NAMES(ret), param);
12574
12575     if (ret->pprivate)
12576         RXi_SET(ret,CALLREGDUPE_PVT(dstr,param));
12577
12578     if (RX_MATCH_COPIED(dstr))
12579         ret->subbeg  = SAVEPVN(ret->subbeg, ret->sublen);
12580     else
12581         ret->subbeg = NULL;
12582 #ifdef PERL_OLD_COPY_ON_WRITE
12583     ret->saved_copy = NULL;
12584 #endif
12585
12586     if (ret->mother_re) {
12587         if (SvPVX_const(dstr) == SvPVX_const(ret->mother_re)) {
12588             /* Our storage points directly to our mother regexp, but that's
12589                1: a buffer in a different thread
12590                2: something we no longer hold a reference on
12591                so we need to copy it locally.  */
12592             /* Note we need to use SvCUR(), rather than
12593                SvLEN(), on our mother_re, because it, in
12594                turn, may well be pointing to its own mother_re.  */
12595             SvPV_set(dstr, SAVEPVN(SvPVX_const(ret->mother_re),
12596                                    SvCUR(ret->mother_re)+1));
12597             SvLEN_set(dstr, SvCUR(ret->mother_re)+1);
12598         }
12599         ret->mother_re      = NULL;
12600     }
12601     ret->gofs = 0;
12602 }
12603 #endif /* PERL_IN_XSUB_RE */
12604
12605 /*
12606    regdupe_internal()
12607    
12608    This is the internal complement to regdupe() which is used to copy
12609    the structure pointed to by the *pprivate pointer in the regexp.
12610    This is the core version of the extension overridable cloning hook.
12611    The regexp structure being duplicated will be copied by perl prior
12612    to this and will be provided as the regexp *r argument, however 
12613    with the /old/ structures pprivate pointer value. Thus this routine
12614    may override any copying normally done by perl.
12615    
12616    It returns a pointer to the new regexp_internal structure.
12617 */
12618
12619 void *
12620 Perl_regdupe_internal(pTHX_ REGEXP * const rx, CLONE_PARAMS *param)
12621 {
12622     dVAR;
12623     struct regexp *const r = (struct regexp *)SvANY(rx);
12624     regexp_internal *reti;
12625     int len;
12626     RXi_GET_DECL(r,ri);
12627
12628     PERL_ARGS_ASSERT_REGDUPE_INTERNAL;
12629     
12630     len = ProgLen(ri);
12631     
12632     Newxc(reti, sizeof(regexp_internal) + len*sizeof(regnode), char, regexp_internal);
12633     Copy(ri->program, reti->program, len+1, regnode);
12634     
12635
12636     reti->regstclass = NULL;
12637
12638     if (ri->data) {
12639         struct reg_data *d;
12640         const int count = ri->data->count;
12641         int i;
12642
12643         Newxc(d, sizeof(struct reg_data) + count*sizeof(void *),
12644                 char, struct reg_data);
12645         Newx(d->what, count, U8);
12646
12647         d->count = count;
12648         for (i = 0; i < count; i++) {
12649             d->what[i] = ri->data->what[i];
12650             switch (d->what[i]) {
12651                 /* legal options are one of: sSfpontTua
12652                    see also regcomp.h and pregfree() */
12653             case 'a': /* actually an AV, but the dup function is identical.  */
12654             case 's':
12655             case 'S':
12656             case 'p': /* actually an AV, but the dup function is identical.  */
12657             case 'u': /* actually an HV, but the dup function is identical.  */
12658                 d->data[i] = sv_dup_inc((const SV *)ri->data->data[i], param);
12659                 break;
12660             case 'f':
12661                 /* This is cheating. */
12662                 Newx(d->data[i], 1, struct regnode_charclass_class);
12663                 StructCopy(ri->data->data[i], d->data[i],
12664                             struct regnode_charclass_class);
12665                 reti->regstclass = (regnode*)d->data[i];
12666                 break;
12667             case 'o':
12668                 /* Compiled op trees are readonly and in shared memory,
12669                    and can thus be shared without duplication. */
12670                 OP_REFCNT_LOCK;
12671                 d->data[i] = (void*)OpREFCNT_inc((OP*)ri->data->data[i]);
12672                 OP_REFCNT_UNLOCK;
12673                 break;
12674             case 'T':
12675                 /* Trie stclasses are readonly and can thus be shared
12676                  * without duplication. We free the stclass in pregfree
12677                  * when the corresponding reg_ac_data struct is freed.
12678                  */
12679                 reti->regstclass= ri->regstclass;
12680                 /* Fall through */
12681             case 't':
12682                 OP_REFCNT_LOCK;
12683                 ((reg_trie_data*)ri->data->data[i])->refcount++;
12684                 OP_REFCNT_UNLOCK;
12685                 /* Fall through */
12686             case 'n':
12687                 d->data[i] = ri->data->data[i];
12688                 break;
12689             default:
12690                 Perl_croak(aTHX_ "panic: re_dup unknown data code '%c'", ri->data->what[i]);
12691             }
12692         }
12693
12694         reti->data = d;
12695     }
12696     else
12697         reti->data = NULL;
12698
12699     reti->name_list_idx = ri->name_list_idx;
12700
12701 #ifdef RE_TRACK_PATTERN_OFFSETS
12702     if (ri->u.offsets) {
12703         Newx(reti->u.offsets, 2*len+1, U32);
12704         Copy(ri->u.offsets, reti->u.offsets, 2*len+1, U32);
12705     }
12706 #else
12707     SetProgLen(reti,len);
12708 #endif
12709
12710     return (void*)reti;
12711 }
12712
12713 #endif    /* USE_ITHREADS */
12714
12715 #ifndef PERL_IN_XSUB_RE
12716
12717 /*
12718  - regnext - dig the "next" pointer out of a node
12719  */
12720 regnode *
12721 Perl_regnext(pTHX_ register regnode *p)
12722 {
12723     dVAR;
12724     register I32 offset;
12725
12726     if (!p)
12727         return(NULL);
12728
12729     if (OP(p) > REGNODE_MAX) {          /* regnode.type is unsigned */
12730         Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d", (int)OP(p), (int)REGNODE_MAX);
12731     }
12732
12733     offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
12734     if (offset == 0)
12735         return(NULL);
12736
12737     return(p+offset);
12738 }
12739 #endif
12740
12741 STATIC void
12742 S_re_croak2(pTHX_ const char* pat1,const char* pat2,...)
12743 {
12744     va_list args;
12745     STRLEN l1 = strlen(pat1);
12746     STRLEN l2 = strlen(pat2);
12747     char buf[512];
12748     SV *msv;
12749     const char *message;
12750
12751     PERL_ARGS_ASSERT_RE_CROAK2;
12752
12753     if (l1 > 510)
12754         l1 = 510;
12755     if (l1 + l2 > 510)
12756         l2 = 510 - l1;
12757     Copy(pat1, buf, l1 , char);
12758     Copy(pat2, buf + l1, l2 , char);
12759     buf[l1 + l2] = '\n';
12760     buf[l1 + l2 + 1] = '\0';
12761 #ifdef I_STDARG
12762     /* ANSI variant takes additional second argument */
12763     va_start(args, pat2);
12764 #else
12765     va_start(args);
12766 #endif
12767     msv = vmess(buf, &args);
12768     va_end(args);
12769     message = SvPV_const(msv,l1);
12770     if (l1 > 512)
12771         l1 = 512;
12772     Copy(message, buf, l1 , char);
12773     buf[l1-1] = '\0';                   /* Overwrite \n */
12774     Perl_croak(aTHX_ "%s", buf);
12775 }
12776
12777 /* XXX Here's a total kludge.  But we need to re-enter for swash routines. */
12778
12779 #ifndef PERL_IN_XSUB_RE
12780 void
12781 Perl_save_re_context(pTHX)
12782 {
12783     dVAR;
12784
12785     struct re_save_state *state;
12786
12787     SAVEVPTR(PL_curcop);
12788     SSGROW(SAVESTACK_ALLOC_FOR_RE_SAVE_STATE + 1);
12789
12790     state = (struct re_save_state *)(PL_savestack + PL_savestack_ix);
12791     PL_savestack_ix += SAVESTACK_ALLOC_FOR_RE_SAVE_STATE;
12792     SSPUSHUV(SAVEt_RE_STATE);
12793
12794     Copy(&PL_reg_state, state, 1, struct re_save_state);
12795
12796     PL_reg_start_tmp = 0;
12797     PL_reg_start_tmpl = 0;
12798     PL_reg_oldsaved = NULL;
12799     PL_reg_oldsavedlen = 0;
12800     PL_reg_maxiter = 0;
12801     PL_reg_leftiter = 0;
12802     PL_reg_poscache = NULL;
12803     PL_reg_poscache_size = 0;
12804 #ifdef PERL_OLD_COPY_ON_WRITE
12805     PL_nrs = NULL;
12806 #endif
12807
12808     /* Save $1..$n (#18107: UTF-8 s/(\w+)/uc($1)/e); AMS 20021106. */
12809     if (PL_curpm) {
12810         const REGEXP * const rx = PM_GETRE(PL_curpm);
12811         if (rx) {
12812             U32 i;
12813             for (i = 1; i <= RX_NPARENS(rx); i++) {
12814                 char digits[TYPE_CHARS(long)];
12815                 const STRLEN len = my_snprintf(digits, sizeof(digits), "%lu", (long)i);
12816                 GV *const *const gvp
12817                     = (GV**)hv_fetch(PL_defstash, digits, len, 0);
12818
12819                 if (gvp) {
12820                     GV * const gv = *gvp;
12821                     if (SvTYPE(gv) == SVt_PVGV && GvSV(gv))
12822                         save_scalar(gv);
12823                 }
12824             }
12825         }
12826     }
12827 }
12828 #endif
12829
12830 static void
12831 clear_re(pTHX_ void *r)
12832 {
12833     dVAR;
12834     ReREFCNT_dec((REGEXP *)r);
12835 }
12836
12837 #ifdef DEBUGGING
12838
12839 STATIC void
12840 S_put_byte(pTHX_ SV *sv, int c)
12841 {
12842     PERL_ARGS_ASSERT_PUT_BYTE;
12843
12844     /* Our definition of isPRINT() ignores locales, so only bytes that are
12845        not part of UTF-8 are considered printable. I assume that the same
12846        holds for UTF-EBCDIC.
12847        Also, code point 255 is not printable in either (it's E0 in EBCDIC,
12848        which Wikipedia says:
12849
12850        EO, or Eight Ones, is an 8-bit EBCDIC character code represented as all
12851        ones (binary 1111 1111, hexadecimal FF). It is similar, but not
12852        identical, to the ASCII delete (DEL) or rubout control character.
12853        ) So the old condition can be simplified to !isPRINT(c)  */
12854     if (!isPRINT(c)) {
12855         if (c < 256) {
12856             Perl_sv_catpvf(aTHX_ sv, "\\x%02x", c);
12857         }
12858         else {
12859             Perl_sv_catpvf(aTHX_ sv, "\\x{%x}", c);
12860         }
12861     }
12862     else {
12863         const char string = c;
12864         if (c == '-' || c == ']' || c == '\\' || c == '^')
12865             sv_catpvs(sv, "\\");
12866         sv_catpvn(sv, &string, 1);
12867     }
12868 }
12869
12870
12871 #define CLEAR_OPTSTART \
12872     if (optstart) STMT_START { \
12873             DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log, " (%"IVdf" nodes)\n", (IV)(node - optstart))); \
12874             optstart=NULL; \
12875     } STMT_END
12876
12877 #define DUMPUNTIL(b,e) CLEAR_OPTSTART; node=dumpuntil(r,start,(b),(e),last,sv,indent+1,depth+1);
12878
12879 STATIC const regnode *
12880 S_dumpuntil(pTHX_ const regexp *r, const regnode *start, const regnode *node,
12881             const regnode *last, const regnode *plast, 
12882             SV* sv, I32 indent, U32 depth)
12883 {
12884     dVAR;
12885     register U8 op = PSEUDO;    /* Arbitrary non-END op. */
12886     register const regnode *next;
12887     const regnode *optstart= NULL;
12888     
12889     RXi_GET_DECL(r,ri);
12890     GET_RE_DEBUG_FLAGS_DECL;
12891
12892     PERL_ARGS_ASSERT_DUMPUNTIL;
12893
12894 #ifdef DEBUG_DUMPUNTIL
12895     PerlIO_printf(Perl_debug_log, "--- %d : %d - %d - %d\n",indent,node-start,
12896         last ? last-start : 0,plast ? plast-start : 0);
12897 #endif
12898             
12899     if (plast && plast < last) 
12900         last= plast;
12901
12902     while (PL_regkind[op] != END && (!last || node < last)) {
12903         /* While that wasn't END last time... */
12904         NODE_ALIGN(node);
12905         op = OP(node);
12906         if (op == CLOSE || op == WHILEM)
12907             indent--;
12908         next = regnext((regnode *)node);
12909
12910         /* Where, what. */
12911         if (OP(node) == OPTIMIZED) {
12912             if (!optstart && RE_DEBUG_FLAG(RE_DEBUG_COMPILE_OPTIMISE))
12913                 optstart = node;
12914             else
12915                 goto after_print;
12916         } else
12917             CLEAR_OPTSTART;
12918
12919         regprop(r, sv, node);
12920         PerlIO_printf(Perl_debug_log, "%4"IVdf":%*s%s", (IV)(node - start),
12921                       (int)(2*indent + 1), "", SvPVX_const(sv));
12922         
12923         if (OP(node) != OPTIMIZED) {                  
12924             if (next == NULL)           /* Next ptr. */
12925                 PerlIO_printf(Perl_debug_log, " (0)");
12926             else if (PL_regkind[(U8)op] == BRANCH && PL_regkind[OP(next)] != BRANCH )
12927                 PerlIO_printf(Perl_debug_log, " (FAIL)");
12928             else 
12929                 PerlIO_printf(Perl_debug_log, " (%"IVdf")", (IV)(next - start));
12930             (void)PerlIO_putc(Perl_debug_log, '\n'); 
12931         }
12932         
12933       after_print:
12934         if (PL_regkind[(U8)op] == BRANCHJ) {
12935             assert(next);
12936             {
12937                 register const regnode *nnode = (OP(next) == LONGJMP
12938                                              ? regnext((regnode *)next)
12939                                              : next);
12940                 if (last && nnode > last)
12941                     nnode = last;
12942                 DUMPUNTIL(NEXTOPER(NEXTOPER(node)), nnode);
12943             }
12944         }
12945         else if (PL_regkind[(U8)op] == BRANCH) {
12946             assert(next);
12947             DUMPUNTIL(NEXTOPER(node), next);
12948         }
12949         else if ( PL_regkind[(U8)op]  == TRIE ) {
12950             const regnode *this_trie = node;
12951             const char op = OP(node);
12952             const U32 n = ARG(node);
12953             const reg_ac_data * const ac = op>=AHOCORASICK ?
12954                (reg_ac_data *)ri->data->data[n] :
12955                NULL;
12956             const reg_trie_data * const trie =
12957                 (reg_trie_data*)ri->data->data[op<AHOCORASICK ? n : ac->trie];
12958 #ifdef DEBUGGING
12959             AV *const trie_words = MUTABLE_AV(ri->data->data[n + TRIE_WORDS_OFFSET]);
12960 #endif
12961             const regnode *nextbranch= NULL;
12962             I32 word_idx;
12963             sv_setpvs(sv, "");
12964             for (word_idx= 0; word_idx < (I32)trie->wordcount; word_idx++) {
12965                 SV ** const elem_ptr = av_fetch(trie_words,word_idx,0);
12966
12967                 PerlIO_printf(Perl_debug_log, "%*s%s ",
12968                    (int)(2*(indent+3)), "",
12969                     elem_ptr ? pv_pretty(sv, SvPV_nolen_const(*elem_ptr), SvCUR(*elem_ptr), 60,
12970                             PL_colors[0], PL_colors[1],
12971                             (SvUTF8(*elem_ptr) ? PERL_PV_ESCAPE_UNI : 0) |
12972                             PERL_PV_PRETTY_ELLIPSES    |
12973                             PERL_PV_PRETTY_LTGT
12974                             )
12975                             : "???"
12976                 );
12977                 if (trie->jump) {
12978                     U16 dist= trie->jump[word_idx+1];
12979                     PerlIO_printf(Perl_debug_log, "(%"UVuf")\n",
12980                                   (UV)((dist ? this_trie + dist : next) - start));
12981                     if (dist) {
12982                         if (!nextbranch)
12983                             nextbranch= this_trie + trie->jump[0];    
12984                         DUMPUNTIL(this_trie + dist, nextbranch);
12985                     }
12986                     if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
12987                         nextbranch= regnext((regnode *)nextbranch);
12988                 } else {
12989                     PerlIO_printf(Perl_debug_log, "\n");
12990                 }
12991             }
12992             if (last && next > last)
12993                 node= last;
12994             else
12995                 node= next;
12996         }
12997         else if ( op == CURLY ) {   /* "next" might be very big: optimizer */
12998             DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS,
12999                     NEXTOPER(node) + EXTRA_STEP_2ARGS + 1);
13000         }
13001         else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
13002             assert(next);
13003             DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS, next);
13004         }
13005         else if ( op == PLUS || op == STAR) {
13006             DUMPUNTIL(NEXTOPER(node), NEXTOPER(node) + 1);
13007         }
13008         else if (PL_regkind[(U8)op] == ANYOF) {
13009             /* arglen 1 + class block */
13010             node += 1 + ((ANYOF_FLAGS(node) & ANYOF_CLASS)
13011                     ? ANYOF_CLASS_SKIP : ANYOF_SKIP);
13012             node = NEXTOPER(node);
13013         }
13014         else if (PL_regkind[(U8)op] == EXACT) {
13015             /* Literal string, where present. */
13016             node += NODE_SZ_STR(node) - 1;
13017             node = NEXTOPER(node);
13018         }
13019         else {
13020             node = NEXTOPER(node);
13021             node += regarglen[(U8)op];
13022         }
13023         if (op == CURLYX || op == OPEN)
13024             indent++;
13025     }
13026     CLEAR_OPTSTART;
13027 #ifdef DEBUG_DUMPUNTIL    
13028     PerlIO_printf(Perl_debug_log, "--- %d\n", (int)indent);
13029 #endif
13030     return node;
13031 }
13032
13033 #endif  /* DEBUGGING */
13034
13035 /*
13036  * Local variables:
13037  * c-indentation-style: bsd
13038  * c-basic-offset: 4
13039  * indent-tabs-mode: t
13040  * End:
13041  *
13042  * ex: set ts=8 sts=4 sw=4 noet:
13043  */