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