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