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