Patch by Yves Orton to fix the regression reported in :
[p5sagit/p5-mst-13.2.git] / regcomp.c
1 /*    regcomp.c
2  */
3
4 /*
5  * "A fair jaw-cracker dwarf-language must be."  --Samwise Gamgee
6  */
7
8 /* This file contains functions for compiling a regular expression.  See
9  * also regexec.c which funnily enough, contains functions for executing
10  * a regular expression.
11  *
12  * This file is also copied at build time to ext/re/re_comp.c, where
13  * it's built with -DPERL_EXT_RE_BUILD -DPERL_EXT_RE_DEBUG -DPERL_EXT.
14  * This causes the main functions to be compiled under new names and with
15  * debugging support added, which makes "use re 'debug'" work.
16  */
17
18 /* NOTE: this is derived from Henry Spencer's regexp code, and should not
19  * confused with the original package (see point 3 below).  Thanks, Henry!
20  */
21
22 /* Additional note: this code is very heavily munged from Henry's version
23  * in places.  In some spots I've traded clarity for efficiency, so don't
24  * blame Henry for some of the lack of readability.
25  */
26
27 /* The names of the functions have been changed from regcomp and
28  * regexec to  pregcomp and pregexec in order to avoid conflicts
29  * with the POSIX routines of the same names.
30 */
31
32 #ifdef PERL_EXT_RE_BUILD
33 #include "re_top.h"
34 #endif
35
36 /*
37  * pregcomp and pregexec -- regsub and regerror are not used in perl
38  *
39  *      Copyright (c) 1986 by University of Toronto.
40  *      Written by Henry Spencer.  Not derived from licensed software.
41  *
42  *      Permission is granted to anyone to use this software for any
43  *      purpose on any computer system, and to redistribute it freely,
44  *      subject to the following restrictions:
45  *
46  *      1. The author is not responsible for the consequences of use of
47  *              this software, no matter how awful, even if they arise
48  *              from defects in it.
49  *
50  *      2. The origin of this software must not be misrepresented, either
51  *              by explicit claim or by omission.
52  *
53  *      3. Altered versions must be plainly marked as such, and must not
54  *              be misrepresented as being the original software.
55  *
56  *
57  ****    Alterations to Henry's code are...
58  ****
59  ****    Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
60  ****    2000, 2001, 2002, 2003, 2004, 2005, 2006, by Larry Wall and others
61  ****
62  ****    You may distribute under the terms of either the GNU General Public
63  ****    License or the Artistic License, as specified in the README file.
64
65  *
66  * Beware that some of this code is subtly aware of the way operator
67  * precedence is structured in regular expressions.  Serious changes in
68  * regular-expression syntax might require a total rethink.
69  */
70 #include "EXTERN.h"
71 #define PERL_IN_REGCOMP_C
72 #include "perl.h"
73
74 #ifndef PERL_IN_XSUB_RE
75 #  include "INTERN.h"
76 #endif
77
78 #define REG_COMP_C
79 #ifdef PERL_IN_XSUB_RE
80 #  include "re_comp.h"
81 #else
82 #  include "regcomp.h"
83 #endif
84
85 #ifdef op
86 #undef op
87 #endif /* op */
88
89 #ifdef MSDOS
90 #  if defined(BUGGY_MSC6)
91  /* MSC 6.00A breaks on op/regexp.t test 85 unless we turn this off */
92 #    pragma optimize("a",off)
93  /* But MSC 6.00A is happy with 'w', for aliases only across function calls*/
94 #    pragma optimize("w",on )
95 #  endif /* BUGGY_MSC6 */
96 #endif /* MSDOS */
97
98 #ifndef STATIC
99 #define STATIC  static
100 #endif
101
102 typedef struct RExC_state_t {
103     U32         flags;                  /* are we folding, multilining? */
104     char        *precomp;               /* uncompiled string. */
105     regexp      *rx;
106     char        *start;                 /* Start of input for compile */
107     char        *end;                   /* End of input for compile */
108     char        *parse;                 /* Input-scan pointer. */
109     I32         whilem_seen;            /* number of WHILEM in this expr */
110     regnode     *emit_start;            /* Start of emitted-code area */
111     regnode     *emit;                  /* Code-emit pointer; &regdummy = don't = compiling */
112     I32         naughty;                /* How bad is this pattern? */
113     I32         sawback;                /* Did we see \1, ...? */
114     U32         seen;
115     I32         size;                   /* Code size. */
116     I32         npar;                   /* Capture buffer count, (OPEN). */
117     I32         cpar;                   /* Capture buffer count, (CLOSE). */
118     I32         nestroot;               /* root parens we are in - used by accept */
119     I32         extralen;
120     I32         seen_zerolen;
121     I32         seen_evals;
122     regnode     **open_parens;          /* pointers to open parens */
123     regnode     **close_parens;         /* pointers to close parens */
124     regnode     *opend;                 /* END node in program */
125     I32         utf8;
126     HV          *charnames;             /* cache of named sequences */
127     HV          *paren_names;           /* Paren names */
128     regnode     **recurse;              /* Recurse regops */
129     I32         recurse_count;          /* Number of recurse regops */
130 #if ADD_TO_REGEXEC
131     char        *starttry;              /* -Dr: where regtry was called. */
132 #define RExC_starttry   (pRExC_state->starttry)
133 #endif
134 #ifdef DEBUGGING
135     const char  *lastparse;
136     I32         lastnum;
137 #define RExC_lastparse  (pRExC_state->lastparse)
138 #define RExC_lastnum    (pRExC_state->lastnum)
139 #endif
140 } RExC_state_t;
141
142 #define RExC_flags      (pRExC_state->flags)
143 #define RExC_precomp    (pRExC_state->precomp)
144 #define RExC_rx         (pRExC_state->rx)
145 #define RExC_start      (pRExC_state->start)
146 #define RExC_end        (pRExC_state->end)
147 #define RExC_parse      (pRExC_state->parse)
148 #define RExC_whilem_seen        (pRExC_state->whilem_seen)
149 #define RExC_offsets    (pRExC_state->rx->offsets) /* I am not like the others */
150 #define RExC_emit       (pRExC_state->emit)
151 #define RExC_emit_start (pRExC_state->emit_start)
152 #define RExC_naughty    (pRExC_state->naughty)
153 #define RExC_sawback    (pRExC_state->sawback)
154 #define RExC_seen       (pRExC_state->seen)
155 #define RExC_size       (pRExC_state->size)
156 #define RExC_npar       (pRExC_state->npar)
157 #define RExC_cpar       (pRExC_state->cpar)
158 #define RExC_nestroot   (pRExC_state->nestroot)
159 #define RExC_extralen   (pRExC_state->extralen)
160 #define RExC_seen_zerolen       (pRExC_state->seen_zerolen)
161 #define RExC_seen_evals (pRExC_state->seen_evals)
162 #define RExC_utf8       (pRExC_state->utf8)
163 #define RExC_charnames  (pRExC_state->charnames)
164 #define RExC_open_parens        (pRExC_state->open_parens)
165 #define RExC_close_parens       (pRExC_state->close_parens)
166 #define RExC_opend      (pRExC_state->opend)
167 #define RExC_paren_names        (pRExC_state->paren_names)
168 #define RExC_recurse    (pRExC_state->recurse)
169 #define RExC_recurse_count      (pRExC_state->recurse_count)
170
171 #define ISMULT1(c)      ((c) == '*' || (c) == '+' || (c) == '?')
172 #define ISMULT2(s)      ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
173         ((*s) == '{' && regcurly(s)))
174
175 #ifdef SPSTART
176 #undef SPSTART          /* dratted cpp namespace... */
177 #endif
178 /*
179  * Flags to be passed up and down.
180  */
181 #define WORST           0       /* Worst case. */
182 #define HASWIDTH        0x1     /* Known to match non-null strings. */
183 #define SIMPLE          0x2     /* Simple enough to be STAR/PLUS operand. */
184 #define SPSTART         0x4     /* Starts with * or +. */
185 #define TRYAGAIN        0x8     /* Weeded out a declaration. */
186
187 #define REG_NODE_NUM(x) ((x) ? (int)((x)-RExC_emit_start) : -1)
188
189 /* whether trie related optimizations are enabled */
190 #if PERL_ENABLE_EXTENDED_TRIE_OPTIMISATION
191 #define TRIE_STUDY_OPT
192 #define FULL_TRIE_STUDY
193 #define TRIE_STCLASS
194 #endif
195
196
197
198 #define PBYTE(u8str,paren) ((U8*)(u8str))[(paren) >> 3]
199 #define PBITVAL(paren) (1 << ((paren) & 7))
200 #define PAREN_TEST(u8str,paren) ( PBYTE(u8str,paren) & PBITVAL(paren))
201 #define PAREN_SET(u8str,paren) PBYTE(u8str,paren) |= PBITVAL(paren)
202 #define PAREN_UNSET(u8str,paren) PBYTE(u8str,paren) &= (~PBITVAL(paren))
203
204
205 /* About scan_data_t.
206
207   During optimisation we recurse through the regexp program performing
208   various inplace (keyhole style) optimisations. In addition study_chunk
209   and scan_commit populate this data structure with information about
210   what strings MUST appear in the pattern. We look for the longest 
211   string that must appear for at a fixed location, and we look for the
212   longest string that may appear at a floating location. So for instance
213   in the pattern:
214   
215     /FOO[xX]A.*B[xX]BAR/
216     
217   Both 'FOO' and 'A' are fixed strings. Both 'B' and 'BAR' are floating
218   strings (because they follow a .* construct). study_chunk will identify
219   both FOO and BAR as being the longest fixed and floating strings respectively.
220   
221   The strings can be composites, for instance
222   
223      /(f)(o)(o)/
224      
225   will result in a composite fixed substring 'foo'.
226   
227   For each string some basic information is maintained:
228   
229   - offset or min_offset
230     This is the position the string must appear at, or not before.
231     It also implicitly (when combined with minlenp) tells us how many
232     character must match before the string we are searching.
233     Likewise when combined with minlenp and the length of the string
234     tells us how many characters must appear after the string we have 
235     found.
236   
237   - max_offset
238     Only used for floating strings. This is the rightmost point that
239     the string can appear at. Ifset to I32 max it indicates that the
240     string can occur infinitely far to the right.
241   
242   - minlenp
243     A pointer to the minimum length of the pattern that the string 
244     was found inside. This is important as in the case of positive 
245     lookahead or positive lookbehind we can have multiple patterns 
246     involved. Consider
247     
248     /(?=FOO).*F/
249     
250     The minimum length of the pattern overall is 3, the minimum length
251     of the lookahead part is 3, but the minimum length of the part that
252     will actually match is 1. So 'FOO's minimum length is 3, but the 
253     minimum length for the F is 1. This is important as the minimum length
254     is used to determine offsets in front of and behind the string being 
255     looked for.  Since strings can be composites this is the length of the
256     pattern at the time it was commited with a scan_commit. Note that
257     the length is calculated by study_chunk, so that the minimum lengths
258     are not known until the full pattern has been compiled, thus the 
259     pointer to the value.
260   
261   - lookbehind
262   
263     In the case of lookbehind the string being searched for can be
264     offset past the start point of the final matching string. 
265     If this value was just blithely removed from the min_offset it would
266     invalidate some of the calculations for how many chars must match
267     before or after (as they are derived from min_offset and minlen and
268     the length of the string being searched for). 
269     When the final pattern is compiled and the data is moved from the
270     scan_data_t structure into the regexp structure the information
271     about lookbehind is factored in, with the information that would 
272     have been lost precalculated in the end_shift field for the 
273     associated string.
274
275   The fields pos_min and pos_delta are used to store the minimum offset
276   and the delta to the maximum offset at the current point in the pattern.    
277
278 */
279
280 typedef struct scan_data_t {
281     /*I32 len_min;      unused */
282     /*I32 len_delta;    unused */
283     I32 pos_min;
284     I32 pos_delta;
285     SV *last_found;
286     I32 last_end;           /* min value, <0 unless valid. */
287     I32 last_start_min;
288     I32 last_start_max;
289     SV **longest;           /* Either &l_fixed, or &l_float. */
290     SV *longest_fixed;      /* longest fixed string found in pattern */
291     I32 offset_fixed;       /* offset where it starts */
292     I32 *minlen_fixed;      /* pointer to the minlen relevent to the string */
293     I32 lookbehind_fixed;   /* is the position of the string modfied by LB */
294     SV *longest_float;      /* longest floating string found in pattern */
295     I32 offset_float_min;   /* earliest point in string it can appear */
296     I32 offset_float_max;   /* latest point in string it can appear */
297     I32 *minlen_float;      /* pointer to the minlen relevent to the string */
298     I32 lookbehind_float;   /* is the position of the string modified by LB */
299     I32 flags;
300     I32 whilem_c;
301     I32 *last_closep;
302     struct regnode_charclass_class *start_class;
303 } scan_data_t;
304
305 /*
306  * Forward declarations for pregcomp()'s friends.
307  */
308
309 static const scan_data_t zero_scan_data =
310   { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ,0};
311
312 #define SF_BEFORE_EOL           (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
313 #define SF_BEFORE_SEOL          0x0001
314 #define SF_BEFORE_MEOL          0x0002
315 #define SF_FIX_BEFORE_EOL       (SF_FIX_BEFORE_SEOL|SF_FIX_BEFORE_MEOL)
316 #define SF_FL_BEFORE_EOL        (SF_FL_BEFORE_SEOL|SF_FL_BEFORE_MEOL)
317
318 #ifdef NO_UNARY_PLUS
319 #  define SF_FIX_SHIFT_EOL      (0+2)
320 #  define SF_FL_SHIFT_EOL               (0+4)
321 #else
322 #  define SF_FIX_SHIFT_EOL      (+2)
323 #  define SF_FL_SHIFT_EOL               (+4)
324 #endif
325
326 #define SF_FIX_BEFORE_SEOL      (SF_BEFORE_SEOL << SF_FIX_SHIFT_EOL)
327 #define SF_FIX_BEFORE_MEOL      (SF_BEFORE_MEOL << SF_FIX_SHIFT_EOL)
328
329 #define SF_FL_BEFORE_SEOL       (SF_BEFORE_SEOL << SF_FL_SHIFT_EOL)
330 #define SF_FL_BEFORE_MEOL       (SF_BEFORE_MEOL << SF_FL_SHIFT_EOL) /* 0x20 */
331 #define SF_IS_INF               0x0040
332 #define SF_HAS_PAR              0x0080
333 #define SF_IN_PAR               0x0100
334 #define SF_HAS_EVAL             0x0200
335 #define SCF_DO_SUBSTR           0x0400
336 #define SCF_DO_STCLASS_AND      0x0800
337 #define SCF_DO_STCLASS_OR       0x1000
338 #define SCF_DO_STCLASS          (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
339 #define SCF_WHILEM_VISITED_POS  0x2000
340
341 #define SCF_TRIE_RESTUDY        0x4000 /* Do restudy? */
342 #define SCF_SEEN_ACCEPT         0x8000 
343
344 #define UTF (RExC_utf8 != 0)
345 #define LOC ((RExC_flags & PMf_LOCALE) != 0)
346 #define FOLD ((RExC_flags & PMf_FOLD) != 0)
347
348 #define OOB_UNICODE             12345678
349 #define OOB_NAMEDCLASS          -1
350
351 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
352 #define CHR_DIST(a,b) (UTF ? utf8_distance(a,b) : a - b)
353
354
355 /* length of regex to show in messages that don't mark a position within */
356 #define RegexLengthToShowInErrorMessages 127
357
358 /*
359  * If MARKER[12] are adjusted, be sure to adjust the constants at the top
360  * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
361  * op/pragma/warn/regcomp.
362  */
363 #define MARKER1 "<-- HERE"    /* marker as it appears in the description */
364 #define MARKER2 " <-- HERE "  /* marker as it appears within the regex */
365
366 #define REPORT_LOCATION " in regex; marked by " MARKER1 " in m/%.*s" MARKER2 "%s/"
367
368 /*
369  * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
370  * arg. Show regex, up to a maximum length. If it's too long, chop and add
371  * "...".
372  */
373 #define FAIL(msg) STMT_START {                                          \
374     const char *ellipses = "";                                          \
375     IV len = RExC_end - RExC_precomp;                                   \
376                                                                         \
377     if (!SIZE_ONLY)                                                     \
378         SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx);                      \
379     if (len > RegexLengthToShowInErrorMessages) {                       \
380         /* chop 10 shorter than the max, to ensure meaning of "..." */  \
381         len = RegexLengthToShowInErrorMessages - 10;                    \
382         ellipses = "...";                                               \
383     }                                                                   \
384     Perl_croak(aTHX_ "%s in regex m/%.*s%s/",                           \
385             msg, (int)len, RExC_precomp, ellipses);                     \
386 } STMT_END
387
388 /*
389  * Simple_vFAIL -- like FAIL, but marks the current location in the scan
390  */
391 #define Simple_vFAIL(m) STMT_START {                                    \
392     const IV offset = RExC_parse - RExC_precomp;                        \
393     Perl_croak(aTHX_ "%s" REPORT_LOCATION,                              \
394             m, (int)offset, RExC_precomp, RExC_precomp + offset);       \
395 } STMT_END
396
397 /*
398  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
399  */
400 #define vFAIL(m) STMT_START {                           \
401     if (!SIZE_ONLY)                                     \
402         SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx);      \
403     Simple_vFAIL(m);                                    \
404 } STMT_END
405
406 /*
407  * Like Simple_vFAIL(), but accepts two arguments.
408  */
409 #define Simple_vFAIL2(m,a1) STMT_START {                        \
410     const IV offset = RExC_parse - RExC_precomp;                        \
411     S_re_croak2(aTHX_ m, REPORT_LOCATION, a1,                   \
412             (int)offset, RExC_precomp, RExC_precomp + offset);  \
413 } STMT_END
414
415 /*
416  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
417  */
418 #define vFAIL2(m,a1) STMT_START {                       \
419     if (!SIZE_ONLY)                                     \
420         SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx);      \
421     Simple_vFAIL2(m, a1);                               \
422 } STMT_END
423
424
425 /*
426  * Like Simple_vFAIL(), but accepts three arguments.
427  */
428 #define Simple_vFAIL3(m, a1, a2) STMT_START {                   \
429     const IV offset = RExC_parse - RExC_precomp;                \
430     S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2,               \
431             (int)offset, RExC_precomp, RExC_precomp + offset);  \
432 } STMT_END
433
434 /*
435  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
436  */
437 #define vFAIL3(m,a1,a2) STMT_START {                    \
438     if (!SIZE_ONLY)                                     \
439         SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx);      \
440     Simple_vFAIL3(m, a1, a2);                           \
441 } STMT_END
442
443 /*
444  * Like Simple_vFAIL(), but accepts four arguments.
445  */
446 #define Simple_vFAIL4(m, a1, a2, a3) STMT_START {               \
447     const IV offset = RExC_parse - RExC_precomp;                \
448     S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, a3,           \
449             (int)offset, RExC_precomp, RExC_precomp + offset);  \
450 } STMT_END
451
452 #define vWARN(loc,m) STMT_START {                                       \
453     const IV offset = loc - RExC_precomp;                               \
454     Perl_warner(aTHX_ packWARN(WARN_REGEXP), "%s" REPORT_LOCATION,      \
455             m, (int)offset, RExC_precomp, RExC_precomp + offset);       \
456 } STMT_END
457
458 #define vWARNdep(loc,m) STMT_START {                                    \
459     const IV offset = loc - RExC_precomp;                               \
460     Perl_warner(aTHX_ packWARN2(WARN_DEPRECATED, WARN_REGEXP),          \
461             "%s" REPORT_LOCATION,                                       \
462             m, (int)offset, RExC_precomp, RExC_precomp + offset);       \
463 } STMT_END
464
465
466 #define vWARN2(loc, m, a1) STMT_START {                                 \
467     const IV offset = loc - RExC_precomp;                               \
468     Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION,         \
469             a1, (int)offset, RExC_precomp, RExC_precomp + offset);      \
470 } STMT_END
471
472 #define vWARN3(loc, m, a1, a2) STMT_START {                             \
473     const IV offset = loc - RExC_precomp;                               \
474     Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION,         \
475             a1, a2, (int)offset, RExC_precomp, RExC_precomp + offset);  \
476 } STMT_END
477
478 #define vWARN4(loc, m, a1, a2, a3) STMT_START {                         \
479     const IV offset = loc - RExC_precomp;                               \
480     Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION,         \
481             a1, a2, a3, (int)offset, RExC_precomp, RExC_precomp + offset); \
482 } STMT_END
483
484 #define vWARN5(loc, m, a1, a2, a3, a4) STMT_START {                     \
485     const IV offset = loc - RExC_precomp;                               \
486     Perl_warner(aTHX_ packWARN(WARN_REGEXP), m REPORT_LOCATION,         \
487             a1, a2, a3, a4, (int)offset, RExC_precomp, RExC_precomp + offset); \
488 } STMT_END
489
490
491 /* Allow for side effects in s */
492 #define REGC(c,s) STMT_START {                  \
493     if (!SIZE_ONLY) *(s) = (c); else (void)(s); \
494 } STMT_END
495
496 /* Macros for recording node offsets.   20001227 mjd@plover.com 
497  * Nodes are numbered 1, 2, 3, 4.  Node #n's position is recorded in
498  * element 2*n-1 of the array.  Element #2n holds the byte length node #n.
499  * Element 0 holds the number n.
500  * Position is 1 indexed.
501  */
502
503 #define Set_Node_Offset_To_R(node,byte) STMT_START {                    \
504     if (! SIZE_ONLY) {                                                  \
505         MJD_OFFSET_DEBUG(("** (%d) offset of node %d is %d.\n",         \
506                     __LINE__, (int)(node), (int)(byte)));               \
507         if((node) < 0) {                                                \
508             Perl_croak(aTHX_ "value of node is %d in Offset macro", (int)(node)); \
509         } else {                                                        \
510             RExC_offsets[2*(node)-1] = (byte);                          \
511         }                                                               \
512     }                                                                   \
513 } STMT_END
514
515 #define Set_Node_Offset(node,byte) \
516     Set_Node_Offset_To_R((node)-RExC_emit_start, (byte)-RExC_start)
517 #define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
518
519 #define Set_Node_Length_To_R(node,len) STMT_START {                     \
520     if (! SIZE_ONLY) {                                                  \
521         MJD_OFFSET_DEBUG(("** (%d) size of node %d is %d.\n",           \
522                 __LINE__, (int)(node), (int)(len)));                    \
523         if((node) < 0) {                                                \
524             Perl_croak(aTHX_ "value of node is %d in Length macro", (int)(node)); \
525         } else {                                                        \
526             RExC_offsets[2*(node)] = (len);                             \
527         }                                                               \
528     }                                                                   \
529 } STMT_END
530
531 #define Set_Node_Length(node,len) \
532     Set_Node_Length_To_R((node)-RExC_emit_start, len)
533 #define Set_Cur_Node_Length(len) Set_Node_Length(RExC_emit, len)
534 #define Set_Node_Cur_Length(node) \
535     Set_Node_Length(node, RExC_parse - parse_start)
536
537 /* Get offsets and lengths */
538 #define Node_Offset(n) (RExC_offsets[2*((n)-RExC_emit_start)-1])
539 #define Node_Length(n) (RExC_offsets[2*((n)-RExC_emit_start)])
540
541 #define Set_Node_Offset_Length(node,offset,len) STMT_START {    \
542     Set_Node_Offset_To_R((node)-RExC_emit_start, (offset));     \
543     Set_Node_Length_To_R((node)-RExC_emit_start, (len));        \
544 } STMT_END
545
546
547 #if PERL_ENABLE_EXPERIMENTAL_REGEX_OPTIMISATIONS
548 #define EXPERIMENTAL_INPLACESCAN
549 #endif
550
551 #define DEBUG_STUDYDATA(data,depth)                                  \
552 DEBUG_OPTIMISE_MORE_r(if(data){                                           \
553     PerlIO_printf(Perl_debug_log,                                    \
554         "%*s"/* Len:%"IVdf"/%"IVdf" */"Pos:%"IVdf"/%"IVdf           \
555         " Flags: %"IVdf" Whilem_c: %"IVdf" Lcp: %"IVdf" ",           \
556         (int)(depth)*2, "",                                          \
557         (IV)((data)->pos_min),                                       \
558         (IV)((data)->pos_delta),                                     \
559         (IV)((data)->flags),                                         \
560         (IV)((data)->whilem_c),                                      \
561         (IV)((data)->last_closep ? *((data)->last_closep) : -1)      \
562     );                                                               \
563     if ((data)->last_found)                                          \
564         PerlIO_printf(Perl_debug_log,                                \
565             "Last:'%s' %"IVdf":%"IVdf"/%"IVdf" %sFixed:'%s' @ %"IVdf \
566             " %sFloat: '%s' @ %"IVdf"/%"IVdf"",                      \
567             SvPVX_const((data)->last_found),                         \
568             (IV)((data)->last_end),                                  \
569             (IV)((data)->last_start_min),                            \
570             (IV)((data)->last_start_max),                            \
571             ((data)->longest &&                                      \
572              (data)->longest==&((data)->longest_fixed)) ? "*" : "",  \
573             SvPVX_const((data)->longest_fixed),                      \
574             (IV)((data)->offset_fixed),                              \
575             ((data)->longest &&                                      \
576              (data)->longest==&((data)->longest_float)) ? "*" : "",  \
577             SvPVX_const((data)->longest_float),                      \
578             (IV)((data)->offset_float_min),                          \
579             (IV)((data)->offset_float_max)                           \
580         );                                                           \
581     PerlIO_printf(Perl_debug_log,"\n");                              \
582 });
583
584 static void clear_re(pTHX_ void *r);
585
586 /* Mark that we cannot extend a found fixed substring at this point.
587    Update the longest found anchored substring and the longest found
588    floating substrings if needed. */
589
590 STATIC void
591 S_scan_commit(pTHX_ const RExC_state_t *pRExC_state, scan_data_t *data, I32 *minlenp)
592 {
593     const STRLEN l = CHR_SVLEN(data->last_found);
594     const STRLEN old_l = CHR_SVLEN(*data->longest);
595     GET_RE_DEBUG_FLAGS_DECL;
596
597     if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
598         SvSetMagicSV(*data->longest, data->last_found);
599         if (*data->longest == data->longest_fixed) {
600             data->offset_fixed = l ? data->last_start_min : data->pos_min;
601             if (data->flags & SF_BEFORE_EOL)
602                 data->flags
603                     |= ((data->flags & SF_BEFORE_EOL) << SF_FIX_SHIFT_EOL);
604             else
605                 data->flags &= ~SF_FIX_BEFORE_EOL;
606             data->minlen_fixed=minlenp; 
607             data->lookbehind_fixed=0;
608         }
609         else {
610             data->offset_float_min = l ? data->last_start_min : data->pos_min;
611             data->offset_float_max = (l
612                                       ? data->last_start_max
613                                       : data->pos_min + data->pos_delta);
614             if ((U32)data->offset_float_max > (U32)I32_MAX)
615                 data->offset_float_max = I32_MAX;
616             if (data->flags & SF_BEFORE_EOL)
617                 data->flags
618                     |= ((data->flags & SF_BEFORE_EOL) << SF_FL_SHIFT_EOL);
619             else
620                 data->flags &= ~SF_FL_BEFORE_EOL;
621             data->minlen_float=minlenp;
622             data->lookbehind_float=0;
623         }
624     }
625     SvCUR_set(data->last_found, 0);
626     {
627         SV * const sv = data->last_found;
628         if (SvUTF8(sv) && SvMAGICAL(sv)) {
629             MAGIC * const mg = mg_find(sv, PERL_MAGIC_utf8);
630             if (mg)
631                 mg->mg_len = 0;
632         }
633     }
634     data->last_end = -1;
635     data->flags &= ~SF_BEFORE_EOL;
636     DEBUG_STUDYDATA(data,0);
637 }
638
639 /* Can match anything (initialization) */
640 STATIC void
641 S_cl_anything(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
642 {
643     ANYOF_CLASS_ZERO(cl);
644     ANYOF_BITMAP_SETALL(cl);
645     cl->flags = ANYOF_EOS|ANYOF_UNICODE_ALL;
646     if (LOC)
647         cl->flags |= ANYOF_LOCALE;
648 }
649
650 /* Can match anything (initialization) */
651 STATIC int
652 S_cl_is_anything(const struct regnode_charclass_class *cl)
653 {
654     int value;
655
656     for (value = 0; value <= ANYOF_MAX; value += 2)
657         if (ANYOF_CLASS_TEST(cl, value) && ANYOF_CLASS_TEST(cl, value + 1))
658             return 1;
659     if (!(cl->flags & ANYOF_UNICODE_ALL))
660         return 0;
661     if (!ANYOF_BITMAP_TESTALLSET((const void*)cl))
662         return 0;
663     return 1;
664 }
665
666 /* Can match anything (initialization) */
667 STATIC void
668 S_cl_init(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
669 {
670     Zero(cl, 1, struct regnode_charclass_class);
671     cl->type = ANYOF;
672     cl_anything(pRExC_state, cl);
673 }
674
675 STATIC void
676 S_cl_init_zero(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
677 {
678     Zero(cl, 1, struct regnode_charclass_class);
679     cl->type = ANYOF;
680     cl_anything(pRExC_state, cl);
681     if (LOC)
682         cl->flags |= ANYOF_LOCALE;
683 }
684
685 /* 'And' a given class with another one.  Can create false positives */
686 /* We assume that cl is not inverted */
687 STATIC void
688 S_cl_and(struct regnode_charclass_class *cl,
689         const struct regnode_charclass_class *and_with)
690 {
691
692     assert(and_with->type == ANYOF);
693     if (!(and_with->flags & ANYOF_CLASS)
694         && !(cl->flags & ANYOF_CLASS)
695         && (and_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
696         && !(and_with->flags & ANYOF_FOLD)
697         && !(cl->flags & ANYOF_FOLD)) {
698         int i;
699
700         if (and_with->flags & ANYOF_INVERT)
701             for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
702                 cl->bitmap[i] &= ~and_with->bitmap[i];
703         else
704             for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
705                 cl->bitmap[i] &= and_with->bitmap[i];
706     } /* XXXX: logic is complicated otherwise, leave it along for a moment. */
707     if (!(and_with->flags & ANYOF_EOS))
708         cl->flags &= ~ANYOF_EOS;
709
710     if (cl->flags & ANYOF_UNICODE_ALL && and_with->flags & ANYOF_UNICODE &&
711         !(and_with->flags & ANYOF_INVERT)) {
712         cl->flags &= ~ANYOF_UNICODE_ALL;
713         cl->flags |= ANYOF_UNICODE;
714         ARG_SET(cl, ARG(and_with));
715     }
716     if (!(and_with->flags & ANYOF_UNICODE_ALL) &&
717         !(and_with->flags & ANYOF_INVERT))
718         cl->flags &= ~ANYOF_UNICODE_ALL;
719     if (!(and_with->flags & (ANYOF_UNICODE|ANYOF_UNICODE_ALL)) &&
720         !(and_with->flags & ANYOF_INVERT))
721         cl->flags &= ~ANYOF_UNICODE;
722 }
723
724 /* 'OR' a given class with another one.  Can create false positives */
725 /* We assume that cl is not inverted */
726 STATIC void
727 S_cl_or(const RExC_state_t *pRExC_state, struct regnode_charclass_class *cl, const struct regnode_charclass_class *or_with)
728 {
729     if (or_with->flags & ANYOF_INVERT) {
730         /* We do not use
731          * (B1 | CL1) | (!B2 & !CL2) = (B1 | !B2 & !CL2) | (CL1 | (!B2 & !CL2))
732          *   <= (B1 | !B2) | (CL1 | !CL2)
733          * which is wasteful if CL2 is small, but we ignore CL2:
734          *   (B1 | CL1) | (!B2 & !CL2) <= (B1 | CL1) | !B2 = (B1 | !B2) | CL1
735          * XXXX Can we handle case-fold?  Unclear:
736          *   (OK1(i) | OK1(i')) | !(OK1(i) | OK1(i')) =
737          *   (OK1(i) | OK1(i')) | (!OK1(i) & !OK1(i'))
738          */
739         if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
740              && !(or_with->flags & ANYOF_FOLD)
741              && !(cl->flags & ANYOF_FOLD) ) {
742             int i;
743
744             for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
745                 cl->bitmap[i] |= ~or_with->bitmap[i];
746         } /* XXXX: logic is complicated otherwise */
747         else {
748             cl_anything(pRExC_state, cl);
749         }
750     } else {
751         /* (B1 | CL1) | (B2 | CL2) = (B1 | B2) | (CL1 | CL2)) */
752         if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
753              && (!(or_with->flags & ANYOF_FOLD)
754                  || (cl->flags & ANYOF_FOLD)) ) {
755             int i;
756
757             /* OR char bitmap and class bitmap separately */
758             for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
759                 cl->bitmap[i] |= or_with->bitmap[i];
760             if (or_with->flags & ANYOF_CLASS) {
761                 for (i = 0; i < ANYOF_CLASSBITMAP_SIZE; i++)
762                     cl->classflags[i] |= or_with->classflags[i];
763                 cl->flags |= ANYOF_CLASS;
764             }
765         }
766         else { /* XXXX: logic is complicated, leave it along for a moment. */
767             cl_anything(pRExC_state, cl);
768         }
769     }
770     if (or_with->flags & ANYOF_EOS)
771         cl->flags |= ANYOF_EOS;
772
773     if (cl->flags & ANYOF_UNICODE && or_with->flags & ANYOF_UNICODE &&
774         ARG(cl) != ARG(or_with)) {
775         cl->flags |= ANYOF_UNICODE_ALL;
776         cl->flags &= ~ANYOF_UNICODE;
777     }
778     if (or_with->flags & ANYOF_UNICODE_ALL) {
779         cl->flags |= ANYOF_UNICODE_ALL;
780         cl->flags &= ~ANYOF_UNICODE;
781     }
782 }
783
784 #define TRIE_LIST_ITEM(state,idx) (trie->states[state].trans.list)[ idx ]
785 #define TRIE_LIST_CUR(state)  ( TRIE_LIST_ITEM( state, 0 ).forid )
786 #define TRIE_LIST_LEN(state) ( TRIE_LIST_ITEM( state, 0 ).newstate )
787 #define TRIE_LIST_USED(idx)  ( trie->states[state].trans.list ? (TRIE_LIST_CUR( idx ) - 1) : 0 )
788
789
790 #ifdef DEBUGGING
791 /*
792    dump_trie(trie)
793    dump_trie_interim_list(trie,next_alloc)
794    dump_trie_interim_table(trie,next_alloc)
795
796    These routines dump out a trie in a somewhat readable format.
797    The _interim_ variants are used for debugging the interim
798    tables that are used to generate the final compressed
799    representation which is what dump_trie expects.
800
801    Part of the reason for their existance is to provide a form
802    of documentation as to how the different representations function.
803
804 */
805
806 /*
807   dump_trie(trie)
808   Dumps the final compressed table form of the trie to Perl_debug_log.
809   Used for debugging make_trie().
810 */
811  
812 STATIC void
813 S_dump_trie(pTHX_ const struct _reg_trie_data *trie,U32 depth)
814 {
815     U32 state;
816     SV *sv=sv_newmortal();
817     int colwidth= trie->widecharmap ? 6 : 4;
818     GET_RE_DEBUG_FLAGS_DECL;
819
820
821     PerlIO_printf( Perl_debug_log, "%*sChar : %-6s%-6s%-4s ",
822         (int)depth * 2 + 2,"",
823         "Match","Base","Ofs" );
824
825     for( state = 0 ; state < trie->uniquecharcount ; state++ ) {
826         SV ** const tmp = av_fetch( trie->revcharmap, state, 0);
827         if ( tmp ) {
828             PerlIO_printf( Perl_debug_log, "%*s", 
829                 colwidth,
830                 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth, 
831                             PL_colors[0], PL_colors[1],
832                             (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
833                             PERL_PV_ESCAPE_FIRSTCHAR 
834                 ) 
835             );
836         }
837     }
838     PerlIO_printf( Perl_debug_log, "\n%*sState|-----------------------",
839         (int)depth * 2 + 2,"");
840
841     for( state = 0 ; state < trie->uniquecharcount ; state++ )
842         PerlIO_printf( Perl_debug_log, "%.*s", colwidth, "--------");
843     PerlIO_printf( Perl_debug_log, "\n");
844
845     for( state = 1 ; state < trie->statecount ; state++ ) {
846         const U32 base = trie->states[ state ].trans.base;
847
848         PerlIO_printf( Perl_debug_log, "%*s#%4"UVXf"|", (int)depth * 2 + 2,"", (UV)state);
849
850         if ( trie->states[ state ].wordnum ) {
851             PerlIO_printf( Perl_debug_log, " W%4X", trie->states[ state ].wordnum );
852         } else {
853             PerlIO_printf( Perl_debug_log, "%6s", "" );
854         }
855
856         PerlIO_printf( Perl_debug_log, " @%4"UVXf" ", (UV)base );
857
858         if ( base ) {
859             U32 ofs = 0;
860
861             while( ( base + ofs  < trie->uniquecharcount ) ||
862                    ( base + ofs - trie->uniquecharcount < trie->lasttrans
863                      && trie->trans[ base + ofs - trie->uniquecharcount ].check != state))
864                     ofs++;
865
866             PerlIO_printf( Perl_debug_log, "+%2"UVXf"[ ", (UV)ofs);
867
868             for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
869                 if ( ( base + ofs >= trie->uniquecharcount ) &&
870                      ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
871                      trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
872                 {
873                    PerlIO_printf( Perl_debug_log, "%*"UVXf,
874                     colwidth,
875                     (UV)trie->trans[ base + ofs - trie->uniquecharcount ].next );
876                 } else {
877                     PerlIO_printf( Perl_debug_log, "%*s",colwidth,"   ." );
878                 }
879             }
880
881             PerlIO_printf( Perl_debug_log, "]");
882
883         }
884         PerlIO_printf( Perl_debug_log, "\n" );
885     }
886 }    
887 /*
888   dump_trie_interim_list(trie,next_alloc)
889   Dumps a fully constructed but uncompressed trie in list form.
890   List tries normally only are used for construction when the number of 
891   possible chars (trie->uniquecharcount) is very high.
892   Used for debugging make_trie().
893 */
894 STATIC void
895 S_dump_trie_interim_list(pTHX_ const struct _reg_trie_data *trie, U32 next_alloc,U32 depth)
896 {
897     U32 state;
898     SV *sv=sv_newmortal();
899     int colwidth= trie->widecharmap ? 6 : 4;
900     GET_RE_DEBUG_FLAGS_DECL;
901     /* print out the table precompression.  */
902     PerlIO_printf( Perl_debug_log, "%*sState :Word | Transition Data\n%*s%s",
903         (int)depth * 2 + 2,"", (int)depth * 2 + 2,"",
904         "------:-----+-----------------\n" );
905     
906     for( state=1 ; state < next_alloc ; state ++ ) {
907         U16 charid;
908     
909         PerlIO_printf( Perl_debug_log, "%*s %4"UVXf" :",
910             (int)depth * 2 + 2,"", (UV)state  );
911         if ( ! trie->states[ state ].wordnum ) {
912             PerlIO_printf( Perl_debug_log, "%5s| ","");
913         } else {
914             PerlIO_printf( Perl_debug_log, "W%4x| ",
915                 trie->states[ state ].wordnum
916             );
917         }
918         for( charid = 1 ; charid <= TRIE_LIST_USED( state ) ; charid++ ) {
919             SV ** const tmp = av_fetch( trie->revcharmap, TRIE_LIST_ITEM(state,charid).forid, 0);
920             if ( tmp ) {
921                 PerlIO_printf( Perl_debug_log, "%*s:%3X=%4"UVXf" | ",
922                     colwidth,
923                     pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth, 
924                             PL_colors[0], PL_colors[1],
925                             (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
926                             PERL_PV_ESCAPE_FIRSTCHAR 
927                     ) ,
928                     TRIE_LIST_ITEM(state,charid).forid,
929                     (UV)TRIE_LIST_ITEM(state,charid).newstate
930                 );
931                 if (!(charid % 10)) 
932                     PerlIO_printf(Perl_debug_log, "\n%*s| ",
933                         (int)((depth * 2) + 14), "");
934             }
935         }
936         PerlIO_printf( Perl_debug_log, "\n");
937     }
938 }    
939
940 /*
941   dump_trie_interim_table(trie,next_alloc)
942   Dumps a fully constructed but uncompressed trie in table form.
943   This is the normal DFA style state transition table, with a few 
944   twists to facilitate compression later. 
945   Used for debugging make_trie().
946 */
947 STATIC void
948 S_dump_trie_interim_table(pTHX_ const struct _reg_trie_data *trie, U32 next_alloc, U32 depth)
949 {
950     U32 state;
951     U16 charid;
952     SV *sv=sv_newmortal();
953     int colwidth= trie->widecharmap ? 6 : 4;
954     GET_RE_DEBUG_FLAGS_DECL;
955     
956     /*
957        print out the table precompression so that we can do a visual check
958        that they are identical.
959      */
960     
961     PerlIO_printf( Perl_debug_log, "%*sChar : ",(int)depth * 2 + 2,"" );
962
963     for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
964         SV ** const tmp = av_fetch( trie->revcharmap, charid, 0);
965         if ( tmp ) {
966             PerlIO_printf( Perl_debug_log, "%*s", 
967                 colwidth,
968                 pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), colwidth, 
969                             PL_colors[0], PL_colors[1],
970                             (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
971                             PERL_PV_ESCAPE_FIRSTCHAR 
972                 ) 
973             );
974         }
975     }
976
977     PerlIO_printf( Perl_debug_log, "\n%*sState+-",(int)depth * 2 + 2,"" );
978
979     for( charid=0 ; charid < trie->uniquecharcount ; charid++ ) {
980         PerlIO_printf( Perl_debug_log, "%.*s", colwidth,"--------");
981     }
982
983     PerlIO_printf( Perl_debug_log, "\n" );
984
985     for( state=1 ; state < next_alloc ; state += trie->uniquecharcount ) {
986
987         PerlIO_printf( Perl_debug_log, "%*s%4"UVXf" : ", 
988             (int)depth * 2 + 2,"",
989             (UV)TRIE_NODENUM( state ) );
990
991         for( charid = 0 ; charid < trie->uniquecharcount ; charid++ ) {
992             UV v=(UV)SAFE_TRIE_NODENUM( trie->trans[ state + charid ].next );
993             if (v)
994                 PerlIO_printf( Perl_debug_log, "%*"UVXf, colwidth, v );
995             else
996                 PerlIO_printf( Perl_debug_log, "%*s", colwidth, "." );
997         }
998         if ( ! trie->states[ TRIE_NODENUM( state ) ].wordnum ) {
999             PerlIO_printf( Perl_debug_log, " (%4"UVXf")\n", (UV)trie->trans[ state ].check );
1000         } else {
1001             PerlIO_printf( Perl_debug_log, " (%4"UVXf") W%4X\n", (UV)trie->trans[ state ].check,
1002             trie->states[ TRIE_NODENUM( state ) ].wordnum );
1003         }
1004     }
1005 }
1006
1007 #endif
1008
1009 /* make_trie(startbranch,first,last,tail,word_count,flags,depth)
1010   startbranch: the first branch in the whole branch sequence
1011   first      : start branch of sequence of branch-exact nodes.
1012                May be the same as startbranch
1013   last       : Thing following the last branch.
1014                May be the same as tail.
1015   tail       : item following the branch sequence
1016   count      : words in the sequence
1017   flags      : currently the OP() type we will be building one of /EXACT(|F|Fl)/
1018   depth      : indent depth
1019
1020 Inplace optimizes a sequence of 2 or more Branch-Exact nodes into a TRIE node.
1021
1022 A trie is an N'ary tree where the branches are determined by digital
1023 decomposition of the key. IE, at the root node you look up the 1st character and
1024 follow that branch repeat until you find the end of the branches. Nodes can be
1025 marked as "accepting" meaning they represent a complete word. Eg:
1026
1027   /he|she|his|hers/
1028
1029 would convert into the following structure. Numbers represent states, letters
1030 following numbers represent valid transitions on the letter from that state, if
1031 the number is in square brackets it represents an accepting state, otherwise it
1032 will be in parenthesis.
1033
1034       +-h->+-e->[3]-+-r->(8)-+-s->[9]
1035       |    |
1036       |   (2)
1037       |    |
1038      (1)   +-i->(6)-+-s->[7]
1039       |
1040       +-s->(3)-+-h->(4)-+-e->[5]
1041
1042       Accept Word Mapping: 3=>1 (he),5=>2 (she), 7=>3 (his), 9=>4 (hers)
1043
1044 This shows that when matching against the string 'hers' we will begin at state 1
1045 read 'h' and move to state 2, read 'e' and move to state 3 which is accepting,
1046 then read 'r' and go to state 8 followed by 's' which takes us to state 9 which
1047 is also accepting. Thus we know that we can match both 'he' and 'hers' with a
1048 single traverse. We store a mapping from accepting to state to which word was
1049 matched, and then when we have multiple possibilities we try to complete the
1050 rest of the regex in the order in which they occured in the alternation.
1051
1052 The only prior NFA like behaviour that would be changed by the TRIE support is
1053 the silent ignoring of duplicate alternations which are of the form:
1054
1055  / (DUPE|DUPE) X? (?{ ... }) Y /x
1056
1057 Thus EVAL blocks follwing a trie may be called a different number of times with
1058 and without the optimisation. With the optimisations dupes will be silently
1059 ignored. This inconsistant behaviour of EVAL type nodes is well established as
1060 the following demonstrates:
1061
1062  'words'=~/(word|word|word)(?{ print $1 })[xyz]/
1063
1064 which prints out 'word' three times, but
1065
1066  'words'=~/(word|word|word)(?{ print $1 })S/
1067
1068 which doesnt print it out at all. This is due to other optimisations kicking in.
1069
1070 Example of what happens on a structural level:
1071
1072 The regexp /(ac|ad|ab)+/ will produce the folowing debug output:
1073
1074    1: CURLYM[1] {1,32767}(18)
1075    5:   BRANCH(8)
1076    6:     EXACT <ac>(16)
1077    8:   BRANCH(11)
1078    9:     EXACT <ad>(16)
1079   11:   BRANCH(14)
1080   12:     EXACT <ab>(16)
1081   16:   SUCCEED(0)
1082   17:   NOTHING(18)
1083   18: END(0)
1084
1085 This would be optimizable with startbranch=5, first=5, last=16, tail=16
1086 and should turn into:
1087
1088    1: CURLYM[1] {1,32767}(18)
1089    5:   TRIE(16)
1090         [Words:3 Chars Stored:6 Unique Chars:4 States:5 NCP:1]
1091           <ac>
1092           <ad>
1093           <ab>
1094   16:   SUCCEED(0)
1095   17:   NOTHING(18)
1096   18: END(0)
1097
1098 Cases where tail != last would be like /(?foo|bar)baz/:
1099
1100    1: BRANCH(4)
1101    2:   EXACT <foo>(8)
1102    4: BRANCH(7)
1103    5:   EXACT <bar>(8)
1104    7: TAIL(8)
1105    8: EXACT <baz>(10)
1106   10: END(0)
1107
1108 which would be optimizable with startbranch=1, first=1, last=7, tail=8
1109 and would end up looking like:
1110
1111     1: TRIE(8)
1112       [Words:2 Chars Stored:6 Unique Chars:5 States:7 NCP:1]
1113         <foo>
1114         <bar>
1115    7: TAIL(8)
1116    8: EXACT <baz>(10)
1117   10: END(0)
1118
1119     d = uvuni_to_utf8_flags(d, uv, 0);
1120
1121 is the recommended Unicode-aware way of saying
1122
1123     *(d++) = uv;
1124 */
1125
1126 #define TRIE_STORE_REVCHAR                                                 \
1127     STMT_START {                                                           \
1128         SV *tmp = newSVpvs("");                                            \
1129         if (UTF) SvUTF8_on(tmp);                                           \
1130         Perl_sv_catpvf( aTHX_ tmp, "%c", (int)uvc );                       \
1131         av_push( TRIE_REVCHARMAP(trie), tmp );                             \
1132     } STMT_END
1133
1134 #define TRIE_READ_CHAR STMT_START {                                           \
1135     wordlen++;                                                                \
1136     if ( UTF ) {                                                              \
1137         if ( folder ) {                                                       \
1138             if ( foldlen > 0 ) {                                              \
1139                uvc = utf8n_to_uvuni( scan, UTF8_MAXLEN, &len, uniflags );     \
1140                foldlen -= len;                                                \
1141                scan += len;                                                   \
1142                len = 0;                                                       \
1143             } else {                                                          \
1144                 uvc = utf8n_to_uvuni( (const U8*)uc, UTF8_MAXLEN, &len, uniflags);\
1145                 uvc = to_uni_fold( uvc, foldbuf, &foldlen );                  \
1146                 foldlen -= UNISKIP( uvc );                                    \
1147                 scan = foldbuf + UNISKIP( uvc );                              \
1148             }                                                                 \
1149         } else {                                                              \
1150             uvc = utf8n_to_uvuni( (const U8*)uc, UTF8_MAXLEN, &len, uniflags);\
1151         }                                                                     \
1152     } else {                                                                  \
1153         uvc = (U32)*uc;                                                       \
1154         len = 1;                                                              \
1155     }                                                                         \
1156 } STMT_END
1157
1158
1159
1160 #define TRIE_LIST_PUSH(state,fid,ns) STMT_START {               \
1161     if ( TRIE_LIST_CUR( state ) >=TRIE_LIST_LEN( state ) ) {    \
1162         U32 ging = TRIE_LIST_LEN( state ) *= 2;                 \
1163         Renew( trie->states[ state ].trans.list, ging, reg_trie_trans_le ); \
1164     }                                                           \
1165     TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).forid = fid;     \
1166     TRIE_LIST_ITEM( state, TRIE_LIST_CUR( state ) ).newstate = ns;   \
1167     TRIE_LIST_CUR( state )++;                                   \
1168 } STMT_END
1169
1170 #define TRIE_LIST_NEW(state) STMT_START {                       \
1171     Newxz( trie->states[ state ].trans.list,               \
1172         4, reg_trie_trans_le );                                 \
1173      TRIE_LIST_CUR( state ) = 1;                                \
1174      TRIE_LIST_LEN( state ) = 4;                                \
1175 } STMT_END
1176
1177 #define TRIE_HANDLE_WORD(state) STMT_START {                    \
1178     U16 dupe= trie->states[ state ].wordnum;                    \
1179     regnode * const noper_next = regnext( noper );              \
1180                                                                 \
1181     if (trie->wordlen)                                          \
1182         trie->wordlen[ curword ] = wordlen;                     \
1183     DEBUG_r({                                                   \
1184         /* store the word for dumping */                        \
1185         SV* tmp;                                                \
1186         if (OP(noper) != NOTHING)                               \
1187             tmp = newSVpvn(STRING(noper), STR_LEN(noper));      \
1188         else                                                    \
1189             tmp = newSVpvn( "", 0 );                            \
1190         if ( UTF ) SvUTF8_on( tmp );                            \
1191         av_push( trie->words, tmp );                            \
1192     });                                                         \
1193                                                                 \
1194     curword++;                                                  \
1195                                                                 \
1196     if ( noper_next < tail ) {                                  \
1197         if (!trie->jump)                                        \
1198             Newxz( trie->jump, word_count + 1, U16);            \
1199         trie->jump[curword] = (U16)(noper_next - convert);      \
1200         if (!jumper)                                            \
1201             jumper = noper_next;                                \
1202         if (!nextbranch)                                        \
1203             nextbranch= regnext(cur);                           \
1204     }                                                           \
1205                                                                 \
1206     if ( dupe ) {                                               \
1207         /* So it's a dupe. This means we need to maintain a   */\
1208         /* linked-list from the first to the next.            */\
1209         /* we only allocate the nextword buffer when there    */\
1210         /* a dupe, so first time we have to do the allocation */\
1211         if (!trie->nextword)                                    \
1212             Newxz( trie->nextword, word_count + 1, U16);        \
1213         while ( trie->nextword[dupe] )                          \
1214             dupe= trie->nextword[dupe];                         \
1215         trie->nextword[dupe]= curword;                          \
1216     } else {                                                    \
1217         /* we haven't inserted this word yet.                */ \
1218         trie->states[ state ].wordnum = curword;                \
1219     }                                                           \
1220 } STMT_END
1221
1222
1223 #define TRIE_TRANS_STATE(state,base,ucharcount,charid,special)          \
1224      ( ( base + charid >=  ucharcount                                   \
1225          && base + charid < ubound                                      \
1226          && state == trie->trans[ base - ucharcount + charid ].check    \
1227          && trie->trans[ base - ucharcount + charid ].next )            \
1228            ? trie->trans[ base - ucharcount + charid ].next             \
1229            : ( state==1 ? special : 0 )                                 \
1230       )
1231
1232 #define MADE_TRIE       1
1233 #define MADE_JUMP_TRIE  2
1234 #define MADE_EXACT_TRIE 4
1235
1236 STATIC I32
1237 S_make_trie(pTHX_ RExC_state_t *pRExC_state, regnode *startbranch, regnode *first, regnode *last, regnode *tail, U32 word_count, U32 flags, U32 depth)
1238 {
1239     dVAR;
1240     /* first pass, loop through and scan words */
1241     reg_trie_data *trie;
1242     regnode *cur;
1243     const U32 uniflags = UTF8_ALLOW_DEFAULT;
1244     STRLEN len = 0;
1245     UV uvc = 0;
1246     U16 curword = 0;
1247     U32 next_alloc = 0;
1248     regnode *jumper = NULL;
1249     regnode *nextbranch = NULL;
1250     regnode *convert = NULL;
1251     /* we just use folder as a flag in utf8 */
1252     const U8 * const folder = ( flags == EXACTF
1253                        ? PL_fold
1254                        : ( flags == EXACTFL
1255                            ? PL_fold_locale
1256                            : NULL
1257                          )
1258                      );
1259
1260     const U32 data_slot = add_data( pRExC_state, 1, "t" );
1261     SV *re_trie_maxbuff;
1262 #ifndef DEBUGGING
1263     /* these are only used during construction but are useful during
1264      * debugging so we store them in the struct when debugging.
1265      */
1266     STRLEN trie_charcount=0;
1267     AV *trie_revcharmap;
1268 #endif
1269     GET_RE_DEBUG_FLAGS_DECL;
1270 #ifndef DEBUGGING
1271     PERL_UNUSED_ARG(depth);
1272 #endif
1273
1274     Newxz( trie, 1, reg_trie_data );
1275     trie->refcount = 1;
1276     trie->startstate = 1;
1277     trie->wordcount = word_count;
1278     RExC_rx->data->data[ data_slot ] = (void*)trie;
1279     Newxz( trie->charmap, 256, U16 );
1280     if (!(UTF && folder))
1281         Newxz( trie->bitmap, ANYOF_BITMAP_SIZE, char );
1282     DEBUG_r({
1283         trie->words = newAV();
1284     });
1285     TRIE_REVCHARMAP(trie) = newAV();
1286
1287     re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
1288     if (!SvIOK(re_trie_maxbuff)) {
1289         sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
1290     }
1291     DEBUG_OPTIMISE_r({
1292                 PerlIO_printf( Perl_debug_log,
1293                   "%*smake_trie start==%d, first==%d, last==%d, tail==%d depth=%d\n",
1294                   (int)depth * 2 + 2, "", 
1295                   REG_NODE_NUM(startbranch),REG_NODE_NUM(first), 
1296                   REG_NODE_NUM(last), REG_NODE_NUM(tail),
1297                   (int)depth);
1298     });
1299    
1300    /* Find the node we are going to overwrite */
1301     if ( first == startbranch && OP( last ) != BRANCH ) {
1302         /* whole branch chain */
1303         convert = first;
1304     } else {
1305         /* branch sub-chain */
1306         convert = NEXTOPER( first );
1307     }
1308         
1309     /*  -- First loop and Setup --
1310
1311        We first traverse the branches and scan each word to determine if it
1312        contains widechars, and how many unique chars there are, this is
1313        important as we have to build a table with at least as many columns as we
1314        have unique chars.
1315
1316        We use an array of integers to represent the character codes 0..255
1317        (trie->charmap) and we use a an HV* to store unicode characters. We use the
1318        native representation of the character value as the key and IV's for the
1319        coded index.
1320
1321        *TODO* If we keep track of how many times each character is used we can
1322        remap the columns so that the table compression later on is more
1323        efficient in terms of memory by ensuring most common value is in the
1324        middle and the least common are on the outside.  IMO this would be better
1325        than a most to least common mapping as theres a decent chance the most
1326        common letter will share a node with the least common, meaning the node
1327        will not be compressable. With a middle is most common approach the worst
1328        case is when we have the least common nodes twice.
1329
1330      */
1331
1332     for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1333         regnode * const noper = NEXTOPER( cur );
1334         const U8 *uc = (U8*)STRING( noper );
1335         const U8 * const e  = uc + STR_LEN( noper );
1336         STRLEN foldlen = 0;
1337         U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1338         const U8 *scan = (U8*)NULL;
1339         U32 wordlen      = 0;         /* required init */
1340         STRLEN chars=0;
1341
1342         if (OP(noper) == NOTHING) {
1343             trie->minlen= 0;
1344             continue;
1345         }
1346         if (trie->bitmap) {
1347             TRIE_BITMAP_SET(trie,*uc);
1348             if ( folder ) TRIE_BITMAP_SET(trie,folder[ *uc ]);            
1349         }
1350         for ( ; uc < e ; uc += len ) {
1351             TRIE_CHARCOUNT(trie)++;
1352             TRIE_READ_CHAR;
1353             chars++;
1354             if ( uvc < 256 ) {
1355                 if ( !trie->charmap[ uvc ] ) {
1356                     trie->charmap[ uvc ]=( ++trie->uniquecharcount );
1357                     if ( folder )
1358                         trie->charmap[ folder[ uvc ] ] = trie->charmap[ uvc ];
1359                     TRIE_STORE_REVCHAR;
1360                 }
1361             } else {
1362                 SV** svpp;
1363                 if ( !trie->widecharmap )
1364                     trie->widecharmap = newHV();
1365
1366                 svpp = hv_fetch( trie->widecharmap, (char*)&uvc, sizeof( UV ), 1 );
1367
1368                 if ( !svpp )
1369                     Perl_croak( aTHX_ "error creating/fetching widecharmap entry for 0x%"UVXf, uvc );
1370
1371                 if ( !SvTRUE( *svpp ) ) {
1372                     sv_setiv( *svpp, ++trie->uniquecharcount );
1373                     TRIE_STORE_REVCHAR;
1374                 }
1375             }
1376         }
1377         if( cur == first ) {
1378             trie->minlen=chars;
1379             trie->maxlen=chars;
1380         } else if (chars < trie->minlen) {
1381             trie->minlen=chars;
1382         } else if (chars > trie->maxlen) {
1383             trie->maxlen=chars;
1384         }
1385
1386     } /* end first pass */
1387     DEBUG_TRIE_COMPILE_r(
1388         PerlIO_printf( Perl_debug_log, "%*sTRIE(%s): W:%d C:%d Uq:%d Min:%d Max:%d\n",
1389                 (int)depth * 2 + 2,"",
1390                 ( trie->widecharmap ? "UTF8" : "NATIVE" ), (int)word_count,
1391                 (int)TRIE_CHARCOUNT(trie), trie->uniquecharcount,
1392                 (int)trie->minlen, (int)trie->maxlen )
1393     );
1394     Newxz( trie->wordlen, word_count, U32 );
1395
1396     /*
1397         We now know what we are dealing with in terms of unique chars and
1398         string sizes so we can calculate how much memory a naive
1399         representation using a flat table  will take. If it's over a reasonable
1400         limit (as specified by ${^RE_TRIE_MAXBUF}) we use a more memory
1401         conservative but potentially much slower representation using an array
1402         of lists.
1403
1404         At the end we convert both representations into the same compressed
1405         form that will be used in regexec.c for matching with. The latter
1406         is a form that cannot be used to construct with but has memory
1407         properties similar to the list form and access properties similar
1408         to the table form making it both suitable for fast searches and
1409         small enough that its feasable to store for the duration of a program.
1410
1411         See the comment in the code where the compressed table is produced
1412         inplace from the flat tabe representation for an explanation of how
1413         the compression works.
1414
1415     */
1416
1417
1418     if ( (IV)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1) > SvIV(re_trie_maxbuff) ) {
1419         /*
1420             Second Pass -- Array Of Lists Representation
1421
1422             Each state will be represented by a list of charid:state records
1423             (reg_trie_trans_le) the first such element holds the CUR and LEN
1424             points of the allocated array. (See defines above).
1425
1426             We build the initial structure using the lists, and then convert
1427             it into the compressed table form which allows faster lookups
1428             (but cant be modified once converted).
1429         */
1430
1431         STRLEN transcount = 1;
1432
1433         DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log, 
1434             "%*sCompiling trie using list compiler\n",
1435             (int)depth * 2 + 2, ""));
1436
1437         Newxz( trie->states, TRIE_CHARCOUNT(trie) + 2, reg_trie_state );
1438         TRIE_LIST_NEW(1);
1439         next_alloc = 2;
1440
1441         for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1442
1443             regnode * const noper = NEXTOPER( cur );
1444             U8 *uc           = (U8*)STRING( noper );
1445             const U8 * const e = uc + STR_LEN( noper );
1446             U32 state        = 1;         /* required init */
1447             U16 charid       = 0;         /* sanity init */
1448             U8 *scan         = (U8*)NULL; /* sanity init */
1449             STRLEN foldlen   = 0;         /* required init */
1450             U32 wordlen      = 0;         /* required init */
1451             U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1452
1453             if (OP(noper) != NOTHING) {
1454                 for ( ; uc < e ; uc += len ) {
1455
1456                     TRIE_READ_CHAR;
1457
1458                     if ( uvc < 256 ) {
1459                         charid = trie->charmap[ uvc ];
1460                     } else {
1461                         SV** const svpp = hv_fetch( trie->widecharmap, (char*)&uvc, sizeof( UV ), 0);
1462                         if ( !svpp ) {
1463                             charid = 0;
1464                         } else {
1465                             charid=(U16)SvIV( *svpp );
1466                         }
1467                     }
1468                     /* charid is now 0 if we dont know the char read, or nonzero if we do */
1469                     if ( charid ) {
1470
1471                         U16 check;
1472                         U32 newstate = 0;
1473
1474                         charid--;
1475                         if ( !trie->states[ state ].trans.list ) {
1476                             TRIE_LIST_NEW( state );
1477                         }
1478                         for ( check = 1; check <= TRIE_LIST_USED( state ); check++ ) {
1479                             if ( TRIE_LIST_ITEM( state, check ).forid == charid ) {
1480                                 newstate = TRIE_LIST_ITEM( state, check ).newstate;
1481                                 break;
1482                             }
1483                         }
1484                         if ( ! newstate ) {
1485                             newstate = next_alloc++;
1486                             TRIE_LIST_PUSH( state, charid, newstate );
1487                             transcount++;
1488                         }
1489                         state = newstate;
1490                     } else {
1491                         Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
1492                     }
1493                 }
1494             }
1495             TRIE_HANDLE_WORD(state);
1496
1497         } /* end second pass */
1498
1499         /* next alloc is the NEXT state to be allocated */
1500         trie->statecount = next_alloc; 
1501         Renew( trie->states, next_alloc, reg_trie_state );
1502
1503         /* and now dump it out before we compress it */
1504         DEBUG_TRIE_COMPILE_MORE_r(
1505             dump_trie_interim_list(trie,next_alloc,depth+1)
1506         );
1507
1508         Newxz( trie->trans, transcount ,reg_trie_trans );
1509         {
1510             U32 state;
1511             U32 tp = 0;
1512             U32 zp = 0;
1513
1514
1515             for( state=1 ; state < next_alloc ; state ++ ) {
1516                 U32 base=0;
1517
1518                 /*
1519                 DEBUG_TRIE_COMPILE_MORE_r(
1520                     PerlIO_printf( Perl_debug_log, "tp: %d zp: %d ",tp,zp)
1521                 );
1522                 */
1523
1524                 if (trie->states[state].trans.list) {
1525                     U16 minid=TRIE_LIST_ITEM( state, 1).forid;
1526                     U16 maxid=minid;
1527                     U16 idx;
1528
1529                     for( idx = 2 ; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
1530                         const U16 forid = TRIE_LIST_ITEM( state, idx).forid;
1531                         if ( forid < minid ) {
1532                             minid=forid;
1533                         } else if ( forid > maxid ) {
1534                             maxid=forid;
1535                         }
1536                     }
1537                     if ( transcount < tp + maxid - minid + 1) {
1538                         transcount *= 2;
1539                         Renew( trie->trans, transcount, reg_trie_trans );
1540                         Zero( trie->trans + (transcount / 2), transcount / 2 , reg_trie_trans );
1541                     }
1542                     base = trie->uniquecharcount + tp - minid;
1543                     if ( maxid == minid ) {
1544                         U32 set = 0;
1545                         for ( ; zp < tp ; zp++ ) {
1546                             if ( ! trie->trans[ zp ].next ) {
1547                                 base = trie->uniquecharcount + zp - minid;
1548                                 trie->trans[ zp ].next = TRIE_LIST_ITEM( state, 1).newstate;
1549                                 trie->trans[ zp ].check = state;
1550                                 set = 1;
1551                                 break;
1552                             }
1553                         }
1554                         if ( !set ) {
1555                             trie->trans[ tp ].next = TRIE_LIST_ITEM( state, 1).newstate;
1556                             trie->trans[ tp ].check = state;
1557                             tp++;
1558                             zp = tp;
1559                         }
1560                     } else {
1561                         for ( idx=1; idx <= TRIE_LIST_USED( state ) ; idx++ ) {
1562                             const U32 tid = base -  trie->uniquecharcount + TRIE_LIST_ITEM( state, idx ).forid;
1563                             trie->trans[ tid ].next = TRIE_LIST_ITEM( state, idx ).newstate;
1564                             trie->trans[ tid ].check = state;
1565                         }
1566                         tp += ( maxid - minid + 1 );
1567                     }
1568                     Safefree(trie->states[ state ].trans.list);
1569                 }
1570                 /*
1571                 DEBUG_TRIE_COMPILE_MORE_r(
1572                     PerlIO_printf( Perl_debug_log, " base: %d\n",base);
1573                 );
1574                 */
1575                 trie->states[ state ].trans.base=base;
1576             }
1577             trie->lasttrans = tp + 1;
1578         }
1579     } else {
1580         /*
1581            Second Pass -- Flat Table Representation.
1582
1583            we dont use the 0 slot of either trans[] or states[] so we add 1 to each.
1584            We know that we will need Charcount+1 trans at most to store the data
1585            (one row per char at worst case) So we preallocate both structures
1586            assuming worst case.
1587
1588            We then construct the trie using only the .next slots of the entry
1589            structs.
1590
1591            We use the .check field of the first entry of the node  temporarily to
1592            make compression both faster and easier by keeping track of how many non
1593            zero fields are in the node.
1594
1595            Since trans are numbered from 1 any 0 pointer in the table is a FAIL
1596            transition.
1597
1598            There are two terms at use here: state as a TRIE_NODEIDX() which is a
1599            number representing the first entry of the node, and state as a
1600            TRIE_NODENUM() which is the trans number. state 1 is TRIE_NODEIDX(1) and
1601            TRIE_NODENUM(1), state 2 is TRIE_NODEIDX(2) and TRIE_NODENUM(3) if there
1602            are 2 entrys per node. eg:
1603
1604              A B       A B
1605           1. 2 4    1. 3 7
1606           2. 0 3    3. 0 5
1607           3. 0 0    5. 0 0
1608           4. 0 0    7. 0 0
1609
1610            The table is internally in the right hand, idx form. However as we also
1611            have to deal with the states array which is indexed by nodenum we have to
1612            use TRIE_NODENUM() to convert.
1613
1614         */
1615         DEBUG_TRIE_COMPILE_MORE_r( PerlIO_printf( Perl_debug_log, 
1616             "%*sCompiling trie using table compiler\n",
1617             (int)depth * 2 + 2, ""));
1618
1619         Newxz( trie->trans, ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1,
1620               reg_trie_trans );
1621         Newxz( trie->states, TRIE_CHARCOUNT(trie) + 2, reg_trie_state );
1622         next_alloc = trie->uniquecharcount + 1;
1623
1624
1625         for ( cur = first ; cur < last ; cur = regnext( cur ) ) {
1626
1627             regnode * const noper   = NEXTOPER( cur );
1628             const U8 *uc     = (U8*)STRING( noper );
1629             const U8 * const e = uc + STR_LEN( noper );
1630
1631             U32 state        = 1;         /* required init */
1632
1633             U16 charid       = 0;         /* sanity init */
1634             U32 accept_state = 0;         /* sanity init */
1635             U8 *scan         = (U8*)NULL; /* sanity init */
1636
1637             STRLEN foldlen   = 0;         /* required init */
1638             U32 wordlen      = 0;         /* required init */
1639             U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1640
1641             if ( OP(noper) != NOTHING ) {
1642                 for ( ; uc < e ; uc += len ) {
1643
1644                     TRIE_READ_CHAR;
1645
1646                     if ( uvc < 256 ) {
1647                         charid = trie->charmap[ uvc ];
1648                     } else {
1649                         SV* const * const svpp = hv_fetch( trie->widecharmap, (char*)&uvc, sizeof( UV ), 0);
1650                         charid = svpp ? (U16)SvIV(*svpp) : 0;
1651                     }
1652                     if ( charid ) {
1653                         charid--;
1654                         if ( !trie->trans[ state + charid ].next ) {
1655                             trie->trans[ state + charid ].next = next_alloc;
1656                             trie->trans[ state ].check++;
1657                             next_alloc += trie->uniquecharcount;
1658                         }
1659                         state = trie->trans[ state + charid ].next;
1660                     } else {
1661                         Perl_croak( aTHX_ "panic! In trie construction, no char mapping for %"IVdf, uvc );
1662                     }
1663                     /* charid is now 0 if we dont know the char read, or nonzero if we do */
1664                 }
1665             }
1666             accept_state = TRIE_NODENUM( state );
1667             TRIE_HANDLE_WORD(accept_state);
1668
1669         } /* end second pass */
1670
1671         /* and now dump it out before we compress it */
1672         DEBUG_TRIE_COMPILE_MORE_r(
1673             dump_trie_interim_table(trie,next_alloc,depth+1)
1674         );
1675
1676         {
1677         /*
1678            * Inplace compress the table.*
1679
1680            For sparse data sets the table constructed by the trie algorithm will
1681            be mostly 0/FAIL transitions or to put it another way mostly empty.
1682            (Note that leaf nodes will not contain any transitions.)
1683
1684            This algorithm compresses the tables by eliminating most such
1685            transitions, at the cost of a modest bit of extra work during lookup:
1686
1687            - Each states[] entry contains a .base field which indicates the
1688            index in the state[] array wheres its transition data is stored.
1689
1690            - If .base is 0 there are no  valid transitions from that node.
1691
1692            - If .base is nonzero then charid is added to it to find an entry in
1693            the trans array.
1694
1695            -If trans[states[state].base+charid].check!=state then the
1696            transition is taken to be a 0/Fail transition. Thus if there are fail
1697            transitions at the front of the node then the .base offset will point
1698            somewhere inside the previous nodes data (or maybe even into a node
1699            even earlier), but the .check field determines if the transition is
1700            valid.
1701
1702            XXX - wrong maybe?
1703            The following process inplace converts the table to the compressed
1704            table: We first do not compress the root node 1,and mark its all its
1705            .check pointers as 1 and set its .base pointer as 1 as well. This
1706            allows to do a DFA construction from the compressed table later, and
1707            ensures that any .base pointers we calculate later are greater than
1708            0.
1709
1710            - We set 'pos' to indicate the first entry of the second node.
1711
1712            - We then iterate over the columns of the node, finding the first and
1713            last used entry at l and m. We then copy l..m into pos..(pos+m-l),
1714            and set the .check pointers accordingly, and advance pos
1715            appropriately and repreat for the next node. Note that when we copy
1716            the next pointers we have to convert them from the original
1717            NODEIDX form to NODENUM form as the former is not valid post
1718            compression.
1719
1720            - If a node has no transitions used we mark its base as 0 and do not
1721            advance the pos pointer.
1722
1723            - If a node only has one transition we use a second pointer into the
1724            structure to fill in allocated fail transitions from other states.
1725            This pointer is independent of the main pointer and scans forward
1726            looking for null transitions that are allocated to a state. When it
1727            finds one it writes the single transition into the "hole".  If the
1728            pointer doesnt find one the single transition is appended as normal.
1729
1730            - Once compressed we can Renew/realloc the structures to release the
1731            excess space.
1732
1733            See "Table-Compression Methods" in sec 3.9 of the Red Dragon,
1734            specifically Fig 3.47 and the associated pseudocode.
1735
1736            demq
1737         */
1738         const U32 laststate = TRIE_NODENUM( next_alloc );
1739         U32 state, charid;
1740         U32 pos = 0, zp=0;
1741         trie->statecount = laststate;
1742
1743         for ( state = 1 ; state < laststate ; state++ ) {
1744             U8 flag = 0;
1745             const U32 stateidx = TRIE_NODEIDX( state );
1746             const U32 o_used = trie->trans[ stateidx ].check;
1747             U32 used = trie->trans[ stateidx ].check;
1748             trie->trans[ stateidx ].check = 0;
1749
1750             for ( charid = 0 ; used && charid < trie->uniquecharcount ; charid++ ) {
1751                 if ( flag || trie->trans[ stateidx + charid ].next ) {
1752                     if ( trie->trans[ stateidx + charid ].next ) {
1753                         if (o_used == 1) {
1754                             for ( ; zp < pos ; zp++ ) {
1755                                 if ( ! trie->trans[ zp ].next ) {
1756                                     break;
1757                                 }
1758                             }
1759                             trie->states[ state ].trans.base = zp + trie->uniquecharcount - charid ;
1760                             trie->trans[ zp ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
1761                             trie->trans[ zp ].check = state;
1762                             if ( ++zp > pos ) pos = zp;
1763                             break;
1764                         }
1765                         used--;
1766                     }
1767                     if ( !flag ) {
1768                         flag = 1;
1769                         trie->states[ state ].trans.base = pos + trie->uniquecharcount - charid ;
1770                     }
1771                     trie->trans[ pos ].next = SAFE_TRIE_NODENUM( trie->trans[ stateidx + charid ].next );
1772                     trie->trans[ pos ].check = state;
1773                     pos++;
1774                 }
1775             }
1776         }
1777         trie->lasttrans = pos + 1;
1778         Renew( trie->states, laststate, reg_trie_state);
1779         DEBUG_TRIE_COMPILE_MORE_r(
1780                 PerlIO_printf( Perl_debug_log,
1781                     "%*sAlloc: %d Orig: %"IVdf" elements, Final:%"IVdf". Savings of %%%5.2f\n",
1782                     (int)depth * 2 + 2,"",
1783                     (int)( ( TRIE_CHARCOUNT(trie) + 1 ) * trie->uniquecharcount + 1 ),
1784                     (IV)next_alloc,
1785                     (IV)pos,
1786                     ( ( next_alloc - pos ) * 100 ) / (double)next_alloc );
1787             );
1788
1789         } /* end table compress */
1790     }
1791     DEBUG_TRIE_COMPILE_MORE_r(
1792             PerlIO_printf(Perl_debug_log, "%*sStatecount:%"UVxf" Lasttrans:%"UVxf"\n",
1793                 (int)depth * 2 + 2, "",
1794                 (UV)trie->statecount,
1795                 (UV)trie->lasttrans)
1796     );
1797     /* resize the trans array to remove unused space */
1798     Renew( trie->trans, trie->lasttrans, reg_trie_trans);
1799
1800     /* and now dump out the compressed format */
1801     DEBUG_TRIE_COMPILE_r(
1802         dump_trie(trie,depth+1)
1803     );
1804
1805     {   /* Modify the program and insert the new TRIE node*/ 
1806         U8 nodetype =(U8)(flags & 0xFF);
1807         char *str=NULL;
1808         
1809 #ifdef DEBUGGING
1810         regnode *optimize = NULL;
1811         U32 mjd_offset = 0;
1812         U32 mjd_nodelen = 0;
1813 #endif
1814         /*
1815            This means we convert either the first branch or the first Exact,
1816            depending on whether the thing following (in 'last') is a branch
1817            or not and whther first is the startbranch (ie is it a sub part of
1818            the alternation or is it the whole thing.)
1819            Assuming its a sub part we conver the EXACT otherwise we convert
1820            the whole branch sequence, including the first.
1821          */
1822         /* Find the node we are going to overwrite */
1823         if ( first != startbranch || OP( last ) == BRANCH ) {
1824             /* branch sub-chain */
1825             NEXT_OFF( first ) = (U16)(last - first);
1826             DEBUG_r({
1827                 mjd_offset= Node_Offset((convert));
1828                 mjd_nodelen= Node_Length((convert));
1829             });
1830             /* whole branch chain */
1831         } else {
1832             DEBUG_r({
1833                 const  regnode *nop = NEXTOPER( convert );
1834                 mjd_offset= Node_Offset((nop));
1835                 mjd_nodelen= Node_Length((nop));
1836             });
1837         }
1838         
1839         DEBUG_OPTIMISE_r(
1840             PerlIO_printf(Perl_debug_log, "%*sMJD offset:%"UVuf" MJD length:%"UVuf"\n",
1841                 (int)depth * 2 + 2, "",
1842                 (UV)mjd_offset, (UV)mjd_nodelen)
1843         );
1844
1845         /* But first we check to see if there is a common prefix we can 
1846            split out as an EXACT and put in front of the TRIE node.  */
1847         trie->startstate= 1;
1848         if ( trie->bitmap && !trie->widecharmap && !trie->jump  ) {
1849             U32 state;
1850             for ( state = 1 ; state < trie->statecount-1 ; state++ ) {
1851                 U32 ofs = 0;
1852                 I32 idx = -1;
1853                 U32 count = 0;
1854                 const U32 base = trie->states[ state ].trans.base;
1855
1856                 if ( trie->states[state].wordnum )
1857                         count = 1;
1858
1859                 for ( ofs = 0 ; ofs < trie->uniquecharcount ; ofs++ ) {
1860                     if ( ( base + ofs >= trie->uniquecharcount ) &&
1861                          ( base + ofs - trie->uniquecharcount < trie->lasttrans ) &&
1862                          trie->trans[ base + ofs - trie->uniquecharcount ].check == state )
1863                     {
1864                         if ( ++count > 1 ) {
1865                             SV **tmp = av_fetch( TRIE_REVCHARMAP(trie), ofs, 0);
1866                             const U8 *ch = (U8*)SvPV_nolen_const( *tmp );
1867                             if ( state == 1 ) break;
1868                             if ( count == 2 ) {
1869                                 Zero(trie->bitmap, ANYOF_BITMAP_SIZE, char);
1870                                 DEBUG_OPTIMISE_r(
1871                                     PerlIO_printf(Perl_debug_log,
1872                                         "%*sNew Start State=%"UVuf" Class: [",
1873                                         (int)depth * 2 + 2, "",
1874                                         (UV)state));
1875                                 if (idx >= 0) {
1876                                     SV ** const tmp = av_fetch( TRIE_REVCHARMAP(trie), idx, 0);
1877                                     const U8 * const ch = (U8*)SvPV_nolen_const( *tmp );
1878
1879                                     TRIE_BITMAP_SET(trie,*ch);
1880                                     if ( folder )
1881                                         TRIE_BITMAP_SET(trie, folder[ *ch ]);
1882                                     DEBUG_OPTIMISE_r(
1883                                         PerlIO_printf(Perl_debug_log, (char*)ch)
1884                                     );
1885                                 }
1886                             }
1887                             TRIE_BITMAP_SET(trie,*ch);
1888                             if ( folder )
1889                                 TRIE_BITMAP_SET(trie,folder[ *ch ]);
1890                             DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"%s", ch));
1891                         }
1892                         idx = ofs;
1893                     }
1894                 }
1895                 if ( count == 1 ) {
1896                     SV **tmp = av_fetch( TRIE_REVCHARMAP(trie), idx, 0);
1897                     char *ch = SvPV_nolen( *tmp );
1898                     DEBUG_OPTIMISE_r({
1899                         SV *sv=sv_newmortal();
1900                         PerlIO_printf( Perl_debug_log,
1901                             "%*sPrefix State: %"UVuf" Idx:%"UVuf" Char='%s'\n",
1902                             (int)depth * 2 + 2, "",
1903                             (UV)state, (UV)idx, 
1904                             pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 6, 
1905                                 PL_colors[0], PL_colors[1],
1906                                 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0) |
1907                                 PERL_PV_ESCAPE_FIRSTCHAR 
1908                             )
1909                         );
1910                     });
1911                     if ( state==1 ) {
1912                         OP( convert ) = nodetype;
1913                         str=STRING(convert);
1914                         STR_LEN(convert)=0;
1915                     }
1916                     while (*ch) {
1917                         *str++ = *ch++;
1918                         STR_LEN(convert)++;
1919                     }
1920                     
1921                 } else {
1922 #ifdef DEBUGGING            
1923                     if (state>1)
1924                         DEBUG_OPTIMISE_r(PerlIO_printf( Perl_debug_log,"]\n"));
1925 #endif
1926                     break;
1927                 }
1928             }
1929             if (str) {
1930                 regnode *n = convert+NODE_SZ_STR(convert);
1931                 NEXT_OFF(convert) = NODE_SZ_STR(convert);
1932                 trie->startstate = state;
1933                 trie->minlen -= (state - 1);
1934                 trie->maxlen -= (state - 1);
1935                 DEBUG_r({
1936                     regnode *fix = convert;
1937                     U32 word = trie->wordcount;
1938                     mjd_nodelen++;
1939                     Set_Node_Offset_Length(convert, mjd_offset, state - 1);
1940                     while( ++fix < n ) {
1941                         Set_Node_Offset_Length(fix, 0, 0);
1942                     }
1943                     while (word--) {
1944                         SV ** const tmp = av_fetch( trie->words, word, 0 );
1945                         if (tmp) {
1946                             if ( STR_LEN(convert) <= SvCUR(*tmp) )
1947                                 sv_chop(*tmp, SvPV_nolen(*tmp) + STR_LEN(convert));
1948                             else
1949                                 sv_chop(*tmp, SvPV_nolen(*tmp) + SvCUR(*tmp));
1950                         }
1951                     }    
1952                 });
1953                 if (trie->maxlen) {
1954                     convert = n;
1955                 } else {
1956                     NEXT_OFF(convert) = (U16)(tail - convert);
1957                     DEBUG_r(optimize= n);
1958                 }
1959             }
1960         }
1961         if (!jumper) 
1962             jumper = last; 
1963         if ( trie->maxlen ) {
1964             NEXT_OFF( convert ) = (U16)(tail - convert);
1965             ARG_SET( convert, data_slot );
1966             /* Store the offset to the first unabsorbed branch in 
1967                jump[0], which is otherwise unused by the jump logic. 
1968                We use this when dumping a trie and during optimisation. */
1969             if (trie->jump) 
1970                 trie->jump[0] = (U16)(nextbranch - convert);
1971             
1972             /* XXXX */
1973             if ( !trie->states[trie->startstate].wordnum && trie->bitmap && 
1974                  ( (char *)jumper - (char *)convert) >= (int)sizeof(struct regnode_charclass) )
1975             {
1976                 OP( convert ) = TRIEC;
1977                 Copy(trie->bitmap, ((struct regnode_charclass *)convert)->bitmap, ANYOF_BITMAP_SIZE, char);
1978                 Safefree(trie->bitmap);
1979                 trie->bitmap= NULL;
1980             } else 
1981                 OP( convert ) = TRIE;
1982
1983             /* store the type in the flags */
1984             convert->flags = nodetype;
1985             DEBUG_r({
1986             optimize = convert 
1987                       + NODE_STEP_REGNODE 
1988                       + regarglen[ OP( convert ) ];
1989             });
1990             /* XXX We really should free up the resource in trie now, 
1991                    as we won't use them - (which resources?) dmq */
1992         }
1993         /* needed for dumping*/
1994         DEBUG_r(if (optimize) {
1995             regnode *opt = convert;
1996             while ( ++opt < optimize) {
1997                 Set_Node_Offset_Length(opt,0,0);
1998             }
1999             /* 
2000                 Try to clean up some of the debris left after the 
2001                 optimisation.
2002              */
2003             while( optimize < jumper ) {
2004                 mjd_nodelen += Node_Length((optimize));
2005                 OP( optimize ) = OPTIMIZED;
2006                 Set_Node_Offset_Length(optimize,0,0);
2007                 optimize++;
2008             }
2009             Set_Node_Offset_Length(convert,mjd_offset,mjd_nodelen);
2010         });
2011     } /* end node insert */
2012 #ifndef DEBUGGING
2013     SvREFCNT_dec(TRIE_REVCHARMAP(trie));
2014 #endif
2015     return trie->jump 
2016            ? MADE_JUMP_TRIE 
2017            : trie->startstate>1 
2018              ? MADE_EXACT_TRIE 
2019              : MADE_TRIE;
2020 }
2021
2022 STATIC void
2023 S_make_trie_failtable(pTHX_ RExC_state_t *pRExC_state, regnode *source,  regnode *stclass, U32 depth)
2024 {
2025 /* The Trie is constructed and compressed now so we can build a fail array now if its needed
2026
2027    This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and 3.32 in the
2028    "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi, Ullman 1985/88
2029    ISBN 0-201-10088-6
2030
2031    We find the fail state for each state in the trie, this state is the longest proper
2032    suffix of the current states 'word' that is also a proper prefix of another word in our
2033    trie. State 1 represents the word '' and is the thus the default fail state. This allows
2034    the DFA not to have to restart after its tried and failed a word at a given point, it
2035    simply continues as though it had been matching the other word in the first place.
2036    Consider
2037       'abcdgu'=~/abcdefg|cdgu/
2038    When we get to 'd' we are still matching the first word, we would encounter 'g' which would
2039    fail, which would bring use to the state representing 'd' in the second word where we would
2040    try 'g' and succeed, prodceding to match 'cdgu'.
2041  */
2042  /* add a fail transition */
2043     reg_trie_data *trie=(reg_trie_data *)RExC_rx->data->data[ARG(source)];
2044     U32 *q;
2045     const U32 ucharcount = trie->uniquecharcount;
2046     const U32 numstates = trie->statecount;
2047     const U32 ubound = trie->lasttrans + ucharcount;
2048     U32 q_read = 0;
2049     U32 q_write = 0;
2050     U32 charid;
2051     U32 base = trie->states[ 1 ].trans.base;
2052     U32 *fail;
2053     reg_ac_data *aho;
2054     const U32 data_slot = add_data( pRExC_state, 1, "T" );
2055     GET_RE_DEBUG_FLAGS_DECL;
2056 #ifndef DEBUGGING
2057     PERL_UNUSED_ARG(depth);
2058 #endif
2059
2060
2061     ARG_SET( stclass, data_slot );
2062     Newxz( aho, 1, reg_ac_data );
2063     RExC_rx->data->data[ data_slot ] = (void*)aho;
2064     aho->trie=trie;
2065     aho->states=(reg_trie_state *)savepvn((const char*)trie->states,
2066         numstates * sizeof(reg_trie_state));
2067     Newxz( q, numstates, U32);
2068     Newxz( aho->fail, numstates, U32 );
2069     aho->refcount = 1;
2070     fail = aho->fail;
2071     /* initialize fail[0..1] to be 1 so that we always have
2072        a valid final fail state */
2073     fail[ 0 ] = fail[ 1 ] = 1;
2074
2075     for ( charid = 0; charid < ucharcount ; charid++ ) {
2076         const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
2077         if ( newstate ) {
2078             q[ q_write ] = newstate;
2079             /* set to point at the root */
2080             fail[ q[ q_write++ ] ]=1;
2081         }
2082     }
2083     while ( q_read < q_write) {
2084         const U32 cur = q[ q_read++ % numstates ];
2085         base = trie->states[ cur ].trans.base;
2086
2087         for ( charid = 0 ; charid < ucharcount ; charid++ ) {
2088             const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
2089             if (ch_state) {
2090                 U32 fail_state = cur;
2091                 U32 fail_base;
2092                 do {
2093                     fail_state = fail[ fail_state ];
2094                     fail_base = aho->states[ fail_state ].trans.base;
2095                 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
2096
2097                 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
2098                 fail[ ch_state ] = fail_state;
2099                 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
2100                 {
2101                         aho->states[ ch_state ].wordnum =  aho->states[ fail_state ].wordnum;
2102                 }
2103                 q[ q_write++ % numstates] = ch_state;
2104             }
2105         }
2106     }
2107     /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
2108        when we fail in state 1, this allows us to use the
2109        charclass scan to find a valid start char. This is based on the principle
2110        that theres a good chance the string being searched contains lots of stuff
2111        that cant be a start char.
2112      */
2113     fail[ 0 ] = fail[ 1 ] = 0;
2114     DEBUG_TRIE_COMPILE_r({
2115         PerlIO_printf(Perl_debug_log,
2116                       "%*sStclass Failtable (%"UVuf" states): 0", 
2117                       (int)(depth * 2), "", (UV)numstates
2118         );
2119         for( q_read=1; q_read<numstates; q_read++ ) {
2120             PerlIO_printf(Perl_debug_log, ", %"UVuf, (UV)fail[q_read]);
2121         }
2122         PerlIO_printf(Perl_debug_log, "\n");
2123     });
2124     Safefree(q);
2125     /*RExC_seen |= REG_SEEN_TRIEDFA;*/
2126 }
2127
2128
2129 /*
2130  * There are strange code-generation bugs caused on sparc64 by gcc-2.95.2.
2131  * These need to be revisited when a newer toolchain becomes available.
2132  */
2133 #if defined(__sparc64__) && defined(__GNUC__)
2134 #   if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 96)
2135 #       undef  SPARC64_GCC_WORKAROUND
2136 #       define SPARC64_GCC_WORKAROUND 1
2137 #   endif
2138 #endif
2139
2140 #define DEBUG_PEEP(str,scan,depth) \
2141     DEBUG_OPTIMISE_r({if (scan){ \
2142        SV * const mysv=sv_newmortal(); \
2143        regnode *Next = regnext(scan); \
2144        regprop(RExC_rx, mysv, scan); \
2145        PerlIO_printf(Perl_debug_log, "%*s" str ">%3d: %s (%d)\n", \
2146        (int)depth*2, "", REG_NODE_NUM(scan), SvPV_nolen_const(mysv),\
2147        Next ? (REG_NODE_NUM(Next)) : 0 ); \
2148    }});
2149
2150
2151
2152
2153
2154 #define JOIN_EXACT(scan,min,flags) \
2155     if (PL_regkind[OP(scan)] == EXACT) \
2156         join_exact(pRExC_state,(scan),(min),(flags),NULL,depth+1)
2157
2158 STATIC U32
2159 S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan, I32 *min, U32 flags,regnode *val, U32 depth) {
2160     /* Merge several consecutive EXACTish nodes into one. */
2161     regnode *n = regnext(scan);
2162     U32 stringok = 1;
2163     regnode *next = scan + NODE_SZ_STR(scan);
2164     U32 merged = 0;
2165     U32 stopnow = 0;
2166 #ifdef DEBUGGING
2167     regnode *stop = scan;
2168     GET_RE_DEBUG_FLAGS_DECL;
2169 #else
2170     PERL_UNUSED_ARG(depth);
2171 #endif
2172 #ifndef EXPERIMENTAL_INPLACESCAN
2173     PERL_UNUSED_ARG(flags);
2174     PERL_UNUSED_ARG(val);
2175 #endif
2176     DEBUG_PEEP("join",scan,depth);
2177     
2178     /* Skip NOTHING, merge EXACT*. */
2179     while (n &&
2180            ( PL_regkind[OP(n)] == NOTHING ||
2181              (stringok && (OP(n) == OP(scan))))
2182            && NEXT_OFF(n)
2183            && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX) {
2184         
2185         if (OP(n) == TAIL || n > next)
2186             stringok = 0;
2187         if (PL_regkind[OP(n)] == NOTHING) {
2188             DEBUG_PEEP("skip:",n,depth);
2189             NEXT_OFF(scan) += NEXT_OFF(n);
2190             next = n + NODE_STEP_REGNODE;
2191 #ifdef DEBUGGING
2192             if (stringok)
2193                 stop = n;
2194 #endif
2195             n = regnext(n);
2196         }
2197         else if (stringok) {
2198             const unsigned int oldl = STR_LEN(scan);
2199             regnode * const nnext = regnext(n);
2200             
2201             DEBUG_PEEP("merg",n,depth);
2202             
2203             merged++;
2204             if (oldl + STR_LEN(n) > U8_MAX)
2205                 break;
2206             NEXT_OFF(scan) += NEXT_OFF(n);
2207             STR_LEN(scan) += STR_LEN(n);
2208             next = n + NODE_SZ_STR(n);
2209             /* Now we can overwrite *n : */
2210             Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
2211 #ifdef DEBUGGING
2212             stop = next - 1;
2213 #endif
2214             n = nnext;
2215             if (stopnow) break;
2216         }
2217
2218 #ifdef EXPERIMENTAL_INPLACESCAN
2219         if (flags && !NEXT_OFF(n)) {
2220             DEBUG_PEEP("atch", val, depth);
2221             if (reg_off_by_arg[OP(n)]) {
2222                 ARG_SET(n, val - n);
2223             }
2224             else {
2225                 NEXT_OFF(n) = val - n;
2226             }
2227             stopnow = 1;
2228         }
2229 #endif
2230     }
2231     
2232     if (UTF && ( OP(scan) == EXACTF ) && ( STR_LEN(scan) >= 6 ) ) {
2233     /*
2234     Two problematic code points in Unicode casefolding of EXACT nodes:
2235     
2236     U+0390 - GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS
2237     U+03B0 - GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS
2238     
2239     which casefold to
2240     
2241     Unicode                      UTF-8
2242     
2243     U+03B9 U+0308 U+0301         0xCE 0xB9 0xCC 0x88 0xCC 0x81
2244     U+03C5 U+0308 U+0301         0xCF 0x85 0xCC 0x88 0xCC 0x81
2245     
2246     This means that in case-insensitive matching (or "loose matching",
2247     as Unicode calls it), an EXACTF of length six (the UTF-8 encoded byte
2248     length of the above casefolded versions) can match a target string
2249     of length two (the byte length of UTF-8 encoded U+0390 or U+03B0).
2250     This would rather mess up the minimum length computation.
2251     
2252     What we'll do is to look for the tail four bytes, and then peek
2253     at the preceding two bytes to see whether we need to decrease
2254     the minimum length by four (six minus two).
2255     
2256     Thanks to the design of UTF-8, there cannot be false matches:
2257     A sequence of valid UTF-8 bytes cannot be a subsequence of
2258     another valid sequence of UTF-8 bytes.
2259     
2260     */
2261          char * const s0 = STRING(scan), *s, *t;
2262          char * const s1 = s0 + STR_LEN(scan) - 1;
2263          char * const s2 = s1 - 4;
2264 #ifdef EBCDIC /* RD tunifold greek 0390 and 03B0 */
2265          const char t0[] = "\xaf\x49\xaf\x42";
2266 #else
2267          const char t0[] = "\xcc\x88\xcc\x81";
2268 #endif
2269          const char * const t1 = t0 + 3;
2270     
2271          for (s = s0 + 2;
2272               s < s2 && (t = ninstr(s, s1, t0, t1));
2273               s = t + 4) {
2274 #ifdef EBCDIC
2275               if (((U8)t[-1] == 0x68 && (U8)t[-2] == 0xB4) ||
2276                   ((U8)t[-1] == 0x46 && (U8)t[-2] == 0xB5))
2277 #else
2278               if (((U8)t[-1] == 0xB9 && (U8)t[-2] == 0xCE) ||
2279                   ((U8)t[-1] == 0x85 && (U8)t[-2] == 0xCF))
2280 #endif
2281                    *min -= 4;
2282          }
2283     }
2284     
2285 #ifdef DEBUGGING
2286     /* Allow dumping */
2287     n = scan + NODE_SZ_STR(scan);
2288     while (n <= stop) {
2289         if (PL_regkind[OP(n)] != NOTHING || OP(n) == NOTHING) {
2290             OP(n) = OPTIMIZED;
2291             NEXT_OFF(n) = 0;
2292         }
2293         n++;
2294     }
2295 #endif
2296     DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl",scan,depth)});
2297     return stopnow;
2298 }
2299
2300 /* REx optimizer.  Converts nodes into quickier variants "in place".
2301    Finds fixed substrings.  */
2302
2303 /* Stops at toplevel WHILEM as well as at "last". At end *scanp is set
2304    to the position after last scanned or to NULL. */
2305
2306 #define INIT_AND_WITHP \
2307     assert(!and_withp); \
2308     Newx(and_withp,1,struct regnode_charclass_class); \
2309     SAVEFREEPV(and_withp)
2310
2311 /* this is a chain of data about sub patterns we are processing that
2312    need to be handled seperately/specially in study_chunk. Its so
2313    we can simulate recursion without losing state.  */
2314 struct scan_frame;
2315 typedef struct scan_frame {
2316     regnode *last;  /* last node to process in this frame */
2317     regnode *next;  /* next node to process when last is reached */
2318     struct scan_frame *prev; /*previous frame*/
2319     I32 stop; /* what stopparen do we use */
2320 } scan_frame;
2321
2322 STATIC I32
2323 S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
2324                         I32 *minlenp, I32 *deltap,
2325                         regnode *last,
2326                         scan_data_t *data,
2327                         I32 stopparen,
2328                         U8* recursed,
2329                         struct regnode_charclass_class *and_withp,
2330                         U32 flags, U32 depth)
2331                         /* scanp: Start here (read-write). */
2332                         /* deltap: Write maxlen-minlen here. */
2333                         /* last: Stop before this one. */
2334                         /* data: string data about the pattern */
2335                         /* stopparen: treat close N as END */
2336                         /* recursed: which subroutines have we recursed into */
2337                         /* and_withp: Valid if flags & SCF_DO_STCLASS_OR */
2338 {
2339     dVAR;
2340     I32 min = 0, pars = 0, code;
2341     regnode *scan = *scanp, *next;
2342     I32 delta = 0;
2343     int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
2344     int is_inf_internal = 0;            /* The studied chunk is infinite */
2345     I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
2346     scan_data_t data_fake;
2347     SV *re_trie_maxbuff = NULL;
2348     regnode *first_non_open = scan;
2349     I32 stopmin = I32_MAX;
2350     scan_frame *frame = NULL;
2351
2352     GET_RE_DEBUG_FLAGS_DECL;
2353
2354 #ifdef DEBUGGING
2355     StructCopy(&zero_scan_data, &data_fake, scan_data_t);
2356 #endif
2357
2358     if ( depth == 0 ) {
2359         while (first_non_open && OP(first_non_open) == OPEN)
2360             first_non_open=regnext(first_non_open);
2361     }
2362
2363
2364   fake_study_recurse:
2365     while ( scan && OP(scan) != END && scan < last ){
2366         /* Peephole optimizer: */
2367         DEBUG_STUDYDATA(data,depth);
2368         DEBUG_PEEP("Peep",scan,depth);
2369         JOIN_EXACT(scan,&min,0);
2370
2371         /* Follow the next-chain of the current node and optimize
2372            away all the NOTHINGs from it.  */
2373         if (OP(scan) != CURLYX) {
2374             const int max = (reg_off_by_arg[OP(scan)]
2375                        ? I32_MAX
2376                        /* I32 may be smaller than U16 on CRAYs! */
2377                        : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
2378             int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
2379             int noff;
2380             regnode *n = scan;
2381         
2382             /* Skip NOTHING and LONGJMP. */
2383             while ((n = regnext(n))
2384                    && ((PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
2385                        || ((OP(n) == LONGJMP) && (noff = ARG(n))))
2386                    && off + noff < max)
2387                 off += noff;
2388             if (reg_off_by_arg[OP(scan)])
2389                 ARG(scan) = off;
2390             else
2391                 NEXT_OFF(scan) = off;
2392         }
2393
2394
2395
2396         /* The principal pseudo-switch.  Cannot be a switch, since we
2397            look into several different things.  */
2398         if (OP(scan) == BRANCH || OP(scan) == BRANCHJ
2399                    || OP(scan) == IFTHEN) {
2400             next = regnext(scan);
2401             code = OP(scan);
2402             /* demq: the op(next)==code check is to see if we have "branch-branch" AFAICT */
2403         
2404             if (OP(next) == code || code == IFTHEN) {
2405                 /* NOTE - There is similar code to this block below for handling
2406                    TRIE nodes on a re-study.  If you change stuff here check there
2407                    too. */
2408                 I32 max1 = 0, min1 = I32_MAX, num = 0;
2409                 struct regnode_charclass_class accum;
2410                 regnode * const startbranch=scan;
2411                 
2412                 if (flags & SCF_DO_SUBSTR)
2413                     scan_commit(pRExC_state, data, minlenp); /* Cannot merge strings after this. */
2414                 if (flags & SCF_DO_STCLASS)
2415                     cl_init_zero(pRExC_state, &accum);
2416
2417                 while (OP(scan) == code) {
2418                     I32 deltanext, minnext, f = 0, fake;
2419                     struct regnode_charclass_class this_class;
2420
2421                     num++;
2422                     data_fake.flags = 0;
2423                     if (data) {
2424                         data_fake.whilem_c = data->whilem_c;
2425                         data_fake.last_closep = data->last_closep;
2426                     }
2427                     else
2428                         data_fake.last_closep = &fake;
2429                     next = regnext(scan);
2430                     scan = NEXTOPER(scan);
2431                     if (code != BRANCH)
2432                         scan = NEXTOPER(scan);
2433                     if (flags & SCF_DO_STCLASS) {
2434                         cl_init(pRExC_state, &this_class);
2435                         data_fake.start_class = &this_class;
2436                         f = SCF_DO_STCLASS_AND;
2437                     }           
2438                     if (flags & SCF_WHILEM_VISITED_POS)
2439                         f |= SCF_WHILEM_VISITED_POS;
2440
2441                     /* we suppose the run is continuous, last=next...*/
2442                     minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
2443                                           next, &data_fake,
2444                                           stopparen, recursed, NULL, f,depth+1);
2445                     if (min1 > minnext)
2446                         min1 = minnext;
2447                     if (max1 < minnext + deltanext)
2448                         max1 = minnext + deltanext;
2449                     if (deltanext == I32_MAX)
2450                         is_inf = is_inf_internal = 1;
2451                     scan = next;
2452                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
2453                         pars++;
2454                     if (data_fake.flags & SCF_SEEN_ACCEPT) {
2455                         if ( stopmin > minnext) 
2456                             stopmin = min + min1;
2457                         flags &= ~SCF_DO_SUBSTR;
2458                         if (data)
2459                             data->flags |= SCF_SEEN_ACCEPT;
2460                     }
2461                     if (data) {
2462                         if (data_fake.flags & SF_HAS_EVAL)
2463                             data->flags |= SF_HAS_EVAL;
2464                         data->whilem_c = data_fake.whilem_c;
2465                     }
2466                     if (flags & SCF_DO_STCLASS)
2467                         cl_or(pRExC_state, &accum, &this_class);
2468                 }
2469                 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
2470                     min1 = 0;
2471                 if (flags & SCF_DO_SUBSTR) {
2472                     data->pos_min += min1;
2473                     data->pos_delta += max1 - min1;
2474                     if (max1 != min1 || is_inf)
2475                         data->longest = &(data->longest_float);
2476                 }
2477                 min += min1;
2478                 delta += max1 - min1;
2479                 if (flags & SCF_DO_STCLASS_OR) {
2480                     cl_or(pRExC_state, data->start_class, &accum);
2481                     if (min1) {
2482                         cl_and(data->start_class, and_withp);
2483                         flags &= ~SCF_DO_STCLASS;
2484                     }
2485                 }
2486                 else if (flags & SCF_DO_STCLASS_AND) {
2487                     if (min1) {
2488                         cl_and(data->start_class, &accum);
2489                         flags &= ~SCF_DO_STCLASS;
2490                     }
2491                     else {
2492                         /* Switch to OR mode: cache the old value of
2493                          * data->start_class */
2494                         INIT_AND_WITHP;
2495                         StructCopy(data->start_class, and_withp,
2496                                    struct regnode_charclass_class);
2497                         flags &= ~SCF_DO_STCLASS_AND;
2498                         StructCopy(&accum, data->start_class,
2499                                    struct regnode_charclass_class);
2500                         flags |= SCF_DO_STCLASS_OR;
2501                         data->start_class->flags |= ANYOF_EOS;
2502                     }
2503                 }
2504
2505                 if (PERL_ENABLE_TRIE_OPTIMISATION && OP( startbranch ) == BRANCH ) {
2506                 /* demq.
2507
2508                    Assuming this was/is a branch we are dealing with: 'scan' now
2509                    points at the item that follows the branch sequence, whatever
2510                    it is. We now start at the beginning of the sequence and look
2511                    for subsequences of
2512
2513                    BRANCH->EXACT=>x1
2514                    BRANCH->EXACT=>x2
2515                    tail
2516
2517                    which would be constructed from a pattern like /A|LIST|OF|WORDS/
2518
2519                    If we can find such a subseqence we need to turn the first
2520                    element into a trie and then add the subsequent branch exact
2521                    strings to the trie.
2522
2523                    We have two cases
2524
2525                      1. patterns where the whole set of branch can be converted. 
2526
2527                      2. patterns where only a subset can be converted.
2528
2529                    In case 1 we can replace the whole set with a single regop
2530                    for the trie. In case 2 we need to keep the start and end
2531                    branchs so
2532
2533                      'BRANCH EXACT; BRANCH EXACT; BRANCH X'
2534                      becomes BRANCH TRIE; BRANCH X;
2535
2536                   There is an additional case, that being where there is a 
2537                   common prefix, which gets split out into an EXACT like node
2538                   preceding the TRIE node.
2539
2540                   If x(1..n)==tail then we can do a simple trie, if not we make
2541                   a "jump" trie, such that when we match the appropriate word
2542                   we "jump" to the appopriate tail node. Essentailly we turn
2543                   a nested if into a case structure of sorts.
2544
2545                 */
2546                 
2547                     int made=0;
2548                     if (!re_trie_maxbuff) {
2549                         re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
2550                         if (!SvIOK(re_trie_maxbuff))
2551                             sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
2552                     }
2553                     if ( SvIV(re_trie_maxbuff)>=0  ) {
2554                         regnode *cur;
2555                         regnode *first = (regnode *)NULL;
2556                         regnode *last = (regnode *)NULL;
2557                         regnode *tail = scan;
2558                         U8 optype = 0;
2559                         U32 count=0;
2560
2561 #ifdef DEBUGGING
2562                         SV * const mysv = sv_newmortal();       /* for dumping */
2563 #endif
2564                         /* var tail is used because there may be a TAIL
2565                            regop in the way. Ie, the exacts will point to the
2566                            thing following the TAIL, but the last branch will
2567                            point at the TAIL. So we advance tail. If we
2568                            have nested (?:) we may have to move through several
2569                            tails.
2570                          */
2571
2572                         while ( OP( tail ) == TAIL ) {
2573                             /* this is the TAIL generated by (?:) */
2574                             tail = regnext( tail );
2575                         }
2576
2577                         
2578                         DEBUG_OPTIMISE_r({
2579                             regprop(RExC_rx, mysv, tail );
2580                             PerlIO_printf( Perl_debug_log, "%*s%s%s\n",
2581                                 (int)depth * 2 + 2, "", 
2582                                 "Looking for TRIE'able sequences. Tail node is: ", 
2583                                 SvPV_nolen_const( mysv )
2584                             );
2585                         });
2586                         
2587                         /*
2588
2589                            step through the branches, cur represents each
2590                            branch, noper is the first thing to be matched
2591                            as part of that branch and noper_next is the
2592                            regnext() of that node. if noper is an EXACT
2593                            and noper_next is the same as scan (our current
2594                            position in the regex) then the EXACT branch is
2595                            a possible optimization target. Once we have
2596                            two or more consequetive such branches we can
2597                            create a trie of the EXACT's contents and stich
2598                            it in place. If the sequence represents all of
2599                            the branches we eliminate the whole thing and
2600                            replace it with a single TRIE. If it is a
2601                            subsequence then we need to stitch it in. This
2602                            means the first branch has to remain, and needs
2603                            to be repointed at the item on the branch chain
2604                            following the last branch optimized. This could
2605                            be either a BRANCH, in which case the
2606                            subsequence is internal, or it could be the
2607                            item following the branch sequence in which
2608                            case the subsequence is at the end.
2609
2610                         */
2611
2612                         /* dont use tail as the end marker for this traverse */
2613                         for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {
2614                             regnode * const noper = NEXTOPER( cur );
2615 #if defined(DEBUGGING) || defined(NOJUMPTRIE)
2616                             regnode * const noper_next = regnext( noper );
2617 #endif
2618
2619                             DEBUG_OPTIMISE_r({
2620                                 regprop(RExC_rx, mysv, cur);
2621                                 PerlIO_printf( Perl_debug_log, "%*s- %s (%d)",
2622                                    (int)depth * 2 + 2,"", SvPV_nolen_const( mysv ), REG_NODE_NUM(cur) );
2623
2624                                 regprop(RExC_rx, mysv, noper);
2625                                 PerlIO_printf( Perl_debug_log, " -> %s",
2626                                     SvPV_nolen_const(mysv));
2627
2628                                 if ( noper_next ) {
2629                                   regprop(RExC_rx, mysv, noper_next );
2630                                   PerlIO_printf( Perl_debug_log,"\t=> %s\t",
2631                                     SvPV_nolen_const(mysv));
2632                                 }
2633                                 PerlIO_printf( Perl_debug_log, "(First==%d,Last==%d,Cur==%d)\n",
2634                                    REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur) );
2635                             });
2636                             if ( (((first && optype!=NOTHING) ? OP( noper ) == optype
2637                                          : PL_regkind[ OP( noper ) ] == EXACT )
2638                                   || OP(noper) == NOTHING )
2639 #ifdef NOJUMPTRIE
2640                                   && noper_next == tail
2641 #endif
2642                                   && count < U16_MAX)
2643                             {
2644                                 count++;
2645                                 if ( !first || optype == NOTHING ) {
2646                                     if (!first) first = cur;
2647                                     optype = OP( noper );
2648                                 } else {
2649                                     last = cur;
2650                                 }
2651                             } else {
2652                                 if ( last ) {
2653                                     make_trie( pRExC_state, 
2654                                             startbranch, first, cur, tail, count, 
2655                                             optype, depth+1 );
2656                                 }
2657                                 if ( PL_regkind[ OP( noper ) ] == EXACT
2658 #ifdef NOJUMPTRIE
2659                                      && noper_next == tail
2660 #endif
2661                                 ){
2662                                     count = 1;
2663                                     first = cur;
2664                                     optype = OP( noper );
2665                                 } else {
2666                                     count = 0;
2667                                     first = NULL;
2668                                     optype = 0;
2669                                 }
2670                                 last = NULL;
2671                             }
2672                         }
2673                         DEBUG_OPTIMISE_r({
2674                             regprop(RExC_rx, mysv, cur);
2675                             PerlIO_printf( Perl_debug_log,
2676                               "%*s- %s (%d) <SCAN FINISHED>\n", (int)depth * 2 + 2,
2677                               "", SvPV_nolen_const( mysv ),REG_NODE_NUM(cur));
2678
2679                         });
2680                         if ( last ) {
2681                             made= make_trie( pRExC_state, startbranch, first, scan, tail, count, optype, depth+1 );
2682 #ifdef TRIE_STUDY_OPT   
2683                             if ( ((made == MADE_EXACT_TRIE && 
2684                                  startbranch == first) 
2685                                  || ( first_non_open == first )) && 
2686                                  depth==0 ) {
2687                                 flags |= SCF_TRIE_RESTUDY;
2688                                 if ( startbranch == first 
2689                                      && scan == tail ) 
2690                                 {
2691                                     RExC_seen &=~REG_TOP_LEVEL_BRANCHES;
2692                                 }
2693                             }
2694 #endif
2695                         }
2696                     }
2697                     
2698                 } /* do trie */
2699                 
2700             }
2701             else if ( code == BRANCHJ ) {  /* single branch is optimized. */
2702                 scan = NEXTOPER(NEXTOPER(scan));
2703             } else                      /* single branch is optimized. */
2704                 scan = NEXTOPER(scan);
2705             continue;
2706         } else if (OP(scan) == SUSPEND || OP(scan) == GOSUB || OP(scan) == GOSTART) {
2707             scan_frame *newframe = NULL;
2708             I32 paren;
2709             regnode *start;
2710             regnode *end;
2711
2712             if (OP(scan) != SUSPEND) {
2713             /* set the pointer */
2714                 if (OP(scan) == GOSUB) {
2715                     paren = ARG(scan);
2716                     RExC_recurse[ARG2L(scan)] = scan;
2717                     start = RExC_open_parens[paren-1];
2718                     end   = RExC_close_parens[paren-1];
2719                 } else {
2720                     paren = 0;
2721                     start = RExC_rx->program + 1;
2722                     end   = RExC_opend;
2723                 }
2724                 if (!recursed) {
2725                     Newxz(recursed, (((RExC_npar)>>3) +1), U8);
2726                     SAVEFREEPV(recursed);
2727                 }
2728                 if (!PAREN_TEST(recursed,paren+1)) {
2729                     PAREN_SET(recursed,paren+1);
2730                     Newx(newframe,1,scan_frame);
2731                 } else {
2732                     if (flags & SCF_DO_SUBSTR) {
2733                         scan_commit(pRExC_state,data,minlenp);
2734                         data->longest = &(data->longest_float);
2735                     }
2736                     is_inf = is_inf_internal = 1;
2737                     if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
2738                         cl_anything(pRExC_state, data->start_class);
2739                     flags &= ~SCF_DO_STCLASS;
2740                 }
2741             } else {
2742                 Newx(newframe,1,scan_frame);
2743                 paren = stopparen;
2744                 start = scan+2;
2745                 end = regnext(scan);
2746             }
2747             if (newframe) {
2748                 assert(start);
2749                 assert(end);
2750                 SAVEFREEPV(newframe);
2751                 newframe->next = regnext(scan);
2752                 newframe->last = last;
2753                 newframe->stop = stopparen;
2754                 newframe->prev = frame;
2755
2756                 frame = newframe;
2757                 scan =  start;
2758                 stopparen = paren;
2759                 last = end;
2760
2761                 continue;
2762             }
2763         }
2764         else if (OP(scan) == EXACT) {
2765             I32 l = STR_LEN(scan);
2766             UV uc;
2767             if (UTF) {
2768                 const U8 * const s = (U8*)STRING(scan);
2769                 l = utf8_length(s, s + l);
2770                 uc = utf8_to_uvchr(s, NULL);
2771             } else {
2772                 uc = *((U8*)STRING(scan));
2773             }
2774             min += l;
2775             if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
2776                 /* The code below prefers earlier match for fixed
2777                    offset, later match for variable offset.  */
2778                 if (data->last_end == -1) { /* Update the start info. */
2779                     data->last_start_min = data->pos_min;
2780                     data->last_start_max = is_inf
2781                         ? I32_MAX : data->pos_min + data->pos_delta;
2782                 }
2783                 sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));
2784                 if (UTF)
2785                     SvUTF8_on(data->last_found);
2786                 {
2787                     SV * const sv = data->last_found;
2788                     MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
2789                         mg_find(sv, PERL_MAGIC_utf8) : NULL;
2790                     if (mg && mg->mg_len >= 0)
2791                         mg->mg_len += utf8_length((U8*)STRING(scan),
2792                                                   (U8*)STRING(scan)+STR_LEN(scan));
2793                 }
2794                 data->last_end = data->pos_min + l;
2795                 data->pos_min += l; /* As in the first entry. */
2796                 data->flags &= ~SF_BEFORE_EOL;
2797             }
2798             if (flags & SCF_DO_STCLASS_AND) {
2799                 /* Check whether it is compatible with what we know already! */
2800                 int compat = 1;
2801
2802                 if (uc >= 0x100 ||
2803                     (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
2804                     && !ANYOF_BITMAP_TEST(data->start_class, uc)
2805                     && (!(data->start_class->flags & ANYOF_FOLD)
2806                         || !ANYOF_BITMAP_TEST(data->start_class, PL_fold[uc])))
2807                     )
2808                     compat = 0;
2809                 ANYOF_CLASS_ZERO(data->start_class);
2810                 ANYOF_BITMAP_ZERO(data->start_class);
2811                 if (compat)
2812                     ANYOF_BITMAP_SET(data->start_class, uc);
2813                 data->start_class->flags &= ~ANYOF_EOS;
2814                 if (uc < 0x100)
2815                   data->start_class->flags &= ~ANYOF_UNICODE_ALL;
2816             }
2817             else if (flags & SCF_DO_STCLASS_OR) {
2818                 /* false positive possible if the class is case-folded */
2819                 if (uc < 0x100)
2820                     ANYOF_BITMAP_SET(data->start_class, uc);
2821                 else
2822                     data->start_class->flags |= ANYOF_UNICODE_ALL;
2823                 data->start_class->flags &= ~ANYOF_EOS;
2824                 cl_and(data->start_class, and_withp);
2825             }
2826             flags &= ~SCF_DO_STCLASS;
2827         }
2828         else if (PL_regkind[OP(scan)] == EXACT) { /* But OP != EXACT! */
2829             I32 l = STR_LEN(scan);
2830             UV uc = *((U8*)STRING(scan));
2831
2832             /* Search for fixed substrings supports EXACT only. */
2833             if (flags & SCF_DO_SUBSTR) {
2834                 assert(data);
2835                 scan_commit(pRExC_state, data, minlenp);
2836             }
2837             if (UTF) {
2838                 const U8 * const s = (U8 *)STRING(scan);
2839                 l = utf8_length(s, s + l);
2840                 uc = utf8_to_uvchr(s, NULL);
2841             }
2842             min += l;
2843             if (flags & SCF_DO_SUBSTR)
2844                 data->pos_min += l;
2845             if (flags & SCF_DO_STCLASS_AND) {
2846                 /* Check whether it is compatible with what we know already! */
2847                 int compat = 1;
2848
2849                 if (uc >= 0x100 ||
2850                     (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
2851                     && !ANYOF_BITMAP_TEST(data->start_class, uc)
2852                      && !ANYOF_BITMAP_TEST(data->start_class, PL_fold[uc])))
2853                     compat = 0;
2854                 ANYOF_CLASS_ZERO(data->start_class);
2855                 ANYOF_BITMAP_ZERO(data->start_class);
2856                 if (compat) {
2857                     ANYOF_BITMAP_SET(data->start_class, uc);
2858                     data->start_class->flags &= ~ANYOF_EOS;
2859                     data->start_class->flags |= ANYOF_FOLD;
2860                     if (OP(scan) == EXACTFL)
2861                         data->start_class->flags |= ANYOF_LOCALE;
2862                 }
2863             }
2864             else if (flags & SCF_DO_STCLASS_OR) {
2865                 if (data->start_class->flags & ANYOF_FOLD) {
2866                     /* false positive possible if the class is case-folded.
2867                        Assume that the locale settings are the same... */
2868                     if (uc < 0x100)
2869                         ANYOF_BITMAP_SET(data->start_class, uc);
2870                     data->start_class->flags &= ~ANYOF_EOS;
2871                 }
2872                 cl_and(data->start_class, and_withp);
2873             }
2874             flags &= ~SCF_DO_STCLASS;
2875         }
2876         else if (strchr((const char*)PL_varies,OP(scan))) {
2877             I32 mincount, maxcount, minnext, deltanext, fl = 0;
2878             I32 f = flags, pos_before = 0;
2879             regnode * const oscan = scan;
2880             struct regnode_charclass_class this_class;
2881             struct regnode_charclass_class *oclass = NULL;
2882             I32 next_is_eval = 0;
2883
2884             switch (PL_regkind[OP(scan)]) {
2885             case WHILEM:                /* End of (?:...)* . */
2886                 scan = NEXTOPER(scan);
2887                 goto finish;
2888             case PLUS:
2889                 if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
2890                     next = NEXTOPER(scan);
2891                     if (OP(next) == EXACT || (flags & SCF_DO_STCLASS)) {
2892                         mincount = 1;
2893                         maxcount = REG_INFTY;
2894                         next = regnext(scan);
2895                         scan = NEXTOPER(scan);
2896                         goto do_curly;
2897                     }
2898                 }
2899                 if (flags & SCF_DO_SUBSTR)
2900                     data->pos_min++;
2901                 min++;
2902                 /* Fall through. */
2903             case STAR:
2904                 if (flags & SCF_DO_STCLASS) {
2905                     mincount = 0;
2906                     maxcount = REG_INFTY;
2907                     next = regnext(scan);
2908                     scan = NEXTOPER(scan);
2909                     goto do_curly;
2910                 }
2911                 is_inf = is_inf_internal = 1;
2912                 scan = regnext(scan);
2913                 if (flags & SCF_DO_SUBSTR) {
2914                     scan_commit(pRExC_state, data, minlenp); /* Cannot extend fixed substrings */
2915                     data->longest = &(data->longest_float);
2916                 }
2917                 goto optimize_curly_tail;
2918             case CURLY:
2919                 if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM)
2920                     && (scan->flags == stopparen))
2921                 {
2922                     mincount = 1;
2923                     maxcount = 1;
2924                 } else {
2925                     mincount = ARG1(scan);
2926                     maxcount = ARG2(scan);
2927                 }
2928                 next = regnext(scan);
2929                 if (OP(scan) == CURLYX) {
2930                     I32 lp = (data ? *(data->last_closep) : 0);
2931                     scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);
2932                 }
2933                 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
2934                 next_is_eval = (OP(scan) == EVAL);
2935               do_curly:
2936                 if (flags & SCF_DO_SUBSTR) {
2937                     if (mincount == 0) scan_commit(pRExC_state,data,minlenp); /* Cannot extend fixed substrings */
2938                     pos_before = data->pos_min;
2939                 }
2940                 if (data) {
2941                     fl = data->flags;
2942                     data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
2943                     if (is_inf)
2944                         data->flags |= SF_IS_INF;
2945                 }
2946                 if (flags & SCF_DO_STCLASS) {
2947                     cl_init(pRExC_state, &this_class);
2948                     oclass = data->start_class;
2949                     data->start_class = &this_class;
2950                     f |= SCF_DO_STCLASS_AND;
2951                     f &= ~SCF_DO_STCLASS_OR;
2952                 }
2953                 /* These are the cases when once a subexpression
2954                    fails at a particular position, it cannot succeed
2955                    even after backtracking at the enclosing scope.
2956                 
2957                    XXXX what if minimal match and we are at the
2958                         initial run of {n,m}? */
2959                 if ((mincount != maxcount - 1) && (maxcount != REG_INFTY))
2960                     f &= ~SCF_WHILEM_VISITED_POS;
2961
2962                 /* This will finish on WHILEM, setting scan, or on NULL: */
2963                 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext, 
2964                                       last, data, stopparen, recursed, NULL,
2965                                       (mincount == 0
2966                                         ? (f & ~SCF_DO_SUBSTR) : f),depth+1);
2967
2968                 if (flags & SCF_DO_STCLASS)
2969                     data->start_class = oclass;
2970                 if (mincount == 0 || minnext == 0) {
2971                     if (flags & SCF_DO_STCLASS_OR) {
2972                         cl_or(pRExC_state, data->start_class, &this_class);
2973                     }
2974                     else if (flags & SCF_DO_STCLASS_AND) {
2975                         /* Switch to OR mode: cache the old value of
2976                          * data->start_class */
2977                         INIT_AND_WITHP;
2978                         StructCopy(data->start_class, and_withp,
2979                                    struct regnode_charclass_class);
2980                         flags &= ~SCF_DO_STCLASS_AND;
2981                         StructCopy(&this_class, data->start_class,
2982                                    struct regnode_charclass_class);
2983                         flags |= SCF_DO_STCLASS_OR;
2984                         data->start_class->flags |= ANYOF_EOS;
2985                     }
2986                 } else {                /* Non-zero len */
2987                     if (flags & SCF_DO_STCLASS_OR) {
2988                         cl_or(pRExC_state, data->start_class, &this_class);
2989                         cl_and(data->start_class, and_withp);
2990                     }
2991                     else if (flags & SCF_DO_STCLASS_AND)
2992                         cl_and(data->start_class, &this_class);
2993                     flags &= ~SCF_DO_STCLASS;
2994                 }
2995                 if (!scan)              /* It was not CURLYX, but CURLY. */
2996                     scan = next;
2997                 if ( /* ? quantifier ok, except for (?{ ... }) */
2998                     (next_is_eval || !(mincount == 0 && maxcount == 1))
2999                     && (minnext == 0) && (deltanext == 0)
3000                     && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
3001                     && maxcount <= REG_INFTY/3 /* Complement check for big count */
3002                     && ckWARN(WARN_REGEXP))
3003                 {
3004                     vWARN(RExC_parse,
3005                           "Quantifier unexpected on zero-length expression");
3006                 }
3007
3008                 min += minnext * mincount;
3009                 is_inf_internal |= ((maxcount == REG_INFTY
3010                                      && (minnext + deltanext) > 0)
3011                                     || deltanext == I32_MAX);
3012                 is_inf |= is_inf_internal;
3013                 delta += (minnext + deltanext) * maxcount - minnext * mincount;
3014
3015                 /* Try powerful optimization CURLYX => CURLYN. */
3016                 if (  OP(oscan) == CURLYX && data
3017                       && data->flags & SF_IN_PAR
3018                       && !(data->flags & SF_HAS_EVAL)
3019                       && !deltanext && minnext == 1 ) {
3020                     /* Try to optimize to CURLYN.  */
3021                     regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
3022                     regnode * const nxt1 = nxt;
3023 #ifdef DEBUGGING
3024                     regnode *nxt2;
3025 #endif
3026
3027                     /* Skip open. */
3028                     nxt = regnext(nxt);
3029                     if (!strchr((const char*)PL_simple,OP(nxt))
3030                         && !(PL_regkind[OP(nxt)] == EXACT
3031                              && STR_LEN(nxt) == 1))
3032                         goto nogo;
3033 #ifdef DEBUGGING
3034                     nxt2 = nxt;
3035 #endif
3036                     nxt = regnext(nxt);
3037                     if (OP(nxt) != CLOSE)
3038                         goto nogo;
3039                     if (RExC_open_parens) {
3040                         RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
3041                         RExC_close_parens[ARG(nxt1)-1]=nxt+2; /*close->while*/
3042                     }
3043                     /* Now we know that nxt2 is the only contents: */
3044                     oscan->flags = (U8)ARG(nxt);
3045                     OP(oscan) = CURLYN;
3046                     OP(nxt1) = NOTHING; /* was OPEN. */
3047
3048 #ifdef DEBUGGING
3049                     OP(nxt1 + 1) = OPTIMIZED; /* was count. */
3050                     NEXT_OFF(nxt1+ 1) = 0; /* just for consistancy. */
3051                     NEXT_OFF(nxt2) = 0; /* just for consistancy with CURLY. */
3052                     OP(nxt) = OPTIMIZED;        /* was CLOSE. */
3053                     OP(nxt + 1) = OPTIMIZED; /* was count. */
3054                     NEXT_OFF(nxt+ 1) = 0; /* just for consistancy. */
3055 #endif
3056                 }
3057               nogo:
3058
3059                 /* Try optimization CURLYX => CURLYM. */
3060                 if (  OP(oscan) == CURLYX && data
3061                       && !(data->flags & SF_HAS_PAR)
3062                       && !(data->flags & SF_HAS_EVAL)
3063                       && !deltanext     /* atom is fixed width */
3064                       && minnext != 0   /* CURLYM can't handle zero width */
3065                 ) {
3066                     /* XXXX How to optimize if data == 0? */
3067                     /* Optimize to a simpler form.  */
3068                     regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
3069                     regnode *nxt2;
3070
3071                     OP(oscan) = CURLYM;
3072                     while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
3073                             && (OP(nxt2) != WHILEM))
3074                         nxt = nxt2;
3075                     OP(nxt2)  = SUCCEED; /* Whas WHILEM */
3076                     /* Need to optimize away parenths. */
3077                     if (data->flags & SF_IN_PAR) {
3078                         /* Set the parenth number.  */
3079                         regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
3080
3081                         if (OP(nxt) != CLOSE)
3082                             FAIL("Panic opt close");
3083                         oscan->flags = (U8)ARG(nxt);
3084                         if (RExC_open_parens) {
3085                             RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
3086                             RExC_close_parens[ARG(nxt1)-1]=nxt2+1; /*close->NOTHING*/
3087                         }
3088                         OP(nxt1) = OPTIMIZED;   /* was OPEN. */
3089                         OP(nxt) = OPTIMIZED;    /* was CLOSE. */
3090
3091 #ifdef DEBUGGING
3092                         OP(nxt1 + 1) = OPTIMIZED; /* was count. */
3093                         OP(nxt + 1) = OPTIMIZED; /* was count. */
3094                         NEXT_OFF(nxt1 + 1) = 0; /* just for consistancy. */
3095                         NEXT_OFF(nxt + 1) = 0; /* just for consistancy. */
3096 #endif
3097 #if 0
3098                         while ( nxt1 && (OP(nxt1) != WHILEM)) {
3099                             regnode *nnxt = regnext(nxt1);
3100                         
3101                             if (nnxt == nxt) {
3102                                 if (reg_off_by_arg[OP(nxt1)])
3103                                     ARG_SET(nxt1, nxt2 - nxt1);
3104                                 else if (nxt2 - nxt1 < U16_MAX)
3105                                     NEXT_OFF(nxt1) = nxt2 - nxt1;
3106                                 else
3107                                     OP(nxt) = NOTHING;  /* Cannot beautify */
3108                             }
3109                             nxt1 = nnxt;
3110                         }
3111 #endif
3112                         /* Optimize again: */
3113                         study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,
3114                                     NULL, stopparen, recursed, NULL, 0,depth+1);
3115                     }
3116                     else
3117                         oscan->flags = 0;
3118                 }
3119                 else if ((OP(oscan) == CURLYX)
3120                          && (flags & SCF_WHILEM_VISITED_POS)
3121                          /* See the comment on a similar expression above.
3122                             However, this time it not a subexpression
3123                             we care about, but the expression itself. */
3124                          && (maxcount == REG_INFTY)
3125                          && data && ++data->whilem_c < 16) {
3126                     /* This stays as CURLYX, we can put the count/of pair. */
3127                     /* Find WHILEM (as in regexec.c) */
3128                     regnode *nxt = oscan + NEXT_OFF(oscan);
3129
3130                     if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
3131                         nxt += ARG(nxt);
3132                     PREVOPER(nxt)->flags = (U8)(data->whilem_c
3133                         | (RExC_whilem_seen << 4)); /* On WHILEM */
3134                 }
3135                 if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
3136                     pars++;
3137                 if (flags & SCF_DO_SUBSTR) {
3138                     SV *last_str = NULL;
3139                     int counted = mincount != 0;
3140
3141                     if (data->last_end > 0 && mincount != 0) { /* Ends with a string. */
3142 #if defined(SPARC64_GCC_WORKAROUND)
3143                         I32 b = 0;
3144                         STRLEN l = 0;
3145                         const char *s = NULL;
3146                         I32 old = 0;
3147
3148                         if (pos_before >= data->last_start_min)
3149                             b = pos_before;
3150                         else
3151                             b = data->last_start_min;
3152
3153                         l = 0;
3154                         s = SvPV_const(data->last_found, l);
3155                         old = b - data->last_start_min;
3156
3157 #else
3158                         I32 b = pos_before >= data->last_start_min
3159                             ? pos_before : data->last_start_min;
3160                         STRLEN l;
3161                         const char * const s = SvPV_const(data->last_found, l);
3162                         I32 old = b - data->last_start_min;
3163 #endif
3164
3165                         if (UTF)
3166                             old = utf8_hop((U8*)s, old) - (U8*)s;
3167                         
3168                         l -= old;
3169                         /* Get the added string: */
3170                         last_str = newSVpvn(s  + old, l);
3171                         if (UTF)
3172                             SvUTF8_on(last_str);
3173                         if (deltanext == 0 && pos_before == b) {
3174                             /* What was added is a constant string */
3175                             if (mincount > 1) {
3176                                 SvGROW(last_str, (mincount * l) + 1);
3177                                 repeatcpy(SvPVX(last_str) + l,
3178                                           SvPVX_const(last_str), l, mincount - 1);
3179                                 SvCUR_set(last_str, SvCUR(last_str) * mincount);
3180                                 /* Add additional parts. */
3181                                 SvCUR_set(data->last_found,
3182                                           SvCUR(data->last_found) - l);
3183                                 sv_catsv(data->last_found, last_str);
3184                                 {
3185                                     SV * sv = data->last_found;
3186                                     MAGIC *mg =
3187                                         SvUTF8(sv) && SvMAGICAL(sv) ?
3188                                         mg_find(sv, PERL_MAGIC_utf8) : NULL;
3189                                     if (mg && mg->mg_len >= 0)
3190                                         mg->mg_len += CHR_SVLEN(last_str);
3191                                 }
3192                                 data->last_end += l * (mincount - 1);
3193                             }
3194                         } else {
3195                             /* start offset must point into the last copy */
3196                             data->last_start_min += minnext * (mincount - 1);
3197                             data->last_start_max += is_inf ? I32_MAX
3198                                 : (maxcount - 1) * (minnext + data->pos_delta);
3199                         }
3200                     }
3201                     /* It is counted once already... */
3202                     data->pos_min += minnext * (mincount - counted);
3203                     data->pos_delta += - counted * deltanext +
3204                         (minnext + deltanext) * maxcount - minnext * mincount;
3205                     if (mincount != maxcount) {
3206                          /* Cannot extend fixed substrings found inside
3207                             the group.  */
3208                         scan_commit(pRExC_state,data,minlenp);
3209                         if (mincount && last_str) {
3210                             SV * const sv = data->last_found;
3211                             MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
3212                                 mg_find(sv, PERL_MAGIC_utf8) : NULL;
3213
3214                             if (mg)
3215                                 mg->mg_len = -1;
3216                             sv_setsv(sv, last_str);
3217                             data->last_end = data->pos_min;
3218                             data->last_start_min =
3219                                 data->pos_min - CHR_SVLEN(last_str);
3220                             data->last_start_max = is_inf
3221                                 ? I32_MAX
3222                                 : data->pos_min + data->pos_delta
3223                                 - CHR_SVLEN(last_str);
3224                         }
3225                         data->longest = &(data->longest_float);
3226                     }
3227                     SvREFCNT_dec(last_str);
3228                 }
3229                 if (data && (fl & SF_HAS_EVAL))
3230                     data->flags |= SF_HAS_EVAL;
3231               optimize_curly_tail:
3232                 if (OP(oscan) != CURLYX) {
3233                     while (PL_regkind[OP(next = regnext(oscan))] == NOTHING
3234                            && NEXT_OFF(next))
3235                         NEXT_OFF(oscan) += NEXT_OFF(next);
3236                 }
3237                 continue;
3238             default:                    /* REF and CLUMP only? */
3239                 if (flags & SCF_DO_SUBSTR) {
3240                     scan_commit(pRExC_state,data,minlenp);      /* Cannot expect anything... */
3241                     data->longest = &(data->longest_float);
3242                 }
3243                 is_inf = is_inf_internal = 1;
3244                 if (flags & SCF_DO_STCLASS_OR)
3245                     cl_anything(pRExC_state, data->start_class);
3246                 flags &= ~SCF_DO_STCLASS;
3247                 break;
3248             }
3249         }
3250         else if (strchr((const char*)PL_simple,OP(scan))) {
3251             int value = 0;
3252
3253             if (flags & SCF_DO_SUBSTR) {
3254                 scan_commit(pRExC_state,data,minlenp);
3255                 data->pos_min++;
3256             }
3257             min++;
3258             if (flags & SCF_DO_STCLASS) {
3259                 data->start_class->flags &= ~ANYOF_EOS; /* No match on empty */
3260
3261                 /* Some of the logic below assumes that switching
3262                    locale on will only add false positives. */
3263                 switch (PL_regkind[OP(scan)]) {
3264                 case SANY:
3265                 default:
3266                   do_default:
3267                     /* Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d", OP(scan)); */
3268                     if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
3269                         cl_anything(pRExC_state, data->start_class);
3270                     break;
3271                 case REG_ANY:
3272                     if (OP(scan) == SANY)
3273                         goto do_default;
3274                     if (flags & SCF_DO_STCLASS_OR) { /* Everything but \n */
3275                         value = (ANYOF_BITMAP_TEST(data->start_class,'\n')
3276                                  || (data->start_class->flags & ANYOF_CLASS));
3277                         cl_anything(pRExC_state, data->start_class);
3278                     }
3279                     if (flags & SCF_DO_STCLASS_AND || !value)
3280                         ANYOF_BITMAP_CLEAR(data->start_class,'\n');
3281                     break;
3282                 case ANYOF:
3283                     if (flags & SCF_DO_STCLASS_AND)
3284                         cl_and(data->start_class,
3285                                (struct regnode_charclass_class*)scan);
3286                     else
3287                         cl_or(pRExC_state, data->start_class,
3288                               (struct regnode_charclass_class*)scan);
3289                     break;
3290                 case ALNUM:
3291                     if (flags & SCF_DO_STCLASS_AND) {
3292                         if (!(data->start_class->flags & ANYOF_LOCALE)) {
3293                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
3294                             for (value = 0; value < 256; value++)
3295                                 if (!isALNUM(value))
3296                                     ANYOF_BITMAP_CLEAR(data->start_class, value);
3297                         }
3298                     }
3299                     else {
3300                         if (data->start_class->flags & ANYOF_LOCALE)
3301                             ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
3302                         else {
3303                             for (value = 0; value < 256; value++)
3304                                 if (isALNUM(value))
3305                                     ANYOF_BITMAP_SET(data->start_class, value);                 
3306                         }
3307                     }
3308                     break;
3309                 case ALNUML:
3310                     if (flags & SCF_DO_STCLASS_AND) {
3311                         if (data->start_class->flags & ANYOF_LOCALE)
3312                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
3313                     }
3314                     else {
3315                         ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
3316                         data->start_class->flags |= ANYOF_LOCALE;
3317                     }
3318                     break;
3319                 case NALNUM:
3320                     if (flags & SCF_DO_STCLASS_AND) {
3321                         if (!(data->start_class->flags & ANYOF_LOCALE)) {
3322                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
3323                             for (value = 0; value < 256; value++)
3324                                 if (isALNUM(value))
3325                                     ANYOF_BITMAP_CLEAR(data->start_class, value);
3326                         }
3327                     }
3328                     else {
3329                         if (data->start_class->flags & ANYOF_LOCALE)
3330                             ANYOF_CLASS_SET(data->start_class,ANYOF_NALNUM);
3331                         else {
3332                             for (value = 0; value < 256; value++)
3333                                 if (!isALNUM(value))
3334                                     ANYOF_BITMAP_SET(data->start_class, value);                 
3335                         }
3336                     }
3337                     break;
3338                 case NALNUML:
3339                     if (flags & SCF_DO_STCLASS_AND) {
3340                         if (data->start_class->flags & ANYOF_LOCALE)
3341                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
3342                     }
3343                     else {
3344                         data->start_class->flags |= ANYOF_LOCALE;
3345                         ANYOF_CLASS_SET(data->start_class,ANYOF_NALNUM);
3346                     }
3347                     break;
3348                 case SPACE:
3349                     if (flags & SCF_DO_STCLASS_AND) {
3350                         if (!(data->start_class->flags & ANYOF_LOCALE)) {
3351                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NSPACE);
3352                             for (value = 0; value < 256; value++)
3353                                 if (!isSPACE(value))
3354                                     ANYOF_BITMAP_CLEAR(data->start_class, value);
3355                         }
3356                     }
3357                     else {
3358                         if (data->start_class->flags & ANYOF_LOCALE)
3359                             ANYOF_CLASS_SET(data->start_class,ANYOF_SPACE);
3360                         else {
3361                             for (value = 0; value < 256; value++)
3362                                 if (isSPACE(value))
3363                                     ANYOF_BITMAP_SET(data->start_class, value);                 
3364                         }
3365                     }
3366                     break;
3367                 case SPACEL:
3368                     if (flags & SCF_DO_STCLASS_AND) {
3369                         if (data->start_class->flags & ANYOF_LOCALE)
3370                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NSPACE);
3371                     }
3372                     else {
3373                         data->start_class->flags |= ANYOF_LOCALE;
3374                         ANYOF_CLASS_SET(data->start_class,ANYOF_SPACE);
3375                     }
3376                     break;
3377                 case NSPACE:
3378                     if (flags & SCF_DO_STCLASS_AND) {
3379                         if (!(data->start_class->flags & ANYOF_LOCALE)) {
3380                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_SPACE);
3381                             for (value = 0; value < 256; value++)
3382                                 if (isSPACE(value))
3383                                     ANYOF_BITMAP_CLEAR(data->start_class, value);
3384                         }
3385                     }
3386                     else {
3387                         if (data->start_class->flags & ANYOF_LOCALE)
3388                             ANYOF_CLASS_SET(data->start_class,ANYOF_NSPACE);
3389                         else {
3390                             for (value = 0; value < 256; value++)
3391                                 if (!isSPACE(value))
3392                                     ANYOF_BITMAP_SET(data->start_class, value);                 
3393                         }
3394                     }
3395                     break;
3396                 case NSPACEL:
3397                     if (flags & SCF_DO_STCLASS_AND) {
3398                         if (data->start_class->flags & ANYOF_LOCALE) {
3399                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_SPACE);
3400                             for (value = 0; value < 256; value++)
3401                                 if (!isSPACE(value))
3402                                     ANYOF_BITMAP_CLEAR(data->start_class, value);
3403                         }
3404                     }
3405                     else {
3406                         data->start_class->flags |= ANYOF_LOCALE;
3407                         ANYOF_CLASS_SET(data->start_class,ANYOF_NSPACE);
3408                     }
3409                     break;
3410                 case DIGIT:
3411                     if (flags & SCF_DO_STCLASS_AND) {
3412                         ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NDIGIT);
3413                         for (value = 0; value < 256; value++)
3414                             if (!isDIGIT(value))
3415                                 ANYOF_BITMAP_CLEAR(data->start_class, value);
3416                     }
3417                     else {
3418                         if (data->start_class->flags & ANYOF_LOCALE)
3419                             ANYOF_CLASS_SET(data->start_class,ANYOF_DIGIT);
3420                         else {
3421                             for (value = 0; value < 256; value++)
3422                                 if (isDIGIT(value))
3423                                     ANYOF_BITMAP_SET(data->start_class, value);                 
3424                         }
3425                     }
3426                     break;
3427                 case NDIGIT:
3428                     if (flags & SCF_DO_STCLASS_AND) {
3429                         ANYOF_CLASS_CLEAR(data->start_class,ANYOF_DIGIT);
3430                         for (value = 0; value < 256; value++)
3431                             if (isDIGIT(value))
3432                                 ANYOF_BITMAP_CLEAR(data->start_class, value);
3433                     }
3434                     else {
3435                         if (data->start_class->flags & ANYOF_LOCALE)
3436                             ANYOF_CLASS_SET(data->start_class,ANYOF_NDIGIT);
3437                         else {
3438                             for (value = 0; value < 256; value++)
3439                                 if (!isDIGIT(value))
3440                                     ANYOF_BITMAP_SET(data->start_class, value);                 
3441                         }
3442                     }
3443                     break;
3444                 }
3445                 if (flags & SCF_DO_STCLASS_OR)
3446                     cl_and(data->start_class, and_withp);
3447                 flags &= ~SCF_DO_STCLASS;
3448             }
3449         }
3450         else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
3451             data->flags |= (OP(scan) == MEOL
3452                             ? SF_BEFORE_MEOL
3453                             : SF_BEFORE_SEOL);
3454         }
3455         else if (  PL_regkind[OP(scan)] == BRANCHJ
3456                  /* Lookbehind, or need to calculate parens/evals/stclass: */
3457                    && (scan->flags || data || (flags & SCF_DO_STCLASS))
3458                    && (OP(scan) == IFMATCH || OP(scan) == UNLESSM)) {
3459             if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY 
3460                 || OP(scan) == UNLESSM )
3461             {
3462                 /* Negative Lookahead/lookbehind
3463                    In this case we can't do fixed string optimisation.
3464                 */
3465
3466                 I32 deltanext, minnext, fake = 0;
3467                 regnode *nscan;
3468                 struct regnode_charclass_class intrnl;
3469                 int f = 0;
3470
3471                 data_fake.flags = 0;
3472                 if (data) {
3473                     data_fake.whilem_c = data->whilem_c;
3474                     data_fake.last_closep = data->last_closep;
3475                 }
3476                 else
3477                     data_fake.last_closep = &fake;
3478                 if ( flags & SCF_DO_STCLASS && !scan->flags
3479                      && OP(scan) == IFMATCH ) { /* Lookahead */
3480                     cl_init(pRExC_state, &intrnl);
3481                     data_fake.start_class = &intrnl;
3482                     f |= SCF_DO_STCLASS_AND;
3483                 }
3484                 if (flags & SCF_WHILEM_VISITED_POS)
3485                     f |= SCF_WHILEM_VISITED_POS;
3486                 next = regnext(scan);
3487                 nscan = NEXTOPER(NEXTOPER(scan));
3488                 minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext, 
3489                     last, &data_fake, stopparen, recursed, NULL, f, depth+1);
3490                 if (scan->flags) {
3491                     if (deltanext) {
3492                         vFAIL("Variable length lookbehind not implemented");
3493                     }
3494                     else if (minnext > (I32)U8_MAX) {
3495                         vFAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
3496                     }
3497                     scan->flags = (U8)minnext;
3498                 }
3499                 if (data) {
3500                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
3501                         pars++;
3502                     if (data_fake.flags & SF_HAS_EVAL)
3503                         data->flags |= SF_HAS_EVAL;
3504                     data->whilem_c = data_fake.whilem_c;
3505                 }
3506                 if (f & SCF_DO_STCLASS_AND) {
3507                     const int was = (data->start_class->flags & ANYOF_EOS);
3508
3509                     cl_and(data->start_class, &intrnl);
3510                     if (was)
3511                         data->start_class->flags |= ANYOF_EOS;
3512                 }
3513             }
3514 #if PERL_ENABLE_POSITIVE_ASSERTION_STUDY
3515             else {
3516                 /* Positive Lookahead/lookbehind
3517                    In this case we can do fixed string optimisation,
3518                    but we must be careful about it. Note in the case of
3519                    lookbehind the positions will be offset by the minimum
3520                    length of the pattern, something we won't know about
3521                    until after the recurse.
3522                 */
3523                 I32 deltanext, fake = 0;
3524                 regnode *nscan;
3525                 struct regnode_charclass_class intrnl;
3526                 int f = 0;
3527                 /* We use SAVEFREEPV so that when the full compile 
3528                     is finished perl will clean up the allocated 
3529                     minlens when its all done. This was we don't
3530                     have to worry about freeing them when we know
3531                     they wont be used, which would be a pain.
3532                  */
3533                 I32 *minnextp;
3534                 Newx( minnextp, 1, I32 );
3535                 SAVEFREEPV(minnextp);
3536
3537                 if (data) {
3538                     StructCopy(data, &data_fake, scan_data_t);
3539                     if ((flags & SCF_DO_SUBSTR) && data->last_found) {
3540                         f |= SCF_DO_SUBSTR;
3541                         if (scan->flags) 
3542                             scan_commit(pRExC_state, &data_fake,minlenp);
3543                         data_fake.last_found=newSVsv(data->last_found);
3544                     }
3545                 }
3546                 else
3547                     data_fake.last_closep = &fake;
3548                 data_fake.flags = 0;
3549                 if (is_inf)
3550                     data_fake.flags |= SF_IS_INF;
3551                 if ( flags & SCF_DO_STCLASS && !scan->flags
3552                      && OP(scan) == IFMATCH ) { /* Lookahead */
3553                     cl_init(pRExC_state, &intrnl);
3554                     data_fake.start_class = &intrnl;
3555                     f |= SCF_DO_STCLASS_AND;
3556                 }
3557                 if (flags & SCF_WHILEM_VISITED_POS)
3558                     f |= SCF_WHILEM_VISITED_POS;
3559                 next = regnext(scan);
3560                 nscan = NEXTOPER(NEXTOPER(scan));
3561
3562                 *minnextp = study_chunk(pRExC_state, &nscan, minnextp, &deltanext, 
3563                     last, &data_fake, stopparen, recursed, NULL, f,depth+1);
3564                 if (scan->flags) {
3565                     if (deltanext) {
3566                         vFAIL("Variable length lookbehind not implemented");
3567                     }
3568                     else if (*minnextp > (I32)U8_MAX) {
3569                         vFAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
3570                     }
3571                     scan->flags = (U8)*minnextp;
3572                 }
3573
3574                 *minnextp += min;
3575
3576                 if (f & SCF_DO_STCLASS_AND) {
3577                     const int was = (data->start_class->flags & ANYOF_EOS);
3578
3579                     cl_and(data->start_class, &intrnl);
3580                     if (was)
3581                         data->start_class->flags |= ANYOF_EOS;
3582                 }
3583                 if (data) {
3584                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
3585                         pars++;
3586                     if (data_fake.flags & SF_HAS_EVAL)
3587                         data->flags |= SF_HAS_EVAL;
3588                     data->whilem_c = data_fake.whilem_c;
3589                     if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) {
3590                         if (RExC_rx->minlen<*minnextp)
3591                             RExC_rx->minlen=*minnextp;
3592                         scan_commit(pRExC_state, &data_fake, minnextp);
3593                         SvREFCNT_dec(data_fake.last_found);
3594                         
3595                         if ( data_fake.minlen_fixed != minlenp ) 
3596                         {
3597                             data->offset_fixed= data_fake.offset_fixed;
3598                             data->minlen_fixed= data_fake.minlen_fixed;
3599                             data->lookbehind_fixed+= scan->flags;
3600                         }
3601                         if ( data_fake.minlen_float != minlenp )
3602                         {
3603                             data->minlen_float= data_fake.minlen_float;
3604                             data->offset_float_min=data_fake.offset_float_min;
3605                             data->offset_float_max=data_fake.offset_float_max;
3606                             data->lookbehind_float+= scan->flags;
3607                         }
3608                     }
3609                 }
3610
3611
3612             }
3613 #endif
3614         }
3615         else if (OP(scan) == OPEN) {
3616             if (stopparen != (I32)ARG(scan))
3617                 pars++;
3618         }
3619         else if (OP(scan) == CLOSE) {
3620             if (stopparen == (I32)ARG(scan)) {
3621                 break;
3622             }
3623             if ((I32)ARG(scan) == is_par) {
3624                 next = regnext(scan);
3625
3626                 if ( next && (OP(next) != WHILEM) && next < last)
3627                     is_par = 0;         /* Disable optimization */
3628             }
3629             if (data)
3630                 *(data->last_closep) = ARG(scan);
3631         }
3632         else if (OP(scan) == EVAL) {
3633                 if (data)
3634                     data->flags |= SF_HAS_EVAL;
3635         }
3636         else if ( PL_regkind[OP(scan)] == ENDLIKE ) {
3637             if (flags & SCF_DO_SUBSTR) {
3638                 scan_commit(pRExC_state,data,minlenp);
3639                 flags &= ~SCF_DO_SUBSTR;
3640             }
3641             if (data && OP(scan)==ACCEPT) {
3642                 data->flags |= SCF_SEEN_ACCEPT;
3643                 if (stopmin > min)
3644                     stopmin = min;
3645             }
3646         }
3647         else if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */
3648         {
3649                 if (flags & SCF_DO_SUBSTR) {
3650                     scan_commit(pRExC_state,data,minlenp);
3651                     data->longest = &(data->longest_float);
3652                 }
3653                 is_inf = is_inf_internal = 1;
3654                 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
3655                     cl_anything(pRExC_state, data->start_class);
3656                 flags &= ~SCF_DO_STCLASS;
3657         }
3658 #ifdef TRIE_STUDY_OPT
3659 #ifdef FULL_TRIE_STUDY
3660         else if (PL_regkind[OP(scan)] == TRIE) {
3661             /* NOTE - There is similar code to this block above for handling
3662                BRANCH nodes on the initial study.  If you change stuff here
3663                check there too. */
3664             regnode *trie_node= scan;
3665             regnode *tail= regnext(scan);
3666             reg_trie_data *trie = (reg_trie_data*)RExC_rx->data->data[ ARG(scan) ];
3667             I32 max1 = 0, min1 = I32_MAX;
3668             struct regnode_charclass_class accum;
3669
3670             if (flags & SCF_DO_SUBSTR) /* XXXX Add !SUSPEND? */
3671                 scan_commit(pRExC_state, data,minlenp); /* Cannot merge strings after this. */
3672             if (flags & SCF_DO_STCLASS)
3673                 cl_init_zero(pRExC_state, &accum);
3674                 
3675             if (!trie->jump) {
3676                 min1= trie->minlen;
3677                 max1= trie->maxlen;
3678             } else {
3679                 const regnode *nextbranch= NULL;
3680                 U32 word;
3681                 
3682                 for ( word=1 ; word <= trie->wordcount ; word++) 
3683                 {
3684                     I32 deltanext=0, minnext=0, f = 0, fake;
3685                     struct regnode_charclass_class this_class;
3686                     
3687                     data_fake.flags = 0;
3688                     if (data) {
3689                         data_fake.whilem_c = data->whilem_c;
3690                         data_fake.last_closep = data->last_closep;
3691                     }
3692                     else
3693                         data_fake.last_closep = &fake;
3694                         
3695                     if (flags & SCF_DO_STCLASS) {
3696                         cl_init(pRExC_state, &this_class);
3697                         data_fake.start_class = &this_class;
3698                         f = SCF_DO_STCLASS_AND;
3699                     }
3700                     if (flags & SCF_WHILEM_VISITED_POS)
3701                         f |= SCF_WHILEM_VISITED_POS;
3702     
3703                     if (trie->jump[word]) {
3704                         if (!nextbranch)
3705                             nextbranch = trie_node + trie->jump[0];
3706                         scan= trie_node + trie->jump[word];
3707                         /* We go from the jump point to the branch that follows
3708                            it. Note this means we need the vestigal unused branches
3709                            even though they arent otherwise used.
3710                          */
3711                         minnext = study_chunk(pRExC_state, &scan, minlenp, 
3712                             &deltanext, (regnode *)nextbranch, &data_fake, 
3713                             stopparen, recursed, NULL, f,depth+1);
3714                     }
3715                     if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
3716                         nextbranch= regnext((regnode*)nextbranch);
3717                     
3718                     if (min1 > (I32)(minnext + trie->minlen))
3719                         min1 = minnext + trie->minlen;
3720                     if (max1 < (I32)(minnext + deltanext + trie->maxlen))
3721                         max1 = minnext + deltanext + trie->maxlen;
3722                     if (deltanext == I32_MAX)
3723                         is_inf = is_inf_internal = 1;
3724                     
3725                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
3726                         pars++;
3727                     if (data_fake.flags & SCF_SEEN_ACCEPT) {
3728                         if ( stopmin > min + min1) 
3729                             stopmin = min + min1;
3730                         flags &= ~SCF_DO_SUBSTR;
3731                         if (data)
3732                             data->flags |= SCF_SEEN_ACCEPT;
3733                     }
3734                     if (data) {
3735                         if (data_fake.flags & SF_HAS_EVAL)
3736                             data->flags |= SF_HAS_EVAL;
3737                         data->whilem_c = data_fake.whilem_c;
3738                     }
3739                     if (flags & SCF_DO_STCLASS)
3740                         cl_or(pRExC_state, &accum, &this_class);
3741                 }
3742             }
3743             if (flags & SCF_DO_SUBSTR) {
3744                 data->pos_min += min1;
3745                 data->pos_delta += max1 - min1;
3746                 if (max1 != min1 || is_inf)
3747                     data->longest = &(data->longest_float);
3748             }
3749             min += min1;
3750             delta += max1 - min1;
3751             if (flags & SCF_DO_STCLASS_OR) {
3752                 cl_or(pRExC_state, data->start_class, &accum);
3753                 if (min1) {
3754                     cl_and(data->start_class, and_withp);
3755                     flags &= ~SCF_DO_STCLASS;
3756                 }
3757             }
3758             else if (flags & SCF_DO_STCLASS_AND) {
3759                 if (min1) {
3760                     cl_and(data->start_class, &accum);
3761                     flags &= ~SCF_DO_STCLASS;
3762                 }
3763                 else {
3764                     /* Switch to OR mode: cache the old value of
3765                      * data->start_class */
3766                     INIT_AND_WITHP;
3767                     StructCopy(data->start_class, and_withp,
3768                                struct regnode_charclass_class);
3769                     flags &= ~SCF_DO_STCLASS_AND;
3770                     StructCopy(&accum, data->start_class,
3771                                struct regnode_charclass_class);
3772                     flags |= SCF_DO_STCLASS_OR;
3773                     data->start_class->flags |= ANYOF_EOS;
3774                 }
3775             }
3776             scan= tail;
3777             continue;
3778         }
3779 #else
3780         else if (PL_regkind[OP(scan)] == TRIE) {
3781             reg_trie_data *trie = (reg_trie_data*)RExC_rx->data->data[ ARG(scan) ];
3782             U8*bang=NULL;
3783             
3784             min += trie->minlen;
3785             delta += (trie->maxlen - trie->minlen);
3786             flags &= ~SCF_DO_STCLASS; /* xxx */
3787             if (flags & SCF_DO_SUBSTR) {
3788                 scan_commit(pRExC_state,data,minlenp);  /* Cannot expect anything... */
3789                 data->pos_min += trie->minlen;
3790                 data->pos_delta += (trie->maxlen - trie->minlen);
3791                 if (trie->maxlen != trie->minlen)
3792                     data->longest = &(data->longest_float);
3793             }
3794             if (trie->jump) /* no more substrings -- for now /grr*/
3795                 flags &= ~SCF_DO_SUBSTR; 
3796         }
3797 #endif /* old or new */
3798 #endif /* TRIE_STUDY_OPT */     
3799         /* Else: zero-length, ignore. */
3800         scan = regnext(scan);
3801     }
3802     if (frame) {
3803         last = frame->last;
3804         scan = frame->next;
3805         stopparen = frame->stop;
3806         frame = frame->prev;
3807         goto fake_study_recurse;
3808     }
3809
3810   finish:
3811     assert(!frame);
3812
3813     *scanp = scan;
3814     *deltap = is_inf_internal ? I32_MAX : delta;
3815     if (flags & SCF_DO_SUBSTR && is_inf)
3816         data->pos_delta = I32_MAX - data->pos_min;
3817     if (is_par > (I32)U8_MAX)
3818         is_par = 0;
3819     if (is_par && pars==1 && data) {
3820         data->flags |= SF_IN_PAR;
3821         data->flags &= ~SF_HAS_PAR;
3822     }
3823     else if (pars && data) {
3824         data->flags |= SF_HAS_PAR;
3825         data->flags &= ~SF_IN_PAR;
3826     }
3827     if (flags & SCF_DO_STCLASS_OR)
3828         cl_and(data->start_class, and_withp);
3829     if (flags & SCF_TRIE_RESTUDY)
3830         data->flags |=  SCF_TRIE_RESTUDY;
3831     
3832     DEBUG_STUDYDATA(data,depth);
3833     
3834     return min < stopmin ? min : stopmin;
3835 }
3836
3837 STATIC I32
3838 S_add_data(RExC_state_t *pRExC_state, I32 n, const char *s)
3839 {
3840     if (RExC_rx->data) {
3841         const U32 count = RExC_rx->data->count;
3842         Renewc(RExC_rx->data,
3843                sizeof(*RExC_rx->data) + sizeof(void*) * (count + n - 1),
3844                char, struct reg_data);
3845         Renew(RExC_rx->data->what, count + n, U8);
3846         RExC_rx->data->count += n;
3847     }
3848     else {
3849         Newxc(RExC_rx->data, sizeof(*RExC_rx->data) + sizeof(void*) * (n - 1),
3850              char, struct reg_data);
3851         Newx(RExC_rx->data->what, n, U8);
3852         RExC_rx->data->count = n;
3853     }
3854     Copy(s, RExC_rx->data->what + RExC_rx->data->count - n, n, U8);
3855     return RExC_rx->data->count - n;
3856 }
3857
3858 #ifndef PERL_IN_XSUB_RE
3859 void
3860 Perl_reginitcolors(pTHX)
3861 {
3862     dVAR;
3863     const char * const s = PerlEnv_getenv("PERL_RE_COLORS");
3864     if (s) {
3865         char *t = savepv(s);
3866         int i = 0;
3867         PL_colors[0] = t;
3868         while (++i < 6) {
3869             t = strchr(t, '\t');
3870             if (t) {
3871                 *t = '\0';
3872                 PL_colors[i] = ++t;
3873             }
3874             else
3875                 PL_colors[i] = t = (char *)"";
3876         }
3877     } else {
3878         int i = 0;
3879         while (i < 6)
3880             PL_colors[i++] = (char *)"";
3881     }
3882     PL_colorset = 1;
3883 }
3884 #endif
3885
3886
3887 #ifdef TRIE_STUDY_OPT
3888 #define CHECK_RESTUDY_GOTO                                  \
3889         if (                                                \
3890               (data.flags & SCF_TRIE_RESTUDY)               \
3891               && ! restudied++                              \
3892         )     goto reStudy
3893 #else
3894 #define CHECK_RESTUDY_GOTO
3895 #endif        
3896
3897 /*
3898  - pregcomp - compile a regular expression into internal code
3899  *
3900  * We can't allocate space until we know how big the compiled form will be,
3901  * but we can't compile it (and thus know how big it is) until we've got a
3902  * place to put the code.  So we cheat:  we compile it twice, once with code
3903  * generation turned off and size counting turned on, and once "for real".
3904  * This also means that we don't allocate space until we are sure that the
3905  * thing really will compile successfully, and we never have to move the
3906  * code and thus invalidate pointers into it.  (Note that it has to be in
3907  * one piece because free() must be able to free it all.) [NB: not true in perl]
3908  *
3909  * Beware that the optimization-preparation code in here knows about some
3910  * of the structure of the compiled regexp.  [I'll say.]
3911  */
3912
3913
3914
3915 #ifndef PERL_IN_XSUB_RE
3916 #define RE_ENGINE_PTR &PL_core_reg_engine
3917 #else
3918 extern const struct regexp_engine my_reg_engine;
3919 #define RE_ENGINE_PTR &my_reg_engine
3920 #endif
3921 /* these make a few things look better, to avoid indentation */
3922 #define BEGIN_BLOCK {
3923 #define END_BLOCK }
3924  
3925 regexp *
3926 Perl_pregcomp(pTHX_ char *exp, char *xend, PMOP *pm)
3927 {
3928     dVAR;
3929     GET_RE_DEBUG_FLAGS_DECL;
3930     DEBUG_r(if (!PL_colorset) reginitcolors());
3931 #ifndef PERL_IN_XSUB_RE
3932     BEGIN_BLOCK
3933     /* Dispatch a request to compile a regexp to correct 
3934        regexp engine. */
3935     HV * const table = GvHV(PL_hintgv);
3936     if (table) {
3937         SV **ptr= hv_fetchs(table, "regcomp", FALSE);
3938         if (ptr && SvIOK(*ptr) && SvIV(*ptr)) {
3939             const regexp_engine *eng=INT2PTR(regexp_engine*,SvIV(*ptr));
3940             DEBUG_COMPILE_r({
3941                 PerlIO_printf(Perl_debug_log, "Using engine %"UVxf"\n",
3942                     SvIV(*ptr));
3943             });            
3944             return CALLREGCOMP_ENG(eng, exp, xend, pm);
3945         } 
3946     }
3947     END_BLOCK
3948 #endif
3949     BEGIN_BLOCK    
3950     register regexp *r;
3951     regnode *scan;
3952     regnode *first;
3953     I32 flags;
3954     I32 minlen = 0;
3955     I32 sawplus = 0;
3956     I32 sawopen = 0;
3957     scan_data_t data;
3958     RExC_state_t RExC_state;
3959     RExC_state_t * const pRExC_state = &RExC_state;
3960 #ifdef TRIE_STUDY_OPT    
3961     int restudied= 0;
3962     RExC_state_t copyRExC_state;
3963 #endif    
3964     if (exp == NULL)
3965         FAIL("NULL regexp argument");
3966
3967     RExC_utf8 = pm->op_pmdynflags & PMdf_CMP_UTF8;
3968
3969     RExC_precomp = exp;
3970     DEBUG_COMPILE_r({
3971         SV *dsv= sv_newmortal();
3972         RE_PV_QUOTED_DECL(s, RExC_utf8,
3973             dsv, RExC_precomp, (xend - exp), 60);
3974         PerlIO_printf(Perl_debug_log, "%sCompiling REx%s %s\n",
3975                        PL_colors[4],PL_colors[5],s);
3976     });
3977     RExC_flags = pm->op_pmflags;
3978     RExC_sawback = 0;
3979
3980     RExC_seen = 0;
3981     RExC_seen_zerolen = *exp == '^' ? -1 : 0;
3982     RExC_seen_evals = 0;
3983     RExC_extralen = 0;
3984
3985     /* First pass: determine size, legality. */
3986     RExC_parse = exp;
3987     RExC_start = exp;
3988     RExC_end = xend;
3989     RExC_naughty = 0;
3990     RExC_npar = 1;
3991     RExC_cpar = 1;
3992     RExC_nestroot = 0;
3993     RExC_size = 0L;
3994     RExC_emit = &PL_regdummy;
3995     RExC_whilem_seen = 0;
3996     RExC_charnames = NULL;
3997     RExC_open_parens = NULL;
3998     RExC_close_parens = NULL;
3999     RExC_opend = NULL;
4000     RExC_paren_names = NULL;
4001     RExC_recurse = NULL;
4002     RExC_recurse_count = 0;
4003
4004 #if 0 /* REGC() is (currently) a NOP at the first pass.
4005        * Clever compilers notice this and complain. --jhi */
4006     REGC((U8)REG_MAGIC, (char*)RExC_emit);
4007 #endif
4008     DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log, "Starting first pass (sizing)\n"));
4009     if (reg(pRExC_state, 0, &flags,1) == NULL) {
4010         RExC_precomp = NULL;
4011         return(NULL);
4012     }
4013     DEBUG_PARSE_r({
4014         PerlIO_printf(Perl_debug_log, 
4015             "Required size %"IVdf" nodes\n"
4016             "Starting second pass (creation)\n", 
4017             (IV)RExC_size);
4018         RExC_lastnum=0; 
4019         RExC_lastparse=NULL; 
4020     });
4021     /* Small enough for pointer-storage convention?
4022        If extralen==0, this means that we will not need long jumps. */
4023     if (RExC_size >= 0x10000L && RExC_extralen)
4024         RExC_size += RExC_extralen;
4025     else
4026         RExC_extralen = 0;
4027     if (RExC_whilem_seen > 15)
4028         RExC_whilem_seen = 15;
4029
4030 #ifdef DEBUGGING
4031     /* Make room for a sentinel value at the end of the program */
4032     RExC_size++;
4033 #endif
4034
4035     /* Allocate space and zero-initialize. Note, the two step process 
4036        of zeroing when in debug mode, thus anything assigned has to 
4037        happen after that */
4038     Newxc(r, sizeof(regexp) + (unsigned)RExC_size * sizeof(regnode),
4039          char, regexp);
4040     if (r == NULL)
4041         FAIL("Regexp out of space");
4042 #ifdef DEBUGGING
4043     /* avoid reading uninitialized memory in DEBUGGING code in study_chunk() */
4044     Zero(r, sizeof(regexp) + (unsigned)RExC_size * sizeof(regnode), char);
4045 #endif
4046     /* initialization begins here */
4047     r->engine= RE_ENGINE_PTR;
4048     r->refcnt = 1;
4049     r->prelen = xend - exp;
4050     r->precomp = savepvn(RExC_precomp, r->prelen);
4051     r->subbeg = NULL;
4052 #ifdef PERL_OLD_COPY_ON_WRITE
4053     r->saved_copy = NULL;
4054 #endif
4055     r->reganch = pm->op_pmflags & PMf_COMPILETIME;
4056     r->nparens = RExC_npar - 1; /* set early to validate backrefs */
4057     r->lastparen = 0;                   /* mg.c reads this.  */
4058
4059     r->substrs = 0;                     /* Useful during FAIL. */
4060     r->startp = 0;                      /* Useful during FAIL. */
4061     r->endp = 0;                        
4062     r->swap = NULL; 
4063     r->paren_names = 0;
4064     
4065     if (RExC_seen & REG_SEEN_RECURSE) {
4066         Newxz(RExC_open_parens, RExC_npar,regnode *);
4067         SAVEFREEPV(RExC_open_parens);
4068         Newxz(RExC_close_parens,RExC_npar,regnode *);
4069         SAVEFREEPV(RExC_close_parens);
4070     }
4071
4072     /* Useful during FAIL. */
4073     Newxz(r->offsets, 2*RExC_size+1, U32); /* MJD 20001228 */
4074     if (r->offsets) {
4075         r->offsets[0] = RExC_size;
4076     }
4077     DEBUG_OFFSETS_r(PerlIO_printf(Perl_debug_log,
4078                           "%s %"UVuf" bytes for offset annotations.\n",
4079                           r->offsets ? "Got" : "Couldn't get",
4080                           (UV)((2*RExC_size+1) * sizeof(U32))));
4081
4082     RExC_rx = r;
4083
4084     /* Second pass: emit code. */
4085     RExC_flags = pm->op_pmflags;        /* don't let top level (?i) bleed */
4086     RExC_parse = exp;
4087     RExC_end = xend;
4088     RExC_naughty = 0;
4089     RExC_npar = 1;
4090     RExC_cpar = 1;
4091     RExC_emit_start = r->program;
4092     RExC_emit = r->program;
4093 #ifdef DEBUGGING
4094     /* put a sentinal on the end of the program so we can check for
4095        overwrites */
4096     r->program[RExC_size].type = 255;
4097 #endif
4098     /* Store the count of eval-groups for security checks: */
4099     RExC_emit->next_off = (RExC_seen_evals > (I32)U16_MAX) ? U16_MAX : (U16)RExC_seen_evals;
4100     REGC((U8)REG_MAGIC, (char*) RExC_emit++);
4101     r->data = 0;
4102     if (reg(pRExC_state, 0, &flags,1) == NULL)
4103         return(NULL);
4104
4105     /* XXXX To minimize changes to RE engine we always allocate
4106        3-units-long substrs field. */
4107     Newx(r->substrs, 1, struct reg_substr_data);
4108     if (RExC_recurse_count) {
4109         Newxz(RExC_recurse,RExC_recurse_count,regnode *);
4110         SAVEFREEPV(RExC_recurse);
4111     }
4112
4113 reStudy:
4114     r->minlen = minlen = sawplus = sawopen = 0;
4115     Zero(r->substrs, 1, struct reg_substr_data);
4116
4117 #ifdef TRIE_STUDY_OPT
4118     if ( restudied ) {
4119         U32 seen=RExC_seen;
4120         DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log,"Restudying\n"));
4121         
4122         RExC_state = copyRExC_state;
4123         if (seen & REG_TOP_LEVEL_BRANCHES) 
4124             RExC_seen |= REG_TOP_LEVEL_BRANCHES;
4125         else
4126             RExC_seen &= ~REG_TOP_LEVEL_BRANCHES;
4127         if (data.last_found) {
4128             SvREFCNT_dec(data.longest_fixed);
4129             SvREFCNT_dec(data.longest_float);
4130             SvREFCNT_dec(data.last_found);
4131         }
4132         StructCopy(&zero_scan_data, &data, scan_data_t);
4133     } else {
4134         StructCopy(&zero_scan_data, &data, scan_data_t);
4135         copyRExC_state = RExC_state;
4136     }
4137 #else
4138     StructCopy(&zero_scan_data, &data, scan_data_t);
4139 #endif    
4140
4141     /* Dig out information for optimizations. */
4142     r->reganch = pm->op_pmflags & PMf_COMPILETIME; /* Again? */
4143     pm->op_pmflags = RExC_flags;
4144     if (UTF)
4145         r->reganch |= ROPT_UTF8;        /* Unicode in it? */
4146     r->regstclass = NULL;
4147     if (RExC_naughty >= 10)     /* Probably an expensive pattern. */
4148         r->reganch |= ROPT_NAUGHTY;
4149     scan = r->program + 1;              /* First BRANCH. */
4150
4151     /* testing for BRANCH here tells us whether there is "must appear"
4152        data in the pattern. If there is then we can use it for optimisations */
4153     if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES)) { /*  Only one top-level choice. */
4154         I32 fake;
4155         STRLEN longest_float_length, longest_fixed_length;
4156         struct regnode_charclass_class ch_class; /* pointed to by data */
4157         int stclass_flag;
4158         I32 last_close = 0; /* pointed to by data */
4159
4160         first = scan;
4161         /* Skip introductions and multiplicators >= 1. */
4162         while ((OP(first) == OPEN && (sawopen = 1)) ||
4163                /* An OR of *one* alternative - should not happen now. */
4164             (OP(first) == BRANCH && OP(regnext(first)) != BRANCH) ||
4165             /* for now we can't handle lookbehind IFMATCH*/
4166             (OP(first) == IFMATCH && !first->flags) || 
4167             (OP(first) == PLUS) ||
4168             (OP(first) == MINMOD) ||
4169                /* An {n,m} with n>0 */
4170             (PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) ) 
4171         {
4172                 
4173                 if (OP(first) == PLUS)
4174                     sawplus = 1;
4175                 else
4176                     first += regarglen[OP(first)];
4177                 if (OP(first) == IFMATCH) {
4178                     first = NEXTOPER(first);
4179                     first += EXTRA_STEP_2ARGS;
4180                 } else  /* XXX possible optimisation for /(?=)/  */
4181                     first = NEXTOPER(first);
4182         }
4183
4184         /* Starting-point info. */
4185       again:
4186         DEBUG_PEEP("first:",first,0);
4187         /* Ignore EXACT as we deal with it later. */
4188         if (PL_regkind[OP(first)] == EXACT) {
4189             if (OP(first) == EXACT)
4190                 NOOP;   /* Empty, get anchored substr later. */
4191             else if ((OP(first) == EXACTF || OP(first) == EXACTFL))
4192                 r->regstclass = first;
4193         }
4194 #ifdef TRIE_STCLASS     
4195         else if (PL_regkind[OP(first)] == TRIE &&
4196                 ((reg_trie_data *)r->data->data[ ARG(first) ])->minlen>0) 
4197         {
4198             regnode *trie_op;
4199             /* this can happen only on restudy */
4200             if ( OP(first) == TRIE ) {
4201                 struct regnode_1 *trieop;
4202                 Newxz(trieop,1,struct regnode_1);
4203                 StructCopy(first,trieop,struct regnode_1);
4204                 trie_op=(regnode *)trieop;
4205             } else {
4206                 struct regnode_charclass *trieop;
4207                 Newxz(trieop,1,struct regnode_charclass);
4208                 StructCopy(first,trieop,struct regnode_charclass);
4209                 trie_op=(regnode *)trieop;
4210             }
4211             OP(trie_op)+=2;
4212             make_trie_failtable(pRExC_state, (regnode *)first, trie_op, 0);
4213             r->regstclass = trie_op;
4214         }
4215 #endif  
4216         else if (strchr((const char*)PL_simple,OP(first)))
4217             r->regstclass = first;
4218         else if (PL_regkind[OP(first)] == BOUND ||
4219                  PL_regkind[OP(first)] == NBOUND)
4220             r->regstclass = first;
4221         else if (PL_regkind[OP(first)] == BOL) {
4222             r->reganch |= (OP(first) == MBOL
4223                            ? ROPT_ANCH_MBOL
4224                            : (OP(first) == SBOL
4225                               ? ROPT_ANCH_SBOL
4226                               : ROPT_ANCH_BOL));
4227             first = NEXTOPER(first);
4228             goto again;
4229         }
4230         else if (OP(first) == GPOS) {
4231             r->reganch |= ROPT_ANCH_GPOS;
4232             first = NEXTOPER(first);
4233             goto again;
4234         }
4235         else if ((!sawopen || !RExC_sawback) &&
4236             (OP(first) == STAR &&
4237             PL_regkind[OP(NEXTOPER(first))] == REG_ANY) &&
4238             !(r->reganch & ROPT_ANCH) )
4239         {
4240             /* turn .* into ^.* with an implied $*=1 */
4241             const int type =
4242                 (OP(NEXTOPER(first)) == REG_ANY)
4243                     ? ROPT_ANCH_MBOL
4244                     : ROPT_ANCH_SBOL;
4245             r->reganch |= type | ROPT_IMPLICIT;
4246             first = NEXTOPER(first);
4247             goto again;
4248         }
4249         if (sawplus && (!sawopen || !RExC_sawback)
4250             && !(RExC_seen & REG_SEEN_EVAL)) /* May examine pos and $& */
4251             /* x+ must match at the 1st pos of run of x's */
4252             r->reganch |= ROPT_SKIP;
4253
4254         /* Scan is after the zeroth branch, first is atomic matcher. */
4255 #ifdef TRIE_STUDY_OPT
4256         DEBUG_PARSE_r(
4257             if (!restudied)
4258                 PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
4259                               (IV)(first - scan + 1))
4260         );
4261 #else
4262         DEBUG_PARSE_r(
4263             PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
4264                 (IV)(first - scan + 1))
4265         );
4266 #endif
4267
4268
4269         /*
4270         * If there's something expensive in the r.e., find the
4271         * longest literal string that must appear and make it the
4272         * regmust.  Resolve ties in favor of later strings, since
4273         * the regstart check works with the beginning of the r.e.
4274         * and avoiding duplication strengthens checking.  Not a
4275         * strong reason, but sufficient in the absence of others.
4276         * [Now we resolve ties in favor of the earlier string if
4277         * it happens that c_offset_min has been invalidated, since the
4278         * earlier string may buy us something the later one won't.]
4279         */
4280         
4281         data.longest_fixed = newSVpvs("");
4282         data.longest_float = newSVpvs("");
4283         data.last_found = newSVpvs("");
4284         data.longest = &(data.longest_fixed);
4285         first = scan;
4286         if (!r->regstclass) {
4287             cl_init(pRExC_state, &ch_class);
4288             data.start_class = &ch_class;
4289             stclass_flag = SCF_DO_STCLASS_AND;
4290         } else                          /* XXXX Check for BOUND? */
4291             stclass_flag = 0;
4292         data.last_closep = &last_close;
4293         
4294         minlen = study_chunk(pRExC_state, &first, &minlen, &fake, scan + RExC_size, /* Up to end */
4295             &data, -1, NULL, NULL,
4296             SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag,0);
4297
4298         
4299         CHECK_RESTUDY_GOTO;
4300
4301
4302         if ( RExC_npar == 1 && data.longest == &(data.longest_fixed)
4303              && data.last_start_min == 0 && data.last_end > 0
4304              && !RExC_seen_zerolen
4305              && (!(RExC_seen & REG_SEEN_GPOS) || (r->reganch & ROPT_ANCH_GPOS)))
4306             r->reganch |= ROPT_CHECK_ALL;
4307         scan_commit(pRExC_state, &data,&minlen);
4308         SvREFCNT_dec(data.last_found);
4309
4310         /* Note that code very similar to this but for anchored string 
4311            follows immediately below, changes may need to be made to both. 
4312            Be careful. 
4313          */
4314         longest_float_length = CHR_SVLEN(data.longest_float);
4315         if (longest_float_length
4316             || (data.flags & SF_FL_BEFORE_EOL
4317                 && (!(data.flags & SF_FL_BEFORE_MEOL)
4318                     || (RExC_flags & PMf_MULTILINE)))) 
4319         {
4320             I32 t,ml;
4321
4322             if (SvCUR(data.longest_fixed)  /* ok to leave SvCUR */
4323                 && data.offset_fixed == data.offset_float_min
4324                 && SvCUR(data.longest_fixed) == SvCUR(data.longest_float))
4325                     goto remove_float;          /* As in (a)+. */
4326
4327             /* copy the information about the longest float from the reg_scan_data
4328                over to the program. */
4329             if (SvUTF8(data.longest_float)) {
4330                 r->float_utf8 = data.longest_float;
4331                 r->float_substr = NULL;
4332             } else {
4333                 r->float_substr = data.longest_float;
4334                 r->float_utf8 = NULL;
4335             }
4336             /* float_end_shift is how many chars that must be matched that 
4337                follow this item. We calculate it ahead of time as once the
4338                lookbehind offset is added in we lose the ability to correctly
4339                calculate it.*/
4340             ml = data.minlen_float ? *(data.minlen_float) 
4341                                    : (I32)longest_float_length;
4342             r->float_end_shift = ml - data.offset_float_min
4343                 - longest_float_length + (SvTAIL(data.longest_float) != 0)
4344                 + data.lookbehind_float;
4345             r->float_min_offset = data.offset_float_min - data.lookbehind_float;
4346             r->float_max_offset = data.offset_float_max;
4347             if (data.offset_float_max < I32_MAX) /* Don't offset infinity */
4348                 r->float_max_offset -= data.lookbehind_float;
4349             
4350             t = (data.flags & SF_FL_BEFORE_EOL /* Can't have SEOL and MULTI */
4351                        && (!(data.flags & SF_FL_BEFORE_MEOL)
4352                            || (RExC_flags & PMf_MULTILINE)));
4353             fbm_compile(data.longest_float, t ? FBMcf_TAIL : 0);
4354         }
4355         else {
4356           remove_float:
4357             r->float_substr = r->float_utf8 = NULL;
4358             SvREFCNT_dec(data.longest_float);
4359             longest_float_length = 0;
4360         }
4361
4362         /* Note that code very similar to this but for floating string 
4363            is immediately above, changes may need to be made to both. 
4364            Be careful. 
4365          */
4366         longest_fixed_length = CHR_SVLEN(data.longest_fixed);
4367         if (longest_fixed_length
4368             || (data.flags & SF_FIX_BEFORE_EOL /* Cannot have SEOL and MULTI */
4369                 && (!(data.flags & SF_FIX_BEFORE_MEOL)
4370                     || (RExC_flags & PMf_MULTILINE)))) 
4371         {
4372             I32 t,ml;
4373
4374             /* copy the information about the longest fixed 
4375                from the reg_scan_data over to the program. */
4376             if (SvUTF8(data.longest_fixed)) {
4377                 r->anchored_utf8 = data.longest_fixed;
4378                 r->anchored_substr = NULL;
4379             } else {
4380                 r->anchored_substr = data.longest_fixed;
4381                 r->anchored_utf8 = NULL;
4382             }
4383             /* fixed_end_shift is how many chars that must be matched that 
4384                follow this item. We calculate it ahead of time as once the
4385                lookbehind offset is added in we lose the ability to correctly
4386                calculate it.*/
4387             ml = data.minlen_fixed ? *(data.minlen_fixed) 
4388                                    : (I32)longest_fixed_length;
4389             r->anchored_end_shift = ml - data.offset_fixed
4390                 - longest_fixed_length + (SvTAIL(data.longest_fixed) != 0)
4391                 + data.lookbehind_fixed;
4392             r->anchored_offset = data.offset_fixed - data.lookbehind_fixed;
4393
4394             t = (data.flags & SF_FIX_BEFORE_EOL /* Can't have SEOL and MULTI */
4395                  && (!(data.flags & SF_FIX_BEFORE_MEOL)
4396                      || (RExC_flags & PMf_MULTILINE)));
4397             fbm_compile(data.longest_fixed, t ? FBMcf_TAIL : 0);
4398         }
4399         else {
4400             r->anchored_substr = r->anchored_utf8 = NULL;
4401             SvREFCNT_dec(data.longest_fixed);
4402             longest_fixed_length = 0;
4403         }
4404         if (r->regstclass
4405             && (OP(r->regstclass) == REG_ANY || OP(r->regstclass) == SANY))
4406             r->regstclass = NULL;
4407         if ((!(r->anchored_substr || r->anchored_utf8) || r->anchored_offset)
4408             && stclass_flag
4409             && !(data.start_class->flags & ANYOF_EOS)
4410             && !cl_is_anything(data.start_class))
4411         {
4412             const I32 n = add_data(pRExC_state, 1, "f");
4413
4414             Newx(RExC_rx->data->data[n], 1,
4415                 struct regnode_charclass_class);
4416             StructCopy(data.start_class,
4417                        (struct regnode_charclass_class*)RExC_rx->data->data[n],
4418                        struct regnode_charclass_class);
4419             r->regstclass = (regnode*)RExC_rx->data->data[n];
4420             r->reganch &= ~ROPT_SKIP;   /* Used in find_byclass(). */
4421             DEBUG_COMPILE_r({ SV *sv = sv_newmortal();
4422                       regprop(r, sv, (regnode*)data.start_class);
4423                       PerlIO_printf(Perl_debug_log,
4424                                     "synthetic stclass \"%s\".\n",
4425                                     SvPVX_const(sv));});
4426         }
4427
4428         /* A temporary algorithm prefers floated substr to fixed one to dig more info. */
4429         if (longest_fixed_length > longest_float_length) {
4430             r->check_end_shift = r->anchored_end_shift;
4431             r->check_substr = r->anchored_substr;
4432             r->check_utf8 = r->anchored_utf8;
4433             r->check_offset_min = r->check_offset_max = r->anchored_offset;
4434             if (r->reganch & ROPT_ANCH_SINGLE)
4435                 r->reganch |= ROPT_NOSCAN;
4436         }
4437         else {
4438             r->check_end_shift = r->float_end_shift;
4439             r->check_substr = r->float_substr;
4440             r->check_utf8 = r->float_utf8;
4441             r->check_offset_min = r->float_min_offset;
4442             r->check_offset_max = r->float_max_offset;
4443         }
4444         /* XXXX Currently intuiting is not compatible with ANCH_GPOS.
4445            This should be changed ASAP!  */
4446         if ((r->check_substr || r->check_utf8) && !(r->reganch & ROPT_ANCH_GPOS)) {
4447             r->reganch |= RE_USE_INTUIT;
4448             if (SvTAIL(r->check_substr ? r->check_substr : r->check_utf8))
4449                 r->reganch |= RE_INTUIT_TAIL;
4450         }
4451         /* XXX Unneeded? dmq (shouldn't as this is handled elsewhere)
4452         if ( (STRLEN)minlen < longest_float_length )
4453             minlen= longest_float_length;
4454         if ( (STRLEN)minlen < longest_fixed_length )
4455             minlen= longest_fixed_length;     
4456         */
4457     }
4458     else {
4459         /* Several toplevels. Best we can is to set minlen. */
4460         I32 fake;
4461         struct regnode_charclass_class ch_class;
4462         I32 last_close = 0;
4463         
4464         DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log, "\nMulti Top Level\n"));
4465
4466         scan = r->program + 1;
4467         cl_init(pRExC_state, &ch_class);
4468         data.start_class = &ch_class;
4469         data.last_closep = &last_close;
4470
4471         
4472         minlen = study_chunk(pRExC_state, &scan, &minlen, &fake, scan + RExC_size,
4473             &data, -1, NULL, NULL, SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS,0);
4474         
4475         CHECK_RESTUDY_GOTO;
4476
4477         r->check_substr = r->check_utf8 = r->anchored_substr = r->anchored_utf8
4478                 = r->float_substr = r->float_utf8 = NULL;
4479         if (!(data.start_class->flags & ANYOF_EOS)
4480             && !cl_is_anything(data.start_class))
4481         {
4482             const I32 n = add_data(pRExC_state, 1, "f");
4483
4484             Newx(RExC_rx->data->data[n], 1,
4485                 struct regnode_charclass_class);
4486             StructCopy(data.start_class,
4487                        (struct regnode_charclass_class*)RExC_rx->data->data[n],
4488                        struct regnode_charclass_class);
4489             r->regstclass = (regnode*)RExC_rx->data->data[n];
4490             r->reganch &= ~ROPT_SKIP;   /* Used in find_byclass(). */
4491             DEBUG_COMPILE_r({ SV* sv = sv_newmortal();
4492                       regprop(r, sv, (regnode*)data.start_class);
4493                       PerlIO_printf(Perl_debug_log,
4494                                     "synthetic stclass \"%s\".\n",
4495                                     SvPVX_const(sv));});
4496         }
4497     }
4498
4499     /* Guard against an embedded (?=) or (?<=) with a longer minlen than
4500        the "real" pattern. */
4501     DEBUG_OPTIMISE_r({
4502         PerlIO_printf(Perl_debug_log,"minlen: %"IVdf" r->minlen:%"IVdf"\n",
4503             minlen, r->minlen);
4504     });
4505     r->minlenret = minlen;
4506     if (r->minlen < minlen) 
4507         r->minlen = minlen;
4508     
4509     if (RExC_seen & REG_SEEN_GPOS)
4510         r->reganch |= ROPT_GPOS_SEEN;
4511     if (RExC_seen & REG_SEEN_LOOKBEHIND)
4512         r->reganch |= ROPT_LOOKBEHIND_SEEN;
4513     if (RExC_seen & REG_SEEN_EVAL)
4514         r->reganch |= ROPT_EVAL_SEEN;
4515     if (RExC_seen & REG_SEEN_CANY)
4516         r->reganch |= ROPT_CANY_SEEN;
4517     if (RExC_seen & REG_SEEN_VERBARG)
4518         r->reganch |= ROPT_VERBARG_SEEN;
4519     if (RExC_seen & REG_SEEN_CUTGROUP)
4520         r->reganch |= ROPT_CUTGROUP_SEEN;
4521     if (RExC_paren_names)
4522         r->paren_names = (HV*)SvREFCNT_inc(RExC_paren_names);
4523     else
4524         r->paren_names = NULL;
4525                 
4526     if (RExC_recurse_count) {
4527         for ( ; RExC_recurse_count ; RExC_recurse_count-- ) {
4528             const regnode *scan = RExC_recurse[RExC_recurse_count-1];
4529             ARG2L_SET( scan, RExC_open_parens[ARG(scan)-1] - scan );
4530         }
4531     }
4532     Newxz(r->startp, RExC_npar, I32);
4533     Newxz(r->endp, RExC_npar, I32);
4534     /* assume we don't need to swap parens around before we match */
4535
4536     DEBUG_DUMP_r({
4537         PerlIO_printf(Perl_debug_log,"Final program:\n");
4538         regdump(r);
4539     });
4540     DEBUG_OFFSETS_r(if (r->offsets) {
4541         const U32 len = r->offsets[0];
4542         U32 i;
4543         GET_RE_DEBUG_FLAGS_DECL;
4544         PerlIO_printf(Perl_debug_log, "Offsets: [%"UVuf"]\n\t", (UV)r->offsets[0]);
4545         for (i = 1; i <= len; i++) {
4546             if (r->offsets[i*2-1] || r->offsets[i*2])
4547                 PerlIO_printf(Perl_debug_log, "%"UVuf":%"UVuf"[%"UVuf"] ",
4548                 (UV)i, (UV)r->offsets[i*2-1], (UV)r->offsets[i*2]);
4549             }
4550         PerlIO_printf(Perl_debug_log, "\n");
4551     });
4552     return(r);
4553     END_BLOCK    
4554 }
4555
4556 #undef CORE_ONLY_BLOCK
4557 #undef END_BLOCK
4558 #undef RE_ENGINE_PTR
4559
4560 #ifndef PERL_IN_XSUB_RE
4561 SV*
4562 Perl_reg_named_buff_sv(pTHX_ SV* namesv)
4563 {
4564     I32 parno = 0; /* no match */
4565     if (PL_curpm) {
4566         const REGEXP * const rx = PM_GETRE(PL_curpm);
4567         if (rx && rx->paren_names) {            
4568             HE *he_str = hv_fetch_ent( rx->paren_names, namesv, 0, 0 );
4569             if (he_str) {
4570                 IV i;
4571                 SV* sv_dat=HeVAL(he_str);
4572                 I32 *nums=(I32*)SvPVX(sv_dat);
4573                 for ( i=0; i<SvIVX(sv_dat); i++ ) {
4574                     if ((I32)(rx->lastparen) >= nums[i] &&
4575                         rx->endp[nums[i]] != -1) 
4576                     {
4577                         parno = nums[i];
4578                         break;
4579                     }
4580                 }
4581             }
4582         }
4583     }
4584     if ( !parno ) {
4585         return 0;
4586     } else {
4587         GV *gv_paren;
4588         SV *sv= sv_newmortal();
4589         Perl_sv_setpvf(aTHX_ sv, "%"IVdf,(IV)parno);
4590         gv_paren= Perl_gv_fetchsv(aTHX_ sv, GV_ADD, SVt_PVGV);
4591         return GvSVn(gv_paren);
4592     }
4593 }
4594 #endif
4595
4596 /* Scans the name of a named buffer from the pattern.
4597  * If flags is REG_RSN_RETURN_NULL returns null.
4598  * If flags is REG_RSN_RETURN_NAME returns an SV* containing the name
4599  * If flags is REG_RSN_RETURN_DATA returns the data SV* corresponding
4600  * to the parsed name as looked up in the RExC_paren_names hash.
4601  * If there is an error throws a vFAIL().. type exception.
4602  */
4603
4604 #define REG_RSN_RETURN_NULL    0
4605 #define REG_RSN_RETURN_NAME    1
4606 #define REG_RSN_RETURN_DATA    2
4607
4608 STATIC SV*
4609 S_reg_scan_name(pTHX_ RExC_state_t *pRExC_state, U32 flags) {
4610     char *name_start = RExC_parse;
4611     if ( UTF ) {
4612         STRLEN numlen;
4613         while( isIDFIRST_uni(utf8n_to_uvchr((U8*)RExC_parse,
4614             RExC_end - RExC_parse, &numlen, UTF8_ALLOW_DEFAULT)))
4615         {
4616                 RExC_parse += numlen;
4617         }
4618     } else {
4619         while( isIDFIRST(*RExC_parse) )
4620             RExC_parse++;
4621     }
4622     if ( flags ) {
4623         SV* sv_name = sv_2mortal(Perl_newSVpvn(aTHX_ name_start,
4624             (int)(RExC_parse - name_start)));
4625         if (UTF)
4626             SvUTF8_on(sv_name);
4627         if ( flags == REG_RSN_RETURN_NAME)
4628             return sv_name;
4629         else if (flags==REG_RSN_RETURN_DATA) {
4630             HE *he_str = NULL;
4631             SV *sv_dat = NULL;
4632             if ( ! sv_name )      /* should not happen*/
4633                 Perl_croak(aTHX_ "panic: no svname in reg_scan_name");
4634             if (RExC_paren_names)
4635                 he_str = hv_fetch_ent( RExC_paren_names, sv_name, 0, 0 );
4636             if ( he_str )
4637                 sv_dat = HeVAL(he_str);
4638             if ( ! sv_dat )
4639                 vFAIL("Reference to nonexistent named group");
4640             return sv_dat;
4641         }
4642         else {
4643             Perl_croak(aTHX_ "panic: bad flag in reg_scan_name");
4644         }
4645         /* NOT REACHED */
4646     }
4647     return NULL;
4648 }
4649
4650 #define DEBUG_PARSE_MSG(funcname)     DEBUG_PARSE_r({           \
4651     int rem=(int)(RExC_end - RExC_parse);                       \
4652     int cut;                                                    \
4653     int num;                                                    \
4654     int iscut=0;                                                \
4655     if (rem>10) {                                               \
4656         rem=10;                                                 \
4657         iscut=1;                                                \
4658     }                                                           \
4659     cut=10-rem;                                                 \
4660     if (RExC_lastparse!=RExC_parse)                             \
4661         PerlIO_printf(Perl_debug_log," >%.*s%-*s",              \
4662             rem, RExC_parse,                                    \
4663             cut + 4,                                            \
4664             iscut ? "..." : "<"                                 \
4665         );                                                      \
4666     else                                                        \
4667         PerlIO_printf(Perl_debug_log,"%16s","");                \
4668                                                                 \
4669     if (SIZE_ONLY)                                              \
4670        num=RExC_size;                                           \
4671     else                                                        \
4672        num=REG_NODE_NUM(RExC_emit);                             \
4673     if (RExC_lastnum!=num)                                      \
4674        PerlIO_printf(Perl_debug_log,"|%4d",num);                \
4675     else                                                        \
4676        PerlIO_printf(Perl_debug_log,"|%4s","");                 \
4677     PerlIO_printf(Perl_debug_log,"|%*s%-4s",                    \
4678         (int)((depth*2)), "",                                   \
4679         (funcname)                                              \
4680     );                                                          \
4681     RExC_lastnum=num;                                           \
4682     RExC_lastparse=RExC_parse;                                  \
4683 })
4684
4685
4686
4687 #define DEBUG_PARSE(funcname)     DEBUG_PARSE_r({           \
4688     DEBUG_PARSE_MSG((funcname));                            \
4689     PerlIO_printf(Perl_debug_log,"%4s","\n");               \
4690 })
4691 #define DEBUG_PARSE_FMT(funcname,fmt,args)     DEBUG_PARSE_r({           \
4692     DEBUG_PARSE_MSG((funcname));                            \
4693     PerlIO_printf(Perl_debug_log,fmt "\n",args);               \
4694 })
4695 /*
4696  - reg - regular expression, i.e. main body or parenthesized thing
4697  *
4698  * Caller must absorb opening parenthesis.
4699  *
4700  * Combining parenthesis handling with the base level of regular expression
4701  * is a trifle forced, but the need to tie the tails of the branches to what
4702  * follows makes it hard to avoid.
4703  */
4704 #define REGTAIL(x,y,z) regtail((x),(y),(z),depth+1)
4705 #ifdef DEBUGGING
4706 #define REGTAIL_STUDY(x,y,z) regtail_study((x),(y),(z),depth+1)
4707 #else
4708 #define REGTAIL_STUDY(x,y,z) regtail((x),(y),(z),depth+1)
4709 #endif
4710
4711 /* this idea is borrowed from STR_WITH_LEN in handy.h */
4712 #define CHECK_WORD(s,v,l)  \
4713     (((sizeof(s)-1)==(l)) && (strnEQ(start_verb, (s ""), (sizeof(s)-1))))
4714
4715 STATIC regnode *
4716 S_reg(pTHX_ RExC_state_t *pRExC_state, I32 paren, I32 *flagp,U32 depth)
4717     /* paren: Parenthesized? 0=top, 1=(, inside: changed to letter. */
4718 {
4719     dVAR;
4720     register regnode *ret;              /* Will be the head of the group. */
4721     register regnode *br;
4722     register regnode *lastbr;
4723     register regnode *ender = NULL;
4724     register I32 parno = 0;
4725     I32 flags;
4726     const I32 oregflags = RExC_flags;
4727     bool have_branch = 0;
4728     bool is_open = 0;
4729
4730     /* for (?g), (?gc), and (?o) warnings; warning
4731        about (?c) will warn about (?g) -- japhy    */
4732
4733 #define WASTED_O  0x01
4734 #define WASTED_G  0x02
4735 #define WASTED_C  0x04
4736 #define WASTED_GC (0x02|0x04)
4737     I32 wastedflags = 0x00;
4738
4739     char * parse_start = RExC_parse; /* MJD */
4740     char * const oregcomp_parse = RExC_parse;
4741
4742     GET_RE_DEBUG_FLAGS_DECL;
4743     DEBUG_PARSE("reg ");
4744
4745
4746     *flagp = 0;                         /* Tentatively. */
4747
4748
4749     /* Make an OPEN node, if parenthesized. */
4750     if (paren) {
4751         if ( *RExC_parse == '*') { /* (*VERB:ARG) */
4752             char *start_verb = RExC_parse;
4753             STRLEN verb_len = 0;
4754             char *start_arg = NULL;
4755             unsigned char op = 0;
4756             int argok = 1;
4757             int internal_argval = 0; /* internal_argval is only useful if !argok */
4758             while ( *RExC_parse && *RExC_parse != ')' ) {
4759                 if ( *RExC_parse == ':' ) {
4760                     start_arg = RExC_parse + 1;
4761                     break;
4762                 }
4763                 RExC_parse++;
4764             }
4765             ++start_verb;
4766             verb_len = RExC_parse - start_verb;
4767             if ( start_arg ) {
4768                 RExC_parse++;
4769                 while ( *RExC_parse && *RExC_parse != ')' ) 
4770                     RExC_parse++;
4771                 if ( *RExC_parse != ')' ) 
4772                     vFAIL("Unterminated verb pattern argument");
4773                 if ( RExC_parse == start_arg )
4774                     start_arg = NULL;
4775             } else {
4776                 if ( *RExC_parse != ')' )
4777                     vFAIL("Unterminated verb pattern");
4778             }
4779             
4780             switch ( *start_verb ) {
4781             case 'A':  /* (*ACCEPT) */
4782                 if ( CHECK_WORD("ACCEPT",start_verb,verb_len) ) {
4783                     op = ACCEPT;
4784                     internal_argval = RExC_nestroot;
4785                 }
4786                 break;
4787             case 'C':  /* (*COMMIT) */
4788                 if ( CHECK_WORD("COMMIT",start_verb,verb_len) )
4789                     op = COMMIT;
4790                 break;
4791             case 'F':  /* (*FAIL) */
4792                 if ( verb_len==1 || CHECK_WORD("FAIL",start_verb,verb_len) ) {
4793                     op = OPFAIL;
4794                     argok = 0;
4795                 }
4796                 break;
4797             case ':':  /* (*:NAME) */
4798             case 'M':  /* (*MARK:NAME) */
4799                 if ( verb_len==0 || CHECK_WORD("MARK",start_verb,verb_len) ) {
4800                     op = MARKPOINT;
4801                     argok = -1;
4802                 }
4803                 break;
4804             case 'P':  /* (*PRUNE) */
4805                 if ( CHECK_WORD("PRUNE",start_verb,verb_len) )
4806                     op = PRUNE;
4807                 break;
4808             case 'S':   /* (*SKIP) */  
4809                 if ( CHECK_WORD("SKIP",start_verb,verb_len) ) 
4810                     op = SKIP;
4811                 break;
4812             case 'T':  /* (*THEN) */
4813                 /* [19:06] <TimToady> :: is then */
4814                 if ( CHECK_WORD("THEN",start_verb,verb_len) ) {
4815                     op = CUTGROUP;
4816                     RExC_seen |= REG_SEEN_CUTGROUP;
4817                 }
4818                 break;
4819             }
4820             if ( ! op ) {
4821                 RExC_parse++;
4822                 vFAIL3("Unknown verb pattern '%.*s'",
4823                     verb_len, start_verb);
4824             }
4825             if ( argok ) {
4826                 if ( start_arg && internal_argval ) {
4827                     vFAIL3("Verb pattern '%.*s' may not have an argument",
4828                         verb_len, start_verb); 
4829                 } else if ( argok < 0 && !start_arg ) {
4830                     vFAIL3("Verb pattern '%.*s' has a mandatory argument",
4831                         verb_len, start_verb);    
4832                 } else {
4833                     ret = reganode(pRExC_state, op, internal_argval);
4834                     if ( ! internal_argval && ! SIZE_ONLY ) {
4835                         if (start_arg) {
4836                             SV *sv = newSVpvn( start_arg, RExC_parse - start_arg);
4837                             ARG(ret) = add_data( pRExC_state, 1, "S" );
4838                             RExC_rx->data->data[ARG(ret)]=(void*)sv;
4839                             ret->flags = 0;
4840                         } else {
4841                             ret->flags = 1; 
4842                         }
4843                     }               
4844                 }
4845                 if (!internal_argval)
4846                     RExC_seen |= REG_SEEN_VERBARG;
4847             } else if ( start_arg ) {
4848                 vFAIL3("Verb pattern '%.*s' may not have an argument",
4849                         verb_len, start_verb);    
4850             } else {
4851                 ret = reg_node(pRExC_state, op);
4852             }
4853             nextchar(pRExC_state);
4854             return ret;
4855         } else 
4856         if (*RExC_parse == '?') { /* (?...) */
4857             U32 posflags = 0, negflags = 0;
4858             U32 *flagsp = &posflags;
4859             bool is_logical = 0;
4860             const char * const seqstart = RExC_parse;
4861
4862             RExC_parse++;
4863             paren = *RExC_parse++;
4864             ret = NULL;                 /* For look-ahead/behind. */
4865             switch (paren) {
4866
4867             case '<':           /* (?<...) */
4868                 if (*RExC_parse == '!')
4869                     paren = ',';
4870                 else if (*RExC_parse != '=') 
4871                 {               /* (?<...>) */
4872                     char *name_start;
4873                     SV *svname;
4874                     paren= '>';
4875             case '\'':          /* (?'...') */
4876                     name_start= RExC_parse;
4877                     svname = reg_scan_name(pRExC_state,
4878                         SIZE_ONLY ?  /* reverse test from the others */
4879                         REG_RSN_RETURN_NAME : 
4880                         REG_RSN_RETURN_NULL);
4881                     if (RExC_parse == name_start)
4882                         goto unknown;
4883                     if (*RExC_parse != paren)
4884                         vFAIL2("Sequence (?%c... not terminated",
4885                             paren=='>' ? '<' : paren);
4886                     if (SIZE_ONLY) {
4887                         HE *he_str;
4888                         SV *sv_dat = NULL;
4889                         if (!svname) /* shouldnt happen */
4890                             Perl_croak(aTHX_
4891                                 "panic: reg_scan_name returned NULL");
4892                         if (!RExC_paren_names) {
4893                             RExC_paren_names= newHV();
4894                             sv_2mortal((SV*)RExC_paren_names);
4895                         }
4896                         he_str = hv_fetch_ent( RExC_paren_names, svname, 1, 0 );
4897                         if ( he_str )
4898                             sv_dat = HeVAL(he_str);
4899                         if ( ! sv_dat ) {
4900                             /* croak baby croak */
4901                             Perl_croak(aTHX_
4902                                 "panic: paren_name hash element allocation failed");
4903                         } else if ( SvPOK(sv_dat) ) {
4904                             IV count=SvIV(sv_dat);
4905                             I32 *pv=(I32*)SvGROW(sv_dat,SvCUR(sv_dat)+sizeof(I32)+1);
4906                             SvCUR_set(sv_dat,SvCUR(sv_dat)+sizeof(I32));
4907                             pv[count]=RExC_npar;
4908                             SvIVX(sv_dat)++;
4909                         } else {
4910                             (void)SvUPGRADE(sv_dat,SVt_PVNV);
4911                             sv_setpvn(sv_dat, (char *)&(RExC_npar), sizeof(I32));
4912                             SvIOK_on(sv_dat);
4913                             SvIVX(sv_dat)= 1;
4914                         }
4915
4916                         /*sv_dump(sv_dat);*/
4917                     }
4918                     nextchar(pRExC_state);
4919                     paren = 1;
4920                     goto capturing_parens;
4921                 }
4922                 RExC_seen |= REG_SEEN_LOOKBEHIND;
4923                 RExC_parse++;
4924             case '=':           /* (?=...) */
4925             case '!':           /* (?!...) */
4926                 RExC_seen_zerolen++;
4927                 if (*RExC_parse == ')') {
4928                     ret=reg_node(pRExC_state, OPFAIL);
4929                     nextchar(pRExC_state);
4930                     return ret;
4931                 }
4932             case ':':           /* (?:...) */
4933             case '>':           /* (?>...) */
4934                 break;
4935             case '$':           /* (?$...) */
4936             case '@':           /* (?@...) */
4937                 vFAIL2("Sequence (?%c...) not implemented", (int)paren);
4938                 break;
4939             case '#':           /* (?#...) */
4940                 while (*RExC_parse && *RExC_parse != ')')
4941                     RExC_parse++;
4942                 if (*RExC_parse != ')')
4943                     FAIL("Sequence (?#... not terminated");
4944                 nextchar(pRExC_state);
4945                 *flagp = TRYAGAIN;
4946                 return NULL;
4947             case '0' :           /* (?0) */
4948             case 'R' :           /* (?R) */
4949                 if (*RExC_parse != ')')
4950                     FAIL("Sequence (?R) not terminated");
4951                 ret = reg_node(pRExC_state, GOSTART);
4952                 nextchar(pRExC_state);
4953                 return ret;
4954                 /*notreached*/
4955             { /* named and numeric backreferences */
4956                 I32 num;
4957                 char * parse_start;
4958             case '&':            /* (?&NAME) */
4959                 parse_start = RExC_parse - 1;
4960                 {
4961                     SV *sv_dat = reg_scan_name(pRExC_state,
4962                         SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
4963                      num = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
4964                 }
4965                 goto gen_recurse_regop;
4966                 /* NOT REACHED */
4967             case '+':
4968                 if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
4969                     RExC_parse++;
4970                     vFAIL("Illegal pattern");
4971                 }
4972                 goto parse_recursion;
4973                 /* NOT REACHED*/
4974             case '-': /* (?-1) */
4975                 if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
4976                     RExC_parse--; /* rewind to let it be handled later */
4977                     goto parse_flags;
4978                 } 
4979                 /*FALLTHROUGH */
4980             case '1': case '2': case '3': case '4': /* (?1) */
4981             case '5': case '6': case '7': case '8': case '9':
4982                 RExC_parse--;
4983               parse_recursion:
4984                 num = atoi(RExC_parse);
4985                 parse_start = RExC_parse - 1; /* MJD */
4986                 if (*RExC_parse == '-')
4987                     RExC_parse++;
4988                 while (isDIGIT(*RExC_parse))
4989                         RExC_parse++;
4990                 if (*RExC_parse!=')') 
4991                     vFAIL("Expecting close bracket");
4992                         
4993               gen_recurse_regop:
4994                 if ( paren == '-' ) {
4995                     /*
4996                     Diagram of capture buffer numbering.
4997                     Top line is the normal capture buffer numbers
4998                     Botton line is the negative indexing as from
4999                     the X (the (?-2))
5000
5001                     +   1 2    3 4 5 X          6 7
5002                        /(a(x)y)(a(b(c(?-2)d)e)f)(g(h))/
5003                     -   5 4    3 2 1 X          x x
5004
5005                     */
5006                     num = RExC_npar + num;
5007                     if (num < 1)  {
5008                         RExC_parse++;
5009                         vFAIL("Reference to nonexistent group");
5010                     }
5011                 } else if ( paren == '+' ) {
5012                     num = RExC_npar + num - 1;
5013                 }
5014
5015                 ret = reganode(pRExC_state, GOSUB, num);
5016                 if (!SIZE_ONLY) {
5017                     if (num > (I32)RExC_rx->nparens) {
5018                         RExC_parse++;
5019                         vFAIL("Reference to nonexistent group");
5020                     }
5021                     ARG2L_SET( ret, RExC_recurse_count++);
5022                     RExC_emit++;
5023                     DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
5024                         "Recurse #%"UVuf" to %"IVdf"\n", (UV)ARG(ret), (IV)ARG2L(ret)));
5025                 } else {
5026                     RExC_size++;
5027                 }
5028                 RExC_seen |= REG_SEEN_RECURSE;
5029                 Set_Node_Length(ret, 1 + regarglen[OP(ret)]); /* MJD */
5030                 Set_Node_Offset(ret, parse_start); /* MJD */
5031
5032                 nextchar(pRExC_state);
5033                 return ret;
5034             } /* named and numeric backreferences */
5035             /* NOT REACHED */
5036
5037             case 'p':           /* (?p...) */
5038                 if (SIZE_ONLY && ckWARN2(WARN_DEPRECATED, WARN_REGEXP))
5039                     vWARNdep(RExC_parse, "(?p{}) is deprecated - use (??{})");
5040                 /* FALL THROUGH*/
5041             case '?':           /* (??...) */
5042                 is_logical = 1;
5043                 if (*RExC_parse != '{')
5044                     goto unknown;
5045                 paren = *RExC_parse++;
5046                 /* FALL THROUGH */
5047             case '{':           /* (?{...}) */
5048             {
5049                 I32 count = 1, n = 0;
5050                 char c;
5051                 char *s = RExC_parse;
5052
5053                 RExC_seen_zerolen++;
5054                 RExC_seen |= REG_SEEN_EVAL;
5055                 while (count && (c = *RExC_parse)) {
5056                     if (c == '\\') {
5057                         if (RExC_parse[1])
5058                             RExC_parse++;
5059                     }
5060                     else if (c == '{')
5061                         count++;
5062                     else if (c == '}')
5063                         count--;
5064                     RExC_parse++;
5065                 }
5066                 if (*RExC_parse != ')') {
5067                     RExC_parse = s;             
5068                     vFAIL("Sequence (?{...}) not terminated or not {}-balanced");
5069                 }
5070                 if (!SIZE_ONLY) {
5071                     PAD *pad;
5072                     OP_4tree *sop, *rop;
5073                     SV * const sv = newSVpvn(s, RExC_parse - 1 - s);
5074
5075                     ENTER;
5076                     Perl_save_re_context(aTHX);
5077                     rop = sv_compile_2op(sv, &sop, "re", &pad);
5078                     sop->op_private |= OPpREFCOUNTED;
5079                     /* re_dup will OpREFCNT_inc */
5080                     OpREFCNT_set(sop, 1);
5081                     LEAVE;
5082
5083                     n = add_data(pRExC_state, 3, "nop");
5084                     RExC_rx->data->data[n] = (void*)rop;
5085                     RExC_rx->data->data[n+1] = (void*)sop;
5086                     RExC_rx->data->data[n+2] = (void*)pad;
5087                     SvREFCNT_dec(sv);
5088                 }
5089                 else {                                          /* First pass */
5090                     if (PL_reginterp_cnt < ++RExC_seen_evals
5091                         && IN_PERL_RUNTIME)
5092                         /* No compiled RE interpolated, has runtime
5093                            components ===> unsafe.  */
5094                         FAIL("Eval-group not allowed at runtime, use re 'eval'");
5095                     if (PL_tainting && PL_tainted)
5096                         FAIL("Eval-group in insecure regular expression");
5097 #if PERL_VERSION > 8
5098                     if (IN_PERL_COMPILETIME)
5099                         PL_cv_has_eval = 1;
5100 #endif
5101                 }
5102
5103                 nextchar(pRExC_state);
5104                 if (is_logical) {
5105                     ret = reg_node(pRExC_state, LOGICAL);
5106                     if (!SIZE_ONLY)
5107                         ret->flags = 2;
5108                     REGTAIL(pRExC_state, ret, reganode(pRExC_state, EVAL, n));
5109                     /* deal with the length of this later - MJD */
5110                     return ret;
5111                 }
5112                 ret = reganode(pRExC_state, EVAL, n);
5113                 Set_Node_Length(ret, RExC_parse - parse_start + 1);
5114                 Set_Node_Offset(ret, parse_start);
5115                 return ret;
5116             }
5117             case '(':           /* (?(?{...})...) and (?(?=...)...) */
5118             {
5119                 int is_define= 0;
5120                 if (RExC_parse[0] == '?') {        /* (?(?...)) */
5121                     if (RExC_parse[1] == '=' || RExC_parse[1] == '!'
5122                         || RExC_parse[1] == '<'
5123                         || RExC_parse[1] == '{') { /* Lookahead or eval. */
5124                         I32 flag;
5125                         
5126                         ret = reg_node(pRExC_state, LOGICAL);
5127                         if (!SIZE_ONLY)
5128                             ret->flags = 1;
5129                         REGTAIL(pRExC_state, ret, reg(pRExC_state, 1, &flag,depth+1));
5130                         goto insert_if;
5131                     }
5132                 }
5133                 else if ( RExC_parse[0] == '<'     /* (?(<NAME>)...) */
5134                          || RExC_parse[0] == '\'' ) /* (?('NAME')...) */
5135                 {
5136                     char ch = RExC_parse[0] == '<' ? '>' : '\'';
5137                     char *name_start= RExC_parse++;
5138                     I32 num = 0;
5139                     SV *sv_dat=reg_scan_name(pRExC_state,
5140                         SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
5141                     if (RExC_parse == name_start || *RExC_parse != ch)
5142                         vFAIL2("Sequence (?(%c... not terminated",
5143                             (ch == '>' ? '<' : ch));
5144                     RExC_parse++;
5145                     if (!SIZE_ONLY) {
5146                         num = add_data( pRExC_state, 1, "S" );
5147                         RExC_rx->data->data[num]=(void*)sv_dat;
5148                         SvREFCNT_inc(sv_dat);
5149                     }
5150                     ret = reganode(pRExC_state,NGROUPP,num);
5151                     goto insert_if_check_paren;
5152                 }
5153                 else if (RExC_parse[0] == 'D' &&
5154                          RExC_parse[1] == 'E' &&
5155                          RExC_parse[2] == 'F' &&
5156                          RExC_parse[3] == 'I' &&
5157                          RExC_parse[4] == 'N' &&
5158                          RExC_parse[5] == 'E')
5159                 {
5160                     ret = reganode(pRExC_state,DEFINEP,0);
5161                     RExC_parse +=6 ;
5162                     is_define = 1;
5163                     goto insert_if_check_paren;
5164                 }
5165                 else if (RExC_parse[0] == 'R') {
5166                     RExC_parse++;
5167                     parno = 0;
5168                     if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
5169                         parno = atoi(RExC_parse++);
5170                         while (isDIGIT(*RExC_parse))
5171                             RExC_parse++;
5172                     } else if (RExC_parse[0] == '&') {
5173                         SV *sv_dat;
5174                         RExC_parse++;
5175                         sv_dat = reg_scan_name(pRExC_state,
5176                             SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
5177                         parno = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
5178                     }
5179                     ret = reganode(pRExC_state,INSUBP,parno); 
5180                     goto insert_if_check_paren;
5181                 }
5182                 else if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
5183                     /* (?(1)...) */
5184                     char c;
5185                     parno = atoi(RExC_parse++);
5186
5187                     while (isDIGIT(*RExC_parse))
5188                         RExC_parse++;
5189                     ret = reganode(pRExC_state, GROUPP, parno);
5190
5191                  insert_if_check_paren:
5192                     if ((c = *nextchar(pRExC_state)) != ')')
5193                         vFAIL("Switch condition not recognized");
5194                   insert_if:
5195                     REGTAIL(pRExC_state, ret, reganode(pRExC_state, IFTHEN, 0));
5196                     br = regbranch(pRExC_state, &flags, 1,depth+1);
5197                     if (br == NULL)
5198                         br = reganode(pRExC_state, LONGJMP, 0);
5199                     else
5200                         REGTAIL(pRExC_state, br, reganode(pRExC_state, LONGJMP, 0));
5201                     c = *nextchar(pRExC_state);
5202                     if (flags&HASWIDTH)
5203                         *flagp |= HASWIDTH;
5204                     if (c == '|') {
5205                         if (is_define) 
5206                             vFAIL("(?(DEFINE)....) does not allow branches");
5207                         lastbr = reganode(pRExC_state, IFTHEN, 0); /* Fake one for optimizer. */
5208                         regbranch(pRExC_state, &flags, 1,depth+1);
5209                         REGTAIL(pRExC_state, ret, lastbr);
5210                         if (flags&HASWIDTH)
5211                             *flagp |= HASWIDTH;
5212                         c = *nextchar(pRExC_state);
5213                     }
5214                     else
5215                         lastbr = NULL;
5216                     if (c != ')')
5217                         vFAIL("Switch (?(condition)... contains too many branches");
5218                     ender = reg_node(pRExC_state, TAIL);
5219                     REGTAIL(pRExC_state, br, ender);
5220                     if (lastbr) {
5221                         REGTAIL(pRExC_state, lastbr, ender);
5222                         REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender);
5223                     }
5224                     else
5225                         REGTAIL(pRExC_state, ret, ender);
5226                     return ret;
5227                 }
5228                 else {
5229                     vFAIL2("Unknown switch condition (?(%.2s", RExC_parse);
5230                 }
5231             }
5232             case 0:
5233                 RExC_parse--; /* for vFAIL to print correctly */
5234                 vFAIL("Sequence (? incomplete");
5235                 break;
5236             default:
5237                 --RExC_parse;
5238               parse_flags:      /* (?i) */
5239                 while (*RExC_parse && strchr("iogcmsx", *RExC_parse)) {
5240                     /* (?g), (?gc) and (?o) are useless here
5241                        and must be globally applied -- japhy */
5242
5243                     if (*RExC_parse == 'o' || *RExC_parse == 'g') {
5244                         if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
5245                             const I32 wflagbit = *RExC_parse == 'o' ? WASTED_O : WASTED_G;
5246                             if (! (wastedflags & wflagbit) ) {
5247                                 wastedflags |= wflagbit;
5248                                 vWARN5(
5249                                     RExC_parse + 1,
5250                                     "Useless (%s%c) - %suse /%c modifier",
5251                                     flagsp == &negflags ? "?-" : "?",
5252                                     *RExC_parse,
5253                                     flagsp == &negflags ? "don't " : "",
5254                                     *RExC_parse
5255                                 );
5256                             }
5257                         }
5258                     }
5259                     else if (*RExC_parse == 'c') {
5260                         if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
5261                             if (! (wastedflags & WASTED_C) ) {
5262                                 wastedflags |= WASTED_GC;
5263                                 vWARN3(
5264                                     RExC_parse + 1,
5265                                     "Useless (%sc) - %suse /gc modifier",
5266                                     flagsp == &negflags ? "?-" : "?",
5267                                     flagsp == &negflags ? "don't " : ""
5268                                 );
5269                             }
5270                         }
5271                     }
5272                     else { pmflag(flagsp, *RExC_parse); }
5273
5274                     ++RExC_parse;
5275                 }
5276                 if (*RExC_parse == '-') {
5277                     flagsp = &negflags;
5278                     wastedflags = 0;  /* reset so (?g-c) warns twice */
5279                     ++RExC_parse;
5280                     goto parse_flags;
5281                 }
5282                 RExC_flags |= posflags;
5283                 RExC_flags &= ~negflags;
5284                 if (*RExC_parse == ':') {
5285                     RExC_parse++;
5286                     paren = ':';
5287                     break;
5288                 }               
5289               unknown:
5290                 if (*RExC_parse != ')') {
5291                     RExC_parse++;
5292                     vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
5293                 }
5294                 nextchar(pRExC_state);
5295                 *flagp = TRYAGAIN;
5296                 return NULL;
5297             }
5298         }
5299         else {                  /* (...) */
5300           capturing_parens:
5301             parno = RExC_npar;
5302             RExC_npar++;
5303             
5304             ret = reganode(pRExC_state, OPEN, parno);
5305             if (!SIZE_ONLY ){
5306                 if (!RExC_nestroot) 
5307                     RExC_nestroot = parno;
5308                 if (RExC_seen & REG_SEEN_RECURSE) {
5309                     DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
5310                         "Setting open paren #%"IVdf" to %d\n", 
5311                         (IV)parno, REG_NODE_NUM(ret)));
5312                     RExC_open_parens[parno-1]= ret;
5313                 }
5314             }
5315             Set_Node_Length(ret, 1); /* MJD */
5316             Set_Node_Offset(ret, RExC_parse); /* MJD */
5317             is_open = 1;
5318         }
5319     }
5320     else                        /* ! paren */
5321         ret = NULL;
5322
5323     /* Pick up the branches, linking them together. */
5324     parse_start = RExC_parse;   /* MJD */
5325     br = regbranch(pRExC_state, &flags, 1,depth+1);
5326     /*     branch_len = (paren != 0); */
5327
5328     if (br == NULL)
5329         return(NULL);
5330     if (*RExC_parse == '|') {
5331         if (!SIZE_ONLY && RExC_extralen) {
5332             reginsert(pRExC_state, BRANCHJ, br, depth+1);
5333         }
5334         else {                  /* MJD */
5335             reginsert(pRExC_state, BRANCH, br, depth+1);
5336             Set_Node_Length(br, paren != 0);
5337             Set_Node_Offset_To_R(br-RExC_emit_start, parse_start-RExC_start);
5338         }
5339         have_branch = 1;
5340         if (SIZE_ONLY)
5341             RExC_extralen += 1;         /* For BRANCHJ-BRANCH. */
5342     }
5343     else if (paren == ':') {
5344         *flagp |= flags&SIMPLE;
5345     }
5346     if (is_open) {                              /* Starts with OPEN. */
5347         REGTAIL(pRExC_state, ret, br);          /* OPEN -> first. */
5348     }
5349     else if (paren != '?')              /* Not Conditional */
5350         ret = br;
5351     *flagp |= flags & (SPSTART | HASWIDTH);
5352     lastbr = br;
5353     while (*RExC_parse == '|') {
5354         if (!SIZE_ONLY && RExC_extralen) {
5355             ender = reganode(pRExC_state, LONGJMP,0);
5356             REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender); /* Append to the previous. */
5357         }
5358         if (SIZE_ONLY)
5359             RExC_extralen += 2;         /* Account for LONGJMP. */
5360         nextchar(pRExC_state);
5361         br = regbranch(pRExC_state, &flags, 0, depth+1);
5362
5363         if (br == NULL)
5364             return(NULL);
5365         REGTAIL(pRExC_state, lastbr, br);               /* BRANCH -> BRANCH. */
5366         lastbr = br;
5367         if (flags&HASWIDTH)
5368             *flagp |= HASWIDTH;
5369         *flagp |= flags&SPSTART;
5370     }
5371
5372     if (have_branch || paren != ':') {
5373         /* Make a closing node, and hook it on the end. */
5374         switch (paren) {
5375         case ':':
5376             ender = reg_node(pRExC_state, TAIL);
5377             break;
5378         case 1:
5379             RExC_cpar++;
5380             ender = reganode(pRExC_state, CLOSE, parno);
5381             if (!SIZE_ONLY && RExC_seen & REG_SEEN_RECURSE) {
5382                 DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
5383                         "Setting close paren #%"IVdf" to %d\n", 
5384                         (IV)parno, REG_NODE_NUM(ender)));
5385                 RExC_close_parens[parno-1]= ender;
5386                 if (RExC_nestroot == parno) 
5387                     RExC_nestroot = 0;
5388             }       
5389             Set_Node_Offset(ender,RExC_parse+1); /* MJD */
5390             Set_Node_Length(ender,1); /* MJD */
5391             break;
5392         case '<':
5393         case ',':
5394         case '=':
5395         case '!':
5396             *flagp &= ~HASWIDTH;
5397             /* FALL THROUGH */
5398         case '>':
5399             ender = reg_node(pRExC_state, SUCCEED);
5400             break;
5401         case 0:
5402             ender = reg_node(pRExC_state, END);
5403             if (!SIZE_ONLY) {
5404                 assert(!RExC_opend); /* there can only be one! */
5405                 RExC_opend = ender;
5406             }
5407             break;
5408         }
5409         REGTAIL(pRExC_state, lastbr, ender);
5410
5411         if (have_branch && !SIZE_ONLY) {
5412             if (depth==1)
5413                 RExC_seen |= REG_TOP_LEVEL_BRANCHES;
5414
5415             /* Hook the tails of the branches to the closing node. */
5416             for (br = ret; br; br = regnext(br)) {
5417                 const U8 op = PL_regkind[OP(br)];
5418                 if (op == BRANCH) {
5419                     REGTAIL_STUDY(pRExC_state, NEXTOPER(br), ender);
5420                 }
5421                 else if (op == BRANCHJ) {
5422                     REGTAIL_STUDY(pRExC_state, NEXTOPER(NEXTOPER(br)), ender);
5423                 }
5424             }
5425         }
5426     }
5427
5428     {
5429         const char *p;
5430         static const char parens[] = "=!<,>";
5431
5432         if (paren && (p = strchr(parens, paren))) {
5433             U8 node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
5434             int flag = (p - parens) > 1;
5435
5436             if (paren == '>')
5437                 node = SUSPEND, flag = 0;
5438             reginsert(pRExC_state, node,ret, depth+1);
5439             Set_Node_Cur_Length(ret);
5440             Set_Node_Offset(ret, parse_start + 1);
5441             ret->flags = flag;
5442             REGTAIL_STUDY(pRExC_state, ret, reg_node(pRExC_state, TAIL));
5443         }
5444     }
5445
5446     /* Check for proper termination. */
5447     if (paren) {
5448         RExC_flags = oregflags;
5449         if (RExC_parse >= RExC_end || *nextchar(pRExC_state) != ')') {
5450             RExC_parse = oregcomp_parse;
5451             vFAIL("Unmatched (");
5452         }
5453     }
5454     else if (!paren && RExC_parse < RExC_end) {
5455         if (*RExC_parse == ')') {
5456             RExC_parse++;
5457             vFAIL("Unmatched )");
5458         }
5459         else
5460             FAIL("Junk on end of regexp");      /* "Can't happen". */
5461         /* NOTREACHED */
5462     }
5463
5464     return(ret);
5465 }
5466
5467 /*
5468  - regbranch - one alternative of an | operator
5469  *
5470  * Implements the concatenation operator.
5471  */
5472 STATIC regnode *
5473 S_regbranch(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, I32 first, U32 depth)
5474 {
5475     dVAR;
5476     register regnode *ret;
5477     register regnode *chain = NULL;
5478     register regnode *latest;
5479     I32 flags = 0, c = 0;
5480     GET_RE_DEBUG_FLAGS_DECL;
5481     DEBUG_PARSE("brnc");
5482     if (first)
5483         ret = NULL;
5484     else {
5485         if (!SIZE_ONLY && RExC_extralen)
5486             ret = reganode(pRExC_state, BRANCHJ,0);
5487         else {
5488             ret = reg_node(pRExC_state, BRANCH);
5489             Set_Node_Length(ret, 1);
5490         }
5491     }
5492         
5493     if (!first && SIZE_ONLY)
5494         RExC_extralen += 1;                     /* BRANCHJ */
5495
5496     *flagp = WORST;                     /* Tentatively. */
5497
5498     RExC_parse--;
5499     nextchar(pRExC_state);
5500     while (RExC_parse < RExC_end && *RExC_parse != '|' && *RExC_parse != ')') {
5501         flags &= ~TRYAGAIN;
5502         latest = regpiece(pRExC_state, &flags,depth+1);
5503         if (latest == NULL) {
5504             if (flags & TRYAGAIN)
5505                 continue;
5506             return(NULL);
5507         }
5508         else if (ret == NULL)
5509             ret = latest;
5510         *flagp |= flags&HASWIDTH;
5511         if (chain == NULL)      /* First piece. */
5512             *flagp |= flags&SPSTART;
5513         else {
5514             RExC_naughty++;
5515             REGTAIL(pRExC_state, chain, latest);
5516         }
5517         chain = latest;
5518         c++;
5519     }
5520     if (chain == NULL) {        /* Loop ran zero times. */
5521         chain = reg_node(pRExC_state, NOTHING);
5522         if (ret == NULL)
5523             ret = chain;
5524     }
5525     if (c == 1) {
5526         *flagp |= flags&SIMPLE;
5527     }
5528
5529     return ret;
5530 }
5531
5532 /*
5533  - regpiece - something followed by possible [*+?]
5534  *
5535  * Note that the branching code sequences used for ? and the general cases
5536  * of * and + are somewhat optimized:  they use the same NOTHING node as
5537  * both the endmarker for their branch list and the body of the last branch.
5538  * It might seem that this node could be dispensed with entirely, but the
5539  * endmarker role is not redundant.
5540  */
5541 STATIC regnode *
5542 S_regpiece(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
5543 {
5544     dVAR;
5545     register regnode *ret;
5546     register char op;
5547     register char *next;
5548     I32 flags;
5549     const char * const origparse = RExC_parse;
5550     I32 min;
5551     I32 max = REG_INFTY;
5552     char *parse_start;
5553     const char *maxpos = NULL;
5554     GET_RE_DEBUG_FLAGS_DECL;
5555     DEBUG_PARSE("piec");
5556
5557     ret = regatom(pRExC_state, &flags,depth+1);
5558     if (ret == NULL) {
5559         if (flags & TRYAGAIN)
5560             *flagp |= TRYAGAIN;
5561         return(NULL);
5562     }
5563
5564     op = *RExC_parse;
5565
5566     if (op == '{' && regcurly(RExC_parse)) {
5567         maxpos = NULL;
5568         parse_start = RExC_parse; /* MJD */
5569         next = RExC_parse + 1;
5570         while (isDIGIT(*next) || *next == ',') {
5571             if (*next == ',') {
5572                 if (maxpos)
5573                     break;
5574                 else
5575                     maxpos = next;
5576             }
5577             next++;
5578         }
5579         if (*next == '}') {             /* got one */
5580             if (!maxpos)
5581                 maxpos = next;
5582             RExC_parse++;
5583             min = atoi(RExC_parse);
5584             if (*maxpos == ',')
5585                 maxpos++;
5586             else
5587                 maxpos = RExC_parse;
5588             max = atoi(maxpos);
5589             if (!max && *maxpos != '0')
5590                 max = REG_INFTY;                /* meaning "infinity" */
5591             else if (max >= REG_INFTY)
5592                 vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
5593             RExC_parse = next;
5594             nextchar(pRExC_state);
5595
5596         do_curly:
5597             if ((flags&SIMPLE)) {
5598                 RExC_naughty += 2 + RExC_naughty / 2;
5599                 reginsert(pRExC_state, CURLY, ret, depth+1);
5600                 Set_Node_Offset(ret, parse_start+1); /* MJD */
5601                 Set_Node_Cur_Length(ret);
5602             }
5603             else {
5604                 regnode * const w = reg_node(pRExC_state, WHILEM);
5605
5606                 w->flags = 0;
5607                 REGTAIL(pRExC_state, ret, w);
5608                 if (!SIZE_ONLY && RExC_extralen) {
5609                     reginsert(pRExC_state, LONGJMP,ret, depth+1);
5610                     reginsert(pRExC_state, NOTHING,ret, depth+1);
5611                     NEXT_OFF(ret) = 3;  /* Go over LONGJMP. */
5612                 }
5613                 reginsert(pRExC_state, CURLYX,ret, depth+1);
5614                                 /* MJD hk */
5615                 Set_Node_Offset(ret, parse_start+1);
5616                 Set_Node_Length(ret,
5617                                 op == '{' ? (RExC_parse - parse_start) : 1);
5618
5619                 if (!SIZE_ONLY && RExC_extralen)
5620                     NEXT_OFF(ret) = 3;  /* Go over NOTHING to LONGJMP. */
5621                 REGTAIL(pRExC_state, ret, reg_node(pRExC_state, NOTHING));
5622                 if (SIZE_ONLY)
5623                     RExC_whilem_seen++, RExC_extralen += 3;
5624                 RExC_naughty += 4 + RExC_naughty;       /* compound interest */
5625             }
5626             ret->flags = 0;
5627
5628             if (min > 0)
5629                 *flagp = WORST;
5630             if (max > 0)
5631                 *flagp |= HASWIDTH;
5632             if (max && max < min)
5633                 vFAIL("Can't do {n,m} with n > m");
5634             if (!SIZE_ONLY) {
5635                 ARG1_SET(ret, (U16)min);
5636                 ARG2_SET(ret, (U16)max);
5637             }
5638
5639             goto nest_check;
5640         }
5641     }
5642
5643     if (!ISMULT1(op)) {
5644         *flagp = flags;
5645         return(ret);
5646     }
5647
5648 #if 0                           /* Now runtime fix should be reliable. */
5649
5650     /* if this is reinstated, don't forget to put this back into perldiag:
5651
5652             =item Regexp *+ operand could be empty at {#} in regex m/%s/
5653
5654            (F) The part of the regexp subject to either the * or + quantifier
5655            could match an empty string. The {#} shows in the regular
5656            expression about where the problem was discovered.
5657
5658     */
5659
5660     if (!(flags&HASWIDTH) && op != '?')
5661       vFAIL("Regexp *+ operand could be empty");
5662 #endif
5663
5664     parse_start = RExC_parse;
5665     nextchar(pRExC_state);
5666
5667     *flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
5668
5669     if (op == '*' && (flags&SIMPLE)) {
5670         reginsert(pRExC_state, STAR, ret, depth+1);
5671         ret->flags = 0;
5672         RExC_naughty += 4;
5673     }
5674     else if (op == '*') {
5675         min = 0;
5676         goto do_curly;
5677     }
5678     else if (op == '+' && (flags&SIMPLE)) {
5679         reginsert(pRExC_state, PLUS, ret, depth+1);
5680         ret->flags = 0;
5681         RExC_naughty += 3;
5682     }
5683     else if (op == '+') {
5684         min = 1;
5685         goto do_curly;
5686     }
5687     else if (op == '?') {
5688         min = 0; max = 1;
5689         goto do_curly;
5690     }
5691   nest_check:
5692     if (!SIZE_ONLY && !(flags&HASWIDTH) && max > REG_INFTY/3 && ckWARN(WARN_REGEXP)) {
5693         vWARN3(RExC_parse,
5694                "%.*s matches null string many times",
5695                (int)(RExC_parse >= origparse ? RExC_parse - origparse : 0),
5696                origparse);
5697     }
5698
5699     if (RExC_parse < RExC_end && *RExC_parse == '?') {
5700         nextchar(pRExC_state);
5701         reginsert(pRExC_state, MINMOD, ret, depth+1);
5702         REGTAIL(pRExC_state, ret, ret + NODE_STEP_REGNODE);
5703     }
5704 #ifndef REG_ALLOW_MINMOD_SUSPEND
5705     else
5706 #endif
5707     if (RExC_parse < RExC_end && *RExC_parse == '+') {
5708         regnode *ender;
5709         nextchar(pRExC_state);
5710         ender = reg_node(pRExC_state, SUCCEED);
5711         REGTAIL(pRExC_state, ret, ender);
5712         reginsert(pRExC_state, SUSPEND, ret, depth+1);
5713         ret->flags = 0;
5714         ender = reg_node(pRExC_state, TAIL);
5715         REGTAIL(pRExC_state, ret, ender);
5716         /*ret= ender;*/
5717     }
5718
5719     if (RExC_parse < RExC_end && ISMULT2(RExC_parse)) {
5720         RExC_parse++;
5721         vFAIL("Nested quantifiers");
5722     }
5723
5724     return(ret);
5725 }
5726
5727
5728 /* reg_namedseq(pRExC_state,UVp)
5729    
5730    This is expected to be called by a parser routine that has 
5731    recognized'\N' and needs to handle the rest. RExC_parse is 
5732    expected to point at the first char following the N at the time
5733    of the call.
5734    
5735    If valuep is non-null then it is assumed that we are parsing inside 
5736    of a charclass definition and the first codepoint in the resolved
5737    string is returned via *valuep and the routine will return NULL. 
5738    In this mode if a multichar string is returned from the charnames 
5739    handler a warning will be issued, and only the first char in the 
5740    sequence will be examined. If the string returned is zero length
5741    then the value of *valuep is undefined and NON-NULL will 
5742    be returned to indicate failure. (This will NOT be a valid pointer 
5743    to a regnode.)
5744    
5745    If value is null then it is assumed that we are parsing normal text
5746    and inserts a new EXACT node into the program containing the resolved
5747    string and returns a pointer to the new node. If the string is 
5748    zerolength a NOTHING node is emitted.
5749    
5750    On success RExC_parse is set to the char following the endbrace.
5751    Parsing failures will generate a fatal errorvia vFAIL(...)
5752    
5753    NOTE: We cache all results from the charnames handler locally in 
5754    the RExC_charnames hash (created on first use) to prevent a charnames 
5755    handler from playing silly-buggers and returning a short string and 
5756    then a long string for a given pattern. Since the regexp program 
5757    size is calculated during an initial parse this would result
5758    in a buffer overrun so we cache to prevent the charname result from
5759    changing during the course of the parse.
5760    
5761  */
5762 STATIC regnode *
5763 S_reg_namedseq(pTHX_ RExC_state_t *pRExC_state, UV *valuep) 
5764 {
5765     char * name;        /* start of the content of the name */
5766     char * endbrace;    /* endbrace following the name */
5767     SV *sv_str = NULL;  
5768     SV *sv_name = NULL;
5769     STRLEN len; /* this has various purposes throughout the code */
5770     bool cached = 0; /* if this is true then we shouldn't refcount dev sv_str */
5771     regnode *ret = NULL;
5772     
5773     if (*RExC_parse != '{') {
5774         vFAIL("Missing braces on \\N{}");
5775     }
5776     name = RExC_parse+1;
5777     endbrace = strchr(RExC_parse, '}');
5778     if ( ! endbrace ) {
5779         RExC_parse++;
5780         vFAIL("Missing right brace on \\N{}");
5781     } 
5782     RExC_parse = endbrace + 1;  
5783     
5784     
5785     /* RExC_parse points at the beginning brace, 
5786        endbrace points at the last */
5787     if ( name[0]=='U' && name[1]=='+' ) {
5788         /* its a "unicode hex" notation {U+89AB} */
5789         I32 fl = PERL_SCAN_ALLOW_UNDERSCORES
5790             | PERL_SCAN_DISALLOW_PREFIX
5791             | (SIZE_ONLY ? PERL_SCAN_SILENT_ILLDIGIT : 0);
5792         UV cp;
5793         len = (STRLEN)(endbrace - name - 2);
5794         cp = grok_hex(name + 2, &len, &fl, NULL);
5795         if ( len != (STRLEN)(endbrace - name - 2) ) {
5796             cp = 0xFFFD;
5797         }    
5798         if (cp > 0xff)
5799             RExC_utf8 = 1;
5800         if ( valuep ) {
5801             *valuep = cp;
5802             return NULL;
5803         }
5804         sv_str= Perl_newSVpvf_nocontext("%c",(int)cp);
5805     } else {
5806         /* fetch the charnames handler for this scope */
5807         HV * const table = GvHV(PL_hintgv);
5808         SV **cvp= table ? 
5809             hv_fetchs(table, "charnames", FALSE) :
5810             NULL;
5811         SV *cv= cvp ? *cvp : NULL;
5812         HE *he_str;
5813         int count;
5814         /* create an SV with the name as argument */
5815         sv_name = newSVpvn(name, endbrace - name);
5816         
5817         if (!table || !(PL_hints & HINT_LOCALIZE_HH)) {
5818             vFAIL2("Constant(\\N{%s}) unknown: "
5819                   "(possibly a missing \"use charnames ...\")",
5820                   SvPVX(sv_name));
5821         }
5822         if (!cvp || !SvOK(*cvp)) { /* when $^H{charnames} = undef; */
5823             vFAIL2("Constant(\\N{%s}): "
5824                   "$^H{charnames} is not defined",SvPVX(sv_name));
5825         }
5826         
5827         
5828         
5829         if (!RExC_charnames) {
5830             /* make sure our cache is allocated */
5831             RExC_charnames = newHV();
5832             sv_2mortal((SV*)RExC_charnames);
5833         } 
5834             /* see if we have looked this one up before */
5835         he_str = hv_fetch_ent( RExC_charnames, sv_name, 0, 0 );
5836         if ( he_str ) {
5837             sv_str = HeVAL(he_str);
5838             cached = 1;
5839         } else {
5840             dSP ;
5841
5842             ENTER ;
5843             SAVETMPS ;
5844             PUSHMARK(SP) ;
5845             
5846             XPUSHs(sv_name);
5847             
5848             PUTBACK ;
5849             
5850             count= call_sv(cv, G_SCALAR);
5851             
5852             if (count == 1) { /* XXXX is this right? dmq */
5853                 sv_str = POPs;
5854                 SvREFCNT_inc_simple_void(sv_str);
5855             } 
5856             
5857             SPAGAIN ;
5858             PUTBACK ;
5859             FREETMPS ;
5860             LEAVE ;
5861             
5862             if ( !sv_str || !SvOK(sv_str) ) {
5863                 vFAIL2("Constant(\\N{%s}): Call to &{$^H{charnames}} "
5864                       "did not return a defined value",SvPVX(sv_name));
5865             }
5866             if (hv_store_ent( RExC_charnames, sv_name, sv_str, 0))
5867                 cached = 1;
5868         }
5869     }
5870     if (valuep) {
5871         char *p = SvPV(sv_str, len);
5872         if (len) {
5873             STRLEN numlen = 1;
5874             if ( SvUTF8(sv_str) ) {
5875                 *valuep = utf8_to_uvchr((U8*)p, &numlen);
5876                 if (*valuep > 0x7F)
5877                     RExC_utf8 = 1; 
5878                 /* XXXX
5879                   We have to turn on utf8 for high bit chars otherwise
5880                   we get failures with
5881                   
5882                    "ss" =~ /[\N{LATIN SMALL LETTER SHARP S}]/i
5883                    "SS" =~ /[\N{LATIN SMALL LETTER SHARP S}]/i
5884                 
5885                   This is different from what \x{} would do with the same
5886                   codepoint, where the condition is > 0xFF.
5887                   - dmq
5888                 */
5889                 
5890                 
5891             } else {
5892                 *valuep = (UV)*p;
5893                 /* warn if we havent used the whole string? */
5894             }
5895             if (numlen<len && SIZE_ONLY && ckWARN(WARN_REGEXP)) {
5896                 vWARN2(RExC_parse,
5897                     "Ignoring excess chars from \\N{%s} in character class",
5898                     SvPVX(sv_name)
5899                 );
5900             }        
5901         } else if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
5902             vWARN2(RExC_parse,
5903                     "Ignoring zero length \\N{%s} in character class",
5904                     SvPVX(sv_name)
5905                 );
5906         }
5907         if (sv_name)    
5908             SvREFCNT_dec(sv_name);    
5909         if (!cached)
5910             SvREFCNT_dec(sv_str);    
5911         return len ? NULL : (regnode *)&len;
5912     } else if(SvCUR(sv_str)) {     
5913         
5914         char *s; 
5915         char *p, *pend;        
5916         STRLEN charlen = 1;
5917         char * parse_start = name-3; /* needed for the offsets */
5918         GET_RE_DEBUG_FLAGS_DECL;     /* needed for the offsets */
5919         
5920         ret = reg_node(pRExC_state,
5921             (U8)(FOLD ? (LOC ? EXACTFL : EXACTF) : EXACT));
5922         s= STRING(ret);
5923         
5924         if ( RExC_utf8 && !SvUTF8(sv_str) ) {
5925             sv_utf8_upgrade(sv_str);
5926         } else if ( !RExC_utf8 && SvUTF8(sv_str) ) {
5927             RExC_utf8= 1;
5928         }
5929         
5930         p = SvPV(sv_str, len);
5931         pend = p + len;
5932         /* len is the length written, charlen is the size the char read */
5933         for ( len = 0; p < pend; p += charlen ) {
5934             if (UTF) {
5935                 UV uvc = utf8_to_uvchr((U8*)p, &charlen);
5936                 if (FOLD) {
5937                     STRLEN foldlen,numlen;
5938                     U8 tmpbuf[UTF8_MAXBYTES_CASE+1], *foldbuf;
5939                     uvc = toFOLD_uni(uvc, tmpbuf, &foldlen);
5940                     /* Emit all the Unicode characters. */
5941                     
5942                     for (foldbuf = tmpbuf;
5943                         foldlen;
5944                         foldlen -= numlen) 
5945                     {
5946                         uvc = utf8_to_uvchr(foldbuf, &numlen);
5947                         if (numlen > 0) {
5948                             const STRLEN unilen = reguni(pRExC_state, uvc, s);
5949                             s       += unilen;
5950                             len     += unilen;
5951                             /* In EBCDIC the numlen
5952                             * and unilen can differ. */
5953                             foldbuf += numlen;
5954                             if (numlen >= foldlen)
5955                                 break;
5956                         }
5957                         else
5958                             break; /* "Can't happen." */
5959                     }                          
5960                 } else {
5961                     const STRLEN unilen = reguni(pRExC_state, uvc, s);
5962                     if (unilen > 0) {
5963                        s   += unilen;
5964                        len += unilen;
5965                     }
5966                 }
5967             } else {
5968                 len++;
5969                 REGC(*p, s++);
5970             }
5971         }
5972         if (SIZE_ONLY) {
5973             RExC_size += STR_SZ(len);
5974         } else {
5975             STR_LEN(ret) = len;
5976             RExC_emit += STR_SZ(len);
5977         }
5978         Set_Node_Cur_Length(ret); /* MJD */
5979         RExC_parse--; 
5980         nextchar(pRExC_state);
5981     } else {
5982         ret = reg_node(pRExC_state,NOTHING);
5983     }
5984     if (!cached) {
5985         SvREFCNT_dec(sv_str);
5986     }
5987     if (sv_name) {
5988         SvREFCNT_dec(sv_name); 
5989     }
5990     return ret;
5991
5992 }
5993
5994
5995 /*
5996  * reg_recode
5997  *
5998  * It returns the code point in utf8 for the value in *encp.
5999  *    value: a code value in the source encoding
6000  *    encp:  a pointer to an Encode object
6001  *
6002  * If the result from Encode is not a single character,
6003  * it returns U+FFFD (Replacement character) and sets *encp to NULL.
6004  */
6005 STATIC UV
6006 S_reg_recode(pTHX_ const char value, SV **encp)
6007 {
6008     STRLEN numlen = 1;
6009     SV * const sv = sv_2mortal(newSVpvn(&value, numlen));
6010     const char * const s = encp && *encp ? sv_recode_to_utf8(sv, *encp)
6011                                          : SvPVX(sv);
6012     const STRLEN newlen = SvCUR(sv);
6013     UV uv = UNICODE_REPLACEMENT;
6014
6015     if (newlen)
6016         uv = SvUTF8(sv)
6017              ? utf8n_to_uvchr((U8*)s, newlen, &numlen, UTF8_ALLOW_DEFAULT)
6018              : *(U8*)s;
6019
6020     if (!newlen || numlen != newlen) {
6021         uv = UNICODE_REPLACEMENT;
6022         if (encp)
6023             *encp = NULL;
6024     }
6025     return uv;
6026 }
6027
6028
6029 /*
6030  - regatom - the lowest level
6031  *
6032  * Optimization:  gobbles an entire sequence of ordinary characters so that
6033  * it can turn them into a single node, which is smaller to store and
6034  * faster to run.  Backslashed characters are exceptions, each becoming a
6035  * separate node; the code is simpler that way and it's not worth fixing.
6036  *
6037  * [Yes, it is worth fixing, some scripts can run twice the speed.]
6038  * [It looks like its ok, as in S_study_chunk we merge adjacent EXACT nodes]
6039  */
6040 STATIC regnode *
6041 S_regatom(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
6042 {
6043     dVAR;
6044     register regnode *ret = NULL;
6045     I32 flags;
6046     char *parse_start = RExC_parse;
6047     GET_RE_DEBUG_FLAGS_DECL;
6048     DEBUG_PARSE("atom");
6049     *flagp = WORST;             /* Tentatively. */
6050
6051 tryagain:
6052     switch (*RExC_parse) {
6053     case '^':
6054         RExC_seen_zerolen++;
6055         nextchar(pRExC_state);
6056         if (RExC_flags & PMf_MULTILINE)
6057             ret = reg_node(pRExC_state, MBOL);
6058         else if (RExC_flags & PMf_SINGLELINE)
6059             ret = reg_node(pRExC_state, SBOL);
6060         else
6061             ret = reg_node(pRExC_state, BOL);
6062         Set_Node_Length(ret, 1); /* MJD */
6063         break;
6064     case '$':
6065         nextchar(pRExC_state);
6066         if (*RExC_parse)
6067             RExC_seen_zerolen++;
6068         if (RExC_flags & PMf_MULTILINE)
6069             ret = reg_node(pRExC_state, MEOL);
6070         else if (RExC_flags & PMf_SINGLELINE)
6071             ret = reg_node(pRExC_state, SEOL);
6072         else
6073             ret = reg_node(pRExC_state, EOL);
6074         Set_Node_Length(ret, 1); /* MJD */
6075         break;
6076     case '.':
6077         nextchar(pRExC_state);
6078         if (RExC_flags & PMf_SINGLELINE)
6079             ret = reg_node(pRExC_state, SANY);
6080         else
6081             ret = reg_node(pRExC_state, REG_ANY);
6082         *flagp |= HASWIDTH|SIMPLE;
6083         RExC_naughty++;
6084         Set_Node_Length(ret, 1); /* MJD */
6085         break;
6086     case '[':
6087     {
6088         char * const oregcomp_parse = ++RExC_parse;
6089         ret = regclass(pRExC_state,depth+1);
6090         if (*RExC_parse != ']') {
6091             RExC_parse = oregcomp_parse;
6092             vFAIL("Unmatched [");
6093         }
6094         nextchar(pRExC_state);
6095         *flagp |= HASWIDTH|SIMPLE;
6096         Set_Node_Length(ret, RExC_parse - oregcomp_parse + 1); /* MJD */
6097         break;
6098     }
6099     case '(':
6100         nextchar(pRExC_state);
6101         ret = reg(pRExC_state, 1, &flags,depth+1);
6102         if (ret == NULL) {
6103                 if (flags & TRYAGAIN) {
6104                     if (RExC_parse == RExC_end) {
6105                          /* Make parent create an empty node if needed. */
6106                         *flagp |= TRYAGAIN;
6107                         return(NULL);
6108                     }
6109                     goto tryagain;
6110                 }
6111                 return(NULL);
6112         }
6113         *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE);
6114         break;
6115     case '|':
6116     case ')':
6117         if (flags & TRYAGAIN) {
6118             *flagp |= TRYAGAIN;
6119             return NULL;
6120         }
6121         vFAIL("Internal urp");
6122                                 /* Supposed to be caught earlier. */
6123         break;
6124     case '{':
6125         if (!regcurly(RExC_parse)) {
6126             RExC_parse++;
6127             goto defchar;
6128         }
6129         /* FALL THROUGH */
6130     case '?':
6131     case '+':
6132     case '*':
6133         RExC_parse++;
6134         vFAIL("Quantifier follows nothing");
6135         break;
6136     case '\\':
6137         switch (*++RExC_parse) {
6138         case 'A':
6139             RExC_seen_zerolen++;
6140             ret = reg_node(pRExC_state, SBOL);
6141             *flagp |= SIMPLE;
6142             nextchar(pRExC_state);
6143             Set_Node_Length(ret, 2); /* MJD */
6144             break;
6145         case 'G':
6146             ret = reg_node(pRExC_state, GPOS);
6147             RExC_seen |= REG_SEEN_GPOS;
6148             *flagp |= SIMPLE;
6149             nextchar(pRExC_state);
6150             Set_Node_Length(ret, 2); /* MJD */
6151             break;
6152         case 'Z':
6153             ret = reg_node(pRExC_state, SEOL);
6154             *flagp |= SIMPLE;
6155             RExC_seen_zerolen++;                /* Do not optimize RE away */
6156             nextchar(pRExC_state);
6157             break;
6158         case 'z':
6159             ret = reg_node(pRExC_state, EOS);
6160             *flagp |= SIMPLE;
6161             RExC_seen_zerolen++;                /* Do not optimize RE away */
6162             nextchar(pRExC_state);
6163             Set_Node_Length(ret, 2); /* MJD */
6164             break;
6165         case 'C':
6166             ret = reg_node(pRExC_state, CANY);
6167             RExC_seen |= REG_SEEN_CANY;
6168             *flagp |= HASWIDTH|SIMPLE;
6169             nextchar(pRExC_state);
6170             Set_Node_Length(ret, 2); /* MJD */
6171             break;
6172         case 'X':
6173             ret = reg_node(pRExC_state, CLUMP);
6174             *flagp |= HASWIDTH;
6175             nextchar(pRExC_state);
6176             Set_Node_Length(ret, 2); /* MJD */
6177             break;
6178         case 'w':
6179             ret = reg_node(pRExC_state, (U8)(LOC ? ALNUML     : ALNUM));
6180             *flagp |= HASWIDTH|SIMPLE;
6181             nextchar(pRExC_state);
6182             Set_Node_Length(ret, 2); /* MJD */
6183             break;
6184         case 'W':
6185             ret = reg_node(pRExC_state, (U8)(LOC ? NALNUML    : NALNUM));
6186             *flagp |= HASWIDTH|SIMPLE;
6187             nextchar(pRExC_state);
6188             Set_Node_Length(ret, 2); /* MJD */
6189             break;
6190         case 'b':
6191             RExC_seen_zerolen++;
6192             RExC_seen |= REG_SEEN_LOOKBEHIND;
6193             ret = reg_node(pRExC_state, (U8)(LOC ? BOUNDL     : BOUND));
6194             *flagp |= SIMPLE;
6195             nextchar(pRExC_state);
6196             Set_Node_Length(ret, 2); /* MJD */
6197             break;
6198         case 'B':
6199             RExC_seen_zerolen++;
6200             RExC_seen |= REG_SEEN_LOOKBEHIND;
6201             ret = reg_node(pRExC_state, (U8)(LOC ? NBOUNDL    : NBOUND));
6202             *flagp |= SIMPLE;
6203             nextchar(pRExC_state);
6204             Set_Node_Length(ret, 2); /* MJD */
6205             break;
6206         case 's':
6207             ret = reg_node(pRExC_state, (U8)(LOC ? SPACEL     : SPACE));
6208             *flagp |= HASWIDTH|SIMPLE;
6209             nextchar(pRExC_state);
6210             Set_Node_Length(ret, 2); /* MJD */
6211             break;
6212         case 'S':
6213             ret = reg_node(pRExC_state, (U8)(LOC ? NSPACEL    : NSPACE));
6214             *flagp |= HASWIDTH|SIMPLE;
6215             nextchar(pRExC_state);
6216             Set_Node_Length(ret, 2); /* MJD */
6217             break;
6218         case 'd':
6219             ret = reg_node(pRExC_state, DIGIT);
6220             *flagp |= HASWIDTH|SIMPLE;
6221             nextchar(pRExC_state);
6222             Set_Node_Length(ret, 2); /* MJD */
6223             break;
6224         case 'D':
6225             ret = reg_node(pRExC_state, NDIGIT);
6226             *flagp |= HASWIDTH|SIMPLE;
6227             nextchar(pRExC_state);
6228             Set_Node_Length(ret, 2); /* MJD */
6229             break;
6230         case 'p':
6231         case 'P':
6232             {   
6233                 char* const oldregxend = RExC_end;
6234                 char* parse_start = RExC_parse - 2;
6235
6236                 if (RExC_parse[1] == '{') {
6237                   /* a lovely hack--pretend we saw [\pX] instead */
6238                     RExC_end = strchr(RExC_parse, '}');
6239                     if (!RExC_end) {
6240                         const U8 c = (U8)*RExC_parse;
6241                         RExC_parse += 2;
6242                         RExC_end = oldregxend;
6243                         vFAIL2("Missing right brace on \\%c{}", c);
6244                     }
6245                     RExC_end++;
6246                 }
6247                 else {
6248                     RExC_end = RExC_parse + 2;
6249                     if (RExC_end > oldregxend)
6250                         RExC_end = oldregxend;
6251                 }
6252                 RExC_parse--;
6253
6254                 ret = regclass(pRExC_state,depth+1);
6255
6256                 RExC_end = oldregxend;
6257                 RExC_parse--;
6258
6259                 Set_Node_Offset(ret, parse_start + 2);
6260                 Set_Node_Cur_Length(ret);
6261                 nextchar(pRExC_state);
6262                 *flagp |= HASWIDTH|SIMPLE;
6263             }
6264             break;
6265         case 'N': 
6266             /* Handle \N{NAME} here and not below because it can be 
6267             multicharacter. join_exact() will join them up later on. 
6268             Also this makes sure that things like /\N{BLAH}+/ and 
6269             \N{BLAH} being multi char Just Happen. dmq*/
6270             ++RExC_parse;
6271             ret= reg_namedseq(pRExC_state, NULL); 
6272             break;
6273         case 'k':    /* Handle \k<NAME> and \k'NAME' */
6274         {   
6275             char ch= RExC_parse[1];         
6276             if (ch != '<' && ch != '\'') {
6277                 if (SIZE_ONLY)
6278                     vWARN( RExC_parse + 1, 
6279                         "Possible broken named back reference treated as literal k");
6280                 parse_start--;
6281                 goto defchar;
6282             } else {
6283                 char* name_start = (RExC_parse += 2);
6284                 I32 num = 0;
6285                 SV *sv_dat = reg_scan_name(pRExC_state,
6286                     SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
6287                 ch= (ch == '<') ? '>' : '\'';
6288                     
6289                 if (RExC_parse == name_start || *RExC_parse != ch)
6290                     vFAIL2("Sequence \\k%c... not terminated",
6291                         (ch == '>' ? '<' : ch));
6292                 
6293                 RExC_sawback = 1;
6294                 ret = reganode(pRExC_state,
6295                            (U8)(FOLD ? (LOC ? NREFFL : NREFF) : NREF),
6296                            num);
6297                 *flagp |= HASWIDTH;
6298                 
6299                 
6300                 if (!SIZE_ONLY) {
6301                     num = add_data( pRExC_state, 1, "S" );
6302                     ARG_SET(ret,num);
6303                     RExC_rx->data->data[num]=(void*)sv_dat;
6304                     SvREFCNT_inc(sv_dat);
6305                 }    
6306                 /* override incorrect value set in reganode MJD */
6307                 Set_Node_Offset(ret, parse_start+1);
6308                 Set_Node_Cur_Length(ret); /* MJD */
6309                 nextchar(pRExC_state);
6310                                
6311             }
6312             break;
6313         }            
6314         case 'n':
6315         case 'r':
6316         case 't':
6317         case 'f':
6318         case 'e':
6319         case 'a':
6320         case 'x':
6321         case 'c':
6322         case '0':
6323             goto defchar;
6324         case 'R': 
6325         case '1': case '2': case '3': case '4':
6326         case '5': case '6': case '7': case '8': case '9':
6327             {
6328                 I32 num;
6329                 bool isrel=(*RExC_parse=='R');
6330                 if (isrel)
6331                     RExC_parse++;
6332                 num = atoi(RExC_parse);
6333                 if (isrel) {
6334                     num = RExC_cpar - num;
6335                     if (num < 1)
6336                         vFAIL("Reference to nonexistent or unclosed group");
6337                 }
6338                 if (num > 9 && num >= RExC_npar)
6339                     goto defchar;
6340                 else {
6341                     char * const parse_start = RExC_parse - 1; /* MJD */
6342                     while (isDIGIT(*RExC_parse))
6343                         RExC_parse++;
6344
6345                     if (!SIZE_ONLY) {
6346                         if (num > (I32)RExC_rx->nparens)
6347                             vFAIL("Reference to nonexistent group");
6348                         /* People make this error all the time apparently.
6349                            So we cant fail on it, even though we should 
6350                         
6351                         else if (num >= RExC_cpar)
6352                             vFAIL("Reference to unclosed group will always match");
6353                         */
6354                     }
6355                     RExC_sawback = 1;
6356                     ret = reganode(pRExC_state,
6357                                    (U8)(FOLD ? (LOC ? REFFL : REFF) : REF),
6358                                    num);
6359                     *flagp |= HASWIDTH;
6360
6361                     /* override incorrect value set in reganode MJD */
6362                     Set_Node_Offset(ret, parse_start+1);
6363                     Set_Node_Cur_Length(ret); /* MJD */
6364                     RExC_parse--;
6365                     nextchar(pRExC_state);
6366                 }
6367             }
6368             break;
6369         case '\0':
6370             if (RExC_parse >= RExC_end)
6371                 FAIL("Trailing \\");
6372             /* FALL THROUGH */
6373         default:
6374             /* Do not generate "unrecognized" warnings here, we fall
6375                back into the quick-grab loop below */
6376             parse_start--;
6377             goto defchar;
6378         }
6379         break;
6380
6381     case '#':
6382         if (RExC_flags & PMf_EXTENDED) {
6383             while (RExC_parse < RExC_end && *RExC_parse != '\n')
6384                 RExC_parse++;
6385             if (RExC_parse < RExC_end)
6386                 goto tryagain;
6387         }
6388         /* FALL THROUGH */
6389
6390     default: {
6391             register STRLEN len;
6392             register UV ender;
6393             register char *p;
6394             char *s;
6395             STRLEN foldlen;
6396             U8 tmpbuf[UTF8_MAXBYTES_CASE+1], *foldbuf;
6397
6398             parse_start = RExC_parse - 1;
6399
6400             RExC_parse++;
6401
6402         defchar:
6403             ender = 0;
6404             ret = reg_node(pRExC_state,
6405                            (U8)(FOLD ? (LOC ? EXACTFL : EXACTF) : EXACT));
6406             s = STRING(ret);
6407             for (len = 0, p = RExC_parse - 1;
6408               len < 127 && p < RExC_end;
6409               len++)
6410             {
6411                 char * const oldp = p;
6412
6413                 if (RExC_flags & PMf_EXTENDED)
6414                     p = regwhite(p, RExC_end);
6415                 switch (*p) {
6416                 case '^':
6417                 case '$':
6418                 case '.':
6419                 case '[':
6420                 case '(':
6421                 case ')':
6422                 case '|':
6423                     goto loopdone;
6424                 case '\\':
6425                     switch (*++p) {
6426                     case 'A':
6427                     case 'C':
6428                     case 'X':
6429                     case 'G':
6430                     case 'Z':
6431                     case 'z':
6432                     case 'w':
6433                     case 'W':
6434                     case 'b':
6435                     case 'B':
6436                     case 's':
6437                     case 'S':
6438                     case 'd':
6439                     case 'D':
6440                     case 'p':
6441                     case 'P':
6442                     case 'N':
6443                     case 'R':
6444                         --p;
6445                         goto loopdone;
6446                     case 'n':
6447                         ender = '\n';
6448                         p++;
6449                         break;
6450                     case 'r':
6451                         ender = '\r';
6452                         p++;
6453                         break;
6454                     case 't':
6455                         ender = '\t';
6456                         p++;
6457                         break;
6458                     case 'f':
6459                         ender = '\f';
6460                         p++;
6461                         break;
6462                     case 'e':
6463                           ender = ASCII_TO_NATIVE('\033');
6464                         p++;
6465                         break;
6466                     case 'a':
6467                           ender = ASCII_TO_NATIVE('\007');
6468                         p++;
6469                         break;
6470                     case 'x':
6471                         if (*++p == '{') {
6472                             char* const e = strchr(p, '}');
6473         
6474                             if (!e) {
6475                                 RExC_parse = p + 1;
6476                                 vFAIL("Missing right brace on \\x{}");
6477                             }
6478                             else {
6479                                 I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
6480                                     | PERL_SCAN_DISALLOW_PREFIX;
6481                                 STRLEN numlen = e - p - 1;
6482                                 ender = grok_hex(p + 1, &numlen, &flags, NULL);
6483                                 if (ender > 0xff)
6484                                     RExC_utf8 = 1;
6485                                 p = e + 1;
6486                             }
6487                         }
6488                         else {
6489                             I32 flags = PERL_SCAN_DISALLOW_PREFIX;
6490                             STRLEN numlen = 2;
6491                             ender = grok_hex(p, &numlen, &flags, NULL);
6492                             p += numlen;
6493                         }
6494                         if (PL_encoding && ender < 0x100)
6495                             goto recode_encoding;
6496                         break;
6497                     case 'c':
6498                         p++;
6499                         ender = UCHARAT(p++);
6500                         ender = toCTRL(ender);
6501                         break;
6502                     case '0': case '1': case '2': case '3':case '4':
6503                     case '5': case '6': case '7': case '8':case '9':
6504                         if (*p == '0' ||
6505                           (isDIGIT(p[1]) && atoi(p) >= RExC_npar) ) {
6506                             I32 flags = 0;
6507                             STRLEN numlen = 3;
6508                             ender = grok_oct(p, &numlen, &flags, NULL);
6509                             p += numlen;
6510                         }
6511                         else {
6512                             --p;
6513                             goto loopdone;
6514                         }
6515                         if (PL_encoding && ender < 0x100)
6516                             goto recode_encoding;
6517                         break;
6518                     recode_encoding:
6519                         {
6520                             SV* enc = PL_encoding;
6521                             ender = reg_recode((const char)(U8)ender, &enc);
6522                             if (!enc && SIZE_ONLY && ckWARN(WARN_REGEXP))
6523                                 vWARN(p, "Invalid escape in the specified encoding");
6524                             RExC_utf8 = 1;
6525                         }
6526                         break;
6527                     case '\0':
6528                         if (p >= RExC_end)
6529                             FAIL("Trailing \\");
6530                         /* FALL THROUGH */
6531                     default:
6532                         if (!SIZE_ONLY&& isALPHA(*p) && ckWARN(WARN_REGEXP))
6533                             vWARN2(p + 1, "Unrecognized escape \\%c passed through", UCHARAT(p));
6534                         goto normal_default;
6535                     }
6536                     break;
6537                 default:
6538                   normal_default:
6539                     if (UTF8_IS_START(*p) && UTF) {
6540                         STRLEN numlen;
6541                         ender = utf8n_to_uvchr((U8*)p, RExC_end - p,
6542                                                &numlen, UTF8_ALLOW_DEFAULT);
6543                         p += numlen;
6544                     }
6545                     else
6546                         ender = *p++;
6547                     break;
6548                 }
6549                 if (RExC_flags & PMf_EXTENDED)
6550                     p = regwhite(p, RExC_end);
6551                 if (UTF && FOLD) {
6552                     /* Prime the casefolded buffer. */
6553                     ender = toFOLD_uni(ender, tmpbuf, &foldlen);
6554                 }
6555                 if (ISMULT2(p)) { /* Back off on ?+*. */
6556                     if (len)
6557                         p = oldp;
6558                     else if (UTF) {
6559                          if (FOLD) {
6560                               /* Emit all the Unicode characters. */
6561                               STRLEN numlen;
6562                               for (foldbuf = tmpbuf;
6563                                    foldlen;
6564                                    foldlen -= numlen) {
6565                                    ender = utf8_to_uvchr(foldbuf, &numlen);
6566                                    if (numlen > 0) {
6567                                         const STRLEN unilen = reguni(pRExC_state, ender, s);
6568                                         s       += unilen;
6569                                         len     += unilen;
6570                                         /* In EBCDIC the numlen
6571                                          * and unilen can differ. */
6572                                         foldbuf += numlen;
6573                                         if (numlen >= foldlen)
6574                                              break;
6575                                    }
6576                                    else
6577                                         break; /* "Can't happen." */
6578                               }
6579                          }
6580                          else {
6581                               const STRLEN unilen = reguni(pRExC_state, ender, s);
6582                               if (unilen > 0) {
6583                                    s   += unilen;
6584                                    len += unilen;
6585                               }
6586                          }
6587                     }
6588                     else {
6589                         len++;
6590                         REGC((char)ender, s++);
6591                     }
6592                     break;
6593                 }
6594                 if (UTF) {
6595                      if (FOLD) {
6596                           /* Emit all the Unicode characters. */
6597                           STRLEN numlen;
6598                           for (foldbuf = tmpbuf;
6599                                foldlen;
6600                                foldlen -= numlen) {
6601                                ender = utf8_to_uvchr(foldbuf, &numlen);
6602                                if (numlen > 0) {
6603                                     const STRLEN unilen = reguni(pRExC_state, ender, s);
6604                                     len     += unilen;
6605                                     s       += unilen;
6606                                     /* In EBCDIC the numlen
6607                                      * and unilen can differ. */
6608                                     foldbuf += numlen;
6609                                     if (numlen >= foldlen)
6610                                          break;
6611                                }
6612                                else
6613                                     break;
6614                           }
6615                      }
6616                      else {
6617                           const STRLEN unilen = reguni(pRExC_state, ender, s);
6618                           if (unilen > 0) {
6619                                s   += unilen;
6620                                len += unilen;
6621                           }
6622                      }
6623                      len--;
6624                 }
6625                 else
6626                     REGC((char)ender, s++);
6627             }
6628         loopdone:
6629             RExC_parse = p - 1;
6630             Set_Node_Cur_Length(ret); /* MJD */
6631             nextchar(pRExC_state);
6632             {
6633                 /* len is STRLEN which is unsigned, need to copy to signed */
6634                 IV iv = len;
6635                 if (iv < 0)
6636                     vFAIL("Internal disaster");
6637             }
6638             if (len > 0)
6639                 *flagp |= HASWIDTH;
6640             if (len == 1 && UNI_IS_INVARIANT(ender))
6641                 *flagp |= SIMPLE;
6642                 
6643             if (SIZE_ONLY)
6644                 RExC_size += STR_SZ(len);
6645             else {
6646                 STR_LEN(ret) = len;
6647                 RExC_emit += STR_SZ(len);
6648             }
6649         }
6650         break;
6651     }
6652
6653     return(ret);
6654 }
6655
6656 STATIC char *
6657 S_regwhite(char *p, const char *e)
6658 {
6659     while (p < e) {
6660         if (isSPACE(*p))
6661             ++p;
6662         else if (*p == '#') {
6663             do {
6664                 p++;
6665             } while (p < e && *p != '\n');
6666         }
6667         else
6668             break;
6669     }
6670     return p;
6671 }
6672
6673 /* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
6674    Character classes ([:foo:]) can also be negated ([:^foo:]).
6675    Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
6676    Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
6677    but trigger failures because they are currently unimplemented. */
6678
6679 #define POSIXCC_DONE(c)   ((c) == ':')
6680 #define POSIXCC_NOTYET(c) ((c) == '=' || (c) == '.')
6681 #define POSIXCC(c) (POSIXCC_DONE(c) || POSIXCC_NOTYET(c))
6682
6683 STATIC I32
6684 S_regpposixcc(pTHX_ RExC_state_t *pRExC_state, I32 value)
6685 {
6686     dVAR;
6687     I32 namedclass = OOB_NAMEDCLASS;
6688
6689     if (value == '[' && RExC_parse + 1 < RExC_end &&
6690         /* I smell either [: or [= or [. -- POSIX has been here, right? */
6691         POSIXCC(UCHARAT(RExC_parse))) {
6692         const char c = UCHARAT(RExC_parse);
6693         char* const s = RExC_parse++;
6694         
6695         while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != c)
6696             RExC_parse++;
6697         if (RExC_parse == RExC_end)
6698             /* Grandfather lone [:, [=, [. */
6699             RExC_parse = s;
6700         else {
6701             const char* const t = RExC_parse++; /* skip over the c */
6702             assert(*t == c);
6703
6704             if (UCHARAT(RExC_parse) == ']') {
6705                 const char *posixcc = s + 1;
6706                 RExC_parse++; /* skip over the ending ] */
6707
6708                 if (*s == ':') {
6709                     const I32 complement = *posixcc == '^' ? *posixcc++ : 0;
6710                     const I32 skip = t - posixcc;
6711
6712                     /* Initially switch on the length of the name.  */
6713                     switch (skip) {
6714                     case 4:
6715                         if (memEQ(posixcc, "word", 4)) /* this is not POSIX, this is the Perl \w */
6716                             namedclass = complement ? ANYOF_NALNUM : ANYOF_ALNUM;
6717                         break;
6718                     case 5:
6719                         /* Names all of length 5.  */
6720                         /* alnum alpha ascii blank cntrl digit graph lower
6721                            print punct space upper  */
6722                         /* Offset 4 gives the best switch position.  */
6723                         switch (posixcc[4]) {
6724                         case 'a':
6725                             if (memEQ(posixcc, "alph", 4)) /* alpha */
6726                                 namedclass = complement ? ANYOF_NALPHA : ANYOF_ALPHA;
6727                             break;
6728                         case 'e':
6729                             if (memEQ(posixcc, "spac", 4)) /* space */
6730                                 namedclass = complement ? ANYOF_NPSXSPC : ANYOF_PSXSPC;
6731                             break;
6732                         case 'h':
6733                             if (memEQ(posixcc, "grap", 4)) /* graph */
6734                                 namedclass = complement ? ANYOF_NGRAPH : ANYOF_GRAPH;
6735                             break;
6736                         case 'i':
6737                             if (memEQ(posixcc, "asci", 4)) /* ascii */
6738                                 namedclass = complement ? ANYOF_NASCII : ANYOF_ASCII;
6739                             break;
6740                         case 'k':
6741                             if (memEQ(posixcc, "blan", 4)) /* blank */
6742                                 namedclass = complement ? ANYOF_NBLANK : ANYOF_BLANK;
6743                             break;
6744                         case 'l':
6745                             if (memEQ(posixcc, "cntr", 4)) /* cntrl */
6746                                 namedclass = complement ? ANYOF_NCNTRL : ANYOF_CNTRL;
6747                             break;
6748                         case 'm':
6749                             if (memEQ(posixcc, "alnu", 4)) /* alnum */
6750                                 namedclass = complement ? ANYOF_NALNUMC : ANYOF_ALNUMC;
6751                             break;
6752                         case 'r':
6753                             if (memEQ(posixcc, "lowe", 4)) /* lower */
6754                                 namedclass = complement ? ANYOF_NLOWER : ANYOF_LOWER;
6755                             else if (memEQ(posixcc, "uppe", 4)) /* upper */
6756                                 namedclass = complement ? ANYOF_NUPPER : ANYOF_UPPER;
6757                             break;
6758                         case 't':
6759                             if (memEQ(posixcc, "digi", 4)) /* digit */
6760                                 namedclass = complement ? ANYOF_NDIGIT : ANYOF_DIGIT;
6761                             else if (memEQ(posixcc, "prin", 4)) /* print */
6762                                 namedclass = complement ? ANYOF_NPRINT : ANYOF_PRINT;
6763                             else if (memEQ(posixcc, "punc", 4)) /* punct */
6764                                 namedclass = complement ? ANYOF_NPUNCT : ANYOF_PUNCT;
6765                             break;
6766                         }
6767                         break;
6768                     case 6:
6769                         if (memEQ(posixcc, "xdigit", 6))
6770                             namedclass = complement ? ANYOF_NXDIGIT : ANYOF_XDIGIT;
6771                         break;
6772                     }
6773
6774                     if (namedclass == OOB_NAMEDCLASS)
6775                         Simple_vFAIL3("POSIX class [:%.*s:] unknown",
6776                                       t - s - 1, s + 1);
6777                     assert (posixcc[skip] == ':');
6778                     assert (posixcc[skip+1] == ']');
6779                 } else if (!SIZE_ONLY) {
6780                     /* [[=foo=]] and [[.foo.]] are still future. */
6781
6782                     /* adjust RExC_parse so the warning shows after
6783                        the class closes */
6784                     while (UCHARAT(RExC_parse) && UCHARAT(RExC_parse) != ']')
6785                         RExC_parse++;
6786                     Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
6787                 }
6788             } else {
6789                 /* Maternal grandfather:
6790                  * "[:" ending in ":" but not in ":]" */
6791                 RExC_parse = s;
6792             }
6793         }
6794     }
6795
6796     return namedclass;
6797 }
6798
6799 STATIC void
6800 S_checkposixcc(pTHX_ RExC_state_t *pRExC_state)
6801 {
6802     dVAR;
6803     if (POSIXCC(UCHARAT(RExC_parse))) {
6804         const char *s = RExC_parse;
6805         const char  c = *s++;
6806
6807         while (isALNUM(*s))
6808             s++;
6809         if (*s && c == *s && s[1] == ']') {
6810             if (ckWARN(WARN_REGEXP))
6811                 vWARN3(s+2,
6812                         "POSIX syntax [%c %c] belongs inside character classes",
6813                         c, c);
6814
6815             /* [[=foo=]] and [[.foo.]] are still future. */
6816             if (POSIXCC_NOTYET(c)) {
6817                 /* adjust RExC_parse so the error shows after
6818                    the class closes */
6819                 while (UCHARAT(RExC_parse) && UCHARAT(RExC_parse++) != ']')
6820                     NOOP;
6821                 Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
6822             }
6823         }
6824     }
6825 }
6826
6827
6828 /*
6829    parse a class specification and produce either an ANYOF node that
6830    matches the pattern. If the pattern matches a single char only and
6831    that char is < 256 then we produce an EXACT node instead.
6832 */
6833 STATIC regnode *
6834 S_regclass(pTHX_ RExC_state_t *pRExC_state, U32 depth)
6835 {
6836     dVAR;
6837     register UV value = 0;
6838     register UV nextvalue;
6839     register IV prevvalue = OOB_UNICODE;
6840     register IV range = 0;
6841     register regnode *ret;
6842     STRLEN numlen;
6843     IV namedclass;
6844     char *rangebegin = NULL;
6845     bool need_class = 0;
6846     SV *listsv = NULL;
6847     UV n;
6848     bool optimize_invert   = TRUE;
6849     AV* unicode_alternate  = NULL;
6850 #ifdef EBCDIC
6851     UV literal_endpoint = 0;
6852 #endif
6853     UV stored = 0;  /* number of chars stored in the class */
6854
6855     regnode * const orig_emit = RExC_emit; /* Save the original RExC_emit in
6856         case we need to change the emitted regop to an EXACT. */
6857     const char * orig_parse = RExC_parse;
6858     GET_RE_DEBUG_FLAGS_DECL;
6859 #ifndef DEBUGGING
6860     PERL_UNUSED_ARG(depth);
6861 #endif
6862
6863     DEBUG_PARSE("clas");
6864
6865     /* Assume we are going to generate an ANYOF node. */
6866     ret = reganode(pRExC_state, ANYOF, 0);
6867
6868     if (!SIZE_ONLY)
6869         ANYOF_FLAGS(ret) = 0;
6870
6871     if (UCHARAT(RExC_parse) == '^') {   /* Complement of range. */
6872         RExC_naughty++;
6873         RExC_parse++;
6874         if (!SIZE_ONLY)
6875             ANYOF_FLAGS(ret) |= ANYOF_INVERT;
6876     }
6877
6878     if (SIZE_ONLY) {
6879         RExC_size += ANYOF_SKIP;
6880         listsv = &PL_sv_undef; /* For code scanners: listsv always non-NULL. */
6881     }
6882     else {
6883         RExC_emit += ANYOF_SKIP;
6884         if (FOLD)
6885             ANYOF_FLAGS(ret) |= ANYOF_FOLD;
6886         if (LOC)
6887             ANYOF_FLAGS(ret) |= ANYOF_LOCALE;
6888         ANYOF_BITMAP_ZERO(ret);
6889         listsv = newSVpvs("# comment\n");
6890     }
6891
6892     nextvalue = RExC_parse < RExC_end ? UCHARAT(RExC_parse) : 0;
6893
6894     if (!SIZE_ONLY && POSIXCC(nextvalue))
6895         checkposixcc(pRExC_state);
6896
6897     /* allow 1st char to be ] (allowing it to be - is dealt with later) */
6898     if (UCHARAT(RExC_parse) == ']')
6899         goto charclassloop;
6900
6901 parseit:
6902     while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != ']') {
6903
6904     charclassloop:
6905
6906         namedclass = OOB_NAMEDCLASS; /* initialize as illegal */
6907
6908         if (!range)
6909             rangebegin = RExC_parse;
6910         if (UTF) {
6911             value = utf8n_to_uvchr((U8*)RExC_parse,
6912                                    RExC_end - RExC_parse,
6913                                    &numlen, UTF8_ALLOW_DEFAULT);
6914             RExC_parse += numlen;
6915         }
6916         else
6917             value = UCHARAT(RExC_parse++);
6918
6919         nextvalue = RExC_parse < RExC_end ? UCHARAT(RExC_parse) : 0;
6920         if (value == '[' && POSIXCC(nextvalue))
6921             namedclass = regpposixcc(pRExC_state, value);
6922         else if (value == '\\') {
6923             if (UTF) {
6924                 value = utf8n_to_uvchr((U8*)RExC_parse,
6925                                    RExC_end - RExC_parse,
6926                                    &numlen, UTF8_ALLOW_DEFAULT);
6927                 RExC_parse += numlen;
6928             }
6929             else
6930                 value = UCHARAT(RExC_parse++);
6931             /* Some compilers cannot handle switching on 64-bit integer
6932              * values, therefore value cannot be an UV.  Yes, this will
6933              * be a problem later if we want switch on Unicode.
6934              * A similar issue a little bit later when switching on
6935              * namedclass. --jhi */
6936             switch ((I32)value) {
6937             case 'w':   namedclass = ANYOF_ALNUM;       break;
6938             case 'W':   namedclass = ANYOF_NALNUM;      break;
6939             case 's':   namedclass = ANYOF_SPACE;       break;
6940             case 'S':   namedclass = ANYOF_NSPACE;      break;
6941             case 'd':   namedclass = ANYOF_DIGIT;       break;
6942             case 'D':   namedclass = ANYOF_NDIGIT;      break;
6943             case 'N':  /* Handle \N{NAME} in class */
6944                 {
6945                     /* We only pay attention to the first char of 
6946                     multichar strings being returned. I kinda wonder
6947                     if this makes sense as it does change the behaviour
6948                     from earlier versions, OTOH that behaviour was broken
6949                     as well. */
6950                     UV v; /* value is register so we cant & it /grrr */
6951                     if (reg_namedseq(pRExC_state, &v)) {
6952                         goto parseit;
6953                     }
6954                     value= v; 
6955                 }
6956                 break;
6957             case 'p':
6958             case 'P':
6959                 {
6960                 char *e;
6961                 if (RExC_parse >= RExC_end)
6962                     vFAIL2("Empty \\%c{}", (U8)value);
6963                 if (*RExC_parse == '{') {
6964                     const U8 c = (U8)value;
6965                     e = strchr(RExC_parse++, '}');
6966                     if (!e)
6967                         vFAIL2("Missing right brace on \\%c{}", c);
6968                     while (isSPACE(UCHARAT(RExC_parse)))
6969                         RExC_parse++;
6970                     if (e == RExC_parse)
6971                         vFAIL2("Empty \\%c{}", c);
6972                     n = e - RExC_parse;
6973                     while (isSPACE(UCHARAT(RExC_parse + n - 1)))
6974                         n--;
6975                 }
6976                 else {
6977                     e = RExC_parse;
6978                     n = 1;
6979                 }
6980                 if (!SIZE_ONLY) {
6981                     if (UCHARAT(RExC_parse) == '^') {
6982                          RExC_parse++;
6983                          n--;
6984                          value = value == 'p' ? 'P' : 'p'; /* toggle */
6985                          while (isSPACE(UCHARAT(RExC_parse))) {
6986                               RExC_parse++;
6987                               n--;
6988                          }
6989                     }
6990                     Perl_sv_catpvf(aTHX_ listsv, "%cutf8::%.*s\n",
6991                         (value=='p' ? '+' : '!'), (int)n, RExC_parse);
6992                 }
6993                 RExC_parse = e + 1;
6994                 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
6995                 namedclass = ANYOF_MAX;  /* no official name, but it's named */
6996                 }
6997                 break;
6998             case 'n':   value = '\n';                   break;
6999             case 'r':   value = '\r';                   break;
7000             case 't':   value = '\t';                   break;
7001             case 'f':   value = '\f';                   break;
7002             case 'b':   value = '\b';                   break;
7003             case 'e':   value = ASCII_TO_NATIVE('\033');break;
7004             case 'a':   value = ASCII_TO_NATIVE('\007');break;
7005             case 'x':
7006                 if (*RExC_parse == '{') {
7007                     I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
7008                         | PERL_SCAN_DISALLOW_PREFIX;
7009                     char * const e = strchr(RExC_parse++, '}');
7010                     if (!e)
7011                         vFAIL("Missing right brace on \\x{}");
7012
7013                     numlen = e - RExC_parse;
7014                     value = grok_hex(RExC_parse, &numlen, &flags, NULL);
7015                     RExC_parse = e + 1;
7016                 }
7017                 else {
7018                     I32 flags = PERL_SCAN_DISALLOW_PREFIX;
7019                     numlen = 2;
7020                     value = grok_hex(RExC_parse, &numlen, &flags, NULL);
7021                     RExC_parse += numlen;
7022                 }
7023                 if (PL_encoding && value < 0x100)
7024                     goto recode_encoding;
7025                 break;
7026             case 'c':
7027                 value = UCHARAT(RExC_parse++);
7028                 value = toCTRL(value);
7029                 break;
7030             case '0': case '1': case '2': case '3': case '4':
7031             case '5': case '6': case '7': case '8': case '9':
7032                 {
7033                     I32 flags = 0;
7034                     numlen = 3;
7035                     value = grok_oct(--RExC_parse, &numlen, &flags, NULL);
7036                     RExC_parse += numlen;
7037                     if (PL_encoding && value < 0x100)
7038                         goto recode_encoding;
7039                     break;
7040                 }
7041             recode_encoding:
7042                 {
7043                     SV* enc = PL_encoding;
7044                     value = reg_recode((const char)(U8)value, &enc);
7045                     if (!enc && SIZE_ONLY && ckWARN(WARN_REGEXP))
7046                         vWARN(RExC_parse,
7047                               "Invalid escape in the specified encoding");
7048                     break;
7049                 }
7050             default:
7051                 if (!SIZE_ONLY && isALPHA(value) && ckWARN(WARN_REGEXP))
7052                     vWARN2(RExC_parse,
7053                            "Unrecognized escape \\%c in character class passed through",
7054                            (int)value);
7055                 break;
7056             }
7057         } /* end of \blah */
7058 #ifdef EBCDIC
7059         else
7060             literal_endpoint++;
7061 #endif
7062
7063         if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */
7064
7065             if (!SIZE_ONLY && !need_class)
7066                 ANYOF_CLASS_ZERO(ret);
7067
7068             need_class = 1;
7069
7070             /* a bad range like a-\d, a-[:digit:] ? */
7071             if (range) {
7072                 if (!SIZE_ONLY) {
7073                     if (ckWARN(WARN_REGEXP)) {
7074                         const int w =
7075                             RExC_parse >= rangebegin ?
7076                             RExC_parse - rangebegin : 0;
7077                         vWARN4(RExC_parse,
7078                                "False [] range \"%*.*s\"",
7079                                w, w, rangebegin);
7080                     }
7081                     if (prevvalue < 256) {
7082                         ANYOF_BITMAP_SET(ret, prevvalue);
7083                         ANYOF_BITMAP_SET(ret, '-');
7084                     }
7085                     else {
7086                         ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
7087                         Perl_sv_catpvf(aTHX_ listsv,
7088                                        "%04"UVxf"\n%04"UVxf"\n", (UV)prevvalue, (UV) '-');
7089                     }
7090                 }
7091
7092                 range = 0; /* this was not a true range */
7093             }
7094
7095             if (!SIZE_ONLY) {
7096                 const char *what = NULL;
7097                 char yesno = 0;
7098
7099                 if (namedclass > OOB_NAMEDCLASS)
7100                     optimize_invert = FALSE;
7101                 /* Possible truncation here but in some 64-bit environments
7102                  * the compiler gets heartburn about switch on 64-bit values.
7103                  * A similar issue a little earlier when switching on value.
7104                  * --jhi */
7105                 switch ((I32)namedclass) {
7106                 case ANYOF_ALNUM:
7107                     if (LOC)
7108                         ANYOF_CLASS_SET(ret, ANYOF_ALNUM);
7109                     else {
7110                         for (value = 0; value < 256; value++)
7111                             if (isALNUM(value))
7112                                 ANYOF_BITMAP_SET(ret, value);
7113                     }
7114                     yesno = '+';
7115                     what = "Word";      
7116                     break;
7117                 case ANYOF_NALNUM:
7118                     if (LOC)
7119                         ANYOF_CLASS_SET(ret, ANYOF_NALNUM);
7120                     else {
7121                         for (value = 0; value < 256; value++)
7122                             if (!isALNUM(value))
7123                                 ANYOF_BITMAP_SET(ret, value);
7124                     }
7125                     yesno = '!';
7126                     what = "Word";
7127                     break;
7128                 case ANYOF_ALNUMC:
7129                     if (LOC)
7130                         ANYOF_CLASS_SET(ret, ANYOF_ALNUMC);
7131                     else {
7132                         for (value = 0; value < 256; value++)
7133                             if (isALNUMC(value))
7134                                 ANYOF_BITMAP_SET(ret, value);
7135                     }
7136                     yesno = '+';
7137                     what = "Alnum";
7138                     break;
7139                 case ANYOF_NALNUMC:
7140                     if (LOC)
7141                         ANYOF_CLASS_SET(ret, ANYOF_NALNUMC);
7142                     else {
7143                         for (value = 0; value < 256; value++)
7144                             if (!isALNUMC(value))
7145                                 ANYOF_BITMAP_SET(ret, value);
7146                     }
7147                     yesno = '!';
7148                     what = "Alnum";
7149                     break;
7150                 case ANYOF_ALPHA:
7151                     if (LOC)
7152                         ANYOF_CLASS_SET(ret, ANYOF_ALPHA);
7153                     else {
7154                         for (value = 0; value < 256; value++)
7155                             if (isALPHA(value))
7156                                 ANYOF_BITMAP_SET(ret, value);
7157                     }
7158                     yesno = '+';
7159                     what = "Alpha";
7160                     break;
7161                 case ANYOF_NALPHA:
7162                     if (LOC)
7163                         ANYOF_CLASS_SET(ret, ANYOF_NALPHA);
7164                     else {
7165                         for (value = 0; value < 256; value++)
7166                             if (!isALPHA(value))
7167                                 ANYOF_BITMAP_SET(ret, value);
7168                     }
7169                     yesno = '!';
7170                     what = "Alpha";
7171                     break;
7172                 case ANYOF_ASCII:
7173                     if (LOC)
7174                         ANYOF_CLASS_SET(ret, ANYOF_ASCII);
7175                     else {
7176 #ifndef EBCDIC
7177                         for (value = 0; value < 128; value++)
7178                             ANYOF_BITMAP_SET(ret, value);
7179 #else  /* EBCDIC */
7180                         for (value = 0; value < 256; value++) {
7181                             if (isASCII(value))
7182                                 ANYOF_BITMAP_SET(ret, value);
7183                         }
7184 #endif /* EBCDIC */
7185                     }
7186                     yesno = '+';
7187                     what = "ASCII";
7188                     break;
7189                 case ANYOF_NASCII:
7190                     if (LOC)
7191                         ANYOF_CLASS_SET(ret, ANYOF_NASCII);
7192                     else {
7193 #ifndef EBCDIC
7194                         for (value = 128; value < 256; value++)
7195                             ANYOF_BITMAP_SET(ret, value);
7196 #else  /* EBCDIC */
7197                         for (value = 0; value < 256; value++) {
7198                             if (!isASCII(value))
7199                                 ANYOF_BITMAP_SET(ret, value);
7200                         }
7201 #endif /* EBCDIC */
7202                     }
7203                     yesno = '!';
7204                     what = "ASCII";
7205                     break;
7206                 case ANYOF_BLANK:
7207                     if (LOC)
7208                         ANYOF_CLASS_SET(ret, ANYOF_BLANK);
7209                     else {
7210                         for (value = 0; value < 256; value++)
7211                             if (isBLANK(value))
7212                                 ANYOF_BITMAP_SET(ret, value);
7213                     }
7214                     yesno = '+';
7215                     what = "Blank";
7216                     break;
7217                 case ANYOF_NBLANK:
7218                     if (LOC)
7219                         ANYOF_CLASS_SET(ret, ANYOF_NBLANK);
7220                     else {
7221                         for (value = 0; value < 256; value++)
7222                             if (!isBLANK(value))
7223                                 ANYOF_BITMAP_SET(ret, value);
7224                     }
7225                     yesno = '!';
7226                     what = "Blank";
7227                     break;
7228                 case ANYOF_CNTRL:
7229                     if (LOC)
7230                         ANYOF_CLASS_SET(ret, ANYOF_CNTRL);
7231                     else {
7232                         for (value = 0; value < 256; value++)
7233                             if (isCNTRL(value))
7234                                 ANYOF_BITMAP_SET(ret, value);
7235                     }
7236                     yesno = '+';
7237                     what = "Cntrl";
7238                     break;
7239                 case ANYOF_NCNTRL:
7240                     if (LOC)
7241                         ANYOF_CLASS_SET(ret, ANYOF_NCNTRL);
7242                     else {
7243                         for (value = 0; value < 256; value++)
7244                             if (!isCNTRL(value))
7245                                 ANYOF_BITMAP_SET(ret, value);
7246                     }
7247                     yesno = '!';
7248                     what = "Cntrl";
7249                     break;
7250                 case ANYOF_DIGIT:
7251                     if (LOC)
7252                         ANYOF_CLASS_SET(ret, ANYOF_DIGIT);
7253                     else {
7254                         /* consecutive digits assumed */
7255                         for (value = '0'; value <= '9'; value++)
7256                             ANYOF_BITMAP_SET(ret, value);
7257                     }
7258                     yesno = '+';
7259                     what = "Digit";
7260                     break;
7261                 case ANYOF_NDIGIT:
7262                     if (LOC)
7263                         ANYOF_CLASS_SET(ret, ANYOF_NDIGIT);
7264                     else {
7265                         /* consecutive digits assumed */
7266                         for (value = 0; value < '0'; value++)
7267                             ANYOF_BITMAP_SET(ret, value);
7268                         for (value = '9' + 1; value < 256; value++)
7269                             ANYOF_BITMAP_SET(ret, value);
7270                     }
7271                     yesno = '!';
7272                     what = "Digit";
7273                     break;
7274                 case ANYOF_GRAPH:
7275                     if (LOC)
7276                         ANYOF_CLASS_SET(ret, ANYOF_GRAPH);
7277                     else {
7278                         for (value = 0; value < 256; value++)
7279                             if (isGRAPH(value))
7280                                 ANYOF_BITMAP_SET(ret, value);
7281                     }
7282                     yesno = '+';
7283                     what = "Graph";
7284                     break;
7285                 case ANYOF_NGRAPH:
7286                     if (LOC)
7287                         ANYOF_CLASS_SET(ret, ANYOF_NGRAPH);
7288                     else {
7289                         for (value = 0; value < 256; value++)
7290                             if (!isGRAPH(value))
7291                                 ANYOF_BITMAP_SET(ret, value);
7292                     }
7293                     yesno = '!';
7294                     what = "Graph";
7295                     break;
7296                 case ANYOF_LOWER:
7297                     if (LOC)
7298                         ANYOF_CLASS_SET(ret, ANYOF_LOWER);
7299                     else {
7300                         for (value = 0; value < 256; value++)
7301                             if (isLOWER(value))
7302                                 ANYOF_BITMAP_SET(ret, value);
7303                     }
7304                     yesno = '+';
7305                     what = "Lower";
7306                     break;
7307                 case ANYOF_NLOWER:
7308                     if (LOC)
7309                         ANYOF_CLASS_SET(ret, ANYOF_NLOWER);
7310                     else {
7311                         for (value = 0; value < 256; value++)
7312                             if (!isLOWER(value))
7313                                 ANYOF_BITMAP_SET(ret, value);
7314                     }
7315                     yesno = '!';
7316                     what = "Lower";
7317                     break;
7318                 case ANYOF_PRINT:
7319                     if (LOC)
7320                         ANYOF_CLASS_SET(ret, ANYOF_PRINT);
7321                     else {
7322                         for (value = 0; value < 256; value++)
7323                             if (isPRINT(value))
7324                                 ANYOF_BITMAP_SET(ret, value);
7325                     }
7326                     yesno = '+';
7327                     what = "Print";
7328                     break;
7329                 case ANYOF_NPRINT:
7330                     if (LOC)
7331                         ANYOF_CLASS_SET(ret, ANYOF_NPRINT);
7332                     else {
7333                         for (value = 0; value < 256; value++)
7334                             if (!isPRINT(value))
7335                                 ANYOF_BITMAP_SET(ret, value);
7336                     }
7337                     yesno = '!';
7338                     what = "Print";
7339                     break;
7340                 case ANYOF_PSXSPC:
7341                     if (LOC)
7342                         ANYOF_CLASS_SET(ret, ANYOF_PSXSPC);
7343                     else {
7344                         for (value = 0; value < 256; value++)
7345                             if (isPSXSPC(value))
7346                                 ANYOF_BITMAP_SET(ret, value);
7347                     }
7348                     yesno = '+';
7349                     what = "Space";
7350                     break;
7351                 case ANYOF_NPSXSPC:
7352                     if (LOC)
7353                         ANYOF_CLASS_SET(ret, ANYOF_NPSXSPC);
7354                     else {
7355                         for (value = 0; value < 256; value++)
7356                             if (!isPSXSPC(value))
7357                                 ANYOF_BITMAP_SET(ret, value);
7358                     }
7359                     yesno = '!';
7360                     what = "Space";
7361                     break;
7362                 case ANYOF_PUNCT:
7363                     if (LOC)
7364                         ANYOF_CLASS_SET(ret, ANYOF_PUNCT);
7365                     else {
7366                         for (value = 0; value < 256; value++)
7367                             if (isPUNCT(value))
7368                                 ANYOF_BITMAP_SET(ret, value);
7369                     }
7370                     yesno = '+';
7371                     what = "Punct";
7372                     break;
7373                 case ANYOF_NPUNCT:
7374                     if (LOC)
7375                         ANYOF_CLASS_SET(ret, ANYOF_NPUNCT);
7376                     else {
7377                         for (value = 0; value < 256; value++)
7378                             if (!isPUNCT(value))
7379                                 ANYOF_BITMAP_SET(ret, value);
7380                     }
7381                     yesno = '!';
7382                     what = "Punct";
7383                     break;
7384                 case ANYOF_SPACE:
7385                     if (LOC)
7386                         ANYOF_CLASS_SET(ret, ANYOF_SPACE);
7387                     else {
7388                         for (value = 0; value < 256; value++)
7389                             if (isSPACE(value))
7390                                 ANYOF_BITMAP_SET(ret, value);
7391                     }
7392                     yesno = '+';
7393                     what = "SpacePerl";
7394                     break;
7395                 case ANYOF_NSPACE:
7396                     if (LOC)
7397                         ANYOF_CLASS_SET(ret, ANYOF_NSPACE);
7398                     else {
7399                         for (value = 0; value < 256; value++)
7400                             if (!isSPACE(value))
7401                                 ANYOF_BITMAP_SET(ret, value);
7402                     }
7403                     yesno = '!';
7404                     what = "SpacePerl";
7405                     break;
7406                 case ANYOF_UPPER:
7407                     if (LOC)
7408                         ANYOF_CLASS_SET(ret, ANYOF_UPPER);
7409                     else {
7410                         for (value = 0; value < 256; value++)
7411                             if (isUPPER(value))
7412                                 ANYOF_BITMAP_SET(ret, value);
7413                     }
7414                     yesno = '+';
7415                     what = "Upper";
7416                     break;
7417                 case ANYOF_NUPPER:
7418                     if (LOC)
7419                         ANYOF_CLASS_SET(ret, ANYOF_NUPPER);
7420                     else {
7421                         for (value = 0; value < 256; value++)
7422                             if (!isUPPER(value))
7423                                 ANYOF_BITMAP_SET(ret, value);
7424                     }
7425                     yesno = '!';
7426                     what = "Upper";
7427                     break;
7428                 case ANYOF_XDIGIT:
7429                     if (LOC)
7430                         ANYOF_CLASS_SET(ret, ANYOF_XDIGIT);
7431                     else {
7432                         for (value = 0; value < 256; value++)
7433                             if (isXDIGIT(value))
7434                                 ANYOF_BITMAP_SET(ret, value);
7435                     }
7436                     yesno = '+';
7437                     what = "XDigit";
7438                     break;
7439                 case ANYOF_NXDIGIT:
7440                     if (LOC)
7441                         ANYOF_CLASS_SET(ret, ANYOF_NXDIGIT);
7442                     else {
7443                         for (value = 0; value < 256; value++)
7444                             if (!isXDIGIT(value))
7445                                 ANYOF_BITMAP_SET(ret, value);
7446                     }
7447                     yesno = '!';
7448                     what = "XDigit";
7449                     break;
7450                 case ANYOF_MAX:
7451                     /* this is to handle \p and \P */
7452                     break;
7453                 default:
7454                     vFAIL("Invalid [::] class");
7455                     break;
7456                 }
7457                 if (what) {
7458                     /* Strings such as "+utf8::isWord\n" */
7459                     Perl_sv_catpvf(aTHX_ listsv, "%cutf8::Is%s\n", yesno, what);
7460                 }
7461                 if (LOC)
7462                     ANYOF_FLAGS(ret) |= ANYOF_CLASS;
7463                 continue;
7464             }
7465         } /* end of namedclass \blah */
7466
7467         if (range) {
7468             if (prevvalue > (IV)value) /* b-a */ {
7469                 const int w = RExC_parse - rangebegin;
7470                 Simple_vFAIL4("Invalid [] range \"%*.*s\"", w, w, rangebegin);
7471                 range = 0; /* not a valid range */
7472             }
7473         }
7474         else {
7475             prevvalue = value; /* save the beginning of the range */
7476             if (*RExC_parse == '-' && RExC_parse+1 < RExC_end &&
7477                 RExC_parse[1] != ']') {
7478                 RExC_parse++;
7479
7480                 /* a bad range like \w-, [:word:]- ? */
7481                 if (namedclass > OOB_NAMEDCLASS) {
7482                     if (ckWARN(WARN_REGEXP)) {
7483                         const int w =
7484                             RExC_parse >= rangebegin ?
7485                             RExC_parse - rangebegin : 0;
7486                         vWARN4(RExC_parse,
7487                                "False [] range \"%*.*s\"",
7488                                w, w, rangebegin);
7489                     }
7490                     if (!SIZE_ONLY)
7491                         ANYOF_BITMAP_SET(ret, '-');
7492                 } else
7493                     range = 1;  /* yeah, it's a range! */
7494                 continue;       /* but do it the next time */
7495             }
7496         }
7497
7498         /* now is the next time */
7499         /*stored += (value - prevvalue + 1);*/
7500         if (!SIZE_ONLY) {
7501             if (prevvalue < 256) {
7502                 const IV ceilvalue = value < 256 ? value : 255;
7503                 IV i;
7504 #ifdef EBCDIC
7505                 /* In EBCDIC [\x89-\x91] should include
7506                  * the \x8e but [i-j] should not. */
7507                 if (literal_endpoint == 2 &&
7508                     ((isLOWER(prevvalue) && isLOWER(ceilvalue)) ||
7509                      (isUPPER(prevvalue) && isUPPER(ceilvalue))))
7510                 {
7511                     if (isLOWER(prevvalue)) {
7512                         for (i = prevvalue; i <= ceilvalue; i++)
7513                             if (isLOWER(i))
7514                                 ANYOF_BITMAP_SET(ret, i);
7515                     } else {
7516                         for (i = prevvalue; i <= ceilvalue; i++)
7517                             if (isUPPER(i))
7518                                 ANYOF_BITMAP_SET(ret, i);
7519                     }
7520                 }
7521                 else
7522 #endif
7523                       for (i = prevvalue; i <= ceilvalue; i++) {
7524                         if (!ANYOF_BITMAP_TEST(ret,i)) {
7525                             stored++;  
7526                             ANYOF_BITMAP_SET(ret, i);
7527                         }
7528                       }
7529           }
7530           if (value > 255 || UTF) {
7531                 const UV prevnatvalue  = NATIVE_TO_UNI(prevvalue);
7532                 const UV natvalue      = NATIVE_TO_UNI(value);
7533                 stored+=2; /* can't optimize this class */
7534                 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
7535                 if (prevnatvalue < natvalue) { /* what about > ? */
7536                     Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\t%04"UVxf"\n",
7537                                    prevnatvalue, natvalue);
7538                 }
7539                 else if (prevnatvalue == natvalue) {
7540                     Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n", natvalue);
7541                     if (FOLD) {
7542                          U8 foldbuf[UTF8_MAXBYTES_CASE+1];
7543                          STRLEN foldlen;
7544                          const UV f = to_uni_fold(natvalue, foldbuf, &foldlen);
7545
7546 #ifdef EBCDIC /* RD t/uni/fold ff and 6b */
7547                          if (RExC_precomp[0] == ':' &&
7548                              RExC_precomp[1] == '[' &&
7549                              (f == 0xDF || f == 0x92)) {
7550                              f = NATIVE_TO_UNI(f);
7551                         }
7552 #endif
7553                          /* If folding and foldable and a single
7554                           * character, insert also the folded version
7555                           * to the charclass. */
7556                          if (f != value) {
7557 #ifdef EBCDIC /* RD tunifold ligatures s,t fb05, fb06 */
7558                              if ((RExC_precomp[0] == ':' &&
7559                                   RExC_precomp[1] == '[' &&
7560                                   (f == 0xA2 &&
7561                                    (value == 0xFB05 || value == 0xFB06))) ?
7562                                  foldlen == ((STRLEN)UNISKIP(f) - 1) :
7563                                  foldlen == (STRLEN)UNISKIP(f) )
7564 #else
7565                               if (foldlen == (STRLEN)UNISKIP(f))
7566 #endif
7567                                   Perl_sv_catpvf(aTHX_ listsv,
7568                                                  "%04"UVxf"\n", f);
7569                               else {
7570                                   /* Any multicharacter foldings
7571                                    * require the following transform:
7572                                    * [ABCDEF] -> (?:[ABCabcDEFd]|pq|rst)
7573                                    * where E folds into "pq" and F folds
7574                                    * into "rst", all other characters
7575                                    * fold to single characters.  We save
7576                                    * away these multicharacter foldings,
7577                                    * to be later saved as part of the
7578                                    * additional "s" data. */
7579                                   SV *sv;
7580
7581                                   if (!unicode_alternate)
7582                                       unicode_alternate = newAV();
7583                                   sv = newSVpvn((char*)foldbuf, foldlen);
7584                                   SvUTF8_on(sv);
7585                                   av_push(unicode_alternate, sv);
7586                               }
7587                          }
7588
7589                          /* If folding and the value is one of the Greek
7590                           * sigmas insert a few more sigmas to make the
7591                           * folding rules of the sigmas to work right.
7592                           * Note that not all the possible combinations
7593                           * are handled here: some of them are handled
7594                           * by the standard folding rules, and some of
7595                           * them (literal or EXACTF cases) are handled
7596                           * during runtime in regexec.c:S_find_byclass(). */
7597                          if (value == UNICODE_GREEK_SMALL_LETTER_FINAL_SIGMA) {
7598                               Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
7599                                              (UV)UNICODE_GREEK_CAPITAL_LETTER_SIGMA);
7600                               Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
7601                                              (UV)UNICODE_GREEK_SMALL_LETTER_SIGMA);
7602                          }
7603                          else if (value == UNICODE_GREEK_CAPITAL_LETTER_SIGMA)
7604                               Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
7605                                              (UV)UNICODE_GREEK_SMALL_LETTER_SIGMA);
7606                     }
7607                 }
7608             }
7609 #ifdef EBCDIC
7610             literal_endpoint = 0;
7611 #endif
7612         }
7613
7614         range = 0; /* this range (if it was one) is done now */
7615     }
7616
7617     if (need_class) {
7618         ANYOF_FLAGS(ret) |= ANYOF_LARGE;
7619         if (SIZE_ONLY)
7620             RExC_size += ANYOF_CLASS_ADD_SKIP;
7621         else
7622             RExC_emit += ANYOF_CLASS_ADD_SKIP;
7623     }
7624
7625
7626     if (SIZE_ONLY)
7627         return ret;
7628     /****** !SIZE_ONLY AFTER HERE *********/
7629
7630     if( stored == 1 && value < 256
7631         && !( ANYOF_FLAGS(ret) & ( ANYOF_FLAGS_ALL ^ ANYOF_FOLD ) )
7632     ) {
7633         /* optimize single char class to an EXACT node
7634            but *only* when its not a UTF/high char  */
7635         const char * cur_parse= RExC_parse;
7636         RExC_emit = (regnode *)orig_emit;
7637         RExC_parse = (char *)orig_parse;
7638         ret = reg_node(pRExC_state,
7639                        (U8)((ANYOF_FLAGS(ret) & ANYOF_FOLD) ? EXACTF : EXACT));
7640         RExC_parse = (char *)cur_parse;
7641         *STRING(ret)= (char)value;
7642         STR_LEN(ret)= 1;
7643         RExC_emit += STR_SZ(1);
7644         return ret;
7645     }
7646     /* optimize case-insensitive simple patterns (e.g. /[a-z]/i) */
7647     if ( /* If the only flag is folding (plus possibly inversion). */
7648         ((ANYOF_FLAGS(ret) & (ANYOF_FLAGS_ALL ^ ANYOF_INVERT)) == ANYOF_FOLD)
7649        ) {
7650         for (value = 0; value < 256; ++value) {
7651             if (ANYOF_BITMAP_TEST(ret, value)) {
7652                 UV fold = PL_fold[value];
7653
7654                 if (fold != value)
7655                     ANYOF_BITMAP_SET(ret, fold);
7656             }
7657         }
7658         ANYOF_FLAGS(ret) &= ~ANYOF_FOLD;
7659     }
7660
7661     /* optimize inverted simple patterns (e.g. [^a-z]) */
7662     if (optimize_invert &&
7663         /* If the only flag is inversion. */
7664         (ANYOF_FLAGS(ret) & ANYOF_FLAGS_ALL) == ANYOF_INVERT) {
7665         for (value = 0; value < ANYOF_BITMAP_SIZE; ++value)
7666             ANYOF_BITMAP(ret)[value] ^= ANYOF_FLAGS_ALL;
7667         ANYOF_FLAGS(ret) = ANYOF_UNICODE_ALL;
7668     }
7669     {
7670         AV * const av = newAV();
7671         SV *rv;
7672         /* The 0th element stores the character class description
7673          * in its textual form: used later (regexec.c:Perl_regclass_swash())
7674          * to initialize the appropriate swash (which gets stored in
7675          * the 1st element), and also useful for dumping the regnode.
7676          * The 2nd element stores the multicharacter foldings,
7677          * used later (regexec.c:S_reginclass()). */
7678         av_store(av, 0, listsv);
7679         av_store(av, 1, NULL);
7680         av_store(av, 2, (SV*)unicode_alternate);
7681         rv = newRV_noinc((SV*)av);
7682         n = add_data(pRExC_state, 1, "s");
7683         RExC_rx->data->data[n] = (void*)rv;
7684         ARG_SET(ret, n);
7685     }
7686     return ret;
7687 }
7688
7689 STATIC char*
7690 S_nextchar(pTHX_ RExC_state_t *pRExC_state)
7691 {
7692     char* const retval = RExC_parse++;
7693
7694     for (;;) {
7695         if (*RExC_parse == '(' && RExC_parse[1] == '?' &&
7696                 RExC_parse[2] == '#') {
7697             while (*RExC_parse != ')') {
7698                 if (RExC_parse == RExC_end)
7699                     FAIL("Sequence (?#... not terminated");
7700                 RExC_parse++;
7701             }
7702             RExC_parse++;
7703             continue;
7704         }
7705         if (RExC_flags & PMf_EXTENDED) {
7706             if (isSPACE(*RExC_parse)) {
7707                 RExC_parse++;
7708                 continue;
7709             }
7710             else if (*RExC_parse == '#') {
7711                 while (RExC_parse < RExC_end)
7712                     if (*RExC_parse++ == '\n') break;
7713                 continue;
7714             }
7715         }
7716         return retval;
7717     }
7718 }
7719
7720 /*
7721 - reg_node - emit a node
7722 */
7723 STATIC regnode *                        /* Location. */
7724 S_reg_node(pTHX_ RExC_state_t *pRExC_state, U8 op)
7725 {
7726     dVAR;
7727     register regnode *ptr;
7728     regnode * const ret = RExC_emit;
7729     GET_RE_DEBUG_FLAGS_DECL;
7730
7731     if (SIZE_ONLY) {
7732         SIZE_ALIGN(RExC_size);
7733         RExC_size += 1;
7734         return(ret);
7735     }
7736 #ifdef DEBUGGING
7737     if (OP(RExC_emit) == 255)
7738         Perl_croak(aTHX_ "panic: reg_node overrun trying to emit %s: %d ",
7739             reg_name[op], OP(RExC_emit));
7740 #endif  
7741     NODE_ALIGN_FILL(ret);
7742     ptr = ret;
7743     FILL_ADVANCE_NODE(ptr, op);
7744     if (RExC_offsets) {         /* MJD */
7745         MJD_OFFSET_DEBUG(("%s:%d: (op %s) %s %"UVuf" (len %"UVuf") (max %"UVuf").\n", 
7746               "reg_node", __LINE__, 
7747               reg_name[op],
7748               (UV)(RExC_emit - RExC_emit_start) > RExC_offsets[0] 
7749                 ? "Overwriting end of array!\n" : "OK",
7750               (UV)(RExC_emit - RExC_emit_start),
7751               (UV)(RExC_parse - RExC_start),
7752               (UV)RExC_offsets[0])); 
7753         Set_Node_Offset(RExC_emit, RExC_parse + (op == END));
7754     }
7755
7756     RExC_emit = ptr;
7757     return(ret);
7758 }
7759
7760 /*
7761 - reganode - emit a node with an argument
7762 */
7763 STATIC regnode *                        /* Location. */
7764 S_reganode(pTHX_ RExC_state_t *pRExC_state, U8 op, U32 arg)
7765 {
7766     dVAR;
7767     register regnode *ptr;
7768     regnode * const ret = RExC_emit;
7769     GET_RE_DEBUG_FLAGS_DECL;
7770
7771     if (SIZE_ONLY) {
7772         SIZE_ALIGN(RExC_size);
7773         RExC_size += 2;
7774         /* 
7775            We can't do this:
7776            
7777            assert(2==regarglen[op]+1); 
7778         
7779            Anything larger than this has to allocate the extra amount.
7780            If we changed this to be:
7781            
7782            RExC_size += (1 + regarglen[op]);
7783            
7784            then it wouldn't matter. Its not clear what side effect
7785            might come from that so its not done so far.
7786            -- dmq
7787         */
7788         return(ret);
7789     }
7790 #ifdef DEBUGGING
7791     if (OP(RExC_emit) == 255)
7792         Perl_croak(aTHX_ "panic: reganode overwriting end of allocated program space");
7793 #endif 
7794     NODE_ALIGN_FILL(ret);
7795     ptr = ret;
7796     FILL_ADVANCE_NODE_ARG(ptr, op, arg);
7797     if (RExC_offsets) {         /* MJD */
7798         MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s %"UVuf" <- %"UVuf" (max %"UVuf").\n", 
7799               "reganode",
7800               __LINE__,
7801               reg_name[op],
7802               (UV)(RExC_emit - RExC_emit_start) > RExC_offsets[0] ? 
7803               "Overwriting end of array!\n" : "OK",
7804               (UV)(RExC_emit - RExC_emit_start),
7805               (UV)(RExC_parse - RExC_start),
7806               (UV)RExC_offsets[0])); 
7807         Set_Cur_Node_Offset;
7808     }
7809             
7810     RExC_emit = ptr;
7811     return(ret);
7812 }
7813
7814 /*
7815 - reguni - emit (if appropriate) a Unicode character
7816 */
7817 STATIC STRLEN
7818 S_reguni(pTHX_ const RExC_state_t *pRExC_state, UV uv, char* s)
7819 {
7820     dVAR;
7821     return SIZE_ONLY ? UNISKIP(uv) : (uvchr_to_utf8((U8*)s, uv) - (U8*)s);
7822 }
7823
7824 /*
7825 - reginsert - insert an operator in front of already-emitted operand
7826 *
7827 * Means relocating the operand.
7828 */
7829 STATIC void
7830 S_reginsert(pTHX_ RExC_state_t *pRExC_state, U8 op, regnode *opnd, U32 depth)
7831 {
7832     dVAR;
7833     register regnode *src;
7834     register regnode *dst;
7835     register regnode *place;
7836     const int offset = regarglen[(U8)op];
7837     const int size = NODE_STEP_REGNODE + offset;
7838     GET_RE_DEBUG_FLAGS_DECL;
7839 /* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
7840     DEBUG_PARSE_FMT("inst"," - %s",reg_name[op]);
7841     if (SIZE_ONLY) {
7842         RExC_size += size;
7843         return;
7844     }
7845
7846     src = RExC_emit;
7847     RExC_emit += size;
7848     dst = RExC_emit;
7849     if (RExC_open_parens) {
7850         int paren;
7851         DEBUG_PARSE_FMT("inst"," - %"IVdf, (IV)RExC_npar);
7852         for ( paren=0 ; paren < RExC_npar ; paren++ ) {
7853             if ( RExC_open_parens[paren] >= opnd ) {
7854                 DEBUG_PARSE_FMT("open"," - %d",size);
7855                 RExC_open_parens[paren] += size;
7856             } else {
7857                 DEBUG_PARSE_FMT("open"," - %s","ok");
7858             }
7859             if ( RExC_close_parens[paren] >= opnd ) {
7860                 DEBUG_PARSE_FMT("close"," - %d",size);
7861                 RExC_close_parens[paren] += size;
7862             } else {
7863                 DEBUG_PARSE_FMT("close"," - %s","ok");
7864             }
7865         }
7866     }
7867
7868     while (src > opnd) {
7869         StructCopy(--src, --dst, regnode);
7870         if (RExC_offsets) {     /* MJD 20010112 */
7871             MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s copy %"UVuf" -> %"UVuf" (max %"UVuf").\n",
7872                   "reg_insert",
7873                   __LINE__,
7874                   reg_name[op],
7875                   (UV)(dst - RExC_emit_start) > RExC_offsets[0] 
7876                     ? "Overwriting end of array!\n" : "OK",
7877                   (UV)(src - RExC_emit_start),
7878                   (UV)(dst - RExC_emit_start),
7879                   (UV)RExC_offsets[0])); 
7880             Set_Node_Offset_To_R(dst-RExC_emit_start, Node_Offset(src));
7881             Set_Node_Length_To_R(dst-RExC_emit_start, Node_Length(src));
7882         }
7883     }
7884     
7885
7886     place = opnd;               /* Op node, where operand used to be. */
7887     if (RExC_offsets) {         /* MJD */
7888         MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s %"UVuf" <- %"UVuf" (max %"UVuf").\n", 
7889               "reginsert",
7890               __LINE__,
7891               reg_name[op],
7892               (UV)(place - RExC_emit_start) > RExC_offsets[0] 
7893               ? "Overwriting end of array!\n" : "OK",
7894               (UV)(place - RExC_emit_start),
7895               (UV)(RExC_parse - RExC_start),
7896               (UV)RExC_offsets[0]));
7897         Set_Node_Offset(place, RExC_parse);
7898         Set_Node_Length(place, 1);
7899     }
7900     src = NEXTOPER(place);
7901     FILL_ADVANCE_NODE(place, op);
7902     Zero(src, offset, regnode);
7903 }
7904
7905 /*
7906 - regtail - set the next-pointer at the end of a node chain of p to val.
7907 - SEE ALSO: regtail_study
7908 */
7909 /* TODO: All three parms should be const */
7910 STATIC void
7911 S_regtail(pTHX_ RExC_state_t *pRExC_state, regnode *p, const regnode *val,U32 depth)
7912 {
7913     dVAR;
7914     register regnode *scan;
7915     GET_RE_DEBUG_FLAGS_DECL;
7916 #ifndef DEBUGGING
7917     PERL_UNUSED_ARG(depth);
7918 #endif
7919
7920     if (SIZE_ONLY)
7921         return;
7922
7923     /* Find last node. */
7924     scan = p;
7925     for (;;) {
7926         regnode * const temp = regnext(scan);
7927         DEBUG_PARSE_r({
7928             SV * const mysv=sv_newmortal();
7929             DEBUG_PARSE_MSG((scan==p ? "tail" : ""));
7930             regprop(RExC_rx, mysv, scan);
7931             PerlIO_printf(Perl_debug_log, "~ %s (%d) %s %s\n",
7932                 SvPV_nolen_const(mysv), REG_NODE_NUM(scan),
7933                     (temp == NULL ? "->" : ""),
7934                     (temp == NULL ? reg_name[OP(val)] : "")
7935             );
7936         });
7937         if (temp == NULL)
7938             break;
7939         scan = temp;
7940     }
7941
7942     if (reg_off_by_arg[OP(scan)]) {
7943         ARG_SET(scan, val - scan);
7944     }
7945     else {
7946         NEXT_OFF(scan) = val - scan;
7947     }
7948 }
7949
7950 #ifdef DEBUGGING
7951 /*
7952 - regtail_study - set the next-pointer at the end of a node chain of p to val.
7953 - Look for optimizable sequences at the same time.
7954 - currently only looks for EXACT chains.
7955
7956 This is expermental code. The idea is to use this routine to perform 
7957 in place optimizations on branches and groups as they are constructed,
7958 with the long term intention of removing optimization from study_chunk so
7959 that it is purely analytical.
7960
7961 Currently only used when in DEBUG mode. The macro REGTAIL_STUDY() is used
7962 to control which is which.
7963
7964 */
7965 /* TODO: All four parms should be const */
7966
7967 STATIC U8
7968 S_regtail_study(pTHX_ RExC_state_t *pRExC_state, regnode *p, const regnode *val,U32 depth)
7969 {
7970     dVAR;
7971     register regnode *scan;
7972     U8 exact = PSEUDO;
7973 #ifdef EXPERIMENTAL_INPLACESCAN
7974     I32 min = 0;
7975 #endif
7976
7977     GET_RE_DEBUG_FLAGS_DECL;
7978
7979
7980     if (SIZE_ONLY)
7981         return exact;
7982
7983     /* Find last node. */
7984
7985     scan = p;
7986     for (;;) {
7987         regnode * const temp = regnext(scan);
7988 #ifdef EXPERIMENTAL_INPLACESCAN
7989         if (PL_regkind[OP(scan)] == EXACT)
7990             if (join_exact(pRExC_state,scan,&min,1,val,depth+1))
7991                 return EXACT;
7992 #endif
7993         if ( exact ) {
7994             switch (OP(scan)) {
7995                 case EXACT:
7996                 case EXACTF:
7997                 case EXACTFL:
7998                         if( exact == PSEUDO )
7999                             exact= OP(scan);
8000                         else if ( exact != OP(scan) )
8001                             exact= 0;
8002                 case NOTHING:
8003                     break;
8004                 default:
8005                     exact= 0;
8006             }
8007         }
8008         DEBUG_PARSE_r({
8009             SV * const mysv=sv_newmortal();
8010             DEBUG_PARSE_MSG((scan==p ? "tsdy" : ""));
8011             regprop(RExC_rx, mysv, scan);
8012             PerlIO_printf(Perl_debug_log, "~ %s (%d) -> %s\n",
8013                 SvPV_nolen_const(mysv),
8014                 REG_NODE_NUM(scan),
8015                 reg_name[exact]);
8016         });
8017         if (temp == NULL)
8018             break;
8019         scan = temp;
8020     }
8021     DEBUG_PARSE_r({
8022         SV * const mysv_val=sv_newmortal();
8023         DEBUG_PARSE_MSG("");
8024         regprop(RExC_rx, mysv_val, val);
8025         PerlIO_printf(Perl_debug_log, "~ attach to %s (%d) offset to %d\n",
8026             SvPV_nolen_const(mysv_val),
8027             REG_NODE_NUM(val),
8028             val - scan
8029         );
8030     });
8031     if (reg_off_by_arg[OP(scan)]) {
8032         ARG_SET(scan, val - scan);
8033     }
8034     else {
8035         NEXT_OFF(scan) = val - scan;
8036     }
8037
8038     return exact;
8039 }
8040 #endif
8041
8042 /*
8043  - regcurly - a little FSA that accepts {\d+,?\d*}
8044  */
8045 STATIC I32
8046 S_regcurly(register const char *s)
8047 {
8048     if (*s++ != '{')
8049         return FALSE;
8050     if (!isDIGIT(*s))
8051         return FALSE;
8052     while (isDIGIT(*s))
8053         s++;
8054     if (*s == ',')
8055         s++;
8056     while (isDIGIT(*s))
8057         s++;
8058     if (*s != '}')
8059         return FALSE;
8060     return TRUE;
8061 }
8062
8063
8064 /*
8065  - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
8066  */
8067 void
8068 Perl_regdump(pTHX_ const regexp *r)
8069 {
8070 #ifdef DEBUGGING
8071     dVAR;
8072     SV * const sv = sv_newmortal();
8073     SV *dsv= sv_newmortal();
8074
8075     (void)dumpuntil(r, r->program, r->program + 1, NULL, NULL, sv, 0, 0);
8076
8077     /* Header fields of interest. */
8078     if (r->anchored_substr) {
8079         RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->anchored_substr), 
8080             RE_SV_DUMPLEN(r->anchored_substr), 30);
8081         PerlIO_printf(Perl_debug_log,
8082                       "anchored %s%s at %"IVdf" ",
8083                       s, RE_SV_TAIL(r->anchored_substr),
8084                       (IV)r->anchored_offset);
8085     } else if (r->anchored_utf8) {
8086         RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->anchored_utf8), 
8087             RE_SV_DUMPLEN(r->anchored_utf8), 30);
8088         PerlIO_printf(Perl_debug_log,
8089                       "anchored utf8 %s%s at %"IVdf" ",
8090                       s, RE_SV_TAIL(r->anchored_utf8),
8091                       (IV)r->anchored_offset);
8092     }                 
8093     if (r->float_substr) {
8094         RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->float_substr), 
8095             RE_SV_DUMPLEN(r->float_substr), 30);
8096         PerlIO_printf(Perl_debug_log,
8097                       "floating %s%s at %"IVdf"..%"UVuf" ",
8098                       s, RE_SV_TAIL(r->float_substr),
8099                       (IV)r->float_min_offset, (UV)r->float_max_offset);
8100     } else if (r->float_utf8) {
8101         RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->float_utf8), 
8102             RE_SV_DUMPLEN(r->float_utf8), 30);
8103         PerlIO_printf(Perl_debug_log,
8104                       "floating utf8 %s%s at %"IVdf"..%"UVuf" ",
8105                       s, RE_SV_TAIL(r->float_utf8),
8106                       (IV)r->float_min_offset, (UV)r->float_max_offset);
8107     }
8108     if (r->check_substr || r->check_utf8)
8109         PerlIO_printf(Perl_debug_log,
8110                       (const char *)
8111                       (r->check_substr == r->float_substr
8112                        && r->check_utf8 == r->float_utf8
8113                        ? "(checking floating" : "(checking anchored"));
8114     if (r->reganch & ROPT_NOSCAN)
8115         PerlIO_printf(Perl_debug_log, " noscan");
8116     if (r->reganch & ROPT_CHECK_ALL)
8117         PerlIO_printf(Perl_debug_log, " isall");
8118     if (r->check_substr || r->check_utf8)
8119         PerlIO_printf(Perl_debug_log, ") ");
8120
8121     if (r->regstclass) {
8122         regprop(r, sv, r->regstclass);
8123         PerlIO_printf(Perl_debug_log, "stclass %s ", SvPVX_const(sv));
8124     }
8125     if (r->reganch & ROPT_ANCH) {
8126         PerlIO_printf(Perl_debug_log, "anchored");
8127         if (r->reganch & ROPT_ANCH_BOL)
8128             PerlIO_printf(Perl_debug_log, "(BOL)");
8129         if (r->reganch & ROPT_ANCH_MBOL)
8130             PerlIO_printf(Perl_debug_log, "(MBOL)");
8131         if (r->reganch & ROPT_ANCH_SBOL)
8132             PerlIO_printf(Perl_debug_log, "(SBOL)");
8133         if (r->reganch & ROPT_ANCH_GPOS)
8134             PerlIO_printf(Perl_debug_log, "(GPOS)");
8135         PerlIO_putc(Perl_debug_log, ' ');
8136     }
8137     if (r->reganch & ROPT_GPOS_SEEN)
8138         PerlIO_printf(Perl_debug_log, "GPOS ");
8139     if (r->reganch & ROPT_SKIP)
8140         PerlIO_printf(Perl_debug_log, "plus ");
8141     if (r->reganch & ROPT_IMPLICIT)
8142         PerlIO_printf(Perl_debug_log, "implicit ");
8143     PerlIO_printf(Perl_debug_log, "minlen %ld ", (long) r->minlen);
8144     if (r->reganch & ROPT_EVAL_SEEN)
8145         PerlIO_printf(Perl_debug_log, "with eval ");
8146     PerlIO_printf(Perl_debug_log, "\n");
8147 #else
8148     PERL_UNUSED_CONTEXT;
8149     PERL_UNUSED_ARG(r);
8150 #endif  /* DEBUGGING */
8151 }
8152
8153 /*
8154 - regprop - printable representation of opcode
8155 */
8156 void
8157 Perl_regprop(pTHX_ const regexp *prog, SV *sv, const regnode *o)
8158 {
8159 #ifdef DEBUGGING
8160     dVAR;
8161     register int k;
8162     GET_RE_DEBUG_FLAGS_DECL;
8163
8164     sv_setpvn(sv, "", 0);
8165
8166     if (OP(o) > REGNODE_MAX)            /* regnode.type is unsigned */
8167         /* It would be nice to FAIL() here, but this may be called from
8168            regexec.c, and it would be hard to supply pRExC_state. */
8169         Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d", (int)OP(o), (int)REGNODE_MAX);
8170     sv_catpv(sv, reg_name[OP(o)]); /* Take off const! */
8171
8172     k = PL_regkind[OP(o)];
8173
8174     if (k == EXACT) {
8175         SV * const dsv = sv_2mortal(newSVpvs(""));
8176         /* Using is_utf8_string() (via PERL_PV_UNI_DETECT) 
8177          * is a crude hack but it may be the best for now since 
8178          * we have no flag "this EXACTish node was UTF-8" 
8179          * --jhi */
8180         const char * const s = 
8181             pv_pretty(dsv, STRING(o), STR_LEN(o), 60, 
8182                 PL_colors[0], PL_colors[1],
8183                 PERL_PV_ESCAPE_UNI_DETECT |
8184                 PERL_PV_PRETTY_ELIPSES    |
8185                 PERL_PV_PRETTY_LTGT    
8186             ); 
8187         Perl_sv_catpvf(aTHX_ sv, " %s", s );
8188     } else if (k == TRIE) {
8189         /* print the details of the trie in dumpuntil instead, as
8190          * prog->data isn't available here */
8191         const char op = OP(o);
8192         const I32 n = ARG(o);
8193         const reg_ac_data * const ac = IS_TRIE_AC(op) ?
8194                (reg_ac_data *)prog->data->data[n] :
8195                NULL;
8196         const reg_trie_data * const trie = !IS_TRIE_AC(op) ?
8197             (reg_trie_data*)prog->data->data[n] :
8198             ac->trie;
8199         
8200         Perl_sv_catpvf(aTHX_ sv, "-%s",reg_name[o->flags]);
8201         DEBUG_TRIE_COMPILE_r(
8202             Perl_sv_catpvf(aTHX_ sv,
8203                 "<S:%"UVuf"/%"IVdf" W:%"UVuf" L:%"UVuf"/%"UVuf" C:%"UVuf"/%"UVuf">",
8204                 (UV)trie->startstate,
8205                 (IV)trie->statecount-1, /* -1 because of the unused 0 element */
8206                 (UV)trie->wordcount,
8207                 (UV)trie->minlen,
8208                 (UV)trie->maxlen,
8209                 (UV)TRIE_CHARCOUNT(trie),
8210                 (UV)trie->uniquecharcount
8211             )
8212         );
8213         if ( IS_ANYOF_TRIE(op) || trie->bitmap ) {
8214             int i;
8215             int rangestart = -1;
8216             U8* bitmap = IS_ANYOF_TRIE(op) ? (U8*)ANYOF_BITMAP(o) : (U8*)TRIE_BITMAP(trie);
8217             Perl_sv_catpvf(aTHX_ sv, "[");
8218             for (i = 0; i <= 256; i++) {
8219                 if (i < 256 && BITMAP_TEST(bitmap,i)) {
8220                     if (rangestart == -1)
8221                         rangestart = i;
8222                 } else if (rangestart != -1) {
8223                     if (i <= rangestart + 3)
8224                         for (; rangestart < i; rangestart++)
8225                             put_byte(sv, rangestart);
8226                     else {
8227                         put_byte(sv, rangestart);
8228                         sv_catpvs(sv, "-");
8229                         put_byte(sv, i - 1);
8230                     }
8231                     rangestart = -1;
8232                 }
8233             }
8234             Perl_sv_catpvf(aTHX_ sv, "]");
8235         } 
8236          
8237     } else if (k == CURLY) {
8238         if (OP(o) == CURLYM || OP(o) == CURLYN || OP(o) == CURLYX)
8239             Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
8240         Perl_sv_catpvf(aTHX_ sv, " {%d,%d}", ARG1(o), ARG2(o));
8241     }
8242     else if (k == WHILEM && o->flags)                   /* Ordinal/of */
8243         Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
8244     else if (k == REF || k == OPEN || k == CLOSE || k == GROUPP || OP(o)==ACCEPT) 
8245         Perl_sv_catpvf(aTHX_ sv, "%d", (int)ARG(o));    /* Parenth number */
8246     else if (k == GOSUB) 
8247         Perl_sv_catpvf(aTHX_ sv, "%d[%+d]", (int)ARG(o),(int)ARG2L(o)); /* Paren and offset */
8248     else if (k == VERB) {
8249         if (!o->flags) 
8250             Perl_sv_catpvf(aTHX_ sv, ":%"SVf, 
8251                 (SV*)prog->data->data[ ARG( o ) ]);
8252     } else if (k == LOGICAL)
8253         Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags);     /* 2: embedded, otherwise 1 */
8254     else if (k == ANYOF) {
8255         int i, rangestart = -1;
8256         const U8 flags = ANYOF_FLAGS(o);
8257
8258         /* Should be synchronized with * ANYOF_ #xdefines in regcomp.h */
8259         static const char * const anyofs[] = {
8260             "\\w",
8261             "\\W",
8262             "\\s",
8263             "\\S",
8264             "\\d",
8265             "\\D",
8266             "[:alnum:]",
8267             "[:^alnum:]",
8268             "[:alpha:]",
8269             "[:^alpha:]",
8270             "[:ascii:]",
8271             "[:^ascii:]",
8272             "[:ctrl:]",
8273             "[:^ctrl:]",
8274             "[:graph:]",
8275             "[:^graph:]",
8276             "[:lower:]",
8277             "[:^lower:]",
8278             "[:print:]",
8279             "[:^print:]",
8280             "[:punct:]",
8281             "[:^punct:]",
8282             "[:upper:]",
8283             "[:^upper:]",
8284             "[:xdigit:]",
8285             "[:^xdigit:]",
8286             "[:space:]",
8287             "[:^space:]",
8288             "[:blank:]",
8289             "[:^blank:]"
8290         };
8291
8292         if (flags & ANYOF_LOCALE)
8293             sv_catpvs(sv, "{loc}");
8294         if (flags & ANYOF_FOLD)
8295             sv_catpvs(sv, "{i}");
8296         Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
8297         if (flags & ANYOF_INVERT)
8298             sv_catpvs(sv, "^");
8299         for (i = 0; i <= 256; i++) {
8300             if (i < 256 && ANYOF_BITMAP_TEST(o,i)) {
8301                 if (rangestart == -1)
8302                     rangestart = i;
8303             } else if (rangestart != -1) {
8304                 if (i <= rangestart + 3)
8305                     for (; rangestart < i; rangestart++)
8306                         put_byte(sv, rangestart);
8307                 else {
8308                     put_byte(sv, rangestart);
8309                     sv_catpvs(sv, "-");
8310                     put_byte(sv, i - 1);
8311                 }
8312                 rangestart = -1;
8313             }
8314         }
8315
8316         if (o->flags & ANYOF_CLASS)
8317             for (i = 0; i < (int)(sizeof(anyofs)/sizeof(char*)); i++)
8318                 if (ANYOF_CLASS_TEST(o,i))
8319                     sv_catpv(sv, anyofs[i]);
8320
8321         if (flags & ANYOF_UNICODE)
8322             sv_catpvs(sv, "{unicode}");
8323         else if (flags & ANYOF_UNICODE_ALL)
8324             sv_catpvs(sv, "{unicode_all}");
8325
8326         {
8327             SV *lv;
8328             SV * const sw = regclass_swash(prog, o, FALSE, &lv, 0);
8329         
8330             if (lv) {
8331                 if (sw) {
8332                     U8 s[UTF8_MAXBYTES_CASE+1];
8333                 
8334                     for (i = 0; i <= 256; i++) { /* just the first 256 */
8335                         uvchr_to_utf8(s, i);
8336                         
8337                         if (i < 256 && swash_fetch(sw, s, TRUE)) {
8338                             if (rangestart == -1)
8339                                 rangestart = i;
8340                         } else if (rangestart != -1) {
8341                             if (i <= rangestart + 3)
8342                                 for (; rangestart < i; rangestart++) {
8343                                     const U8 * const e = uvchr_to_utf8(s,rangestart);
8344                                     U8 *p;
8345                                     for(p = s; p < e; p++)
8346                                         put_byte(sv, *p);
8347                                 }
8348                             else {
8349                                 const U8 *e = uvchr_to_utf8(s,rangestart);
8350                                 U8 *p;
8351                                 for (p = s; p < e; p++)
8352                                     put_byte(sv, *p);
8353                                 sv_catpvs(sv, "-");
8354                                 e = uvchr_to_utf8(s, i-1);
8355                                 for (p = s; p < e; p++)
8356                                     put_byte(sv, *p);
8357                                 }
8358                                 rangestart = -1;
8359                             }
8360                         }
8361                         
8362                     sv_catpvs(sv, "..."); /* et cetera */
8363                 }
8364
8365                 {
8366                     char *s = savesvpv(lv);
8367                     char * const origs = s;
8368                 
8369                     while (*s && *s != '\n')
8370                         s++;
8371                 
8372                     if (*s == '\n') {
8373                         const char * const t = ++s;
8374                         
8375                         while (*s) {
8376                             if (*s == '\n')
8377                                 *s = ' ';
8378                             s++;
8379                         }
8380                         if (s[-1] == ' ')
8381                             s[-1] = 0;
8382                         
8383                         sv_catpv(sv, t);
8384                     }
8385                 
8386                     Safefree(origs);
8387                 }
8388             }
8389         }
8390
8391         Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
8392     }
8393     else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH))
8394         Perl_sv_catpvf(aTHX_ sv, "[%d]", -(o->flags));
8395 #else
8396     PERL_UNUSED_CONTEXT;
8397     PERL_UNUSED_ARG(sv);
8398     PERL_UNUSED_ARG(o);
8399     PERL_UNUSED_ARG(prog);
8400 #endif  /* DEBUGGING */
8401 }
8402
8403 SV *
8404 Perl_re_intuit_string(pTHX_ regexp *prog)
8405 {                               /* Assume that RE_INTUIT is set */
8406     dVAR;
8407     GET_RE_DEBUG_FLAGS_DECL;
8408     PERL_UNUSED_CONTEXT;
8409
8410     DEBUG_COMPILE_r(
8411         {
8412             const char * const s = SvPV_nolen_const(prog->check_substr
8413                       ? prog->check_substr : prog->check_utf8);
8414
8415             if (!PL_colorset) reginitcolors();
8416             PerlIO_printf(Perl_debug_log,
8417                       "%sUsing REx %ssubstr:%s \"%s%.60s%s%s\"\n",
8418                       PL_colors[4],
8419                       prog->check_substr ? "" : "utf8 ",
8420                       PL_colors[5],PL_colors[0],
8421                       s,
8422                       PL_colors[1],
8423                       (strlen(s) > 60 ? "..." : ""));
8424         } );
8425
8426     return prog->check_substr ? prog->check_substr : prog->check_utf8;
8427 }
8428
8429 /* 
8430    pregfree - free a regexp
8431    
8432    See regdupe below if you change anything here. 
8433 */
8434
8435 void
8436 Perl_pregfree(pTHX_ struct regexp *r)
8437 {
8438     dVAR;
8439
8440     GET_RE_DEBUG_FLAGS_DECL;
8441
8442     if (!r || (--r->refcnt > 0))
8443         return;
8444     DEBUG_COMPILE_r({
8445         if (!PL_colorset)
8446             reginitcolors();
8447         {
8448             SV *dsv= sv_newmortal();
8449             RE_PV_QUOTED_DECL(s, (r->reganch & ROPT_UTF8),
8450                 dsv, r->precomp, r->prelen, 60);
8451             PerlIO_printf(Perl_debug_log,"%sFreeing REx:%s %s\n", 
8452                 PL_colors[4],PL_colors[5],s);
8453         }
8454     });
8455
8456     /* gcov results gave these as non-null 100% of the time, so there's no
8457        optimisation in checking them before calling Safefree  */
8458     Safefree(r->precomp);
8459     Safefree(r->offsets);             /* 20010421 MJD */
8460     RX_MATCH_COPY_FREE(r);
8461 #ifdef PERL_OLD_COPY_ON_WRITE
8462     if (r->saved_copy)
8463         SvREFCNT_dec(r->saved_copy);
8464 #endif
8465     if (r->substrs) {
8466         if (r->anchored_substr)
8467             SvREFCNT_dec(r->anchored_substr);
8468         if (r->anchored_utf8)
8469             SvREFCNT_dec(r->anchored_utf8);
8470         if (r->float_substr)
8471             SvREFCNT_dec(r->float_substr);
8472         if (r->float_utf8)
8473             SvREFCNT_dec(r->float_utf8);
8474         Safefree(r->substrs);
8475     }
8476     if (r->paren_names)
8477             SvREFCNT_dec(r->paren_names);
8478     if (r->data) {
8479         int n = r->data->count;
8480         PAD* new_comppad = NULL;
8481         PAD* old_comppad;
8482         PADOFFSET refcnt;
8483
8484         while (--n >= 0) {
8485           /* If you add a ->what type here, update the comment in regcomp.h */
8486             switch (r->data->what[n]) {
8487             case 's':
8488             case 'S':
8489                 SvREFCNT_dec((SV*)r->data->data[n]);
8490                 break;
8491             case 'f':
8492                 Safefree(r->data->data[n]);
8493                 break;
8494             case 'p':
8495                 new_comppad = (AV*)r->data->data[n];
8496                 break;
8497             case 'o':
8498                 if (new_comppad == NULL)
8499                     Perl_croak(aTHX_ "panic: pregfree comppad");
8500                 PAD_SAVE_LOCAL(old_comppad,
8501                     /* Watch out for global destruction's random ordering. */
8502                     (SvTYPE(new_comppad) == SVt_PVAV) ? new_comppad : NULL
8503                 );
8504                 OP_REFCNT_LOCK;
8505                 refcnt = OpREFCNT_dec((OP_4tree*)r->data->data[n]);
8506                 OP_REFCNT_UNLOCK;
8507                 if (!refcnt)
8508                     op_free((OP_4tree*)r->data->data[n]);
8509
8510                 PAD_RESTORE_LOCAL(old_comppad);
8511                 SvREFCNT_dec((SV*)new_comppad);
8512                 new_comppad = NULL;
8513                 break;
8514             case 'n':
8515                 break;
8516             case 'T':           
8517                 { /* Aho Corasick add-on structure for a trie node.
8518                      Used in stclass optimization only */
8519                     U32 refcount;
8520                     reg_ac_data *aho=(reg_ac_data*)r->data->data[n];
8521                     OP_REFCNT_LOCK;
8522                     refcount = --aho->refcount;
8523                     OP_REFCNT_UNLOCK;
8524                     if ( !refcount ) {
8525                         Safefree(aho->states);
8526                         Safefree(aho->fail);
8527                         aho->trie=NULL; /* not necessary to free this as it is 
8528                                            handled by the 't' case */
8529                         Safefree(r->data->data[n]); /* do this last!!!! */
8530                         Safefree(r->regstclass);
8531                     }
8532                 }
8533                 break;
8534             case 't':
8535                 {
8536                     /* trie structure. */
8537                     U32 refcount;
8538                     reg_trie_data *trie=(reg_trie_data*)r->data->data[n];
8539                     OP_REFCNT_LOCK;
8540                     refcount = --trie->refcount;
8541                     OP_REFCNT_UNLOCK;
8542                     if ( !refcount ) {
8543                         Safefree(trie->charmap);
8544                         if (trie->widecharmap)
8545                             SvREFCNT_dec((SV*)trie->widecharmap);
8546                         Safefree(trie->states);
8547                         Safefree(trie->trans);
8548                         if (trie->bitmap)
8549                             Safefree(trie->bitmap);
8550                         if (trie->wordlen)
8551                             Safefree(trie->wordlen);
8552                         if (trie->jump)
8553                             Safefree(trie->jump);
8554                         if (trie->nextword)
8555                             Safefree(trie->nextword);
8556 #ifdef DEBUGGING
8557                         if (trie->words)
8558                             SvREFCNT_dec((SV*)trie->words);
8559                         if (trie->revcharmap)
8560                             SvREFCNT_dec((SV*)trie->revcharmap);
8561 #endif
8562                         Safefree(r->data->data[n]); /* do this last!!!! */
8563                     }
8564                 }
8565                 break;
8566             default:
8567                 Perl_croak(aTHX_ "panic: regfree data code '%c'", r->data->what[n]);
8568             }
8569         }
8570         Safefree(r->data->what);
8571         Safefree(r->data);
8572     }
8573     Safefree(r->startp);
8574     Safefree(r->endp);
8575     if (r->swap) {
8576         Safefree(r->swap->startp);
8577         Safefree(r->swap->endp);
8578         Safefree(r->swap);
8579     }
8580     Safefree(r);
8581 }
8582
8583 #define sv_dup_inc(s,t) SvREFCNT_inc(sv_dup(s,t))
8584 #define av_dup_inc(s,t) (AV*)SvREFCNT_inc(sv_dup((SV*)s,t))
8585 #define hv_dup_inc(s,t) (HV*)SvREFCNT_inc(sv_dup((SV*)s,t))
8586 #define SAVEPVN(p,n)    ((p) ? savepvn(p,n) : NULL)
8587
8588 /* 
8589    regdupe - duplicate a regexp. 
8590    
8591    This routine is called by sv.c's re_dup and is expected to clone a 
8592    given regexp structure. It is a no-op when not under USE_ITHREADS. 
8593    (Originally this *was* re_dup() for change history see sv.c)
8594    
8595    See pregfree() above if you change anything here. 
8596 */
8597 #if defined(USE_ITHREADS)
8598 regexp *
8599 Perl_regdupe(pTHX_ const regexp *r, CLONE_PARAMS *param)
8600 {
8601     dVAR;
8602     REGEXP *ret;
8603     int i, len, npar;
8604     struct reg_substr_datum *s;
8605
8606     if (!r)
8607         return (REGEXP *)NULL;
8608
8609     if ((ret = (REGEXP *)ptr_table_fetch(PL_ptr_table, r)))
8610         return ret;
8611
8612     len = r->offsets[0];
8613     npar = r->nparens+1;
8614
8615     Newxc(ret, sizeof(regexp) + (len+1)*sizeof(regnode), char, regexp);
8616     Copy(r->program, ret->program, len+1, regnode);
8617
8618     Newx(ret->startp, npar, I32);
8619     Copy(r->startp, ret->startp, npar, I32);
8620     Newx(ret->endp, npar, I32);
8621     Copy(r->startp, ret->startp, npar, I32);
8622     if(r->swap) {
8623         Newx(ret->swap, 1, regexp_paren_ofs);
8624         /* no need to copy these */
8625         Newx(ret->swap->startp, npar, I32);
8626         Newx(ret->swap->endp, npar, I32);
8627     } else {
8628         ret->swap = NULL;
8629     }
8630
8631     Newx(ret->substrs, 1, struct reg_substr_data);
8632     for (s = ret->substrs->data, i = 0; i < 3; i++, s++) {
8633         s->min_offset = r->substrs->data[i].min_offset;
8634         s->max_offset = r->substrs->data[i].max_offset;
8635         s->end_shift  = r->substrs->data[i].end_shift;
8636         s->substr     = sv_dup_inc(r->substrs->data[i].substr, param);
8637         s->utf8_substr = sv_dup_inc(r->substrs->data[i].utf8_substr, param);
8638     }
8639
8640     ret->regstclass = NULL;
8641     if (r->data) {
8642         struct reg_data *d;
8643         const int count = r->data->count;
8644         int i;
8645
8646         Newxc(d, sizeof(struct reg_data) + count*sizeof(void *),
8647                 char, struct reg_data);
8648         Newx(d->what, count, U8);
8649
8650         d->count = count;
8651         for (i = 0; i < count; i++) {
8652             d->what[i] = r->data->what[i];
8653             switch (d->what[i]) {
8654                 /* legal options are one of: sSfpont
8655                    see also regcomp.h and pregfree() */
8656             case 's':
8657             case 'S':
8658                 d->data[i] = sv_dup_inc((SV *)r->data->data[i], param);
8659                 break;
8660             case 'p':
8661                 d->data[i] = av_dup_inc((AV *)r->data->data[i], param);
8662                 break;
8663             case 'f':
8664                 /* This is cheating. */
8665                 Newx(d->data[i], 1, struct regnode_charclass_class);
8666                 StructCopy(r->data->data[i], d->data[i],
8667                             struct regnode_charclass_class);
8668                 ret->regstclass = (regnode*)d->data[i];
8669                 break;
8670             case 'o':
8671                 /* Compiled op trees are readonly, and can thus be
8672                    shared without duplication. */
8673                 OP_REFCNT_LOCK;
8674                 d->data[i] = (void*)OpREFCNT_inc((OP*)r->data->data[i]);
8675                 OP_REFCNT_UNLOCK;
8676                 break;
8677             case 'n':
8678                 d->data[i] = r->data->data[i];
8679                 break;
8680             case 't':
8681                 d->data[i] = r->data->data[i];
8682                 OP_REFCNT_LOCK;
8683                 ((reg_trie_data*)d->data[i])->refcount++;
8684                 OP_REFCNT_UNLOCK;
8685                 break;
8686             case 'T':
8687                 d->data[i] = r->data->data[i];
8688                 OP_REFCNT_LOCK;
8689                 ((reg_ac_data*)d->data[i])->refcount++;
8690                 OP_REFCNT_UNLOCK;
8691                 /* Trie stclasses are readonly and can thus be shared
8692                  * without duplication. We free the stclass in pregfree
8693                  * when the corresponding reg_ac_data struct is freed.
8694                  */
8695                 ret->regstclass= r->regstclass;
8696                 break;
8697             default:
8698                 Perl_croak(aTHX_ "panic: re_dup unknown data code '%c'", r->data->what[i]);
8699             }
8700         }
8701
8702         ret->data = d;
8703     }
8704     else
8705         ret->data = NULL;
8706
8707     Newx(ret->offsets, 2*len+1, U32);
8708     Copy(r->offsets, ret->offsets, 2*len+1, U32);
8709
8710     ret->precomp        = SAVEPVN(r->precomp, r->prelen);
8711     ret->refcnt         = r->refcnt;
8712     ret->minlen         = r->minlen;
8713     ret->minlenret      = r->minlenret;
8714     ret->prelen         = r->prelen;
8715     ret->nparens        = r->nparens;
8716     ret->lastparen      = r->lastparen;
8717     ret->lastcloseparen = r->lastcloseparen;
8718     ret->reganch        = r->reganch;
8719
8720     ret->sublen         = r->sublen;
8721
8722     ret->engine         = r->engine;
8723     
8724     ret->paren_names    = hv_dup_inc(r->paren_names, param);
8725
8726     if (RX_MATCH_COPIED(ret))
8727         ret->subbeg  = SAVEPVN(r->subbeg, r->sublen);
8728     else
8729         ret->subbeg = NULL;
8730 #ifdef PERL_OLD_COPY_ON_WRITE
8731     ret->saved_copy = NULL;
8732 #endif
8733
8734     ptr_table_store(PL_ptr_table, r, ret);
8735     return ret;
8736 }
8737 #endif    
8738
8739 /* 
8740    reg_stringify() 
8741    
8742    converts a regexp embedded in a MAGIC struct to its stringified form, 
8743    caching the converted form in the struct and returns the cached 
8744    string. 
8745
8746    If lp is nonnull then it is used to return the length of the 
8747    resulting string
8748    
8749    If flags is nonnull and the returned string contains UTF8 then 
8750    (flags & 1) will be true.
8751    
8752    If haseval is nonnull then it is used to return whether the pattern 
8753    contains evals.
8754    
8755    Normally called via macro: 
8756    
8757         CALLREG_STRINGIFY(mg,0,0);
8758         
8759    And internally with
8760    
8761         CALLREG_AS_STR(mg,lp,flags,haseval)        
8762     
8763    See sv_2pv_flags() in sv.c for an example of internal usage.
8764     
8765  */
8766
8767 char *
8768 Perl_reg_stringify(pTHX_ MAGIC *mg, STRLEN *lp, U32 *flags, I32 *haseval ) {
8769     dVAR;
8770     const regexp * const re = (regexp *)mg->mg_obj;
8771
8772     if (!mg->mg_ptr) {
8773         const char *fptr = "msix";
8774         char reflags[6];
8775         char ch;
8776         int left = 0;
8777         int right = 4;
8778         bool need_newline = 0;
8779         U16 reganch = (U16)((re->reganch & PMf_COMPILETIME) >> 12);
8780
8781         while((ch = *fptr++)) {
8782             if(reganch & 1) {
8783                 reflags[left++] = ch;
8784             }
8785             else {
8786                 reflags[right--] = ch;
8787             }
8788             reganch >>= 1;
8789         }
8790         if(left != 4) {
8791             reflags[left] = '-';
8792             left = 5;
8793         }
8794
8795         mg->mg_len = re->prelen + 4 + left;
8796         /*
8797          * If /x was used, we have to worry about a regex ending with a
8798          * comment later being embedded within another regex. If so, we don't
8799          * want this regex's "commentization" to leak out to the right part of
8800          * the enclosing regex, we must cap it with a newline.
8801          *
8802          * So, if /x was used, we scan backwards from the end of the regex. If
8803          * we find a '#' before we find a newline, we need to add a newline
8804          * ourself. If we find a '\n' first (or if we don't find '#' or '\n'),
8805          * we don't need to add anything.  -jfriedl
8806          */
8807         if (PMf_EXTENDED & re->reganch) {
8808             const char *endptr = re->precomp + re->prelen;
8809             while (endptr >= re->precomp) {
8810                 const char c = *(endptr--);
8811                 if (c == '\n')
8812                     break; /* don't need another */
8813                 if (c == '#') {
8814                     /* we end while in a comment, so we need a newline */
8815                     mg->mg_len++; /* save space for it */
8816                     need_newline = 1; /* note to add it */
8817                     break;
8818                 }
8819             }
8820         }
8821
8822         Newx(mg->mg_ptr, mg->mg_len + 1 + left, char);
8823         mg->mg_ptr[0] = '(';
8824         mg->mg_ptr[1] = '?';
8825         Copy(reflags, mg->mg_ptr+2, left, char);
8826         *(mg->mg_ptr+left+2) = ':';
8827         Copy(re->precomp, mg->mg_ptr+3+left, re->prelen, char);
8828         if (need_newline)
8829             mg->mg_ptr[mg->mg_len - 2] = '\n';
8830         mg->mg_ptr[mg->mg_len - 1] = ')';
8831         mg->mg_ptr[mg->mg_len] = 0;
8832     }
8833     if (haseval) 
8834         *haseval = re->program[0].next_off;
8835     if (flags)    
8836         *flags = ((re->reganch & ROPT_UTF8) ? 1 : 0);
8837     
8838     if (lp)
8839         *lp = mg->mg_len;
8840     return mg->mg_ptr;
8841 }
8842
8843
8844 #ifndef PERL_IN_XSUB_RE
8845 /*
8846  - regnext - dig the "next" pointer out of a node
8847  */
8848 regnode *
8849 Perl_regnext(pTHX_ register regnode *p)
8850 {
8851     dVAR;
8852     register I32 offset;
8853
8854     if (p == &PL_regdummy)
8855         return(NULL);
8856
8857     offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
8858     if (offset == 0)
8859         return(NULL);
8860
8861     return(p+offset);
8862 }
8863 #endif
8864
8865 STATIC void     
8866 S_re_croak2(pTHX_ const char* pat1,const char* pat2,...)
8867 {
8868     va_list args;
8869     STRLEN l1 = strlen(pat1);
8870     STRLEN l2 = strlen(pat2);
8871     char buf[512];
8872     SV *msv;
8873     const char *message;
8874
8875     if (l1 > 510)
8876         l1 = 510;
8877     if (l1 + l2 > 510)
8878         l2 = 510 - l1;
8879     Copy(pat1, buf, l1 , char);
8880     Copy(pat2, buf + l1, l2 , char);
8881     buf[l1 + l2] = '\n';
8882     buf[l1 + l2 + 1] = '\0';
8883 #ifdef I_STDARG
8884     /* ANSI variant takes additional second argument */
8885     va_start(args, pat2);
8886 #else
8887     va_start(args);
8888 #endif
8889     msv = vmess(buf, &args);
8890     va_end(args);
8891     message = SvPV_const(msv,l1);
8892     if (l1 > 512)
8893         l1 = 512;
8894     Copy(message, buf, l1 , char);
8895     buf[l1-1] = '\0';                   /* Overwrite \n */
8896     Perl_croak(aTHX_ "%s", buf);
8897 }
8898
8899 /* XXX Here's a total kludge.  But we need to re-enter for swash routines. */
8900
8901 #ifndef PERL_IN_XSUB_RE
8902 void
8903 Perl_save_re_context(pTHX)
8904 {
8905     dVAR;
8906
8907     struct re_save_state *state;
8908
8909     SAVEVPTR(PL_curcop);
8910     SSGROW(SAVESTACK_ALLOC_FOR_RE_SAVE_STATE + 1);
8911
8912     state = (struct re_save_state *)(PL_savestack + PL_savestack_ix);
8913     PL_savestack_ix += SAVESTACK_ALLOC_FOR_RE_SAVE_STATE;
8914     SSPUSHINT(SAVEt_RE_STATE);
8915
8916     Copy(&PL_reg_state, state, 1, struct re_save_state);
8917
8918     PL_reg_start_tmp = 0;
8919     PL_reg_start_tmpl = 0;
8920     PL_reg_oldsaved = NULL;
8921     PL_reg_oldsavedlen = 0;
8922     PL_reg_maxiter = 0;
8923     PL_reg_leftiter = 0;
8924     PL_reg_poscache = NULL;
8925     PL_reg_poscache_size = 0;
8926 #ifdef PERL_OLD_COPY_ON_WRITE
8927     PL_nrs = NULL;
8928 #endif
8929
8930     /* Save $1..$n (#18107: UTF-8 s/(\w+)/uc($1)/e); AMS 20021106. */
8931     if (PL_curpm) {
8932         const REGEXP * const rx = PM_GETRE(PL_curpm);
8933         if (rx) {
8934             U32 i;
8935             for (i = 1; i <= rx->nparens; i++) {
8936                 char digits[TYPE_CHARS(long)];
8937                 const STRLEN len = my_snprintf(digits, sizeof(digits), "%lu", (long)i);
8938                 GV *const *const gvp
8939                     = (GV**)hv_fetch(PL_defstash, digits, len, 0);
8940
8941                 if (gvp) {
8942                     GV * const gv = *gvp;
8943                     if (SvTYPE(gv) == SVt_PVGV && GvSV(gv))
8944                         save_scalar(gv);
8945                 }
8946             }
8947         }
8948     }
8949 }
8950 #endif
8951
8952 static void
8953 clear_re(pTHX_ void *r)
8954 {
8955     dVAR;
8956     ReREFCNT_dec((regexp *)r);
8957 }
8958
8959 #ifdef DEBUGGING
8960
8961 STATIC void
8962 S_put_byte(pTHX_ SV *sv, int c)
8963 {
8964     if (isCNTRL(c) || c == 255 || !isPRINT(c))
8965         Perl_sv_catpvf(aTHX_ sv, "\\%o", c);
8966     else if (c == '-' || c == ']' || c == '\\' || c == '^')
8967         Perl_sv_catpvf(aTHX_ sv, "\\%c", c);
8968     else
8969         Perl_sv_catpvf(aTHX_ sv, "%c", c);
8970 }
8971
8972
8973 #define CLEAR_OPTSTART \
8974     if (optstart) STMT_START { \
8975             DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log, " (%d nodes)\n", node - optstart)); \
8976             optstart=NULL; \
8977     } STMT_END
8978
8979 #define DUMPUNTIL(b,e) CLEAR_OPTSTART; node=dumpuntil(r,start,(b),(e),last,sv,indent+1,depth+1);
8980
8981 STATIC const regnode *
8982 S_dumpuntil(pTHX_ const regexp *r, const regnode *start, const regnode *node,
8983             const regnode *last, const regnode *plast, 
8984             SV* sv, I32 indent, U32 depth)
8985 {
8986     dVAR;
8987     register U8 op = PSEUDO;    /* Arbitrary non-END op. */
8988     register const regnode *next;
8989     const regnode *optstart= NULL;
8990     GET_RE_DEBUG_FLAGS_DECL;
8991
8992 #ifdef DEBUG_DUMPUNTIL
8993     PerlIO_printf(Perl_debug_log, "--- %d : %d - %d - %d\n",indent,node-start,
8994         last ? last-start : 0,plast ? plast-start : 0);
8995 #endif
8996             
8997     if (plast && plast < last) 
8998         last= plast;
8999
9000     while (PL_regkind[op] != END && (!last || node < last)) {
9001         /* While that wasn't END last time... */
9002
9003         NODE_ALIGN(node);
9004         op = OP(node);
9005         if (op == CLOSE || op == WHILEM)
9006             indent--;
9007         next = regnext((regnode *)node);
9008         
9009         /* Where, what. */
9010         if (OP(node) == OPTIMIZED) {
9011             if (!optstart && RE_DEBUG_FLAG(RE_DEBUG_COMPILE_OPTIMISE))
9012                 optstart = node;
9013             else
9014                 goto after_print;
9015         } else
9016             CLEAR_OPTSTART;
9017             
9018         regprop(r, sv, node);
9019         PerlIO_printf(Perl_debug_log, "%4"IVdf":%*s%s", (IV)(node - start),
9020                       (int)(2*indent + 1), "", SvPVX_const(sv));
9021
9022         if (OP(node) != OPTIMIZED) {
9023             if (next == NULL)           /* Next ptr. */
9024                 PerlIO_printf(Perl_debug_log, "(0)");
9025             else if (PL_regkind[(U8)op] == BRANCH && PL_regkind[OP(next)] != BRANCH )
9026                 PerlIO_printf(Perl_debug_log, "(FAIL)");
9027             else
9028                 PerlIO_printf(Perl_debug_log, "(%"IVdf")", (IV)(next - start));
9029                 
9030             /*if (PL_regkind[(U8)op]  != TRIE)*/
9031                 (void)PerlIO_putc(Perl_debug_log, '\n');
9032         }
9033
9034       after_print:
9035         if (PL_regkind[(U8)op] == BRANCHJ) {
9036             assert(next);
9037             {
9038                 register const regnode *nnode = (OP(next) == LONGJMP
9039                                              ? regnext((regnode *)next)
9040                                              : next);
9041                 if (last && nnode > last)
9042                     nnode = last;
9043                 DUMPUNTIL(NEXTOPER(NEXTOPER(node)), nnode);
9044             }
9045         }
9046         else if (PL_regkind[(U8)op] == BRANCH) {
9047             assert(next);
9048             DUMPUNTIL(NEXTOPER(node), next);
9049         }
9050         else if ( PL_regkind[(U8)op]  == TRIE ) {
9051             const regnode *this_trie = node;
9052             const char op = OP(node);
9053             const I32 n = ARG(node);
9054             const reg_ac_data * const ac = op>=AHOCORASICK ?
9055                (reg_ac_data *)r->data->data[n] :
9056                NULL;
9057             const reg_trie_data * const trie = op<AHOCORASICK ?
9058                 (reg_trie_data*)r->data->data[n] :
9059                 ac->trie;
9060             const regnode *nextbranch= NULL;
9061             I32 word_idx;
9062             sv_setpvn(sv, "", 0);
9063             for (word_idx= 0; word_idx < (I32)trie->wordcount; word_idx++) {
9064                 SV ** const elem_ptr = av_fetch(trie->words,word_idx,0);
9065                 
9066                 PerlIO_printf(Perl_debug_log, "%*s%s ",
9067                    (int)(2*(indent+3)), "",
9068                     elem_ptr ? pv_pretty(sv, SvPV_nolen_const(*elem_ptr), SvCUR(*elem_ptr), 60,
9069                             PL_colors[0], PL_colors[1],
9070                             (SvUTF8(*elem_ptr) ? PERL_PV_ESCAPE_UNI : 0) |
9071                             PERL_PV_PRETTY_ELIPSES    |
9072                             PERL_PV_PRETTY_LTGT
9073                             )
9074                             : "???"
9075                 );
9076                 if (trie->jump) {
9077                     U16 dist= trie->jump[word_idx+1];
9078                     PerlIO_printf(Perl_debug_log, "(%u)\n",
9079                         (dist ? this_trie + dist : next) - start);
9080                     if (dist) {
9081                         if (!nextbranch)
9082                             nextbranch= this_trie + trie->jump[0];    
9083                         DUMPUNTIL(this_trie + dist, nextbranch);
9084                     }
9085                     if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
9086                         nextbranch= regnext((regnode *)nextbranch);
9087                 } else {
9088                     PerlIO_printf(Perl_debug_log, "\n");
9089                 }
9090             }
9091             if (last && next > last)
9092                 node= last;
9093             else
9094                 node= next;
9095         }
9096         else if ( op == CURLY ) {   /* "next" might be very big: optimizer */
9097             DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS,
9098                     NEXTOPER(node) + EXTRA_STEP_2ARGS + 1);
9099         }
9100         else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
9101             assert(next);
9102             DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS, next);
9103         }
9104         else if ( op == PLUS || op == STAR) {
9105             DUMPUNTIL(NEXTOPER(node), NEXTOPER(node) + 1);
9106         }
9107         else if (op == ANYOF) {
9108             /* arglen 1 + class block */
9109             node += 1 + ((ANYOF_FLAGS(node) & ANYOF_LARGE)
9110                     ? ANYOF_CLASS_SKIP : ANYOF_SKIP);
9111             node = NEXTOPER(node);
9112         }
9113         else if (PL_regkind[(U8)op] == EXACT) {
9114             /* Literal string, where present. */
9115             node += NODE_SZ_STR(node) - 1;
9116             node = NEXTOPER(node);
9117         }
9118         else {
9119             node = NEXTOPER(node);
9120             node += regarglen[(U8)op];
9121         }
9122         if (op == CURLYX || op == OPEN)
9123             indent++;
9124     }
9125     CLEAR_OPTSTART;
9126 #ifdef DEBUG_DUMPUNTIL    
9127     PerlIO_printf(Perl_debug_log, "--- %d\n",indent);
9128 #endif
9129     return node;
9130 }
9131
9132 #endif  /* DEBUGGING */
9133
9134 /*
9135  * Local variables:
9136  * c-indentation-style: bsd
9137  * c-basic-offset: 4
9138  * indent-tabs-mode: t
9139  * End:
9140  *
9141  * ex: set ts=8 sts=4 sw=4 noet:
9142  */