]> git.vpit.fr Git - perl/modules/re-engine-Hooks.git/blob - src/5013004/regcomp.c
Attach the callbacks to every regexps in a thread-safe way
[perl/modules/re-engine-Hooks.git] / src / 5013004 / 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
2163     /*  Finish populating the prev field of the wordinfo array.  Walk back
2164      *  from each accept state until we find another accept state, and if
2165      *  so, point the first word's .prev field at the second word. If the
2166      *  second already has a .prev field set, stop now. This will be the
2167      *  case either if we've already processed that word's accept state,
2168      *  or that that state had multiple words, and the overspill words
2169      *  were already linked up earlier.
2170      */
2171     {
2172         U16 word;
2173         U32 state;
2174         U16 prev;
2175
2176         for (word=1; word <= trie->wordcount; word++) {
2177             prev = 0;
2178             if (trie->wordinfo[word].prev)
2179                 continue;
2180             state = trie->wordinfo[word].accept;
2181             while (state) {
2182                 state = prev_states[state];
2183                 if (!state)
2184                     break;
2185                 prev = trie->states[state].wordnum;
2186                 if (prev)
2187                     break;
2188             }
2189             trie->wordinfo[word].prev = prev;
2190         }
2191         Safefree(prev_states);
2192     }
2193
2194
2195     /* and now dump out the compressed format */
2196     DEBUG_TRIE_COMPILE_r(dump_trie(trie, widecharmap, revcharmap, depth+1));
2197
2198     RExC_rxi->data->data[ data_slot + 1 ] = (void*)widecharmap;
2199 #ifdef DEBUGGING
2200     RExC_rxi->data->data[ data_slot + TRIE_WORDS_OFFSET ] = (void*)trie_words;
2201     RExC_rxi->data->data[ data_slot + 3 ] = (void*)revcharmap;
2202 #else
2203     SvREFCNT_dec(revcharmap);
2204 #endif
2205     return trie->jump 
2206            ? MADE_JUMP_TRIE 
2207            : trie->startstate>1 
2208              ? MADE_EXACT_TRIE 
2209              : MADE_TRIE;
2210 }
2211
2212 STATIC void
2213 S_make_trie_failtable(pTHX_ RExC_state_t *pRExC_state, regnode *source,  regnode *stclass, U32 depth)
2214 {
2215 /* The Trie is constructed and compressed now so we can build a fail array now if its needed
2216
2217    This is basically the Aho-Corasick algorithm. Its from exercise 3.31 and 3.32 in the
2218    "Red Dragon" -- Compilers, principles, techniques, and tools. Aho, Sethi, Ullman 1985/88
2219    ISBN 0-201-10088-6
2220
2221    We find the fail state for each state in the trie, this state is the longest proper
2222    suffix of the current states 'word' that is also a proper prefix of another word in our
2223    trie. State 1 represents the word '' and is the thus the default fail state. This allows
2224    the DFA not to have to restart after its tried and failed a word at a given point, it
2225    simply continues as though it had been matching the other word in the first place.
2226    Consider
2227       'abcdgu'=~/abcdefg|cdgu/
2228    When we get to 'd' we are still matching the first word, we would encounter 'g' which would
2229    fail, which would bring use to the state representing 'd' in the second word where we would
2230    try 'g' and succeed, prodceding to match 'cdgu'.
2231  */
2232  /* add a fail transition */
2233     const U32 trie_offset = ARG(source);
2234     reg_trie_data *trie=(reg_trie_data *)RExC_rxi->data->data[trie_offset];
2235     U32 *q;
2236     const U32 ucharcount = trie->uniquecharcount;
2237     const U32 numstates = trie->statecount;
2238     const U32 ubound = trie->lasttrans + ucharcount;
2239     U32 q_read = 0;
2240     U32 q_write = 0;
2241     U32 charid;
2242     U32 base = trie->states[ 1 ].trans.base;
2243     U32 *fail;
2244     reg_ac_data *aho;
2245     const U32 data_slot = add_data( pRExC_state, 1, "T" );
2246     GET_RE_DEBUG_FLAGS_DECL;
2247
2248     PERL_ARGS_ASSERT_MAKE_TRIE_FAILTABLE;
2249 #ifndef DEBUGGING
2250     PERL_UNUSED_ARG(depth);
2251 #endif
2252
2253
2254     ARG_SET( stclass, data_slot );
2255     aho = (reg_ac_data *) PerlMemShared_calloc( 1, sizeof(reg_ac_data) );
2256     RExC_rxi->data->data[ data_slot ] = (void*)aho;
2257     aho->trie=trie_offset;
2258     aho->states=(reg_trie_state *)PerlMemShared_malloc( numstates * sizeof(reg_trie_state) );
2259     Copy( trie->states, aho->states, numstates, reg_trie_state );
2260     Newxz( q, numstates, U32);
2261     aho->fail = (U32 *) PerlMemShared_calloc( numstates, sizeof(U32) );
2262     aho->refcount = 1;
2263     fail = aho->fail;
2264     /* initialize fail[0..1] to be 1 so that we always have
2265        a valid final fail state */
2266     fail[ 0 ] = fail[ 1 ] = 1;
2267
2268     for ( charid = 0; charid < ucharcount ; charid++ ) {
2269         const U32 newstate = TRIE_TRANS_STATE( 1, base, ucharcount, charid, 0 );
2270         if ( newstate ) {
2271             q[ q_write ] = newstate;
2272             /* set to point at the root */
2273             fail[ q[ q_write++ ] ]=1;
2274         }
2275     }
2276     while ( q_read < q_write) {
2277         const U32 cur = q[ q_read++ % numstates ];
2278         base = trie->states[ cur ].trans.base;
2279
2280         for ( charid = 0 ; charid < ucharcount ; charid++ ) {
2281             const U32 ch_state = TRIE_TRANS_STATE( cur, base, ucharcount, charid, 1 );
2282             if (ch_state) {
2283                 U32 fail_state = cur;
2284                 U32 fail_base;
2285                 do {
2286                     fail_state = fail[ fail_state ];
2287                     fail_base = aho->states[ fail_state ].trans.base;
2288                 } while ( !TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 ) );
2289
2290                 fail_state = TRIE_TRANS_STATE( fail_state, fail_base, ucharcount, charid, 1 );
2291                 fail[ ch_state ] = fail_state;
2292                 if ( !aho->states[ ch_state ].wordnum && aho->states[ fail_state ].wordnum )
2293                 {
2294                         aho->states[ ch_state ].wordnum =  aho->states[ fail_state ].wordnum;
2295                 }
2296                 q[ q_write++ % numstates] = ch_state;
2297             }
2298         }
2299     }
2300     /* restore fail[0..1] to 0 so that we "fall out" of the AC loop
2301        when we fail in state 1, this allows us to use the
2302        charclass scan to find a valid start char. This is based on the principle
2303        that theres a good chance the string being searched contains lots of stuff
2304        that cant be a start char.
2305      */
2306     fail[ 0 ] = fail[ 1 ] = 0;
2307     DEBUG_TRIE_COMPILE_r({
2308         PerlIO_printf(Perl_debug_log,
2309                       "%*sStclass Failtable (%"UVuf" states): 0", 
2310                       (int)(depth * 2), "", (UV)numstates
2311         );
2312         for( q_read=1; q_read<numstates; q_read++ ) {
2313             PerlIO_printf(Perl_debug_log, ", %"UVuf, (UV)fail[q_read]);
2314         }
2315         PerlIO_printf(Perl_debug_log, "\n");
2316     });
2317     Safefree(q);
2318     /*RExC_seen |= REG_SEEN_TRIEDFA;*/
2319 }
2320
2321
2322 /*
2323  * There are strange code-generation bugs caused on sparc64 by gcc-2.95.2.
2324  * These need to be revisited when a newer toolchain becomes available.
2325  */
2326 #if defined(__sparc64__) && defined(__GNUC__)
2327 #   if __GNUC__ < 2 || (__GNUC__ == 2 && __GNUC_MINOR__ < 96)
2328 #       undef  SPARC64_GCC_WORKAROUND
2329 #       define SPARC64_GCC_WORKAROUND 1
2330 #   endif
2331 #endif
2332
2333 #define DEBUG_PEEP(str,scan,depth) \
2334     DEBUG_OPTIMISE_r({if (scan){ \
2335        SV * const mysv=sv_newmortal(); \
2336        regnode *Next = regnext(scan); \
2337        regprop(RExC_rx, mysv, scan); \
2338        PerlIO_printf(Perl_debug_log, "%*s" str ">%3d: %s (%d)\n", \
2339        (int)depth*2, "", REG_NODE_NUM(scan), SvPV_nolen_const(mysv),\
2340        Next ? (REG_NODE_NUM(Next)) : 0 ); \
2341    }});
2342
2343
2344
2345
2346
2347 #define JOIN_EXACT(scan,min,flags) \
2348     if (PL_regkind[OP(scan)] == EXACT) \
2349         join_exact(pRExC_state,(scan),(min),(flags),NULL,depth+1)
2350
2351 STATIC U32
2352 S_join_exact(pTHX_ RExC_state_t *pRExC_state, regnode *scan, I32 *min, U32 flags,regnode *val, U32 depth) {
2353     /* Merge several consecutive EXACTish nodes into one. */
2354     regnode *n = regnext(scan);
2355     U32 stringok = 1;
2356     regnode *next = scan + NODE_SZ_STR(scan);
2357     U32 merged = 0;
2358     U32 stopnow = 0;
2359 #ifdef DEBUGGING
2360     regnode *stop = scan;
2361     GET_RE_DEBUG_FLAGS_DECL;
2362 #else
2363     PERL_UNUSED_ARG(depth);
2364 #endif
2365
2366     PERL_ARGS_ASSERT_JOIN_EXACT;
2367 #ifndef EXPERIMENTAL_INPLACESCAN
2368     PERL_UNUSED_ARG(flags);
2369     PERL_UNUSED_ARG(val);
2370 #endif
2371     DEBUG_PEEP("join",scan,depth);
2372     
2373     /* Skip NOTHING, merge EXACT*. */
2374     while (n &&
2375            ( PL_regkind[OP(n)] == NOTHING ||
2376              (stringok && (OP(n) == OP(scan))))
2377            && NEXT_OFF(n)
2378            && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX) {
2379         
2380         if (OP(n) == TAIL || n > next)
2381             stringok = 0;
2382         if (PL_regkind[OP(n)] == NOTHING) {
2383             DEBUG_PEEP("skip:",n,depth);
2384             NEXT_OFF(scan) += NEXT_OFF(n);
2385             next = n + NODE_STEP_REGNODE;
2386 #ifdef DEBUGGING
2387             if (stringok)
2388                 stop = n;
2389 #endif
2390             n = regnext(n);
2391         }
2392         else if (stringok) {
2393             const unsigned int oldl = STR_LEN(scan);
2394             regnode * const nnext = regnext(n);
2395             
2396             DEBUG_PEEP("merg",n,depth);
2397             
2398             merged++;
2399             if (oldl + STR_LEN(n) > U8_MAX)
2400                 break;
2401             NEXT_OFF(scan) += NEXT_OFF(n);
2402             STR_LEN(scan) += STR_LEN(n);
2403             next = n + NODE_SZ_STR(n);
2404             /* Now we can overwrite *n : */
2405             Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
2406 #ifdef DEBUGGING
2407             stop = next - 1;
2408 #endif
2409             n = nnext;
2410             if (stopnow) break;
2411         }
2412
2413 #ifdef EXPERIMENTAL_INPLACESCAN
2414         if (flags && !NEXT_OFF(n)) {
2415             DEBUG_PEEP("atch", val, depth);
2416             if (reg_off_by_arg[OP(n)]) {
2417                 ARG_SET(n, val - n);
2418             }
2419             else {
2420                 NEXT_OFF(n) = val - n;
2421             }
2422             stopnow = 1;
2423         }
2424 #endif
2425     }
2426     
2427     if (UTF && ( OP(scan) == EXACTF ) && ( STR_LEN(scan) >= 6 ) ) {
2428     /*
2429     Two problematic code points in Unicode casefolding of EXACT nodes:
2430     
2431     U+0390 - GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS
2432     U+03B0 - GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS
2433     
2434     which casefold to
2435     
2436     Unicode                      UTF-8
2437     
2438     U+03B9 U+0308 U+0301         0xCE 0xB9 0xCC 0x88 0xCC 0x81
2439     U+03C5 U+0308 U+0301         0xCF 0x85 0xCC 0x88 0xCC 0x81
2440     
2441     This means that in case-insensitive matching (or "loose matching",
2442     as Unicode calls it), an EXACTF of length six (the UTF-8 encoded byte
2443     length of the above casefolded versions) can match a target string
2444     of length two (the byte length of UTF-8 encoded U+0390 or U+03B0).
2445     This would rather mess up the minimum length computation.
2446     
2447     What we'll do is to look for the tail four bytes, and then peek
2448     at the preceding two bytes to see whether we need to decrease
2449     the minimum length by four (six minus two).
2450     
2451     Thanks to the design of UTF-8, there cannot be false matches:
2452     A sequence of valid UTF-8 bytes cannot be a subsequence of
2453     another valid sequence of UTF-8 bytes.
2454     
2455     */
2456          char * const s0 = STRING(scan), *s, *t;
2457          char * const s1 = s0 + STR_LEN(scan) - 1;
2458          char * const s2 = s1 - 4;
2459 #ifdef EBCDIC /* RD tunifold greek 0390 and 03B0 */
2460          const char t0[] = "\xaf\x49\xaf\x42";
2461 #else
2462          const char t0[] = "\xcc\x88\xcc\x81";
2463 #endif
2464          const char * const t1 = t0 + 3;
2465     
2466          for (s = s0 + 2;
2467               s < s2 && (t = ninstr(s, s1, t0, t1));
2468               s = t + 4) {
2469 #ifdef EBCDIC
2470               if (((U8)t[-1] == 0x68 && (U8)t[-2] == 0xB4) ||
2471                   ((U8)t[-1] == 0x46 && (U8)t[-2] == 0xB5))
2472 #else
2473               if (((U8)t[-1] == 0xB9 && (U8)t[-2] == 0xCE) ||
2474                   ((U8)t[-1] == 0x85 && (U8)t[-2] == 0xCF))
2475 #endif
2476                    *min -= 4;
2477          }
2478     }
2479     
2480 #ifdef DEBUGGING
2481     /* Allow dumping */
2482     n = scan + NODE_SZ_STR(scan);
2483     while (n <= stop) {
2484         if (PL_regkind[OP(n)] != NOTHING || OP(n) == NOTHING) {
2485             OP(n) = OPTIMIZED;
2486             NEXT_OFF(n) = 0;
2487         }
2488         n++;
2489     }
2490 #endif
2491     DEBUG_OPTIMISE_r(if (merged){DEBUG_PEEP("finl",scan,depth)});
2492     return stopnow;
2493 }
2494
2495 /* REx optimizer.  Converts nodes into quickier variants "in place".
2496    Finds fixed substrings.  */
2497
2498 /* Stops at toplevel WHILEM as well as at "last". At end *scanp is set
2499    to the position after last scanned or to NULL. */
2500
2501 #define INIT_AND_WITHP \
2502     assert(!and_withp); \
2503     Newx(and_withp,1,struct regnode_charclass_class); \
2504     SAVEFREEPV(and_withp)
2505
2506 /* this is a chain of data about sub patterns we are processing that
2507    need to be handled seperately/specially in study_chunk. Its so
2508    we can simulate recursion without losing state.  */
2509 struct scan_frame;
2510 typedef struct scan_frame {
2511     regnode *last;  /* last node to process in this frame */
2512     regnode *next;  /* next node to process when last is reached */
2513     struct scan_frame *prev; /*previous frame*/
2514     I32 stop; /* what stopparen do we use */
2515 } scan_frame;
2516
2517
2518 #define SCAN_COMMIT(s, data, m) scan_commit(s, data, m, is_inf)
2519
2520 #define CASE_SYNST_FNC(nAmE)                                       \
2521 case nAmE:                                                         \
2522     if (flags & SCF_DO_STCLASS_AND) {                              \
2523             for (value = 0; value < 256; value++)                  \
2524                 if (!is_ ## nAmE ## _cp(value))                       \
2525                     ANYOF_BITMAP_CLEAR(data->start_class, value);  \
2526     }                                                              \
2527     else {                                                         \
2528             for (value = 0; value < 256; value++)                  \
2529                 if (is_ ## nAmE ## _cp(value))                        \
2530                     ANYOF_BITMAP_SET(data->start_class, value);    \
2531     }                                                              \
2532     break;                                                         \
2533 case N ## nAmE:                                                    \
2534     if (flags & SCF_DO_STCLASS_AND) {                              \
2535             for (value = 0; value < 256; value++)                   \
2536                 if (is_ ## nAmE ## _cp(value))                         \
2537                     ANYOF_BITMAP_CLEAR(data->start_class, value);   \
2538     }                                                               \
2539     else {                                                          \
2540             for (value = 0; value < 256; value++)                   \
2541                 if (!is_ ## nAmE ## _cp(value))                        \
2542                     ANYOF_BITMAP_SET(data->start_class, value);     \
2543     }                                                               \
2544     break
2545
2546
2547
2548 STATIC I32
2549 S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
2550                         I32 *minlenp, I32 *deltap,
2551                         regnode *last,
2552                         scan_data_t *data,
2553                         I32 stopparen,
2554                         U8* recursed,
2555                         struct regnode_charclass_class *and_withp,
2556                         U32 flags, U32 depth)
2557                         /* scanp: Start here (read-write). */
2558                         /* deltap: Write maxlen-minlen here. */
2559                         /* last: Stop before this one. */
2560                         /* data: string data about the pattern */
2561                         /* stopparen: treat close N as END */
2562                         /* recursed: which subroutines have we recursed into */
2563                         /* and_withp: Valid if flags & SCF_DO_STCLASS_OR */
2564 {
2565     dVAR;
2566     I32 min = 0, pars = 0, code;
2567     regnode *scan = *scanp, *next;
2568     I32 delta = 0;
2569     int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
2570     int is_inf_internal = 0;            /* The studied chunk is infinite */
2571     I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
2572     scan_data_t data_fake;
2573     SV *re_trie_maxbuff = NULL;
2574     regnode *first_non_open = scan;
2575     I32 stopmin = I32_MAX;
2576     scan_frame *frame = NULL;
2577     GET_RE_DEBUG_FLAGS_DECL;
2578
2579     PERL_ARGS_ASSERT_STUDY_CHUNK;
2580
2581 #ifdef DEBUGGING
2582     StructCopy(&zero_scan_data, &data_fake, scan_data_t);
2583 #endif
2584
2585     if ( depth == 0 ) {
2586         while (first_non_open && OP(first_non_open) == OPEN)
2587             first_non_open=regnext(first_non_open);
2588     }
2589
2590
2591   fake_study_recurse:
2592     while ( scan && OP(scan) != END && scan < last ){
2593         /* Peephole optimizer: */
2594         DEBUG_STUDYDATA("Peep:", data,depth);
2595         DEBUG_PEEP("Peep",scan,depth);
2596         JOIN_EXACT(scan,&min,0);
2597
2598         /* Follow the next-chain of the current node and optimize
2599            away all the NOTHINGs from it.  */
2600         if (OP(scan) != CURLYX) {
2601             const int max = (reg_off_by_arg[OP(scan)]
2602                        ? I32_MAX
2603                        /* I32 may be smaller than U16 on CRAYs! */
2604                        : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
2605             int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
2606             int noff;
2607             regnode *n = scan;
2608         
2609             /* Skip NOTHING and LONGJMP. */
2610             while ((n = regnext(n))
2611                    && ((PL_regkind[OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
2612                        || ((OP(n) == LONGJMP) && (noff = ARG(n))))
2613                    && off + noff < max)
2614                 off += noff;
2615             if (reg_off_by_arg[OP(scan)])
2616                 ARG(scan) = off;
2617             else
2618                 NEXT_OFF(scan) = off;
2619         }
2620
2621
2622
2623         /* The principal pseudo-switch.  Cannot be a switch, since we
2624            look into several different things.  */
2625         if (OP(scan) == BRANCH || OP(scan) == BRANCHJ
2626                    || OP(scan) == IFTHEN) {
2627             next = regnext(scan);
2628             code = OP(scan);
2629             /* demq: the op(next)==code check is to see if we have "branch-branch" AFAICT */
2630         
2631             if (OP(next) == code || code == IFTHEN) {
2632                 /* NOTE - There is similar code to this block below for handling
2633                    TRIE nodes on a re-study.  If you change stuff here check there
2634                    too. */
2635                 I32 max1 = 0, min1 = I32_MAX, num = 0;
2636                 struct regnode_charclass_class accum;
2637                 regnode * const startbranch=scan;
2638                 
2639                 if (flags & SCF_DO_SUBSTR)
2640                     SCAN_COMMIT(pRExC_state, data, minlenp); /* Cannot merge strings after this. */
2641                 if (flags & SCF_DO_STCLASS)
2642                     cl_init_zero(pRExC_state, &accum);
2643
2644                 while (OP(scan) == code) {
2645                     I32 deltanext, minnext, f = 0, fake;
2646                     struct regnode_charclass_class this_class;
2647
2648                     num++;
2649                     data_fake.flags = 0;
2650                     if (data) {
2651                         data_fake.whilem_c = data->whilem_c;
2652                         data_fake.last_closep = data->last_closep;
2653                     }
2654                     else
2655                         data_fake.last_closep = &fake;
2656
2657                     data_fake.pos_delta = delta;
2658                     next = regnext(scan);
2659                     scan = NEXTOPER(scan);
2660                     if (code != BRANCH)
2661                         scan = NEXTOPER(scan);
2662                     if (flags & SCF_DO_STCLASS) {
2663                         cl_init(pRExC_state, &this_class);
2664                         data_fake.start_class = &this_class;
2665                         f = SCF_DO_STCLASS_AND;
2666                     }
2667                     if (flags & SCF_WHILEM_VISITED_POS)
2668                         f |= SCF_WHILEM_VISITED_POS;
2669
2670                     /* we suppose the run is continuous, last=next...*/
2671                     minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext,
2672                                           next, &data_fake,
2673                                           stopparen, recursed, NULL, f,depth+1);
2674                     if (min1 > minnext)
2675                         min1 = minnext;
2676                     if (max1 < minnext + deltanext)
2677                         max1 = minnext + deltanext;
2678                     if (deltanext == I32_MAX)
2679                         is_inf = is_inf_internal = 1;
2680                     scan = next;
2681                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
2682                         pars++;
2683                     if (data_fake.flags & SCF_SEEN_ACCEPT) {
2684                         if ( stopmin > minnext) 
2685                             stopmin = min + min1;
2686                         flags &= ~SCF_DO_SUBSTR;
2687                         if (data)
2688                             data->flags |= SCF_SEEN_ACCEPT;
2689                     }
2690                     if (data) {
2691                         if (data_fake.flags & SF_HAS_EVAL)
2692                             data->flags |= SF_HAS_EVAL;
2693                         data->whilem_c = data_fake.whilem_c;
2694                     }
2695                     if (flags & SCF_DO_STCLASS)
2696                         cl_or(pRExC_state, &accum, &this_class);
2697                 }
2698                 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
2699                     min1 = 0;
2700                 if (flags & SCF_DO_SUBSTR) {
2701                     data->pos_min += min1;
2702                     data->pos_delta += max1 - min1;
2703                     if (max1 != min1 || is_inf)
2704                         data->longest = &(data->longest_float);
2705                 }
2706                 min += min1;
2707                 delta += max1 - min1;
2708                 if (flags & SCF_DO_STCLASS_OR) {
2709                     cl_or(pRExC_state, data->start_class, &accum);
2710                     if (min1) {
2711                         cl_and(data->start_class, and_withp);
2712                         flags &= ~SCF_DO_STCLASS;
2713                     }
2714                 }
2715                 else if (flags & SCF_DO_STCLASS_AND) {
2716                     if (min1) {
2717                         cl_and(data->start_class, &accum);
2718                         flags &= ~SCF_DO_STCLASS;
2719                     }
2720                     else {
2721                         /* Switch to OR mode: cache the old value of
2722                          * data->start_class */
2723                         INIT_AND_WITHP;
2724                         StructCopy(data->start_class, and_withp,
2725                                    struct regnode_charclass_class);
2726                         flags &= ~SCF_DO_STCLASS_AND;
2727                         StructCopy(&accum, data->start_class,
2728                                    struct regnode_charclass_class);
2729                         flags |= SCF_DO_STCLASS_OR;
2730                         data->start_class->flags |= ANYOF_EOS;
2731                     }
2732                 }
2733
2734                 if (PERL_ENABLE_TRIE_OPTIMISATION && OP( startbranch ) == BRANCH ) {
2735                 /* demq.
2736
2737                    Assuming this was/is a branch we are dealing with: 'scan' now
2738                    points at the item that follows the branch sequence, whatever
2739                    it is. We now start at the beginning of the sequence and look
2740                    for subsequences of
2741
2742                    BRANCH->EXACT=>x1
2743                    BRANCH->EXACT=>x2
2744                    tail
2745
2746                    which would be constructed from a pattern like /A|LIST|OF|WORDS/
2747
2748                    If we can find such a subseqence we need to turn the first
2749                    element into a trie and then add the subsequent branch exact
2750                    strings to the trie.
2751
2752                    We have two cases
2753
2754                      1. patterns where the whole set of branch can be converted. 
2755
2756                      2. patterns where only a subset can be converted.
2757
2758                    In case 1 we can replace the whole set with a single regop
2759                    for the trie. In case 2 we need to keep the start and end
2760                    branchs so
2761
2762                      'BRANCH EXACT; BRANCH EXACT; BRANCH X'
2763                      becomes BRANCH TRIE; BRANCH X;
2764
2765                   There is an additional case, that being where there is a 
2766                   common prefix, which gets split out into an EXACT like node
2767                   preceding the TRIE node.
2768
2769                   If x(1..n)==tail then we can do a simple trie, if not we make
2770                   a "jump" trie, such that when we match the appropriate word
2771                   we "jump" to the appopriate tail node. Essentailly we turn
2772                   a nested if into a case structure of sorts.
2773
2774                 */
2775                 
2776                     int made=0;
2777                     if (!re_trie_maxbuff) {
2778                         re_trie_maxbuff = get_sv(RE_TRIE_MAXBUF_NAME, 1);
2779                         if (!SvIOK(re_trie_maxbuff))
2780                             sv_setiv(re_trie_maxbuff, RE_TRIE_MAXBUF_INIT);
2781                     }
2782                     if ( SvIV(re_trie_maxbuff)>=0  ) {
2783                         regnode *cur;
2784                         regnode *first = (regnode *)NULL;
2785                         regnode *last = (regnode *)NULL;
2786                         regnode *tail = scan;
2787                         U8 optype = 0;
2788                         U32 count=0;
2789
2790 #ifdef DEBUGGING
2791                         SV * const mysv = sv_newmortal();       /* for dumping */
2792 #endif
2793                         /* var tail is used because there may be a TAIL
2794                            regop in the way. Ie, the exacts will point to the
2795                            thing following the TAIL, but the last branch will
2796                            point at the TAIL. So we advance tail. If we
2797                            have nested (?:) we may have to move through several
2798                            tails.
2799                          */
2800
2801                         while ( OP( tail ) == TAIL ) {
2802                             /* this is the TAIL generated by (?:) */
2803                             tail = regnext( tail );
2804                         }
2805
2806                         
2807                         DEBUG_OPTIMISE_r({
2808                             regprop(RExC_rx, mysv, tail );
2809                             PerlIO_printf( Perl_debug_log, "%*s%s%s\n",
2810                                 (int)depth * 2 + 2, "", 
2811                                 "Looking for TRIE'able sequences. Tail node is: ", 
2812                                 SvPV_nolen_const( mysv )
2813                             );
2814                         });
2815                         
2816                         /*
2817
2818                            step through the branches, cur represents each
2819                            branch, noper is the first thing to be matched
2820                            as part of that branch and noper_next is the
2821                            regnext() of that node. if noper is an EXACT
2822                            and noper_next is the same as scan (our current
2823                            position in the regex) then the EXACT branch is
2824                            a possible optimization target. Once we have
2825                            two or more consequetive such branches we can
2826                            create a trie of the EXACT's contents and stich
2827                            it in place. If the sequence represents all of
2828                            the branches we eliminate the whole thing and
2829                            replace it with a single TRIE. If it is a
2830                            subsequence then we need to stitch it in. This
2831                            means the first branch has to remain, and needs
2832                            to be repointed at the item on the branch chain
2833                            following the last branch optimized. This could
2834                            be either a BRANCH, in which case the
2835                            subsequence is internal, or it could be the
2836                            item following the branch sequence in which
2837                            case the subsequence is at the end.
2838
2839                         */
2840
2841                         /* dont use tail as the end marker for this traverse */
2842                         for ( cur = startbranch ; cur != scan ; cur = regnext( cur ) ) {
2843                             regnode * const noper = NEXTOPER( cur );
2844 #if defined(DEBUGGING) || defined(NOJUMPTRIE)
2845                             regnode * const noper_next = regnext( noper );
2846 #endif
2847
2848                             DEBUG_OPTIMISE_r({
2849                                 regprop(RExC_rx, mysv, cur);
2850                                 PerlIO_printf( Perl_debug_log, "%*s- %s (%d)",
2851                                    (int)depth * 2 + 2,"", SvPV_nolen_const( mysv ), REG_NODE_NUM(cur) );
2852
2853                                 regprop(RExC_rx, mysv, noper);
2854                                 PerlIO_printf( Perl_debug_log, " -> %s",
2855                                     SvPV_nolen_const(mysv));
2856
2857                                 if ( noper_next ) {
2858                                   regprop(RExC_rx, mysv, noper_next );
2859                                   PerlIO_printf( Perl_debug_log,"\t=> %s\t",
2860                                     SvPV_nolen_const(mysv));
2861                                 }
2862                                 PerlIO_printf( Perl_debug_log, "(First==%d,Last==%d,Cur==%d)\n",
2863                                    REG_NODE_NUM(first), REG_NODE_NUM(last), REG_NODE_NUM(cur) );
2864                             });
2865                             if ( (((first && optype!=NOTHING) ? OP( noper ) == optype
2866                                          : PL_regkind[ OP( noper ) ] == EXACT )
2867                                   || OP(noper) == NOTHING )
2868 #ifdef NOJUMPTRIE
2869                                   && noper_next == tail
2870 #endif
2871                                   && count < U16_MAX)
2872                             {
2873                                 count++;
2874                                 if ( !first || optype == NOTHING ) {
2875                                     if (!first) first = cur;
2876                                     optype = OP( noper );
2877                                 } else {
2878                                     last = cur;
2879                                 }
2880                             } else {
2881 /* 
2882     Currently we do not believe that the trie logic can
2883     handle case insensitive matching properly when the
2884     pattern is not unicode (thus forcing unicode semantics).
2885
2886     If/when this is fixed the following define can be swapped
2887     in below to fully enable trie logic.
2888
2889 #define TRIE_TYPE_IS_SAFE 1
2890
2891 */
2892 #define TRIE_TYPE_IS_SAFE (UTF || optype==EXACT)
2893
2894                                 if ( last && TRIE_TYPE_IS_SAFE ) {
2895                                     make_trie( pRExC_state, 
2896                                             startbranch, first, cur, tail, count, 
2897                                             optype, depth+1 );
2898                                 }
2899                                 if ( PL_regkind[ OP( noper ) ] == EXACT
2900 #ifdef NOJUMPTRIE
2901                                      && noper_next == tail
2902 #endif
2903                                 ){
2904                                     count = 1;
2905                                     first = cur;
2906                                     optype = OP( noper );
2907                                 } else {
2908                                     count = 0;
2909                                     first = NULL;
2910                                     optype = 0;
2911                                 }
2912                                 last = NULL;
2913                             }
2914                         }
2915                         DEBUG_OPTIMISE_r({
2916                             regprop(RExC_rx, mysv, cur);
2917                             PerlIO_printf( Perl_debug_log,
2918                               "%*s- %s (%d) <SCAN FINISHED>\n", (int)depth * 2 + 2,
2919                               "", SvPV_nolen_const( mysv ),REG_NODE_NUM(cur));
2920
2921                         });
2922                         
2923                         if ( last && TRIE_TYPE_IS_SAFE ) {
2924                             made= make_trie( pRExC_state, startbranch, first, scan, tail, count, optype, depth+1 );
2925 #ifdef TRIE_STUDY_OPT   
2926                             if ( ((made == MADE_EXACT_TRIE && 
2927                                  startbranch == first) 
2928                                  || ( first_non_open == first )) && 
2929                                  depth==0 ) {
2930                                 flags |= SCF_TRIE_RESTUDY;
2931                                 if ( startbranch == first 
2932                                      && scan == tail ) 
2933                                 {
2934                                     RExC_seen &=~REG_TOP_LEVEL_BRANCHES;
2935                                 }
2936                             }
2937 #endif
2938                         }
2939                     }
2940                     
2941                 } /* do trie */
2942                 
2943             }
2944             else if ( code == BRANCHJ ) {  /* single branch is optimized. */
2945                 scan = NEXTOPER(NEXTOPER(scan));
2946             } else                      /* single branch is optimized. */
2947                 scan = NEXTOPER(scan);
2948             continue;
2949         } else if (OP(scan) == SUSPEND || OP(scan) == GOSUB || OP(scan) == GOSTART) {
2950             scan_frame *newframe = NULL;
2951             I32 paren;
2952             regnode *start;
2953             regnode *end;
2954
2955             if (OP(scan) != SUSPEND) {
2956             /* set the pointer */
2957                 if (OP(scan) == GOSUB) {
2958                     paren = ARG(scan);
2959                     RExC_recurse[ARG2L(scan)] = scan;
2960                     start = RExC_open_parens[paren-1];
2961                     end   = RExC_close_parens[paren-1];
2962                 } else {
2963                     paren = 0;
2964                     start = RExC_rxi->program + 1;
2965                     end   = RExC_opend;
2966                 }
2967                 if (!recursed) {
2968                     Newxz(recursed, (((RExC_npar)>>3) +1), U8);
2969                     SAVEFREEPV(recursed);
2970                 }
2971                 if (!PAREN_TEST(recursed,paren+1)) {
2972                     PAREN_SET(recursed,paren+1);
2973                     Newx(newframe,1,scan_frame);
2974                 } else {
2975                     if (flags & SCF_DO_SUBSTR) {
2976                         SCAN_COMMIT(pRExC_state,data,minlenp);
2977                         data->longest = &(data->longest_float);
2978                     }
2979                     is_inf = is_inf_internal = 1;
2980                     if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
2981                         cl_anything(pRExC_state, data->start_class);
2982                     flags &= ~SCF_DO_STCLASS;
2983                 }
2984             } else {
2985                 Newx(newframe,1,scan_frame);
2986                 paren = stopparen;
2987                 start = scan+2;
2988                 end = regnext(scan);
2989             }
2990             if (newframe) {
2991                 assert(start);
2992                 assert(end);
2993                 SAVEFREEPV(newframe);
2994                 newframe->next = regnext(scan);
2995                 newframe->last = last;
2996                 newframe->stop = stopparen;
2997                 newframe->prev = frame;
2998
2999                 frame = newframe;
3000                 scan =  start;
3001                 stopparen = paren;
3002                 last = end;
3003
3004                 continue;
3005             }
3006         }
3007         else if (OP(scan) == EXACT) {
3008             I32 l = STR_LEN(scan);
3009             UV uc;
3010             if (UTF) {
3011                 const U8 * const s = (U8*)STRING(scan);
3012                 l = utf8_length(s, s + l);
3013                 uc = utf8_to_uvchr(s, NULL);
3014             } else {
3015                 uc = *((U8*)STRING(scan));
3016             }
3017             min += l;
3018             if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
3019                 /* The code below prefers earlier match for fixed
3020                    offset, later match for variable offset.  */
3021                 if (data->last_end == -1) { /* Update the start info. */
3022                     data->last_start_min = data->pos_min;
3023                     data->last_start_max = is_inf
3024                         ? I32_MAX : data->pos_min + data->pos_delta;
3025                 }
3026                 sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));
3027                 if (UTF)
3028                     SvUTF8_on(data->last_found);
3029                 {
3030                     SV * const sv = data->last_found;
3031                     MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
3032                         mg_find(sv, PERL_MAGIC_utf8) : NULL;
3033                     if (mg && mg->mg_len >= 0)
3034                         mg->mg_len += utf8_length((U8*)STRING(scan),
3035                                                   (U8*)STRING(scan)+STR_LEN(scan));
3036                 }
3037                 data->last_end = data->pos_min + l;
3038                 data->pos_min += l; /* As in the first entry. */
3039                 data->flags &= ~SF_BEFORE_EOL;
3040             }
3041             if (flags & SCF_DO_STCLASS_AND) {
3042                 /* Check whether it is compatible with what we know already! */
3043                 int compat = 1;
3044
3045                 if (uc >= 0x100 ||
3046                     (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
3047                     && !ANYOF_BITMAP_TEST(data->start_class, uc)
3048                     && (!(data->start_class->flags & ANYOF_FOLD)
3049                         || !ANYOF_BITMAP_TEST(data->start_class, PL_fold[uc])))
3050                     )
3051                     compat = 0;
3052                 ANYOF_CLASS_ZERO(data->start_class);
3053                 ANYOF_BITMAP_ZERO(data->start_class);
3054                 if (compat)
3055                     ANYOF_BITMAP_SET(data->start_class, uc);
3056                 data->start_class->flags &= ~ANYOF_EOS;
3057                 if (uc < 0x100)
3058                   data->start_class->flags &= ~ANYOF_UNICODE_ALL;
3059             }
3060             else if (flags & SCF_DO_STCLASS_OR) {
3061                 /* false positive possible if the class is case-folded */
3062                 if (uc < 0x100)
3063                     ANYOF_BITMAP_SET(data->start_class, uc);
3064                 else
3065                     data->start_class->flags |= ANYOF_UNICODE_ALL;
3066                 data->start_class->flags &= ~ANYOF_EOS;
3067                 cl_and(data->start_class, and_withp);
3068             }
3069             flags &= ~SCF_DO_STCLASS;
3070         }
3071         else if (PL_regkind[OP(scan)] == EXACT) { /* But OP != EXACT! */
3072             I32 l = STR_LEN(scan);
3073             UV uc = *((U8*)STRING(scan));
3074
3075             /* Search for fixed substrings supports EXACT only. */
3076             if (flags & SCF_DO_SUBSTR) {
3077                 assert(data);
3078                 SCAN_COMMIT(pRExC_state, data, minlenp);
3079             }
3080             if (UTF) {
3081                 const U8 * const s = (U8 *)STRING(scan);
3082                 l = utf8_length(s, s + l);
3083                 uc = utf8_to_uvchr(s, NULL);
3084             }
3085             min += l;
3086             if (flags & SCF_DO_SUBSTR)
3087                 data->pos_min += l;
3088             if (flags & SCF_DO_STCLASS_AND) {
3089                 /* Check whether it is compatible with what we know already! */
3090                 int compat = 1;
3091
3092                 if (uc >= 0x100 ||
3093                     (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
3094                     && !ANYOF_BITMAP_TEST(data->start_class, uc)
3095                      && !ANYOF_BITMAP_TEST(data->start_class, PL_fold[uc])))
3096                     compat = 0;
3097                 ANYOF_CLASS_ZERO(data->start_class);
3098                 ANYOF_BITMAP_ZERO(data->start_class);
3099                 if (compat) {
3100                     ANYOF_BITMAP_SET(data->start_class, uc);
3101                     data->start_class->flags &= ~ANYOF_EOS;
3102                     data->start_class->flags |= ANYOF_FOLD;
3103                     if (OP(scan) == EXACTFL)
3104                         data->start_class->flags |= ANYOF_LOCALE;
3105                 }
3106             }
3107             else if (flags & SCF_DO_STCLASS_OR) {
3108                 if (data->start_class->flags & ANYOF_FOLD) {
3109                     /* false positive possible if the class is case-folded.
3110                        Assume that the locale settings are the same... */
3111                     if (uc < 0x100)
3112                         ANYOF_BITMAP_SET(data->start_class, uc);
3113                     data->start_class->flags &= ~ANYOF_EOS;
3114                 }
3115                 cl_and(data->start_class, and_withp);
3116             }
3117             flags &= ~SCF_DO_STCLASS;
3118         }
3119         else if (REGNODE_VARIES(OP(scan))) {
3120             I32 mincount, maxcount, minnext, deltanext, fl = 0;
3121             I32 f = flags, pos_before = 0;
3122             regnode * const oscan = scan;
3123             struct regnode_charclass_class this_class;
3124             struct regnode_charclass_class *oclass = NULL;
3125             I32 next_is_eval = 0;
3126
3127             switch (PL_regkind[OP(scan)]) {
3128             case WHILEM:                /* End of (?:...)* . */
3129                 scan = NEXTOPER(scan);
3130                 goto finish;
3131             case PLUS:
3132                 if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
3133                     next = NEXTOPER(scan);
3134                     if (OP(next) == EXACT || (flags & SCF_DO_STCLASS)) {
3135                         mincount = 1;
3136                         maxcount = REG_INFTY;
3137                         next = regnext(scan);
3138                         scan = NEXTOPER(scan);
3139                         goto do_curly;
3140                     }
3141                 }
3142                 if (flags & SCF_DO_SUBSTR)
3143                     data->pos_min++;
3144                 min++;
3145                 /* Fall through. */
3146             case STAR:
3147                 if (flags & SCF_DO_STCLASS) {
3148                     mincount = 0;
3149                     maxcount = REG_INFTY;
3150                     next = regnext(scan);
3151                     scan = NEXTOPER(scan);
3152                     goto do_curly;
3153                 }
3154                 is_inf = is_inf_internal = 1;
3155                 scan = regnext(scan);
3156                 if (flags & SCF_DO_SUBSTR) {
3157                     SCAN_COMMIT(pRExC_state, data, minlenp); /* Cannot extend fixed substrings */
3158                     data->longest = &(data->longest_float);
3159                 }
3160                 goto optimize_curly_tail;
3161             case CURLY:
3162                 if (stopparen>0 && (OP(scan)==CURLYN || OP(scan)==CURLYM)
3163                     && (scan->flags == stopparen))
3164                 {
3165                     mincount = 1;
3166                     maxcount = 1;
3167                 } else {
3168                     mincount = ARG1(scan);
3169                     maxcount = ARG2(scan);
3170                 }
3171                 next = regnext(scan);
3172                 if (OP(scan) == CURLYX) {
3173                     I32 lp = (data ? *(data->last_closep) : 0);
3174                     scan->flags = ((lp <= (I32)U8_MAX) ? (U8)lp : U8_MAX);
3175                 }
3176                 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
3177                 next_is_eval = (OP(scan) == EVAL);
3178               do_curly:
3179                 if (flags & SCF_DO_SUBSTR) {
3180                     if (mincount == 0) SCAN_COMMIT(pRExC_state,data,minlenp); /* Cannot extend fixed substrings */
3181                     pos_before = data->pos_min;
3182                 }
3183                 if (data) {
3184                     fl = data->flags;
3185                     data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
3186                     if (is_inf)
3187                         data->flags |= SF_IS_INF;
3188                 }
3189                 if (flags & SCF_DO_STCLASS) {
3190                     cl_init(pRExC_state, &this_class);
3191                     oclass = data->start_class;
3192                     data->start_class = &this_class;
3193                     f |= SCF_DO_STCLASS_AND;
3194                     f &= ~SCF_DO_STCLASS_OR;
3195                 }
3196                 /* These are the cases when once a subexpression
3197                    fails at a particular position, it cannot succeed
3198                    even after backtracking at the enclosing scope.
3199                 
3200                    XXXX what if minimal match and we are at the
3201                         initial run of {n,m}? */
3202                 if ((mincount != maxcount - 1) && (maxcount != REG_INFTY))
3203                     f &= ~SCF_WHILEM_VISITED_POS;
3204
3205                 /* This will finish on WHILEM, setting scan, or on NULL: */
3206                 minnext = study_chunk(pRExC_state, &scan, minlenp, &deltanext, 
3207                                       last, data, stopparen, recursed, NULL,
3208                                       (mincount == 0
3209                                         ? (f & ~SCF_DO_SUBSTR) : f),depth+1);
3210
3211                 if (flags & SCF_DO_STCLASS)
3212                     data->start_class = oclass;
3213                 if (mincount == 0 || minnext == 0) {
3214                     if (flags & SCF_DO_STCLASS_OR) {
3215                         cl_or(pRExC_state, data->start_class, &this_class);
3216                     }
3217                     else if (flags & SCF_DO_STCLASS_AND) {
3218                         /* Switch to OR mode: cache the old value of
3219                          * data->start_class */
3220                         INIT_AND_WITHP;
3221                         StructCopy(data->start_class, and_withp,
3222                                    struct regnode_charclass_class);
3223                         flags &= ~SCF_DO_STCLASS_AND;
3224                         StructCopy(&this_class, data->start_class,
3225                                    struct regnode_charclass_class);
3226                         flags |= SCF_DO_STCLASS_OR;
3227                         data->start_class->flags |= ANYOF_EOS;
3228                     }
3229                 } else {                /* Non-zero len */
3230                     if (flags & SCF_DO_STCLASS_OR) {
3231                         cl_or(pRExC_state, data->start_class, &this_class);
3232                         cl_and(data->start_class, and_withp);
3233                     }
3234                     else if (flags & SCF_DO_STCLASS_AND)
3235                         cl_and(data->start_class, &this_class);
3236                     flags &= ~SCF_DO_STCLASS;
3237                 }
3238                 if (!scan)              /* It was not CURLYX, but CURLY. */
3239                     scan = next;
3240                 if ( /* ? quantifier ok, except for (?{ ... }) */
3241                     (next_is_eval || !(mincount == 0 && maxcount == 1))
3242                     && (minnext == 0) && (deltanext == 0)
3243                     && data && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
3244                     && maxcount <= REG_INFTY/3) /* Complement check for big count */
3245                 {
3246                     ckWARNreg(RExC_parse,
3247                               "Quantifier unexpected on zero-length expression");
3248                 }
3249
3250                 min += minnext * mincount;
3251                 is_inf_internal |= ((maxcount == REG_INFTY
3252                                      && (minnext + deltanext) > 0)
3253                                     || deltanext == I32_MAX);
3254                 is_inf |= is_inf_internal;
3255                 delta += (minnext + deltanext) * maxcount - minnext * mincount;
3256
3257                 /* Try powerful optimization CURLYX => CURLYN. */
3258                 if (  OP(oscan) == CURLYX && data
3259                       && data->flags & SF_IN_PAR
3260                       && !(data->flags & SF_HAS_EVAL)
3261                       && !deltanext && minnext == 1 ) {
3262                     /* Try to optimize to CURLYN.  */
3263                     regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
3264                     regnode * const nxt1 = nxt;
3265 #ifdef DEBUGGING
3266                     regnode *nxt2;
3267 #endif
3268
3269                     /* Skip open. */
3270                     nxt = regnext(nxt);
3271                     if (!REGNODE_SIMPLE(OP(nxt))
3272                         && !(PL_regkind[OP(nxt)] == EXACT
3273                              && STR_LEN(nxt) == 1))
3274                         goto nogo;
3275 #ifdef DEBUGGING
3276                     nxt2 = nxt;
3277 #endif
3278                     nxt = regnext(nxt);
3279                     if (OP(nxt) != CLOSE)
3280                         goto nogo;
3281                     if (RExC_open_parens) {
3282                         RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
3283                         RExC_close_parens[ARG(nxt1)-1]=nxt+2; /*close->while*/
3284                     }
3285                     /* Now we know that nxt2 is the only contents: */
3286                     oscan->flags = (U8)ARG(nxt);
3287                     OP(oscan) = CURLYN;
3288                     OP(nxt1) = NOTHING; /* was OPEN. */
3289
3290 #ifdef DEBUGGING
3291                     OP(nxt1 + 1) = OPTIMIZED; /* was count. */
3292                     NEXT_OFF(nxt1+ 1) = 0; /* just for consistancy. */
3293                     NEXT_OFF(nxt2) = 0; /* just for consistancy with CURLY. */
3294                     OP(nxt) = OPTIMIZED;        /* was CLOSE. */
3295                     OP(nxt + 1) = OPTIMIZED; /* was count. */
3296                     NEXT_OFF(nxt+ 1) = 0; /* just for consistancy. */
3297 #endif
3298                 }
3299               nogo:
3300
3301                 /* Try optimization CURLYX => CURLYM. */
3302                 if (  OP(oscan) == CURLYX && data
3303                       && !(data->flags & SF_HAS_PAR)
3304                       && !(data->flags & SF_HAS_EVAL)
3305                       && !deltanext     /* atom is fixed width */
3306                       && minnext != 0   /* CURLYM can't handle zero width */
3307                 ) {
3308                     /* XXXX How to optimize if data == 0? */
3309                     /* Optimize to a simpler form.  */
3310                     regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
3311                     regnode *nxt2;
3312
3313                     OP(oscan) = CURLYM;
3314                     while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
3315                             && (OP(nxt2) != WHILEM))
3316                         nxt = nxt2;
3317                     OP(nxt2)  = SUCCEED; /* Whas WHILEM */
3318                     /* Need to optimize away parenths. */
3319                     if ((data->flags & SF_IN_PAR) && OP(nxt) == CLOSE) {
3320                         /* Set the parenth number.  */
3321                         regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
3322
3323                         oscan->flags = (U8)ARG(nxt);
3324                         if (RExC_open_parens) {
3325                             RExC_open_parens[ARG(nxt1)-1]=oscan; /*open->CURLYM*/
3326                             RExC_close_parens[ARG(nxt1)-1]=nxt2+1; /*close->NOTHING*/
3327                         }
3328                         OP(nxt1) = OPTIMIZED;   /* was OPEN. */
3329                         OP(nxt) = OPTIMIZED;    /* was CLOSE. */
3330
3331 #ifdef DEBUGGING
3332                         OP(nxt1 + 1) = OPTIMIZED; /* was count. */
3333                         OP(nxt + 1) = OPTIMIZED; /* was count. */
3334                         NEXT_OFF(nxt1 + 1) = 0; /* just for consistancy. */
3335                         NEXT_OFF(nxt + 1) = 0; /* just for consistancy. */
3336 #endif
3337 #if 0
3338                         while ( nxt1 && (OP(nxt1) != WHILEM)) {
3339                             regnode *nnxt = regnext(nxt1);
3340                         
3341                             if (nnxt == nxt) {
3342                                 if (reg_off_by_arg[OP(nxt1)])
3343                                     ARG_SET(nxt1, nxt2 - nxt1);
3344                                 else if (nxt2 - nxt1 < U16_MAX)
3345                                     NEXT_OFF(nxt1) = nxt2 - nxt1;
3346                                 else
3347                                     OP(nxt) = NOTHING;  /* Cannot beautify */
3348                             }
3349                             nxt1 = nnxt;
3350                         }
3351 #endif
3352                         /* Optimize again: */
3353                         study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,
3354                                     NULL, stopparen, recursed, NULL, 0,depth+1);
3355                     }
3356                     else
3357                         oscan->flags = 0;
3358                 }
3359                 else if ((OP(oscan) == CURLYX)
3360                          && (flags & SCF_WHILEM_VISITED_POS)
3361                          /* See the comment on a similar expression above.
3362                             However, this time it not a subexpression
3363                             we care about, but the expression itself. */
3364                          && (maxcount == REG_INFTY)
3365                          && data && ++data->whilem_c < 16) {
3366                     /* This stays as CURLYX, we can put the count/of pair. */
3367                     /* Find WHILEM (as in regexec.c) */
3368                     regnode *nxt = oscan + NEXT_OFF(oscan);
3369
3370                     if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
3371                         nxt += ARG(nxt);
3372                     PREVOPER(nxt)->flags = (U8)(data->whilem_c
3373                         | (RExC_whilem_seen << 4)); /* On WHILEM */
3374                 }
3375                 if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
3376                     pars++;
3377                 if (flags & SCF_DO_SUBSTR) {
3378                     SV *last_str = NULL;
3379                     int counted = mincount != 0;
3380
3381                     if (data->last_end > 0 && mincount != 0) { /* Ends with a string. */
3382 #if defined(SPARC64_GCC_WORKAROUND)
3383                         I32 b = 0;
3384                         STRLEN l = 0;
3385                         const char *s = NULL;
3386                         I32 old = 0;
3387
3388                         if (pos_before >= data->last_start_min)
3389                             b = pos_before;
3390                         else
3391                             b = data->last_start_min;
3392
3393                         l = 0;
3394                         s = SvPV_const(data->last_found, l);
3395                         old = b - data->last_start_min;
3396
3397 #else
3398                         I32 b = pos_before >= data->last_start_min
3399                             ? pos_before : data->last_start_min;
3400                         STRLEN l;
3401                         const char * const s = SvPV_const(data->last_found, l);
3402                         I32 old = b - data->last_start_min;
3403 #endif
3404
3405                         if (UTF)
3406                             old = utf8_hop((U8*)s, old) - (U8*)s;
3407                         
3408                         l -= old;
3409                         /* Get the added string: */
3410                         last_str = newSVpvn_utf8(s  + old, l, UTF);
3411                         if (deltanext == 0 && pos_before == b) {
3412                             /* What was added is a constant string */
3413                             if (mincount > 1) {
3414                                 SvGROW(last_str, (mincount * l) + 1);
3415                                 repeatcpy(SvPVX(last_str) + l,
3416                                           SvPVX_const(last_str), l, mincount - 1);
3417                                 SvCUR_set(last_str, SvCUR(last_str) * mincount);
3418                                 /* Add additional parts. */
3419                                 SvCUR_set(data->last_found,
3420                                           SvCUR(data->last_found) - l);
3421                                 sv_catsv(data->last_found, last_str);
3422                                 {
3423                                     SV * sv = data->last_found;
3424                                     MAGIC *mg =
3425                                         SvUTF8(sv) && SvMAGICAL(sv) ?
3426                                         mg_find(sv, PERL_MAGIC_utf8) : NULL;
3427                                     if (mg && mg->mg_len >= 0)
3428                                         mg->mg_len += CHR_SVLEN(last_str) - l;
3429                                 }
3430                                 data->last_end += l * (mincount - 1);
3431                             }
3432                         } else {
3433                             /* start offset must point into the last copy */
3434                             data->last_start_min += minnext * (mincount - 1);
3435                             data->last_start_max += is_inf ? I32_MAX
3436                                 : (maxcount - 1) * (minnext + data->pos_delta);
3437                         }
3438                     }
3439                     /* It is counted once already... */
3440                     data->pos_min += minnext * (mincount - counted);
3441                     data->pos_delta += - counted * deltanext +
3442                         (minnext + deltanext) * maxcount - minnext * mincount;
3443                     if (mincount != maxcount) {
3444                          /* Cannot extend fixed substrings found inside
3445                             the group.  */
3446                         SCAN_COMMIT(pRExC_state,data,minlenp);
3447                         if (mincount && last_str) {
3448                             SV * const sv = data->last_found;
3449                             MAGIC * const mg = SvUTF8(sv) && SvMAGICAL(sv) ?
3450                                 mg_find(sv, PERL_MAGIC_utf8) : NULL;
3451
3452                             if (mg)
3453                                 mg->mg_len = -1;
3454                             sv_setsv(sv, last_str);
3455                             data->last_end = data->pos_min;
3456                             data->last_start_min =
3457                                 data->pos_min - CHR_SVLEN(last_str);
3458                             data->last_start_max = is_inf
3459                                 ? I32_MAX
3460                                 : data->pos_min + data->pos_delta
3461                                 - CHR_SVLEN(last_str);
3462                         }
3463                         data->longest = &(data->longest_float);
3464                     }
3465                     SvREFCNT_dec(last_str);
3466                 }
3467                 if (data && (fl & SF_HAS_EVAL))
3468                     data->flags |= SF_HAS_EVAL;
3469               optimize_curly_tail:
3470                 if (OP(oscan) != CURLYX) {
3471                     while (PL_regkind[OP(next = regnext(oscan))] == NOTHING
3472                            && NEXT_OFF(next))
3473                         NEXT_OFF(oscan) += NEXT_OFF(next);
3474                 }
3475                 continue;
3476             default:                    /* REF and CLUMP only? */
3477                 if (flags & SCF_DO_SUBSTR) {
3478                     SCAN_COMMIT(pRExC_state,data,minlenp);      /* Cannot expect anything... */
3479                     data->longest = &(data->longest_float);
3480                 }
3481                 is_inf = is_inf_internal = 1;
3482                 if (flags & SCF_DO_STCLASS_OR)
3483                     cl_anything(pRExC_state, data->start_class);
3484                 flags &= ~SCF_DO_STCLASS;
3485                 break;
3486             }
3487         }
3488         else if (OP(scan) == LNBREAK) {
3489             if (flags & SCF_DO_STCLASS) {
3490                 int value = 0;
3491                 data->start_class->flags &= ~ANYOF_EOS; /* No match on empty */
3492                 if (flags & SCF_DO_STCLASS_AND) {
3493                     for (value = 0; value < 256; value++)
3494                         if (!is_VERTWS_cp(value))
3495                             ANYOF_BITMAP_CLEAR(data->start_class, value);  
3496                 }                                                              
3497                 else {                                                         
3498                     for (value = 0; value < 256; value++)
3499                         if (is_VERTWS_cp(value))
3500                             ANYOF_BITMAP_SET(data->start_class, value);    
3501                 }                                                              
3502                 if (flags & SCF_DO_STCLASS_OR)
3503                     cl_and(data->start_class, and_withp);
3504                 flags &= ~SCF_DO_STCLASS;
3505             }
3506             min += 1;
3507             delta += 1;
3508             if (flags & SCF_DO_SUBSTR) {
3509                 SCAN_COMMIT(pRExC_state,data,minlenp);  /* Cannot expect anything... */
3510                 data->pos_min += 1;
3511                 data->pos_delta += 1;
3512                 data->longest = &(data->longest_float);
3513             }
3514             
3515         }
3516         else if (OP(scan) == FOLDCHAR) {
3517             int d = ARG(scan)==0xDF ? 1 : 2;
3518             flags &= ~SCF_DO_STCLASS;
3519             min += 1;
3520             delta += d;
3521             if (flags & SCF_DO_SUBSTR) {
3522                 SCAN_COMMIT(pRExC_state,data,minlenp);  /* Cannot expect anything... */
3523                 data->pos_min += 1;
3524                 data->pos_delta += d;
3525                 data->longest = &(data->longest_float);
3526             }
3527         }
3528         else if (REGNODE_SIMPLE(OP(scan))) {
3529             int value = 0;
3530
3531             if (flags & SCF_DO_SUBSTR) {
3532                 SCAN_COMMIT(pRExC_state,data,minlenp);
3533                 data->pos_min++;
3534             }
3535             min++;
3536             if (flags & SCF_DO_STCLASS) {
3537                 data->start_class->flags &= ~ANYOF_EOS; /* No match on empty */
3538
3539                 /* Some of the logic below assumes that switching
3540                    locale on will only add false positives. */
3541                 switch (PL_regkind[OP(scan)]) {
3542                 case SANY:
3543                 default:
3544                   do_default:
3545                     /* Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d", OP(scan)); */
3546                     if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
3547                         cl_anything(pRExC_state, data->start_class);
3548                     break;
3549                 case REG_ANY:
3550                     if (OP(scan) == SANY)
3551                         goto do_default;
3552                     if (flags & SCF_DO_STCLASS_OR) { /* Everything but \n */
3553                         value = (ANYOF_BITMAP_TEST(data->start_class,'\n')
3554                                  || (data->start_class->flags & ANYOF_CLASS));
3555                         cl_anything(pRExC_state, data->start_class);
3556                     }
3557                     if (flags & SCF_DO_STCLASS_AND || !value)
3558                         ANYOF_BITMAP_CLEAR(data->start_class,'\n');
3559                     break;
3560                 case ANYOF:
3561                     if (flags & SCF_DO_STCLASS_AND)
3562                         cl_and(data->start_class,
3563                                (struct regnode_charclass_class*)scan);
3564                     else
3565                         cl_or(pRExC_state, data->start_class,
3566                               (struct regnode_charclass_class*)scan);
3567                     break;
3568                 case ALNUM:
3569                     if (flags & SCF_DO_STCLASS_AND) {
3570                         if (!(data->start_class->flags & ANYOF_LOCALE)) {
3571                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
3572                             for (value = 0; value < 256; value++)
3573                                 if (!isALNUM(value))
3574                                     ANYOF_BITMAP_CLEAR(data->start_class, value);
3575                         }
3576                     }
3577                     else {
3578                         if (data->start_class->flags & ANYOF_LOCALE)
3579                             ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
3580                         else {
3581                             for (value = 0; value < 256; value++)
3582                                 if (isALNUM(value))
3583                                     ANYOF_BITMAP_SET(data->start_class, value);                 
3584                         }
3585                     }
3586                     break;
3587                 case ALNUML:
3588                     if (flags & SCF_DO_STCLASS_AND) {
3589                         if (data->start_class->flags & ANYOF_LOCALE)
3590                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
3591                     }
3592                     else {
3593                         ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
3594                         data->start_class->flags |= ANYOF_LOCALE;
3595                     }
3596                     break;
3597                 case NALNUM:
3598                     if (flags & SCF_DO_STCLASS_AND) {
3599                         if (!(data->start_class->flags & ANYOF_LOCALE)) {
3600                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
3601                             for (value = 0; value < 256; value++)
3602                                 if (isALNUM(value))
3603                                     ANYOF_BITMAP_CLEAR(data->start_class, value);
3604                         }
3605                     }
3606                     else {
3607                         if (data->start_class->flags & ANYOF_LOCALE)
3608                             ANYOF_CLASS_SET(data->start_class,ANYOF_NALNUM);
3609                         else {
3610                             for (value = 0; value < 256; value++)
3611                                 if (!isALNUM(value))
3612                                     ANYOF_BITMAP_SET(data->start_class, value);                 
3613                         }
3614                     }
3615                     break;
3616                 case NALNUML:
3617                     if (flags & SCF_DO_STCLASS_AND) {
3618                         if (data->start_class->flags & ANYOF_LOCALE)
3619                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
3620                     }
3621                     else {
3622                         data->start_class->flags |= ANYOF_LOCALE;
3623                         ANYOF_CLASS_SET(data->start_class,ANYOF_NALNUM);
3624                     }
3625                     break;
3626                 case SPACE:
3627                     if (flags & SCF_DO_STCLASS_AND) {
3628                         if (!(data->start_class->flags & ANYOF_LOCALE)) {
3629                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NSPACE);
3630                             for (value = 0; value < 256; value++)
3631                                 if (!isSPACE(value))
3632                                     ANYOF_BITMAP_CLEAR(data->start_class, value);
3633                         }
3634                     }
3635                     else {
3636                         if (data->start_class->flags & ANYOF_LOCALE)
3637                             ANYOF_CLASS_SET(data->start_class,ANYOF_SPACE);
3638                         else {
3639                             for (value = 0; value < 256; value++)
3640                                 if (isSPACE(value))
3641                                     ANYOF_BITMAP_SET(data->start_class, value);                 
3642                         }
3643                     }
3644                     break;
3645                 case SPACEL:
3646                     if (flags & SCF_DO_STCLASS_AND) {
3647                         if (data->start_class->flags & ANYOF_LOCALE)
3648                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NSPACE);
3649                     }
3650                     else {
3651                         data->start_class->flags |= ANYOF_LOCALE;
3652                         ANYOF_CLASS_SET(data->start_class,ANYOF_SPACE);
3653                     }
3654                     break;
3655                 case NSPACE:
3656                     if (flags & SCF_DO_STCLASS_AND) {
3657                         if (!(data->start_class->flags & ANYOF_LOCALE)) {
3658                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_SPACE);
3659                             for (value = 0; value < 256; value++)
3660                                 if (isSPACE(value))
3661                                     ANYOF_BITMAP_CLEAR(data->start_class, value);
3662                         }
3663                     }
3664                     else {
3665                         if (data->start_class->flags & ANYOF_LOCALE)
3666                             ANYOF_CLASS_SET(data->start_class,ANYOF_NSPACE);
3667                         else {
3668                             for (value = 0; value < 256; value++)
3669                                 if (!isSPACE(value))
3670                                     ANYOF_BITMAP_SET(data->start_class, value);                 
3671                         }
3672                     }
3673                     break;
3674                 case NSPACEL:
3675                     if (flags & SCF_DO_STCLASS_AND) {
3676                         if (data->start_class->flags & ANYOF_LOCALE) {
3677                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_SPACE);
3678                             for (value = 0; value < 256; value++)
3679                                 if (!isSPACE(value))
3680                                     ANYOF_BITMAP_CLEAR(data->start_class, value);
3681                         }
3682                     }
3683                     else {
3684                         data->start_class->flags |= ANYOF_LOCALE;
3685                         ANYOF_CLASS_SET(data->start_class,ANYOF_NSPACE);
3686                     }
3687                     break;
3688                 case DIGIT:
3689                     if (flags & SCF_DO_STCLASS_AND) {
3690                         ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NDIGIT);
3691                         for (value = 0; value < 256; value++)
3692                             if (!isDIGIT(value))
3693                                 ANYOF_BITMAP_CLEAR(data->start_class, value);
3694                     }
3695                     else {
3696                         if (data->start_class->flags & ANYOF_LOCALE)
3697                             ANYOF_CLASS_SET(data->start_class,ANYOF_DIGIT);
3698                         else {
3699                             for (value = 0; value < 256; value++)
3700                                 if (isDIGIT(value))
3701                                     ANYOF_BITMAP_SET(data->start_class, value);                 
3702                         }
3703                     }
3704                     break;
3705                 case NDIGIT:
3706                     if (flags & SCF_DO_STCLASS_AND) {
3707                         ANYOF_CLASS_CLEAR(data->start_class,ANYOF_DIGIT);
3708                         for (value = 0; value < 256; value++)
3709                             if (isDIGIT(value))
3710                                 ANYOF_BITMAP_CLEAR(data->start_class, value);
3711                     }
3712                     else {
3713                         if (data->start_class->flags & ANYOF_LOCALE)
3714                             ANYOF_CLASS_SET(data->start_class,ANYOF_NDIGIT);
3715                         else {
3716                             for (value = 0; value < 256; value++)
3717                                 if (!isDIGIT(value))
3718                                     ANYOF_BITMAP_SET(data->start_class, value);                 
3719                         }
3720                     }
3721                     break;
3722                 CASE_SYNST_FNC(VERTWS);
3723                 CASE_SYNST_FNC(HORIZWS);
3724                 
3725                 }
3726                 if (flags & SCF_DO_STCLASS_OR)
3727                     cl_and(data->start_class, and_withp);
3728                 flags &= ~SCF_DO_STCLASS;
3729             }
3730         }
3731         else if (PL_regkind[OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
3732             data->flags |= (OP(scan) == MEOL
3733                             ? SF_BEFORE_MEOL
3734                             : SF_BEFORE_SEOL);
3735         }
3736         else if (  PL_regkind[OP(scan)] == BRANCHJ
3737                  /* Lookbehind, or need to calculate parens/evals/stclass: */
3738                    && (scan->flags || data || (flags & SCF_DO_STCLASS))
3739                    && (OP(scan) == IFMATCH || OP(scan) == UNLESSM)) {
3740             if ( !PERL_ENABLE_POSITIVE_ASSERTION_STUDY 
3741                 || OP(scan) == UNLESSM )
3742             {
3743                 /* Negative Lookahead/lookbehind
3744                    In this case we can't do fixed string optimisation.
3745                 */
3746
3747                 I32 deltanext, minnext, fake = 0;
3748                 regnode *nscan;
3749                 struct regnode_charclass_class intrnl;
3750                 int f = 0;
3751
3752                 data_fake.flags = 0;
3753                 if (data) {
3754                     data_fake.whilem_c = data->whilem_c;
3755                     data_fake.last_closep = data->last_closep;
3756                 }
3757                 else
3758                     data_fake.last_closep = &fake;
3759                 data_fake.pos_delta = delta;
3760                 if ( flags & SCF_DO_STCLASS && !scan->flags
3761                      && OP(scan) == IFMATCH ) { /* Lookahead */
3762                     cl_init(pRExC_state, &intrnl);
3763                     data_fake.start_class = &intrnl;
3764                     f |= SCF_DO_STCLASS_AND;
3765                 }
3766                 if (flags & SCF_WHILEM_VISITED_POS)
3767                     f |= SCF_WHILEM_VISITED_POS;
3768                 next = regnext(scan);
3769                 nscan = NEXTOPER(NEXTOPER(scan));
3770                 minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext, 
3771                     last, &data_fake, stopparen, recursed, NULL, f, depth+1);
3772                 if (scan->flags) {
3773                     if (deltanext) {
3774                         FAIL("Variable length lookbehind not implemented");
3775                     }
3776                     else if (minnext > (I32)U8_MAX) {
3777                         FAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
3778                     }
3779                     scan->flags = (U8)minnext;
3780                 }
3781                 if (data) {
3782                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
3783                         pars++;
3784                     if (data_fake.flags & SF_HAS_EVAL)
3785                         data->flags |= SF_HAS_EVAL;
3786                     data->whilem_c = data_fake.whilem_c;
3787                 }
3788                 if (f & SCF_DO_STCLASS_AND) {
3789                     if (flags & SCF_DO_STCLASS_OR) {
3790                         /* OR before, AND after: ideally we would recurse with
3791                          * data_fake to get the AND applied by study of the
3792                          * remainder of the pattern, and then derecurse;
3793                          * *** HACK *** for now just treat as "no information".
3794                          * See [perl #56690].
3795                          */
3796                         cl_init(pRExC_state, data->start_class);
3797                     }  else {
3798                         /* AND before and after: combine and continue */
3799                         const int was = (data->start_class->flags & ANYOF_EOS);
3800
3801                         cl_and(data->start_class, &intrnl);
3802                         if (was)
3803                             data->start_class->flags |= ANYOF_EOS;
3804                     }
3805                 }
3806             }
3807 #if PERL_ENABLE_POSITIVE_ASSERTION_STUDY
3808             else {
3809                 /* Positive Lookahead/lookbehind
3810                    In this case we can do fixed string optimisation,
3811                    but we must be careful about it. Note in the case of
3812                    lookbehind the positions will be offset by the minimum
3813                    length of the pattern, something we won't know about
3814                    until after the recurse.
3815                 */
3816                 I32 deltanext, fake = 0;
3817                 regnode *nscan;
3818                 struct regnode_charclass_class intrnl;
3819                 int f = 0;
3820                 /* We use SAVEFREEPV so that when the full compile 
3821                     is finished perl will clean up the allocated 
3822                     minlens when its all done. This was we don't
3823                     have to worry about freeing them when we know
3824                     they wont be used, which would be a pain.
3825                  */
3826                 I32 *minnextp;
3827                 Newx( minnextp, 1, I32 );
3828                 SAVEFREEPV(minnextp);
3829
3830                 if (data) {
3831                     StructCopy(data, &data_fake, scan_data_t);
3832                     if ((flags & SCF_DO_SUBSTR) && data->last_found) {
3833                         f |= SCF_DO_SUBSTR;
3834                         if (scan->flags) 
3835                             SCAN_COMMIT(pRExC_state, &data_fake,minlenp);
3836                         data_fake.last_found=newSVsv(data->last_found);
3837                     }
3838                 }
3839                 else
3840                     data_fake.last_closep = &fake;
3841                 data_fake.flags = 0;
3842                 data_fake.pos_delta = delta;
3843                 if (is_inf)
3844                     data_fake.flags |= SF_IS_INF;
3845                 if ( flags & SCF_DO_STCLASS && !scan->flags
3846                      && OP(scan) == IFMATCH ) { /* Lookahead */
3847                     cl_init(pRExC_state, &intrnl);
3848                     data_fake.start_class = &intrnl;
3849                     f |= SCF_DO_STCLASS_AND;
3850                 }
3851                 if (flags & SCF_WHILEM_VISITED_POS)
3852                     f |= SCF_WHILEM_VISITED_POS;
3853                 next = regnext(scan);
3854                 nscan = NEXTOPER(NEXTOPER(scan));
3855
3856                 *minnextp = study_chunk(pRExC_state, &nscan, minnextp, &deltanext, 
3857                     last, &data_fake, stopparen, recursed, NULL, f,depth+1);
3858                 if (scan->flags) {
3859                     if (deltanext) {
3860                         FAIL("Variable length lookbehind not implemented");
3861                     }
3862                     else if (*minnextp > (I32)U8_MAX) {
3863                         FAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
3864                     }
3865                     scan->flags = (U8)*minnextp;
3866                 }
3867
3868                 *minnextp += min;
3869
3870                 if (f & SCF_DO_STCLASS_AND) {
3871                     const int was = (data->start_class->flags & ANYOF_EOS);
3872
3873                     cl_and(data->start_class, &intrnl);
3874                     if (was)
3875                         data->start_class->flags |= ANYOF_EOS;
3876                 }
3877                 if (data) {
3878                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
3879                         pars++;
3880                     if (data_fake.flags & SF_HAS_EVAL)
3881                         data->flags |= SF_HAS_EVAL;
3882                     data->whilem_c = data_fake.whilem_c;
3883                     if ((flags & SCF_DO_SUBSTR) && data_fake.last_found) {
3884                         if (RExC_rx->minlen<*minnextp)
3885                             RExC_rx->minlen=*minnextp;
3886                         SCAN_COMMIT(pRExC_state, &data_fake, minnextp);
3887                         SvREFCNT_dec(data_fake.last_found);
3888                         
3889                         if ( data_fake.minlen_fixed != minlenp ) 
3890                         {
3891                             data->offset_fixed= data_fake.offset_fixed;
3892                             data->minlen_fixed= data_fake.minlen_fixed;
3893                             data->lookbehind_fixed+= scan->flags;
3894                         }
3895                         if ( data_fake.minlen_float != minlenp )
3896                         {
3897                             data->minlen_float= data_fake.minlen_float;
3898                             data->offset_float_min=data_fake.offset_float_min;
3899                             data->offset_float_max=data_fake.offset_float_max;
3900                             data->lookbehind_float+= scan->flags;
3901                         }
3902                     }
3903                 }
3904
3905
3906             }
3907 #endif
3908         }
3909         else if (OP(scan) == OPEN) {
3910             if (stopparen != (I32)ARG(scan))
3911                 pars++;
3912         }
3913         else if (OP(scan) == CLOSE) {
3914             if (stopparen == (I32)ARG(scan)) {
3915                 break;
3916             }
3917             if ((I32)ARG(scan) == is_par) {
3918                 next = regnext(scan);
3919
3920                 if ( next && (OP(next) != WHILEM) && next < last)
3921                     is_par = 0;         /* Disable optimization */
3922             }
3923             if (data)
3924                 *(data->last_closep) = ARG(scan);
3925         }
3926         else if (OP(scan) == EVAL) {
3927                 if (data)
3928                     data->flags |= SF_HAS_EVAL;
3929         }
3930         else if ( PL_regkind[OP(scan)] == ENDLIKE ) {
3931             if (flags & SCF_DO_SUBSTR) {
3932                 SCAN_COMMIT(pRExC_state,data,minlenp);
3933                 flags &= ~SCF_DO_SUBSTR;
3934             }
3935             if (data && OP(scan)==ACCEPT) {
3936                 data->flags |= SCF_SEEN_ACCEPT;
3937                 if (stopmin > min)
3938                     stopmin = min;
3939             }
3940         }
3941         else if (OP(scan) == LOGICAL && scan->flags == 2) /* Embedded follows */
3942         {
3943                 if (flags & SCF_DO_SUBSTR) {
3944                     SCAN_COMMIT(pRExC_state,data,minlenp);
3945                     data->longest = &(data->longest_float);
3946                 }
3947                 is_inf = is_inf_internal = 1;
3948                 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
3949                     cl_anything(pRExC_state, data->start_class);
3950                 flags &= ~SCF_DO_STCLASS;
3951         }
3952         else if (OP(scan) == GPOS) {
3953             if (!(RExC_rx->extflags & RXf_GPOS_FLOAT) &&
3954                 !(delta || is_inf || (data && data->pos_delta))) 
3955             {
3956                 if (!(RExC_rx->extflags & RXf_ANCH) && (flags & SCF_DO_SUBSTR))
3957                     RExC_rx->extflags |= RXf_ANCH_GPOS;
3958                 if (RExC_rx->gofs < (U32)min)
3959                     RExC_rx->gofs = min;
3960             } else {
3961                 RExC_rx->extflags |= RXf_GPOS_FLOAT;
3962                 RExC_rx->gofs = 0;
3963             }       
3964         }
3965 #ifdef TRIE_STUDY_OPT
3966 #ifdef FULL_TRIE_STUDY
3967         else if (PL_regkind[OP(scan)] == TRIE) {
3968             /* NOTE - There is similar code to this block above for handling
3969                BRANCH nodes on the initial study.  If you change stuff here
3970                check there too. */
3971             regnode *trie_node= scan;
3972             regnode *tail= regnext(scan);
3973             reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
3974             I32 max1 = 0, min1 = I32_MAX;
3975             struct regnode_charclass_class accum;
3976
3977             if (flags & SCF_DO_SUBSTR) /* XXXX Add !SUSPEND? */
3978                 SCAN_COMMIT(pRExC_state, data,minlenp); /* Cannot merge strings after this. */
3979             if (flags & SCF_DO_STCLASS)
3980                 cl_init_zero(pRExC_state, &accum);
3981                 
3982             if (!trie->jump) {
3983                 min1= trie->minlen;
3984                 max1= trie->maxlen;
3985             } else {
3986                 const regnode *nextbranch= NULL;
3987                 U32 word;
3988                 
3989                 for ( word=1 ; word <= trie->wordcount ; word++) 
3990                 {
3991                     I32 deltanext=0, minnext=0, f = 0, fake;
3992                     struct regnode_charclass_class this_class;
3993                     
3994                     data_fake.flags = 0;
3995                     if (data) {
3996                         data_fake.whilem_c = data->whilem_c;
3997                         data_fake.last_closep = data->last_closep;
3998                     }
3999                     else
4000                         data_fake.last_closep = &fake;
4001                     data_fake.pos_delta = delta;
4002                     if (flags & SCF_DO_STCLASS) {
4003                         cl_init(pRExC_state, &this_class);
4004                         data_fake.start_class = &this_class;
4005                         f = SCF_DO_STCLASS_AND;
4006                     }
4007                     if (flags & SCF_WHILEM_VISITED_POS)
4008                         f |= SCF_WHILEM_VISITED_POS;
4009     
4010                     if (trie->jump[word]) {
4011                         if (!nextbranch)
4012                             nextbranch = trie_node + trie->jump[0];
4013                         scan= trie_node + trie->jump[word];
4014                         /* We go from the jump point to the branch that follows
4015                            it. Note this means we need the vestigal unused branches
4016                            even though they arent otherwise used.
4017                          */
4018                         minnext = study_chunk(pRExC_state, &scan, minlenp, 
4019                             &deltanext, (regnode *)nextbranch, &data_fake, 
4020                             stopparen, recursed, NULL, f,depth+1);
4021                     }
4022                     if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
4023                         nextbranch= regnext((regnode*)nextbranch);
4024                     
4025                     if (min1 > (I32)(minnext + trie->minlen))
4026                         min1 = minnext + trie->minlen;
4027                     if (max1 < (I32)(minnext + deltanext + trie->maxlen))
4028                         max1 = minnext + deltanext + trie->maxlen;
4029                     if (deltanext == I32_MAX)
4030                         is_inf = is_inf_internal = 1;
4031                     
4032                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
4033                         pars++;
4034                     if (data_fake.flags & SCF_SEEN_ACCEPT) {
4035                         if ( stopmin > min + min1) 
4036                             stopmin = min + min1;
4037                         flags &= ~SCF_DO_SUBSTR;
4038                         if (data)
4039                             data->flags |= SCF_SEEN_ACCEPT;
4040                     }
4041                     if (data) {
4042                         if (data_fake.flags & SF_HAS_EVAL)
4043                             data->flags |= SF_HAS_EVAL;
4044                         data->whilem_c = data_fake.whilem_c;
4045                     }
4046                     if (flags & SCF_DO_STCLASS)
4047                         cl_or(pRExC_state, &accum, &this_class);
4048                 }
4049             }
4050             if (flags & SCF_DO_SUBSTR) {
4051                 data->pos_min += min1;
4052                 data->pos_delta += max1 - min1;
4053                 if (max1 != min1 || is_inf)
4054                     data->longest = &(data->longest_float);
4055             }
4056             min += min1;
4057             delta += max1 - min1;
4058             if (flags & SCF_DO_STCLASS_OR) {
4059                 cl_or(pRExC_state, data->start_class, &accum);
4060                 if (min1) {
4061                     cl_and(data->start_class, and_withp);
4062                     flags &= ~SCF_DO_STCLASS;
4063                 }
4064             }
4065             else if (flags & SCF_DO_STCLASS_AND) {
4066                 if (min1) {
4067                     cl_and(data->start_class, &accum);
4068                     flags &= ~SCF_DO_STCLASS;
4069                 }
4070                 else {
4071                     /* Switch to OR mode: cache the old value of
4072                      * data->start_class */
4073                     INIT_AND_WITHP;
4074                     StructCopy(data->start_class, and_withp,
4075                                struct regnode_charclass_class);
4076                     flags &= ~SCF_DO_STCLASS_AND;
4077                     StructCopy(&accum, data->start_class,
4078                                struct regnode_charclass_class);
4079                     flags |= SCF_DO_STCLASS_OR;
4080                     data->start_class->flags |= ANYOF_EOS;
4081                 }
4082             }
4083             scan= tail;
4084             continue;
4085         }
4086 #else
4087         else if (PL_regkind[OP(scan)] == TRIE) {
4088             reg_trie_data *trie = (reg_trie_data*)RExC_rxi->data->data[ ARG(scan) ];
4089             U8*bang=NULL;
4090             
4091             min += trie->minlen;
4092             delta += (trie->maxlen - trie->minlen);
4093             flags &= ~SCF_DO_STCLASS; /* xxx */
4094             if (flags & SCF_DO_SUBSTR) {
4095                 SCAN_COMMIT(pRExC_state,data,minlenp);  /* Cannot expect anything... */
4096                 data->pos_min += trie->minlen;
4097                 data->pos_delta += (trie->maxlen - trie->minlen);
4098                 if (trie->maxlen != trie->minlen)
4099                     data->longest = &(data->longest_float);
4100             }
4101             if (trie->jump) /* no more substrings -- for now /grr*/
4102                 flags &= ~SCF_DO_SUBSTR; 
4103         }
4104 #endif /* old or new */
4105 #endif /* TRIE_STUDY_OPT */     
4106
4107         /* Else: zero-length, ignore. */
4108         scan = regnext(scan);
4109     }
4110     if (frame) {
4111         last = frame->last;
4112         scan = frame->next;
4113         stopparen = frame->stop;
4114         frame = frame->prev;
4115         goto fake_study_recurse;
4116     }
4117
4118   finish:
4119     assert(!frame);
4120     DEBUG_STUDYDATA("pre-fin:",data,depth);
4121
4122     *scanp = scan;
4123     *deltap = is_inf_internal ? I32_MAX : delta;
4124     if (flags & SCF_DO_SUBSTR && is_inf)
4125         data->pos_delta = I32_MAX - data->pos_min;
4126     if (is_par > (I32)U8_MAX)
4127         is_par = 0;
4128     if (is_par && pars==1 && data) {
4129         data->flags |= SF_IN_PAR;
4130         data->flags &= ~SF_HAS_PAR;
4131     }
4132     else if (pars && data) {
4133         data->flags |= SF_HAS_PAR;
4134         data->flags &= ~SF_IN_PAR;
4135     }
4136     if (flags & SCF_DO_STCLASS_OR)
4137         cl_and(data->start_class, and_withp);
4138     if (flags & SCF_TRIE_RESTUDY)
4139         data->flags |=  SCF_TRIE_RESTUDY;
4140     
4141     DEBUG_STUDYDATA("post-fin:",data,depth);
4142     
4143     return min < stopmin ? min : stopmin;
4144 }
4145
4146 STATIC U32
4147 S_add_data(RExC_state_t *pRExC_state, U32 n, const char *s)
4148 {
4149     U32 count = RExC_rxi->data ? RExC_rxi->data->count : 0;
4150
4151     PERL_ARGS_ASSERT_ADD_DATA;
4152
4153     Renewc(RExC_rxi->data,
4154            sizeof(*RExC_rxi->data) + sizeof(void*) * (count + n - 1),
4155            char, struct reg_data);
4156     if(count)
4157         Renew(RExC_rxi->data->what, count + n, U8);
4158     else
4159         Newx(RExC_rxi->data->what, n, U8);
4160     RExC_rxi->data->count = count + n;
4161     Copy(s, RExC_rxi->data->what + count, n, U8);
4162     return count;
4163 }
4164
4165 /*XXX: todo make this not included in a non debugging perl */
4166 #ifndef PERL_IN_XSUB_RE
4167 void
4168 Perl_reginitcolors(pTHX)
4169 {
4170     dVAR;
4171     const char * const s = PerlEnv_getenv("PERL_RE_COLORS");
4172     if (s) {
4173         char *t = savepv(s);
4174         int i = 0;
4175         PL_colors[0] = t;
4176         while (++i < 6) {
4177             t = strchr(t, '\t');
4178             if (t) {
4179                 *t = '\0';
4180                 PL_colors[i] = ++t;
4181             }
4182             else
4183                 PL_colors[i] = t = (char *)"";
4184         }
4185     } else {
4186         int i = 0;
4187         while (i < 6)
4188             PL_colors[i++] = (char *)"";
4189     }
4190     PL_colorset = 1;
4191 }
4192 #endif
4193
4194
4195 #ifdef TRIE_STUDY_OPT
4196 #define CHECK_RESTUDY_GOTO                                  \
4197         if (                                                \
4198               (data.flags & SCF_TRIE_RESTUDY)               \
4199               && ! restudied++                              \
4200         )     goto reStudy
4201 #else
4202 #define CHECK_RESTUDY_GOTO
4203 #endif        
4204
4205 /*
4206  - pregcomp - compile a regular expression into internal code
4207  *
4208  * We can't allocate space until we know how big the compiled form will be,
4209  * but we can't compile it (and thus know how big it is) until we've got a
4210  * place to put the code.  So we cheat:  we compile it twice, once with code
4211  * generation turned off and size counting turned on, and once "for real".
4212  * This also means that we don't allocate space until we are sure that the
4213  * thing really will compile successfully, and we never have to move the
4214  * code and thus invalidate pointers into it.  (Note that it has to be in
4215  * one piece because free() must be able to free it all.) [NB: not true in perl]
4216  *
4217  * Beware that the optimization-preparation code in here knows about some
4218  * of the structure of the compiled regexp.  [I'll say.]
4219  */
4220
4221
4222
4223 #ifndef PERL_IN_XSUB_RE
4224 #define RE_ENGINE_PTR &PL_core_reg_engine
4225 #else
4226 extern const struct regexp_engine my_reg_engine;
4227 #define RE_ENGINE_PTR &my_reg_engine
4228 #endif
4229
4230 #ifndef PERL_IN_XSUB_RE 
4231 REGEXP *
4232 Perl_pregcomp(pTHX_ SV * const pattern, const U32 flags)
4233 {
4234     dVAR;
4235     HV * const table = GvHV(PL_hintgv);
4236
4237     PERL_ARGS_ASSERT_PREGCOMP;
4238
4239     /* Dispatch a request to compile a regexp to correct 
4240        regexp engine. */
4241     if (table) {
4242         SV **ptr= hv_fetchs(table, "regcomp", FALSE);
4243         GET_RE_DEBUG_FLAGS_DECL;
4244         if (ptr && SvIOK(*ptr) && SvIV(*ptr)) {
4245             const regexp_engine *eng=INT2PTR(regexp_engine*,SvIV(*ptr));
4246             DEBUG_COMPILE_r({
4247                 PerlIO_printf(Perl_debug_log, "Using engine %"UVxf"\n",
4248                     SvIV(*ptr));
4249             });            
4250             return CALLREGCOMP_ENG(eng, pattern, flags);
4251         } 
4252     }
4253     return Perl_re_compile(aTHX_ pattern, flags);
4254 }
4255 #endif
4256
4257 REGEXP *
4258 Perl_re_compile(pTHX_ SV * const pattern, U32 pm_flags)
4259 {
4260     dVAR;
4261     REGEXP *rx;
4262     struct regexp *r;
4263     register regexp_internal *ri;
4264     STRLEN plen;
4265     char  *exp = SvPV(pattern, plen);
4266     char* xend = exp + plen;
4267     regnode *scan;
4268     I32 flags;
4269     I32 minlen = 0;
4270     I32 sawplus = 0;
4271     I32 sawopen = 0;
4272     scan_data_t data;
4273     RExC_state_t RExC_state;
4274     RExC_state_t * const pRExC_state = &RExC_state;
4275 #ifdef TRIE_STUDY_OPT    
4276     int restudied= 0;
4277     RExC_state_t copyRExC_state;
4278 #endif    
4279     GET_RE_DEBUG_FLAGS_DECL;
4280
4281     PERL_ARGS_ASSERT_RE_COMPILE;
4282
4283     DEBUG_r(if (!PL_colorset) reginitcolors());
4284
4285     RExC_utf8 = RExC_orig_utf8 = SvUTF8(pattern);
4286
4287     DEBUG_COMPILE_r({
4288         SV *dsv= sv_newmortal();
4289         RE_PV_QUOTED_DECL(s, RExC_utf8,
4290             dsv, exp, plen, 60);
4291         PerlIO_printf(Perl_debug_log, "%sCompiling REx%s %s\n",
4292                        PL_colors[4],PL_colors[5],s);
4293     });
4294
4295 redo_first_pass:
4296     RExC_precomp = exp;
4297     RExC_flags = pm_flags;
4298     RExC_sawback = 0;
4299
4300     RExC_seen = 0;
4301     RExC_seen_zerolen = *exp == '^' ? -1 : 0;
4302     RExC_seen_evals = 0;
4303     RExC_extralen = 0;
4304
4305     /* First pass: determine size, legality. */
4306     RExC_parse = exp;
4307     RExC_start = exp;
4308     RExC_end = xend;
4309     RExC_naughty = 0;
4310     RExC_npar = 1;
4311     RExC_nestroot = 0;
4312     RExC_size = 0L;
4313     RExC_emit = &PL_regdummy;
4314     RExC_whilem_seen = 0;
4315     RExC_open_parens = NULL;
4316     RExC_close_parens = NULL;
4317     RExC_opend = NULL;
4318     RExC_paren_names = NULL;
4319 #ifdef DEBUGGING
4320     RExC_paren_name_list = NULL;
4321 #endif
4322     RExC_recurse = NULL;
4323     RExC_recurse_count = 0;
4324
4325 #if 0 /* REGC() is (currently) a NOP at the first pass.
4326        * Clever compilers notice this and complain. --jhi */
4327     REGC((U8)REG_MAGIC, (char*)RExC_emit);
4328 #endif
4329     DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log, "Starting first pass (sizing)\n"));
4330     if (reg(pRExC_state, 0, &flags,1) == NULL) {
4331         RExC_precomp = NULL;
4332         return(NULL);
4333     }
4334     if (RExC_utf8 && !RExC_orig_utf8) {
4335         /* It's possible to write a regexp in ascii that represents Unicode
4336         codepoints outside of the byte range, such as via \x{100}. If we
4337         detect such a sequence we have to convert the entire pattern to utf8
4338         and then recompile, as our sizing calculation will have been based
4339         on 1 byte == 1 character, but we will need to use utf8 to encode
4340         at least some part of the pattern, and therefore must convert the whole
4341         thing.
4342         XXX: somehow figure out how to make this less expensive...
4343         -- dmq */
4344         STRLEN len = plen;
4345         DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log,
4346             "UTF8 mismatch! Converting to utf8 for resizing and compile\n"));
4347         exp = (char*)Perl_bytes_to_utf8(aTHX_ (U8*)exp, &len);
4348         xend = exp + len;
4349         RExC_orig_utf8 = RExC_utf8;
4350         SAVEFREEPV(exp);
4351         goto redo_first_pass;
4352     }
4353     DEBUG_PARSE_r({
4354         PerlIO_printf(Perl_debug_log, 
4355             "Required size %"IVdf" nodes\n"
4356             "Starting second pass (creation)\n", 
4357             (IV)RExC_size);
4358         RExC_lastnum=0; 
4359         RExC_lastparse=NULL; 
4360     });
4361     /* Small enough for pointer-storage convention?
4362        If extralen==0, this means that we will not need long jumps. */
4363     if (RExC_size >= 0x10000L && RExC_extralen)
4364         RExC_size += RExC_extralen;
4365     else
4366         RExC_extralen = 0;
4367     if (RExC_whilem_seen > 15)
4368         RExC_whilem_seen = 15;
4369
4370     /* Allocate space and zero-initialize. Note, the two step process 
4371        of zeroing when in debug mode, thus anything assigned has to 
4372        happen after that */
4373     rx = (REGEXP*) newSV_type(SVt_REGEXP);
4374     r = (struct regexp*)SvANY(rx);
4375     Newxc(ri, sizeof(regexp_internal) + (unsigned)RExC_size * sizeof(regnode),
4376          char, regexp_internal);
4377     if ( r == NULL || ri == NULL )
4378         FAIL("Regexp out of space");
4379 #ifdef DEBUGGING
4380     /* avoid reading uninitialized memory in DEBUGGING code in study_chunk() */
4381     Zero(ri, sizeof(regexp_internal) + (unsigned)RExC_size * sizeof(regnode), char);
4382 #else 
4383     /* bulk initialize base fields with 0. */
4384     Zero(ri, sizeof(regexp_internal), char);        
4385 #endif
4386
4387     /* non-zero initialization begins here */
4388     RXi_SET( r, ri );
4389     r->engine= RE_ENGINE_PTR;
4390     r->extflags = pm_flags;
4391     {
4392         bool has_p     = ((r->extflags & RXf_PMf_KEEPCOPY) == RXf_PMf_KEEPCOPY);
4393         bool has_minus = ((r->extflags & RXf_PMf_STD_PMMOD) != RXf_PMf_STD_PMMOD);
4394         bool has_runon = ((RExC_seen & REG_SEEN_RUN_ON_COMMENT)==REG_SEEN_RUN_ON_COMMENT);
4395         U16 reganch = (U16)((r->extflags & RXf_PMf_STD_PMMOD)
4396                             >> RXf_PMf_STD_PMMOD_SHIFT);
4397         const char *fptr = STD_PAT_MODS;        /*"msix"*/
4398         char *p;
4399         const STRLEN wraplen = plen + has_minus + has_p + has_runon
4400             + (sizeof(STD_PAT_MODS) - 1)
4401             + (sizeof("(?:)") - 1);
4402
4403         p = sv_grow(MUTABLE_SV(rx), wraplen + 1);
4404         SvCUR_set(rx, wraplen);
4405         SvPOK_on(rx);
4406         SvFLAGS(rx) |= SvUTF8(pattern);
4407         *p++='('; *p++='?';
4408         if (has_p)
4409             *p++ = KEEPCOPY_PAT_MOD; /*'p'*/
4410         {
4411             char *r = p + (sizeof(STD_PAT_MODS) - 1) + has_minus - 1;
4412             char *colon = r + 1;
4413             char ch;
4414
4415             while((ch = *fptr++)) {
4416                 if(reganch & 1)
4417                     *p++ = ch;
4418                 else
4419                     *r-- = ch;
4420                 reganch >>= 1;
4421             }
4422             if(has_minus) {
4423                 *r = '-';
4424                 p = colon;
4425             }
4426         }
4427
4428         *p++ = ':';
4429         Copy(RExC_precomp, p, plen, char);
4430         assert ((RX_WRAPPED(rx) - p) < 16);
4431         r->pre_prefix = p - RX_WRAPPED(rx);
4432         p += plen;
4433         if (has_runon)
4434             *p++ = '\n';
4435         *p++ = ')';
4436         *p = 0;
4437     }
4438
4439     r->intflags = 0;
4440     r->nparens = RExC_npar - 1; /* set early to validate backrefs */
4441     
4442     if (RExC_seen & REG_SEEN_RECURSE) {
4443         Newxz(RExC_open_parens, RExC_npar,regnode *);
4444         SAVEFREEPV(RExC_open_parens);
4445         Newxz(RExC_close_parens,RExC_npar,regnode *);
4446         SAVEFREEPV(RExC_close_parens);
4447     }
4448
4449     /* Useful during FAIL. */
4450 #ifdef RE_TRACK_PATTERN_OFFSETS
4451     Newxz(ri->u.offsets, 2*RExC_size+1, U32); /* MJD 20001228 */
4452     DEBUG_OFFSETS_r(PerlIO_printf(Perl_debug_log,
4453                           "%s %"UVuf" bytes for offset annotations.\n",
4454                           ri->u.offsets ? "Got" : "Couldn't get",
4455                           (UV)((2*RExC_size+1) * sizeof(U32))));
4456 #endif
4457     SetProgLen(ri,RExC_size);
4458     RExC_rx_sv = rx;
4459     RExC_rx = r;
4460     RExC_rxi = ri;
4461     REH_CALL_COMP_BEGIN_HOOK(pRExC_state->rx);
4462
4463     /* Second pass: emit code. */
4464     RExC_flags = pm_flags;      /* don't let top level (?i) bleed */
4465     RExC_parse = exp;
4466     RExC_end = xend;
4467     RExC_naughty = 0;
4468     RExC_npar = 1;
4469     RExC_emit_start = ri->program;
4470     RExC_emit = ri->program;
4471     RExC_emit_bound = ri->program + RExC_size + 1;
4472
4473     /* Store the count of eval-groups for security checks: */
4474     RExC_rx->seen_evals = RExC_seen_evals;
4475     REGC((U8)REG_MAGIC, (char*) RExC_emit++);
4476     if (reg(pRExC_state, 0, &flags,1) == NULL) {
4477         ReREFCNT_dec(rx);   
4478         return(NULL);
4479     }
4480     /* XXXX To minimize changes to RE engine we always allocate
4481        3-units-long substrs field. */
4482     Newx(r->substrs, 1, struct reg_substr_data);
4483     if (RExC_recurse_count) {
4484         Newxz(RExC_recurse,RExC_recurse_count,regnode *);
4485         SAVEFREEPV(RExC_recurse);
4486     }
4487
4488 reStudy:
4489     r->minlen = minlen = sawplus = sawopen = 0;
4490     Zero(r->substrs, 1, struct reg_substr_data);
4491
4492 #ifdef TRIE_STUDY_OPT
4493     if (!restudied) {
4494         StructCopy(&zero_scan_data, &data, scan_data_t);
4495         copyRExC_state = RExC_state;
4496     } else {
4497         U32 seen=RExC_seen;
4498         DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log,"Restudying\n"));
4499         
4500         RExC_state = copyRExC_state;
4501         if (seen & REG_TOP_LEVEL_BRANCHES) 
4502             RExC_seen |= REG_TOP_LEVEL_BRANCHES;
4503         else
4504             RExC_seen &= ~REG_TOP_LEVEL_BRANCHES;
4505         if (data.last_found) {
4506             SvREFCNT_dec(data.longest_fixed);
4507             SvREFCNT_dec(data.longest_float);
4508             SvREFCNT_dec(data.last_found);
4509         }
4510         StructCopy(&zero_scan_data, &data, scan_data_t);
4511     }
4512 #else
4513     StructCopy(&zero_scan_data, &data, scan_data_t);
4514 #endif    
4515
4516     /* Dig out information for optimizations. */
4517     r->extflags = RExC_flags; /* was pm_op */
4518     /*dmq: removed as part of de-PMOP: pm->op_pmflags = RExC_flags; */
4519  
4520     if (UTF)
4521         SvUTF8_on(rx);  /* Unicode in it? */
4522     ri->regstclass = NULL;
4523     if (RExC_naughty >= 10)     /* Probably an expensive pattern. */
4524         r->intflags |= PREGf_NAUGHTY;
4525     scan = ri->program + 1;             /* First BRANCH. */
4526
4527     /* testing for BRANCH here tells us whether there is "must appear"
4528        data in the pattern. If there is then we can use it for optimisations */
4529     if (!(RExC_seen & REG_TOP_LEVEL_BRANCHES)) { /*  Only one top-level choice. */
4530         I32 fake;
4531         STRLEN longest_float_length, longest_fixed_length;
4532         struct regnode_charclass_class ch_class; /* pointed to by data */
4533         int stclass_flag;
4534         I32 last_close = 0; /* pointed to by data */
4535         regnode *first= scan;
4536         regnode *first_next= regnext(first);
4537         
4538         /*
4539          * Skip introductions and multiplicators >= 1
4540          * so that we can extract the 'meat' of the pattern that must 
4541          * match in the large if() sequence following.
4542          * NOTE that EXACT is NOT covered here, as it is normally
4543          * picked up by the optimiser separately. 
4544          *
4545          * This is unfortunate as the optimiser isnt handling lookahead
4546          * properly currently.
4547          *
4548          */
4549         while ((OP(first) == OPEN && (sawopen = 1)) ||
4550                /* An OR of *one* alternative - should not happen now. */
4551             (OP(first) == BRANCH && OP(first_next) != BRANCH) ||
4552             /* for now we can't handle lookbehind IFMATCH*/
4553             (OP(first) == IFMATCH && !first->flags) || 
4554             (OP(first) == PLUS) ||
4555             (OP(first) == MINMOD) ||
4556                /* An {n,m} with n>0 */
4557             (PL_regkind[OP(first)] == CURLY && ARG1(first) > 0) ||
4558             (OP(first) == NOTHING && PL_regkind[OP(first_next)] != END ))
4559         {
4560                 /* 
4561                  * the only op that could be a regnode is PLUS, all the rest
4562                  * will be regnode_1 or regnode_2.
4563                  *
4564                  */
4565                 if (OP(first) == PLUS)
4566                     sawplus = 1;
4567                 else
4568                     first += regarglen[OP(first)];
4569                 
4570                 first = NEXTOPER(first);
4571                 first_next= regnext(first);
4572         }
4573
4574         /* Starting-point info. */
4575       again:
4576         DEBUG_PEEP("first:",first,0);
4577         /* Ignore EXACT as we deal with it later. */
4578         if (PL_regkind[OP(first)] == EXACT) {
4579             if (OP(first) == EXACT)
4580                 NOOP;   /* Empty, get anchored substr later. */
4581             else if ((OP(first) == EXACTF || OP(first) == EXACTFL))
4582                 ri->regstclass = first;
4583         }
4584 #ifdef TRIE_STCLASS     
4585         else if (PL_regkind[OP(first)] == TRIE &&
4586                 ((reg_trie_data *)ri->data->data[ ARG(first) ])->minlen>0) 
4587         {
4588             regnode *trie_op;
4589             /* this can happen only on restudy */
4590             if ( OP(first) == TRIE ) {
4591                 struct regnode_1 *trieop = (struct regnode_1 *)
4592                     PerlMemShared_calloc(1, sizeof(struct regnode_1));
4593                 StructCopy(first,trieop,struct regnode_1);
4594                 trie_op=(regnode *)trieop;
4595             } else {
4596                 struct regnode_charclass *trieop = (struct regnode_charclass *)
4597                     PerlMemShared_calloc(1, sizeof(struct regnode_charclass));
4598                 StructCopy(first,trieop,struct regnode_charclass);
4599                 trie_op=(regnode *)trieop;
4600             }
4601             OP(trie_op)+=2;
4602             make_trie_failtable(pRExC_state, (regnode *)first, trie_op, 0);
4603             ri->regstclass = trie_op;
4604         }
4605 #endif  
4606         else if (REGNODE_SIMPLE(OP(first)))
4607             ri->regstclass = first;
4608         else if (PL_regkind[OP(first)] == BOUND ||
4609                  PL_regkind[OP(first)] == NBOUND)
4610             ri->regstclass = first;
4611         else if (PL_regkind[OP(first)] == BOL) {
4612             r->extflags |= (OP(first) == MBOL
4613                            ? RXf_ANCH_MBOL
4614                            : (OP(first) == SBOL
4615                               ? RXf_ANCH_SBOL
4616                               : RXf_ANCH_BOL));
4617             first = NEXTOPER(first);
4618             goto again;
4619         }
4620         else if (OP(first) == GPOS) {
4621             r->extflags |= RXf_ANCH_GPOS;
4622             first = NEXTOPER(first);
4623             goto again;
4624         }
4625         else if ((!sawopen || !RExC_sawback) &&
4626             (OP(first) == STAR &&
4627             PL_regkind[OP(NEXTOPER(first))] == REG_ANY) &&
4628             !(r->extflags & RXf_ANCH) && !(RExC_seen & REG_SEEN_EVAL))
4629         {
4630             /* turn .* into ^.* with an implied $*=1 */
4631             const int type =
4632                 (OP(NEXTOPER(first)) == REG_ANY)
4633                     ? RXf_ANCH_MBOL
4634                     : RXf_ANCH_SBOL;
4635             r->extflags |= type;
4636             r->intflags |= PREGf_IMPLICIT;
4637             first = NEXTOPER(first);
4638             goto again;
4639         }
4640         if (sawplus && (!sawopen || !RExC_sawback)
4641             && !(RExC_seen & REG_SEEN_EVAL)) /* May examine pos and $& */
4642             /* x+ must match at the 1st pos of run of x's */
4643             r->intflags |= PREGf_SKIP;
4644
4645         /* Scan is after the zeroth branch, first is atomic matcher. */
4646 #ifdef TRIE_STUDY_OPT
4647         DEBUG_PARSE_r(
4648             if (!restudied)
4649                 PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
4650                               (IV)(first - scan + 1))
4651         );
4652 #else
4653         DEBUG_PARSE_r(
4654             PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
4655                 (IV)(first - scan + 1))
4656         );
4657 #endif
4658
4659
4660         /*
4661         * If there's something expensive in the r.e., find the
4662         * longest literal string that must appear and make it the
4663         * regmust.  Resolve ties in favor of later strings, since
4664         * the regstart check works with the beginning of the r.e.
4665         * and avoiding duplication strengthens checking.  Not a
4666         * strong reason, but sufficient in the absence of others.
4667         * [Now we resolve ties in favor of the earlier string if
4668         * it happens that c_offset_min has been invalidated, since the
4669         * earlier string may buy us something the later one won't.]
4670         */
4671         
4672         data.longest_fixed = newSVpvs("");
4673         data.longest_float = newSVpvs("");
4674         data.last_found = newSVpvs("");
4675         data.longest = &(data.longest_fixed);
4676         first = scan;
4677         if (!ri->regstclass) {
4678             cl_init(pRExC_state, &ch_class);
4679             data.start_class = &ch_class;
4680             stclass_flag = SCF_DO_STCLASS_AND;
4681         } else                          /* XXXX Check for BOUND? */
4682             stclass_flag = 0;
4683         data.last_closep = &last_close;
4684         
4685         minlen = study_chunk(pRExC_state, &first, &minlen, &fake, scan + RExC_size, /* Up to end */
4686             &data, -1, NULL, NULL,
4687             SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag,0);
4688
4689         
4690         CHECK_RESTUDY_GOTO;
4691
4692
4693         if ( RExC_npar == 1 && data.longest == &(data.longest_fixed)
4694              && data.last_start_min == 0 && data.last_end > 0
4695              && !RExC_seen_zerolen
4696              && !(RExC_seen & REG_SEEN_VERBARG)
4697              && (!(RExC_seen & REG_SEEN_GPOS) || (r->extflags & RXf_ANCH_GPOS)))
4698             r->extflags |= RXf_CHECK_ALL;
4699         scan_commit(pRExC_state, &data,&minlen,0);
4700         SvREFCNT_dec(data.last_found);
4701
4702         /* Note that code very similar to this but for anchored string 
4703            follows immediately below, changes may need to be made to both. 
4704            Be careful. 
4705          */
4706         longest_float_length = CHR_SVLEN(data.longest_float);
4707         if (longest_float_length
4708             || (data.flags & SF_FL_BEFORE_EOL
4709                 && (!(data.flags & SF_FL_BEFORE_MEOL)
4710                     || (RExC_flags & RXf_PMf_MULTILINE)))) 
4711         {
4712             I32 t,ml;
4713
4714             if (SvCUR(data.longest_fixed)  /* ok to leave SvCUR */
4715                 && data.offset_fixed == data.offset_float_min
4716                 && SvCUR(data.longest_fixed) == SvCUR(data.longest_float))
4717                     goto remove_float;          /* As in (a)+. */
4718
4719             /* copy the information about the longest float from the reg_scan_data
4720                over to the program. */
4721             if (SvUTF8(data.longest_float)) {
4722                 r->float_utf8 = data.longest_float;
4723                 r->float_substr = NULL;
4724             } else {
4725                 r->float_substr = data.longest_float;
4726                 r->float_utf8 = NULL;
4727             }
4728             /* float_end_shift is how many chars that must be matched that 
4729                follow this item. We calculate it ahead of time as once the
4730                lookbehind offset is added in we lose the ability to correctly
4731                calculate it.*/
4732             ml = data.minlen_float ? *(data.minlen_float) 
4733                                    : (I32)longest_float_length;
4734             r->float_end_shift = ml - data.offset_float_min
4735                 - longest_float_length + (SvTAIL(data.longest_float) != 0)
4736                 + data.lookbehind_float;
4737             r->float_min_offset = data.offset_float_min - data.lookbehind_float;
4738             r->float_max_offset = data.offset_float_max;
4739             if (data.offset_float_max < I32_MAX) /* Don't offset infinity */
4740                 r->float_max_offset -= data.lookbehind_float;
4741             
4742             t = (data.flags & SF_FL_BEFORE_EOL /* Can't have SEOL and MULTI */
4743                        && (!(data.flags & SF_FL_BEFORE_MEOL)
4744                            || (RExC_flags & RXf_PMf_MULTILINE)));
4745             fbm_compile(data.longest_float, t ? FBMcf_TAIL : 0);
4746         }
4747         else {
4748           remove_float:
4749             r->float_substr = r->float_utf8 = NULL;
4750             SvREFCNT_dec(data.longest_float);
4751             longest_float_length = 0;
4752         }
4753
4754         /* Note that code very similar to this but for floating string 
4755            is immediately above, changes may need to be made to both. 
4756            Be careful. 
4757          */
4758         longest_fixed_length = CHR_SVLEN(data.longest_fixed);
4759         if (longest_fixed_length
4760             || (data.flags & SF_FIX_BEFORE_EOL /* Cannot have SEOL and MULTI */
4761                 && (!(data.flags & SF_FIX_BEFORE_MEOL)
4762                     || (RExC_flags & RXf_PMf_MULTILINE)))) 
4763         {
4764             I32 t,ml;
4765
4766             /* copy the information about the longest fixed 
4767                from the reg_scan_data over to the program. */
4768             if (SvUTF8(data.longest_fixed)) {
4769                 r->anchored_utf8 = data.longest_fixed;
4770                 r->anchored_substr = NULL;
4771             } else {
4772                 r->anchored_substr = data.longest_fixed;
4773                 r->anchored_utf8 = NULL;
4774             }
4775             /* fixed_end_shift is how many chars that must be matched that 
4776                follow this item. We calculate it ahead of time as once the
4777                lookbehind offset is added in we lose the ability to correctly
4778                calculate it.*/
4779             ml = data.minlen_fixed ? *(data.minlen_fixed) 
4780                                    : (I32)longest_fixed_length;
4781             r->anchored_end_shift = ml - data.offset_fixed
4782                 - longest_fixed_length + (SvTAIL(data.longest_fixed) != 0)
4783                 + data.lookbehind_fixed;
4784             r->anchored_offset = data.offset_fixed - data.lookbehind_fixed;
4785
4786             t = (data.flags & SF_FIX_BEFORE_EOL /* Can't have SEOL and MULTI */
4787                  && (!(data.flags & SF_FIX_BEFORE_MEOL)
4788                      || (RExC_flags & RXf_PMf_MULTILINE)));
4789             fbm_compile(data.longest_fixed, t ? FBMcf_TAIL : 0);
4790         }
4791         else {
4792             r->anchored_substr = r->anchored_utf8 = NULL;
4793             SvREFCNT_dec(data.longest_fixed);
4794             longest_fixed_length = 0;
4795         }
4796         if (ri->regstclass
4797             && (OP(ri->regstclass) == REG_ANY || OP(ri->regstclass) == SANY))
4798             ri->regstclass = NULL;
4799         if ((!(r->anchored_substr || r->anchored_utf8) || r->anchored_offset)
4800             && stclass_flag
4801             && !(data.start_class->flags & ANYOF_EOS)
4802             && !cl_is_anything(data.start_class))
4803         {
4804             const U32 n = add_data(pRExC_state, 1, "f");
4805
4806             Newx(RExC_rxi->data->data[n], 1,
4807                 struct regnode_charclass_class);
4808             StructCopy(data.start_class,
4809                        (struct regnode_charclass_class*)RExC_rxi->data->data[n],
4810                        struct regnode_charclass_class);
4811             ri->regstclass = (regnode*)RExC_rxi->data->data[n];
4812             r->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
4813             DEBUG_COMPILE_r({ SV *sv = sv_newmortal();
4814                       regprop(r, sv, (regnode*)data.start_class);
4815                       PerlIO_printf(Perl_debug_log,
4816                                     "synthetic stclass \"%s\".\n",
4817                                     SvPVX_const(sv));});
4818         }
4819
4820         /* A temporary algorithm prefers floated substr to fixed one to dig more info. */
4821         if (longest_fixed_length > longest_float_length) {
4822             r->check_end_shift = r->anchored_end_shift;
4823             r->check_substr = r->anchored_substr;
4824             r->check_utf8 = r->anchored_utf8;
4825             r->check_offset_min = r->check_offset_max = r->anchored_offset;
4826             if (r->extflags & RXf_ANCH_SINGLE)
4827                 r->extflags |= RXf_NOSCAN;
4828         }
4829         else {
4830             r->check_end_shift = r->float_end_shift;
4831             r->check_substr = r->float_substr;
4832             r->check_utf8 = r->float_utf8;
4833             r->check_offset_min = r->float_min_offset;
4834             r->check_offset_max = r->float_max_offset;
4835         }
4836         /* XXXX Currently intuiting is not compatible with ANCH_GPOS.
4837            This should be changed ASAP!  */
4838         if ((r->check_substr || r->check_utf8) && !(r->extflags & RXf_ANCH_GPOS)) {
4839             r->extflags |= RXf_USE_INTUIT;
4840             if (SvTAIL(r->check_substr ? r->check_substr : r->check_utf8))
4841                 r->extflags |= RXf_INTUIT_TAIL;
4842         }
4843         /* XXX Unneeded? dmq (shouldn't as this is handled elsewhere)
4844         if ( (STRLEN)minlen < longest_float_length )
4845             minlen= longest_float_length;
4846         if ( (STRLEN)minlen < longest_fixed_length )
4847             minlen= longest_fixed_length;     
4848         */
4849     }
4850     else {
4851         /* Several toplevels. Best we can is to set minlen. */
4852         I32 fake;
4853         struct regnode_charclass_class ch_class;
4854         I32 last_close = 0;
4855         
4856         DEBUG_PARSE_r(PerlIO_printf(Perl_debug_log, "\nMulti Top Level\n"));
4857
4858         scan = ri->program + 1;
4859         cl_init(pRExC_state, &ch_class);
4860         data.start_class = &ch_class;
4861         data.last_closep = &last_close;
4862
4863         
4864         minlen = study_chunk(pRExC_state, &scan, &minlen, &fake, scan + RExC_size,
4865             &data, -1, NULL, NULL, SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS,0);
4866         
4867         CHECK_RESTUDY_GOTO;
4868
4869         r->check_substr = r->check_utf8 = r->anchored_substr = r->anchored_utf8
4870                 = r->float_substr = r->float_utf8 = NULL;
4871         if (!(data.start_class->flags & ANYOF_EOS)
4872             && !cl_is_anything(data.start_class))
4873         {
4874             const U32 n = add_data(pRExC_state, 1, "f");
4875
4876             Newx(RExC_rxi->data->data[n], 1,
4877                 struct regnode_charclass_class);
4878             StructCopy(data.start_class,
4879                        (struct regnode_charclass_class*)RExC_rxi->data->data[n],
4880                        struct regnode_charclass_class);
4881             ri->regstclass = (regnode*)RExC_rxi->data->data[n];
4882             r->intflags &= ~PREGf_SKIP; /* Used in find_byclass(). */
4883             DEBUG_COMPILE_r({ SV* sv = sv_newmortal();
4884                       regprop(r, sv, (regnode*)data.start_class);
4885                       PerlIO_printf(Perl_debug_log,
4886                                     "synthetic stclass \"%s\".\n",
4887                                     SvPVX_const(sv));});
4888         }
4889     }
4890
4891     /* Guard against an embedded (?=) or (?<=) with a longer minlen than
4892        the "real" pattern. */
4893     DEBUG_OPTIMISE_r({
4894         PerlIO_printf(Perl_debug_log,"minlen: %"IVdf" r->minlen:%"IVdf"\n",
4895                       (IV)minlen, (IV)r->minlen);
4896     });
4897     r->minlenret = minlen;
4898     if (r->minlen < minlen) 
4899         r->minlen = minlen;
4900     
4901     if (RExC_seen & REG_SEEN_GPOS)
4902         r->extflags |= RXf_GPOS_SEEN;
4903     if (RExC_seen & REG_SEEN_LOOKBEHIND)
4904         r->extflags |= RXf_LOOKBEHIND_SEEN;
4905     if (RExC_seen & REG_SEEN_EVAL)
4906         r->extflags |= RXf_EVAL_SEEN;
4907     if (RExC_seen & REG_SEEN_CANY)
4908         r->extflags |= RXf_CANY_SEEN;
4909     if (RExC_seen & REG_SEEN_VERBARG)
4910         r->intflags |= PREGf_VERBARG_SEEN;
4911     if (RExC_seen & REG_SEEN_CUTGROUP)
4912         r->intflags |= PREGf_CUTGROUP_SEEN;
4913     if (RExC_paren_names)
4914         RXp_PAREN_NAMES(r) = MUTABLE_HV(SvREFCNT_inc(RExC_paren_names));
4915     else
4916         RXp_PAREN_NAMES(r) = NULL;
4917
4918 #ifdef STUPID_PATTERN_CHECKS            
4919     if (RX_PRELEN(rx) == 0)
4920         r->extflags |= RXf_NULL;
4921     if (r->extflags & RXf_SPLIT && RX_PRELEN(rx) == 1 && RX_PRECOMP(rx)[0] == ' ')
4922         /* XXX: this should happen BEFORE we compile */
4923         r->extflags |= (RXf_SKIPWHITE|RXf_WHITE); 
4924     else if (RX_PRELEN(rx) == 3 && memEQ("\\s+", RX_PRECOMP(rx), 3))
4925         r->extflags |= RXf_WHITE;
4926     else if (RX_PRELEN(rx) == 1 && RXp_PRECOMP(rx)[0] == '^')
4927         r->extflags |= RXf_START_ONLY;
4928 #else
4929     if (r->extflags & RXf_SPLIT && RX_PRELEN(rx) == 1 && RX_PRECOMP(rx)[0] == ' ')
4930             /* XXX: this should happen BEFORE we compile */
4931             r->extflags |= (RXf_SKIPWHITE|RXf_WHITE); 
4932     else {
4933         regnode *first = ri->program + 1;
4934         U8 fop = OP(first);
4935         U8 nop = OP(NEXTOPER(first));
4936         
4937         if (PL_regkind[fop] == NOTHING && nop == END)
4938             r->extflags |= RXf_NULL;
4939         else if (PL_regkind[fop] == BOL && nop == END)
4940             r->extflags |= RXf_START_ONLY;
4941         else if (fop == PLUS && nop ==SPACE && OP(regnext(first))==END)
4942             r->extflags |= RXf_WHITE;    
4943     }
4944 #endif
4945 #ifdef DEBUGGING
4946     if (RExC_paren_names) {
4947         ri->name_list_idx = add_data( pRExC_state, 1, "a" );
4948         ri->data->data[ri->name_list_idx] = (void*)SvREFCNT_inc(RExC_paren_name_list);
4949     } else
4950 #endif
4951         ri->name_list_idx = 0;
4952
4953     if (RExC_recurse_count) {
4954         for ( ; RExC_recurse_count ; RExC_recurse_count-- ) {
4955             const regnode *scan = RExC_recurse[RExC_recurse_count-1];
4956             ARG2L_SET( scan, RExC_open_parens[ARG(scan)-1] - scan );
4957         }
4958     }
4959     Newxz(r->offs, RExC_npar, regexp_paren_pair);
4960     /* assume we don't need to swap parens around before we match */
4961
4962     DEBUG_DUMP_r({
4963         PerlIO_printf(Perl_debug_log,"Final program:\n");
4964         regdump(r);
4965     });
4966 #ifdef RE_TRACK_PATTERN_OFFSETS
4967     DEBUG_OFFSETS_r(if (ri->u.offsets) {
4968         const U32 len = ri->u.offsets[0];
4969         U32 i;
4970         GET_RE_DEBUG_FLAGS_DECL;
4971         PerlIO_printf(Perl_debug_log, "Offsets: [%"UVuf"]\n\t", (UV)ri->u.offsets[0]);
4972         for (i = 1; i <= len; i++) {
4973             if (ri->u.offsets[i*2-1] || ri->u.offsets[i*2])
4974                 PerlIO_printf(Perl_debug_log, "%"UVuf":%"UVuf"[%"UVuf"] ",
4975                 (UV)i, (UV)ri->u.offsets[i*2-1], (UV)ri->u.offsets[i*2]);
4976             }
4977         PerlIO_printf(Perl_debug_log, "\n");
4978     });
4979 #endif
4980     return rx;
4981 }
4982
4983 #undef RE_ENGINE_PTR
4984
4985
4986 SV*
4987 Perl_reg_named_buff(pTHX_ REGEXP * const rx, SV * const key, SV * const value,
4988                     const U32 flags)
4989 {
4990     PERL_ARGS_ASSERT_REG_NAMED_BUFF;
4991
4992     PERL_UNUSED_ARG(value);
4993
4994     if (flags & RXapif_FETCH) {
4995         return reg_named_buff_fetch(rx, key, flags);
4996     } else if (flags & (RXapif_STORE | RXapif_DELETE | RXapif_CLEAR)) {
4997         Perl_croak_no_modify(aTHX);
4998         return NULL;
4999     } else if (flags & RXapif_EXISTS) {
5000         return reg_named_buff_exists(rx, key, flags)
5001             ? &PL_sv_yes
5002             : &PL_sv_no;
5003     } else if (flags & RXapif_REGNAMES) {
5004         return reg_named_buff_all(rx, flags);
5005     } else if (flags & (RXapif_SCALAR | RXapif_REGNAMES_COUNT)) {
5006         return reg_named_buff_scalar(rx, flags);
5007     } else {
5008         Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff", (int)flags);
5009         return NULL;
5010     }
5011 }
5012
5013 SV*
5014 Perl_reg_named_buff_iter(pTHX_ REGEXP * const rx, const SV * const lastkey,
5015                          const U32 flags)
5016 {
5017     PERL_ARGS_ASSERT_REG_NAMED_BUFF_ITER;
5018     PERL_UNUSED_ARG(lastkey);
5019
5020     if (flags & RXapif_FIRSTKEY)
5021         return reg_named_buff_firstkey(rx, flags);
5022     else if (flags & RXapif_NEXTKEY)
5023         return reg_named_buff_nextkey(rx, flags);
5024     else {
5025         Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_iter", (int)flags);
5026         return NULL;
5027     }
5028 }
5029
5030 SV*
5031 Perl_reg_named_buff_fetch(pTHX_ REGEXP * const r, SV * const namesv,
5032                           const U32 flags)
5033 {
5034     AV *retarray = NULL;
5035     SV *ret;
5036     struct regexp *const rx = (struct regexp *)SvANY(r);
5037
5038     PERL_ARGS_ASSERT_REG_NAMED_BUFF_FETCH;
5039
5040     if (flags & RXapif_ALL)
5041         retarray=newAV();
5042
5043     if (rx && RXp_PAREN_NAMES(rx)) {
5044         HE *he_str = hv_fetch_ent( RXp_PAREN_NAMES(rx), namesv, 0, 0 );
5045         if (he_str) {
5046             IV i;
5047             SV* sv_dat=HeVAL(he_str);
5048             I32 *nums=(I32*)SvPVX(sv_dat);
5049             for ( i=0; i<SvIVX(sv_dat); i++ ) {
5050                 if ((I32)(rx->nparens) >= nums[i]
5051                     && rx->offs[nums[i]].start != -1
5052                     && rx->offs[nums[i]].end != -1)
5053                 {
5054                     ret = newSVpvs("");
5055                     CALLREG_NUMBUF_FETCH(r,nums[i],ret);
5056                     if (!retarray)
5057                         return ret;
5058                 } else {
5059                     ret = newSVsv(&PL_sv_undef);
5060                 }
5061                 if (retarray)
5062                     av_push(retarray, ret);
5063             }
5064             if (retarray)
5065                 return newRV_noinc(MUTABLE_SV(retarray));
5066         }
5067     }
5068     return NULL;
5069 }
5070
5071 bool
5072 Perl_reg_named_buff_exists(pTHX_ REGEXP * const r, SV * const key,
5073                            const U32 flags)
5074 {
5075     struct regexp *const rx = (struct regexp *)SvANY(r);
5076
5077     PERL_ARGS_ASSERT_REG_NAMED_BUFF_EXISTS;
5078
5079     if (rx && RXp_PAREN_NAMES(rx)) {
5080         if (flags & RXapif_ALL) {
5081             return hv_exists_ent(RXp_PAREN_NAMES(rx), key, 0);
5082         } else {
5083             SV *sv = CALLREG_NAMED_BUFF_FETCH(r, key, flags);
5084             if (sv) {
5085                 SvREFCNT_dec(sv);
5086                 return TRUE;
5087             } else {
5088                 return FALSE;
5089             }
5090         }
5091     } else {
5092         return FALSE;
5093     }
5094 }
5095
5096 SV*
5097 Perl_reg_named_buff_firstkey(pTHX_ REGEXP * const r, const U32 flags)
5098 {
5099     struct regexp *const rx = (struct regexp *)SvANY(r);
5100
5101     PERL_ARGS_ASSERT_REG_NAMED_BUFF_FIRSTKEY;
5102
5103     if ( rx && RXp_PAREN_NAMES(rx) ) {
5104         (void)hv_iterinit(RXp_PAREN_NAMES(rx));
5105
5106         return CALLREG_NAMED_BUFF_NEXTKEY(r, NULL, flags & ~RXapif_FIRSTKEY);
5107     } else {
5108         return FALSE;
5109     }
5110 }
5111
5112 SV*
5113 Perl_reg_named_buff_nextkey(pTHX_ REGEXP * const r, const U32 flags)
5114 {
5115     struct regexp *const rx = (struct regexp *)SvANY(r);
5116     GET_RE_DEBUG_FLAGS_DECL;
5117
5118     PERL_ARGS_ASSERT_REG_NAMED_BUFF_NEXTKEY;
5119
5120     if (rx && RXp_PAREN_NAMES(rx)) {
5121         HV *hv = RXp_PAREN_NAMES(rx);
5122         HE *temphe;
5123         while ( (temphe = hv_iternext_flags(hv,0)) ) {
5124             IV i;
5125             IV parno = 0;
5126             SV* sv_dat = HeVAL(temphe);
5127             I32 *nums = (I32*)SvPVX(sv_dat);
5128             for ( i = 0; i < SvIVX(sv_dat); i++ ) {
5129                 if ((I32)(rx->lastparen) >= nums[i] &&
5130                     rx->offs[nums[i]].start != -1 &&
5131                     rx->offs[nums[i]].end != -1)
5132                 {
5133                     parno = nums[i];
5134                     break;
5135                 }
5136             }
5137             if (parno || flags & RXapif_ALL) {
5138                 return newSVhek(HeKEY_hek(temphe));
5139             }
5140         }
5141     }
5142     return NULL;
5143 }
5144
5145 SV*
5146 Perl_reg_named_buff_scalar(pTHX_ REGEXP * const r, const U32 flags)
5147 {
5148     SV *ret;
5149     AV *av;
5150     I32 length;
5151     struct regexp *const rx = (struct regexp *)SvANY(r);
5152
5153     PERL_ARGS_ASSERT_REG_NAMED_BUFF_SCALAR;
5154
5155     if (rx && RXp_PAREN_NAMES(rx)) {
5156         if (flags & (RXapif_ALL | RXapif_REGNAMES_COUNT)) {
5157             return newSViv(HvTOTALKEYS(RXp_PAREN_NAMES(rx)));
5158         } else if (flags & RXapif_ONE) {
5159             ret = CALLREG_NAMED_BUFF_ALL(r, (flags | RXapif_REGNAMES));
5160             av = MUTABLE_AV(SvRV(ret));
5161             length = av_len(av);
5162             SvREFCNT_dec(ret);
5163             return newSViv(length + 1);
5164         } else {
5165             Perl_croak(aTHX_ "panic: Unknown flags %d in named_buff_scalar", (int)flags);
5166             return NULL;
5167         }
5168     }
5169     return &PL_sv_undef;
5170 }
5171
5172 SV*
5173 Perl_reg_named_buff_all(pTHX_ REGEXP * const r, const U32 flags)
5174 {
5175     struct regexp *const rx = (struct regexp *)SvANY(r);
5176     AV *av = newAV();
5177
5178     PERL_ARGS_ASSERT_REG_NAMED_BUFF_ALL;
5179
5180     if (rx && RXp_PAREN_NAMES(rx)) {
5181         HV *hv= RXp_PAREN_NAMES(rx);
5182         HE *temphe;
5183         (void)hv_iterinit(hv);
5184         while ( (temphe = hv_iternext_flags(hv,0)) ) {
5185             IV i;
5186             IV parno = 0;
5187             SV* sv_dat = HeVAL(temphe);
5188             I32 *nums = (I32*)SvPVX(sv_dat);
5189             for ( i = 0; i < SvIVX(sv_dat); i++ ) {
5190                 if ((I32)(rx->lastparen) >= nums[i] &&
5191                     rx->offs[nums[i]].start != -1 &&
5192                     rx->offs[nums[i]].end != -1)
5193                 {
5194                     parno = nums[i];
5195                     break;
5196                 }
5197             }
5198             if (parno || flags & RXapif_ALL) {
5199                 av_push(av, newSVhek(HeKEY_hek(temphe)));
5200             }
5201         }
5202     }
5203
5204     return newRV_noinc(MUTABLE_SV(av));
5205 }
5206
5207 void
5208 Perl_reg_numbered_buff_fetch(pTHX_ REGEXP * const r, const I32 paren,
5209                              SV * const sv)
5210 {
5211     struct regexp *const rx = (struct regexp *)SvANY(r);
5212     char *s = NULL;
5213     I32 i = 0;
5214     I32 s1, t1;
5215
5216     PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_FETCH;
5217         
5218     if (!rx->subbeg) {
5219         sv_setsv(sv,&PL_sv_undef);
5220         return;
5221     } 
5222     else               
5223     if (paren == RX_BUFF_IDX_PREMATCH && rx->offs[0].start != -1) {
5224         /* $` */
5225         i = rx->offs[0].start;
5226         s = rx->subbeg;
5227     }
5228     else 
5229     if (paren == RX_BUFF_IDX_POSTMATCH && rx->offs[0].end != -1) {
5230         /* $' */
5231         s = rx->subbeg + rx->offs[0].end;
5232         i = rx->sublen - rx->offs[0].end;
5233     } 
5234     else
5235     if ( 0 <= paren && paren <= (I32)rx->nparens &&
5236         (s1 = rx->offs[paren].start) != -1 &&
5237         (t1 = rx->offs[paren].end) != -1)
5238     {
5239         /* $& $1 ... */
5240         i = t1 - s1;
5241         s = rx->subbeg + s1;
5242     } else {
5243         sv_setsv(sv,&PL_sv_undef);
5244         return;
5245     }          
5246     assert(rx->sublen >= (s - rx->subbeg) + i );
5247     if (i >= 0) {
5248         const int oldtainted = PL_tainted;
5249         TAINT_NOT;
5250         sv_setpvn(sv, s, i);
5251         PL_tainted = oldtainted;
5252         if ( (rx->extflags & RXf_CANY_SEEN)
5253             ? (RXp_MATCH_UTF8(rx)
5254                         && (!i || is_utf8_string((U8*)s, i)))
5255             : (RXp_MATCH_UTF8(rx)) )
5256         {
5257             SvUTF8_on(sv);
5258         }
5259         else
5260             SvUTF8_off(sv);
5261         if (PL_tainting) {
5262             if (RXp_MATCH_TAINTED(rx)) {
5263                 if (SvTYPE(sv) >= SVt_PVMG) {
5264                     MAGIC* const mg = SvMAGIC(sv);
5265                     MAGIC* mgt;
5266                     PL_tainted = 1;
5267                     SvMAGIC_set(sv, mg->mg_moremagic);
5268                     SvTAINT(sv);
5269                     if ((mgt = SvMAGIC(sv))) {
5270                         mg->mg_moremagic = mgt;
5271                         SvMAGIC_set(sv, mg);
5272                     }
5273                 } else {
5274                     PL_tainted = 1;
5275                     SvTAINT(sv);
5276                 }
5277             } else 
5278                 SvTAINTED_off(sv);
5279         }
5280     } else {
5281         sv_setsv(sv,&PL_sv_undef);
5282         return;
5283     }
5284 }
5285
5286 void
5287 Perl_reg_numbered_buff_store(pTHX_ REGEXP * const rx, const I32 paren,
5288                                                          SV const * const value)
5289 {
5290     PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_STORE;
5291
5292     PERL_UNUSED_ARG(rx);
5293     PERL_UNUSED_ARG(paren);
5294     PERL_UNUSED_ARG(value);
5295
5296     if (!PL_localizing)
5297         Perl_croak_no_modify(aTHX);
5298 }
5299
5300 I32
5301 Perl_reg_numbered_buff_length(pTHX_ REGEXP * const r, const SV * const sv,
5302                               const I32 paren)
5303 {
5304     struct regexp *const rx = (struct regexp *)SvANY(r);
5305     I32 i;
5306     I32 s1, t1;
5307
5308     PERL_ARGS_ASSERT_REG_NUMBERED_BUFF_LENGTH;
5309
5310     /* Some of this code was originally in C<Perl_magic_len> in F<mg.c> */
5311         switch (paren) {
5312       /* $` / ${^PREMATCH} */
5313       case RX_BUFF_IDX_PREMATCH:
5314         if (rx->offs[0].start != -1) {
5315                         i = rx->offs[0].start;
5316                         if (i > 0) {
5317                                 s1 = 0;
5318                                 t1 = i;
5319                                 goto getlen;
5320                         }
5321             }
5322         return 0;
5323       /* $' / ${^POSTMATCH} */
5324       case RX_BUFF_IDX_POSTMATCH:
5325             if (rx->offs[0].end != -1) {
5326                         i = rx->sublen - rx->offs[0].end;
5327                         if (i > 0) {
5328                                 s1 = rx->offs[0].end;
5329                                 t1 = rx->sublen;
5330                                 goto getlen;
5331                         }
5332             }
5333         return 0;
5334       /* $& / ${^MATCH}, $1, $2, ... */
5335       default:
5336             if (paren <= (I32)rx->nparens &&
5337             (s1 = rx->offs[paren].start) != -1 &&
5338             (t1 = rx->offs[paren].end) != -1)
5339             {
5340             i = t1 - s1;
5341             goto getlen;
5342         } else {
5343             if (ckWARN(WARN_UNINITIALIZED))
5344                 report_uninit((const SV *)sv);
5345             return 0;
5346         }
5347     }
5348   getlen:
5349     if (i > 0 && RXp_MATCH_UTF8(rx)) {
5350         const char * const s = rx->subbeg + s1;
5351         const U8 *ep;
5352         STRLEN el;
5353
5354         i = t1 - s1;
5355         if (is_utf8_string_loclen((U8*)s, i, &ep, &el))
5356                         i = el;
5357     }
5358     return i;
5359 }
5360
5361 SV*
5362 Perl_reg_qr_package(pTHX_ REGEXP * const rx)
5363 {
5364     PERL_ARGS_ASSERT_REG_QR_PACKAGE;
5365         PERL_UNUSED_ARG(rx);
5366         if (0)
5367             return NULL;
5368         else
5369             return newSVpvs("Regexp");
5370 }
5371
5372 /* Scans the name of a named buffer from the pattern.
5373  * If flags is REG_RSN_RETURN_NULL returns null.
5374  * If flags is REG_RSN_RETURN_NAME returns an SV* containing the name
5375  * If flags is REG_RSN_RETURN_DATA returns the data SV* corresponding
5376  * to the parsed name as looked up in the RExC_paren_names hash.
5377  * If there is an error throws a vFAIL().. type exception.
5378  */
5379
5380 #define REG_RSN_RETURN_NULL    0
5381 #define REG_RSN_RETURN_NAME    1
5382 #define REG_RSN_RETURN_DATA    2
5383
5384 STATIC SV*
5385 S_reg_scan_name(pTHX_ RExC_state_t *pRExC_state, U32 flags)
5386 {
5387     char *name_start = RExC_parse;
5388
5389     PERL_ARGS_ASSERT_REG_SCAN_NAME;
5390
5391     if (isIDFIRST_lazy_if(RExC_parse, UTF)) {
5392          /* skip IDFIRST by using do...while */
5393         if (UTF)
5394             do {
5395                 RExC_parse += UTF8SKIP(RExC_parse);
5396             } while (isALNUM_utf8((U8*)RExC_parse));
5397         else
5398             do {
5399                 RExC_parse++;
5400             } while (isALNUM(*RExC_parse));
5401     }
5402
5403     if ( flags ) {
5404         SV* sv_name
5405             = newSVpvn_flags(name_start, (int)(RExC_parse - name_start),
5406                              SVs_TEMP | (UTF ? SVf_UTF8 : 0));
5407         if ( flags == REG_RSN_RETURN_NAME)
5408             return sv_name;
5409         else if (flags==REG_RSN_RETURN_DATA) {
5410             HE *he_str = NULL;
5411             SV *sv_dat = NULL;
5412             if ( ! sv_name )      /* should not happen*/
5413                 Perl_croak(aTHX_ "panic: no svname in reg_scan_name");
5414             if (RExC_paren_names)
5415                 he_str = hv_fetch_ent( RExC_paren_names, sv_name, 0, 0 );
5416             if ( he_str )
5417                 sv_dat = HeVAL(he_str);
5418             if ( ! sv_dat )
5419                 vFAIL("Reference to nonexistent named group");
5420             return sv_dat;
5421         }
5422         else {
5423             Perl_croak(aTHX_ "panic: bad flag in reg_scan_name");
5424         }
5425         /* NOT REACHED */
5426     }
5427     return NULL;
5428 }
5429
5430 #define DEBUG_PARSE_MSG(funcname)     DEBUG_PARSE_r({           \
5431     int rem=(int)(RExC_end - RExC_parse);                       \
5432     int cut;                                                    \
5433     int num;                                                    \
5434     int iscut=0;                                                \
5435     if (rem>10) {                                               \
5436         rem=10;                                                 \
5437         iscut=1;                                                \
5438     }                                                           \
5439     cut=10-rem;                                                 \
5440     if (RExC_lastparse!=RExC_parse)                             \
5441         PerlIO_printf(Perl_debug_log," >%.*s%-*s",              \
5442             rem, RExC_parse,                                    \
5443             cut + 4,                                            \
5444             iscut ? "..." : "<"                                 \
5445         );                                                      \
5446     else                                                        \
5447         PerlIO_printf(Perl_debug_log,"%16s","");                \
5448                                                                 \
5449     if (SIZE_ONLY)                                              \
5450        num = RExC_size + 1;                                     \
5451     else                                                        \
5452        num=REG_NODE_NUM(RExC_emit);                             \
5453     if (RExC_lastnum!=num)                                      \
5454        PerlIO_printf(Perl_debug_log,"|%4d",num);                \
5455     else                                                        \
5456        PerlIO_printf(Perl_debug_log,"|%4s","");                 \
5457     PerlIO_printf(Perl_debug_log,"|%*s%-4s",                    \
5458         (int)((depth*2)), "",                                   \
5459         (funcname)                                              \
5460     );                                                          \
5461     RExC_lastnum=num;                                           \
5462     RExC_lastparse=RExC_parse;                                  \
5463 })
5464
5465
5466
5467 #define DEBUG_PARSE(funcname)     DEBUG_PARSE_r({           \
5468     DEBUG_PARSE_MSG((funcname));                            \
5469     PerlIO_printf(Perl_debug_log,"%4s","\n");               \
5470 })
5471 #define DEBUG_PARSE_FMT(funcname,fmt,args)     DEBUG_PARSE_r({           \
5472     DEBUG_PARSE_MSG((funcname));                            \
5473     PerlIO_printf(Perl_debug_log,fmt "\n",args);               \
5474 })
5475 /*
5476  - reg - regular expression, i.e. main body or parenthesized thing
5477  *
5478  * Caller must absorb opening parenthesis.
5479  *
5480  * Combining parenthesis handling with the base level of regular expression
5481  * is a trifle forced, but the need to tie the tails of the branches to what
5482  * follows makes it hard to avoid.
5483  */
5484 #define REGTAIL(x,y,z) regtail((x),(y),(z),depth+1)
5485 #ifdef DEBUGGING
5486 #define REGTAIL_STUDY(x,y,z) regtail_study((x),(y),(z),depth+1)
5487 #else
5488 #define REGTAIL_STUDY(x,y,z) regtail((x),(y),(z),depth+1)
5489 #endif
5490
5491 STATIC regnode *
5492 S_reg(pTHX_ RExC_state_t *pRExC_state, I32 paren, I32 *flagp,U32 depth)
5493     /* paren: Parenthesized? 0=top, 1=(, inside: changed to letter. */
5494 {
5495     dVAR;
5496     register regnode *ret;              /* Will be the head of the group. */
5497     register regnode *br;
5498     register regnode *lastbr;
5499     register regnode *ender = NULL;
5500     register I32 parno = 0;
5501     I32 flags;
5502     U32 oregflags = RExC_flags;
5503     bool have_branch = 0;
5504     bool is_open = 0;
5505     I32 freeze_paren = 0;
5506     I32 after_freeze = 0;
5507
5508     /* for (?g), (?gc), and (?o) warnings; warning
5509        about (?c) will warn about (?g) -- japhy    */
5510
5511 #define WASTED_O  0x01
5512 #define WASTED_G  0x02
5513 #define WASTED_C  0x04
5514 #define WASTED_GC (0x02|0x04)
5515     I32 wastedflags = 0x00;
5516
5517     char * parse_start = RExC_parse; /* MJD */
5518     char * const oregcomp_parse = RExC_parse;
5519
5520     GET_RE_DEBUG_FLAGS_DECL;
5521
5522     PERL_ARGS_ASSERT_REG;
5523     DEBUG_PARSE("reg ");
5524
5525     *flagp = 0;                         /* Tentatively. */
5526
5527
5528     /* Make an OPEN node, if parenthesized. */
5529     if (paren) {
5530         if ( *RExC_parse == '*') { /* (*VERB:ARG) */
5531             char *start_verb = RExC_parse;
5532             STRLEN verb_len = 0;
5533             char *start_arg = NULL;
5534             unsigned char op = 0;
5535             int argok = 1;
5536             int internal_argval = 0; /* internal_argval is only useful if !argok */
5537             while ( *RExC_parse && *RExC_parse != ')' ) {
5538                 if ( *RExC_parse == ':' ) {
5539                     start_arg = RExC_parse + 1;
5540                     break;
5541                 }
5542                 RExC_parse++;
5543             }
5544             ++start_verb;
5545             verb_len = RExC_parse - start_verb;
5546             if ( start_arg ) {
5547                 RExC_parse++;
5548                 while ( *RExC_parse && *RExC_parse != ')' ) 
5549                     RExC_parse++;
5550                 if ( *RExC_parse != ')' ) 
5551                     vFAIL("Unterminated verb pattern argument");
5552                 if ( RExC_parse == start_arg )
5553                     start_arg = NULL;
5554             } else {
5555                 if ( *RExC_parse != ')' )
5556                     vFAIL("Unterminated verb pattern");
5557             }
5558             
5559             switch ( *start_verb ) {
5560             case 'A':  /* (*ACCEPT) */
5561                 if ( memEQs(start_verb,verb_len,"ACCEPT") ) {
5562                     op = ACCEPT;
5563                     internal_argval = RExC_nestroot;
5564                 }
5565                 break;
5566             case 'C':  /* (*COMMIT) */
5567                 if ( memEQs(start_verb,verb_len,"COMMIT") )
5568                     op = COMMIT;
5569                 break;
5570             case 'F':  /* (*FAIL) */
5571                 if ( verb_len==1 || memEQs(start_verb,verb_len,"FAIL") ) {
5572                     op = OPFAIL;
5573                     argok = 0;
5574                 }
5575                 break;
5576             case ':':  /* (*:NAME) */
5577             case 'M':  /* (*MARK:NAME) */
5578                 if ( verb_len==0 || memEQs(start_verb,verb_len,"MARK") ) {
5579                     op = MARKPOINT;
5580                     argok = -1;
5581                 }
5582                 break;
5583             case 'P':  /* (*PRUNE) */
5584                 if ( memEQs(start_verb,verb_len,"PRUNE") )
5585                     op = PRUNE;
5586                 break;
5587             case 'S':   /* (*SKIP) */  
5588                 if ( memEQs(start_verb,verb_len,"SKIP") ) 
5589                     op = SKIP;
5590                 break;
5591             case 'T':  /* (*THEN) */
5592                 /* [19:06] <TimToady> :: is then */
5593                 if ( memEQs(start_verb,verb_len,"THEN") ) {
5594                     op = CUTGROUP;
5595                     RExC_seen |= REG_SEEN_CUTGROUP;
5596                 }
5597                 break;
5598             }
5599             if ( ! op ) {
5600                 RExC_parse++;
5601                 vFAIL3("Unknown verb pattern '%.*s'",
5602                     verb_len, start_verb);
5603             }
5604             if ( argok ) {
5605                 if ( start_arg && internal_argval ) {
5606                     vFAIL3("Verb pattern '%.*s' may not have an argument",
5607                         verb_len, start_verb); 
5608                 } else if ( argok < 0 && !start_arg ) {
5609                     vFAIL3("Verb pattern '%.*s' has a mandatory argument",
5610                         verb_len, start_verb);    
5611                 } else {
5612                     ret = reganode(pRExC_state, op, internal_argval);
5613                     if ( ! internal_argval && ! SIZE_ONLY ) {
5614                         if (start_arg) {
5615                             SV *sv = newSVpvn( start_arg, RExC_parse - start_arg);
5616                             ARG(ret) = add_data( pRExC_state, 1, "S" );
5617                             RExC_rxi->data->data[ARG(ret)]=(void*)sv;
5618                             ret->flags = 0;
5619                         } else {
5620                             ret->flags = 1; 
5621                         }
5622                     }               
5623                 }
5624                 if (!internal_argval)
5625                     RExC_seen |= REG_SEEN_VERBARG;
5626             } else if ( start_arg ) {
5627                 vFAIL3("Verb pattern '%.*s' may not have an argument",
5628                         verb_len, start_verb);    
5629             } else {
5630                 ret = reg_node(pRExC_state, op);
5631             }
5632             nextchar(pRExC_state);
5633             return ret;
5634         } else 
5635         if (*RExC_parse == '?') { /* (?...) */
5636             bool is_logical = 0;
5637             const char * const seqstart = RExC_parse;
5638
5639             RExC_parse++;
5640             paren = *RExC_parse++;
5641             ret = NULL;                 /* For look-ahead/behind. */
5642             switch (paren) {
5643
5644             case 'P':   /* (?P...) variants for those used to PCRE/Python */
5645                 paren = *RExC_parse++;
5646                 if ( paren == '<')         /* (?P<...>) named capture */
5647                     goto named_capture;
5648                 else if (paren == '>') {   /* (?P>name) named recursion */
5649                     goto named_recursion;
5650                 }
5651                 else if (paren == '=') {   /* (?P=...)  named backref */
5652                     /* this pretty much dupes the code for \k<NAME> in regatom(), if
5653                        you change this make sure you change that */
5654                     char* name_start = RExC_parse;
5655                     U32 num = 0;
5656                     SV *sv_dat = reg_scan_name(pRExC_state,
5657                         SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
5658                     if (RExC_parse == name_start || *RExC_parse != ')')
5659                         vFAIL2("Sequence %.3s... not terminated",parse_start);
5660
5661                     if (!SIZE_ONLY) {
5662                         num = add_data( pRExC_state, 1, "S" );
5663                         RExC_rxi->data->data[num]=(void*)sv_dat;
5664                         SvREFCNT_inc_simple_void(sv_dat);
5665                     }
5666                     RExC_sawback = 1;
5667                     ret = reganode(pRExC_state,
5668                            (U8)(FOLD ? (LOC ? NREFFL : NREFF) : NREF),
5669                            num);
5670                     *flagp |= HASWIDTH;
5671
5672                     Set_Node_Offset(ret, parse_start+1);
5673                     Set_Node_Cur_Length(ret); /* MJD */
5674
5675                     nextchar(pRExC_state);
5676                     return ret;
5677                 }
5678                 RExC_parse++;
5679                 vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
5680                 /*NOTREACHED*/
5681             case '<':           /* (?<...) */
5682                 if (*RExC_parse == '!')
5683                     paren = ',';
5684                 else if (*RExC_parse != '=') 
5685               named_capture:
5686                 {               /* (?<...>) */
5687                     char *name_start;
5688                     SV *svname;
5689                     paren= '>';
5690             case '\'':          /* (?'...') */
5691                     name_start= RExC_parse;
5692                     svname = reg_scan_name(pRExC_state,
5693                         SIZE_ONLY ?  /* reverse test from the others */
5694                         REG_RSN_RETURN_NAME : 
5695                         REG_RSN_RETURN_NULL);
5696                     if (RExC_parse == name_start) {
5697                         RExC_parse++;
5698                         vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
5699                         /*NOTREACHED*/
5700                     }
5701                     if (*RExC_parse != paren)
5702                         vFAIL2("Sequence (?%c... not terminated",
5703                             paren=='>' ? '<' : paren);
5704                     if (SIZE_ONLY) {
5705                         HE *he_str;
5706                         SV *sv_dat = NULL;
5707                         if (!svname) /* shouldnt happen */
5708                             Perl_croak(aTHX_
5709                                 "panic: reg_scan_name returned NULL");
5710                         if (!RExC_paren_names) {
5711                             RExC_paren_names= newHV();
5712                             sv_2mortal(MUTABLE_SV(RExC_paren_names));
5713 #ifdef DEBUGGING
5714                             RExC_paren_name_list= newAV();
5715                             sv_2mortal(MUTABLE_SV(RExC_paren_name_list));
5716 #endif
5717                         }
5718                         he_str = hv_fetch_ent( RExC_paren_names, svname, 1, 0 );
5719                         if ( he_str )
5720                             sv_dat = HeVAL(he_str);
5721                         if ( ! sv_dat ) {
5722                             /* croak baby croak */
5723                             Perl_croak(aTHX_
5724                                 "panic: paren_name hash element allocation failed");
5725                         } else if ( SvPOK(sv_dat) ) {
5726                             /* (?|...) can mean we have dupes so scan to check
5727                                its already been stored. Maybe a flag indicating
5728                                we are inside such a construct would be useful,
5729                                but the arrays are likely to be quite small, so
5730                                for now we punt -- dmq */
5731                             IV count = SvIV(sv_dat);
5732                             I32 *pv = (I32*)SvPVX(sv_dat);
5733                             IV i;
5734                             for ( i = 0 ; i < count ; i++ ) {
5735                                 if ( pv[i] == RExC_npar ) {
5736                                     count = 0;
5737                                     break;
5738                                 }
5739                             }
5740                             if ( count ) {
5741                                 pv = (I32*)SvGROW(sv_dat, SvCUR(sv_dat) + sizeof(I32)+1);
5742                                 SvCUR_set(sv_dat, SvCUR(sv_dat) + sizeof(I32));
5743                                 pv[count] = RExC_npar;
5744                                 SvIV_set(sv_dat, SvIVX(sv_dat) + 1);
5745                             }
5746                         } else {
5747                             (void)SvUPGRADE(sv_dat,SVt_PVNV);
5748                             sv_setpvn(sv_dat, (char *)&(RExC_npar), sizeof(I32));
5749                             SvIOK_on(sv_dat);
5750                             SvIV_set(sv_dat, 1);
5751                         }
5752 #ifdef DEBUGGING
5753                         if (!av_store(RExC_paren_name_list, RExC_npar, SvREFCNT_inc(svname)))
5754                             SvREFCNT_dec(svname);
5755 #endif
5756
5757                         /*sv_dump(sv_dat);*/
5758                     }
5759                     nextchar(pRExC_state);
5760                     paren = 1;
5761                     goto capturing_parens;
5762                 }
5763                 RExC_seen |= REG_SEEN_LOOKBEHIND;
5764                 RExC_parse++;
5765             case '=':           /* (?=...) */
5766                 RExC_seen_zerolen++;
5767                         break;
5768             case '!':           /* (?!...) */
5769                 RExC_seen_zerolen++;
5770                 if (*RExC_parse == ')') {
5771                     ret=reg_node(pRExC_state, OPFAIL);
5772                     nextchar(pRExC_state);
5773                     return ret;
5774                 }
5775                 break;
5776             case '|':           /* (?|...) */
5777                 /* branch reset, behave like a (?:...) except that
5778                    buffers in alternations share the same numbers */
5779                 paren = ':'; 
5780                 after_freeze = freeze_paren = RExC_npar;
5781                 break;
5782             case ':':           /* (?:...) */
5783             case '>':           /* (?>...) */
5784                 break;
5785             case '$':           /* (?$...) */
5786             case '@':           /* (?@...) */
5787                 vFAIL2("Sequence (?%c...) not implemented", (int)paren);
5788                 break;
5789             case '#':           /* (?#...) */
5790                 while (*RExC_parse && *RExC_parse != ')')
5791                     RExC_parse++;
5792                 if (*RExC_parse != ')')
5793                     FAIL("Sequence (?#... not terminated");
5794                 nextchar(pRExC_state);
5795                 *flagp = TRYAGAIN;
5796                 return NULL;
5797             case '0' :           /* (?0) */
5798             case 'R' :           /* (?R) */
5799                 if (*RExC_parse != ')')
5800                     FAIL("Sequence (?R) not terminated");
5801                 ret = reg_node(pRExC_state, GOSTART);
5802                 *flagp |= POSTPONED;
5803                 nextchar(pRExC_state);
5804                 return ret;
5805                 /*notreached*/
5806             { /* named and numeric backreferences */
5807                 I32 num;
5808             case '&':            /* (?&NAME) */
5809                 parse_start = RExC_parse - 1;
5810               named_recursion:
5811                 {
5812                     SV *sv_dat = reg_scan_name(pRExC_state,
5813                         SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
5814                      num = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
5815                 }
5816                 goto gen_recurse_regop;
5817                 /* NOT REACHED */
5818             case '+':
5819                 if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
5820                     RExC_parse++;
5821                     vFAIL("Illegal pattern");
5822                 }
5823                 goto parse_recursion;
5824                 /* NOT REACHED*/
5825             case '-': /* (?-1) */
5826                 if (!(RExC_parse[0] >= '1' && RExC_parse[0] <= '9')) {
5827                     RExC_parse--; /* rewind to let it be handled later */
5828                     goto parse_flags;
5829                 } 
5830                 /*FALLTHROUGH */
5831             case '1': case '2': case '3': case '4': /* (?1) */
5832             case '5': case '6': case '7': case '8': case '9':
5833                 RExC_parse--;
5834               parse_recursion:
5835                 num = atoi(RExC_parse);
5836                 parse_start = RExC_parse - 1; /* MJD */
5837                 if (*RExC_parse == '-')
5838                     RExC_parse++;
5839                 while (isDIGIT(*RExC_parse))
5840                         RExC_parse++;
5841                 if (*RExC_parse!=')') 
5842                     vFAIL("Expecting close bracket");
5843                         
5844               gen_recurse_regop:
5845                 if ( paren == '-' ) {
5846                     /*
5847                     Diagram of capture buffer numbering.
5848                     Top line is the normal capture buffer numbers
5849                     Botton line is the negative indexing as from
5850                     the X (the (?-2))
5851
5852                     +   1 2    3 4 5 X          6 7
5853                        /(a(x)y)(a(b(c(?-2)d)e)f)(g(h))/
5854                     -   5 4    3 2 1 X          x x
5855
5856                     */
5857                     num = RExC_npar + num;
5858                     if (num < 1)  {
5859                         RExC_parse++;
5860                         vFAIL("Reference to nonexistent group");
5861                     }
5862                 } else if ( paren == '+' ) {
5863                     num = RExC_npar + num - 1;
5864                 }
5865
5866                 ret = reganode(pRExC_state, GOSUB, num);
5867                 if (!SIZE_ONLY) {
5868                     if (num > (I32)RExC_rx->nparens) {
5869                         RExC_parse++;
5870                         vFAIL("Reference to nonexistent group");
5871                     }
5872                     ARG2L_SET( ret, RExC_recurse_count++);
5873                     RExC_emit++;
5874                     DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
5875                         "Recurse #%"UVuf" to %"IVdf"\n", (UV)ARG(ret), (IV)ARG2L(ret)));
5876                 } else {
5877                     RExC_size++;
5878                 }
5879                 RExC_seen |= REG_SEEN_RECURSE;
5880                 Set_Node_Length(ret, 1 + regarglen[OP(ret)]); /* MJD */
5881                 Set_Node_Offset(ret, parse_start); /* MJD */
5882
5883                 *flagp |= POSTPONED;
5884                 nextchar(pRExC_state);
5885                 return ret;
5886             } /* named and numeric backreferences */
5887             /* NOT REACHED */
5888
5889             case '?':           /* (??...) */
5890                 is_logical = 1;
5891                 if (*RExC_parse != '{') {
5892                     RExC_parse++;
5893                     vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
5894                     /*NOTREACHED*/
5895                 }
5896                 *flagp |= POSTPONED;
5897                 paren = *RExC_parse++;
5898                 /* FALL THROUGH */
5899             case '{':           /* (?{...}) */
5900             {
5901                 I32 count = 1;
5902                 U32 n = 0;
5903                 char c;
5904                 char *s = RExC_parse;
5905
5906                 RExC_seen_zerolen++;
5907                 RExC_seen |= REG_SEEN_EVAL;
5908                 while (count && (c = *RExC_parse)) {
5909                     if (c == '\\') {
5910                         if (RExC_parse[1])
5911                             RExC_parse++;
5912                     }
5913                     else if (c == '{')
5914                         count++;
5915                     else if (c == '}')
5916                         count--;
5917                     RExC_parse++;
5918                 }
5919                 if (*RExC_parse != ')') {
5920                     RExC_parse = s;             
5921                     vFAIL("Sequence (?{...}) not terminated or not {}-balanced");
5922                 }
5923                 if (!SIZE_ONLY) {
5924                     PAD *pad;
5925                     OP_4tree *sop, *rop;
5926                     SV * const sv = newSVpvn(s, RExC_parse - 1 - s);
5927
5928                     ENTER;
5929                     Perl_save_re_context(aTHX);
5930                     rop = sv_compile_2op(sv, &sop, "re", &pad);
5931                     sop->op_private |= OPpREFCOUNTED;
5932                     /* re_dup will OpREFCNT_inc */
5933                     OpREFCNT_set(sop, 1);
5934                     LEAVE;
5935
5936                     n = add_data(pRExC_state, 3, "nop");
5937                     RExC_rxi->data->data[n] = (void*)rop;
5938                     RExC_rxi->data->data[n+1] = (void*)sop;
5939                     RExC_rxi->data->data[n+2] = (void*)pad;
5940                     SvREFCNT_dec(sv);
5941                 }
5942                 else {                                          /* First pass */
5943                     if (PL_reginterp_cnt < ++RExC_seen_evals
5944                         && IN_PERL_RUNTIME)
5945                         /* No compiled RE interpolated, has runtime
5946                            components ===> unsafe.  */
5947                         FAIL("Eval-group not allowed at runtime, use re 'eval'");
5948                     if (PL_tainting && PL_tainted)
5949                         FAIL("Eval-group in insecure regular expression");
5950 #if PERL_VERSION > 8
5951                     if (IN_PERL_COMPILETIME)
5952                         PL_cv_has_eval = 1;
5953 #endif
5954                 }
5955
5956                 nextchar(pRExC_state);
5957                 if (is_logical) {
5958                     ret = reg_node(pRExC_state, LOGICAL);
5959                     if (!SIZE_ONLY)
5960                         ret->flags = 2;
5961                     REGTAIL(pRExC_state, ret, reganode(pRExC_state, EVAL, n));
5962                     /* deal with the length of this later - MJD */
5963                     return ret;
5964                 }
5965                 ret = reganode(pRExC_state, EVAL, n);
5966                 Set_Node_Length(ret, RExC_parse - parse_start + 1);
5967                 Set_Node_Offset(ret, parse_start);
5968                 return ret;
5969             }
5970             case '(':           /* (?(?{...})...) and (?(?=...)...) */
5971             {
5972                 int is_define= 0;
5973                 if (RExC_parse[0] == '?') {        /* (?(?...)) */
5974                     if (RExC_parse[1] == '=' || RExC_parse[1] == '!'
5975                         || RExC_parse[1] == '<'
5976                         || RExC_parse[1] == '{') { /* Lookahead or eval. */
5977                         I32 flag;
5978                         
5979                         ret = reg_node(pRExC_state, LOGICAL);
5980                         if (!SIZE_ONLY)
5981                             ret->flags = 1;
5982                         REGTAIL(pRExC_state, ret, reg(pRExC_state, 1, &flag,depth+1));
5983                         goto insert_if;
5984                     }
5985                 }
5986                 else if ( RExC_parse[0] == '<'     /* (?(<NAME>)...) */
5987                          || RExC_parse[0] == '\'' ) /* (?('NAME')...) */
5988                 {
5989                     char ch = RExC_parse[0] == '<' ? '>' : '\'';
5990                     char *name_start= RExC_parse++;
5991                     U32 num = 0;
5992                     SV *sv_dat=reg_scan_name(pRExC_state,
5993                         SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
5994                     if (RExC_parse == name_start || *RExC_parse != ch)
5995                         vFAIL2("Sequence (?(%c... not terminated",
5996                             (ch == '>' ? '<' : ch));
5997                     RExC_parse++;
5998                     if (!SIZE_ONLY) {
5999                         num = add_data( pRExC_state, 1, "S" );
6000                         RExC_rxi->data->data[num]=(void*)sv_dat;
6001                         SvREFCNT_inc_simple_void(sv_dat);
6002                     }
6003                     ret = reganode(pRExC_state,NGROUPP,num);
6004                     goto insert_if_check_paren;
6005                 }
6006                 else if (RExC_parse[0] == 'D' &&
6007                          RExC_parse[1] == 'E' &&
6008                          RExC_parse[2] == 'F' &&
6009                          RExC_parse[3] == 'I' &&
6010                          RExC_parse[4] == 'N' &&
6011                          RExC_parse[5] == 'E')
6012                 {
6013                     ret = reganode(pRExC_state,DEFINEP,0);
6014                     RExC_parse +=6 ;
6015                     is_define = 1;
6016                     goto insert_if_check_paren;
6017                 }
6018                 else if (RExC_parse[0] == 'R') {
6019                     RExC_parse++;
6020                     parno = 0;
6021                     if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
6022                         parno = atoi(RExC_parse++);
6023                         while (isDIGIT(*RExC_parse))
6024                             RExC_parse++;
6025                     } else if (RExC_parse[0] == '&') {
6026                         SV *sv_dat;
6027                         RExC_parse++;
6028                         sv_dat = reg_scan_name(pRExC_state,
6029                             SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
6030                         parno = sv_dat ? *((I32 *)SvPVX(sv_dat)) : 0;
6031                     }
6032                     ret = reganode(pRExC_state,INSUBP,parno); 
6033                     goto insert_if_check_paren;
6034                 }
6035                 else if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
6036                     /* (?(1)...) */
6037                     char c;
6038                     parno = atoi(RExC_parse++);
6039
6040                     while (isDIGIT(*RExC_parse))
6041                         RExC_parse++;
6042                     ret = reganode(pRExC_state, GROUPP, parno);
6043
6044                  insert_if_check_paren:
6045                     if ((c = *nextchar(pRExC_state)) != ')')
6046                         vFAIL("Switch condition not recognized");
6047                   insert_if:
6048                     REGTAIL(pRExC_state, ret, reganode(pRExC_state, IFTHEN, 0));
6049                     br = regbranch(pRExC_state, &flags, 1,depth+1);
6050                     if (br == NULL)
6051                         br = reganode(pRExC_state, LONGJMP, 0);
6052                     else
6053                         REGTAIL(pRExC_state, br, reganode(pRExC_state, LONGJMP, 0));
6054                     c = *nextchar(pRExC_state);
6055                     if (flags&HASWIDTH)
6056                         *flagp |= HASWIDTH;
6057                     if (c == '|') {
6058                         if (is_define) 
6059                             vFAIL("(?(DEFINE)....) does not allow branches");
6060                         lastbr = reganode(pRExC_state, IFTHEN, 0); /* Fake one for optimizer. */
6061                         regbranch(pRExC_state, &flags, 1,depth+1);
6062                         REGTAIL(pRExC_state, ret, lastbr);
6063                         if (flags&HASWIDTH)
6064                             *flagp |= HASWIDTH;
6065                         c = *nextchar(pRExC_state);
6066                     }
6067                     else
6068                         lastbr = NULL;
6069                     if (c != ')')
6070                         vFAIL("Switch (?(condition)... contains too many branches");
6071                     ender = reg_node(pRExC_state, TAIL);
6072                     REGTAIL(pRExC_state, br, ender);
6073                     if (lastbr) {
6074                         REGTAIL(pRExC_state, lastbr, ender);
6075                         REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender);
6076                     }
6077                     else
6078                         REGTAIL(pRExC_state, ret, ender);
6079                     RExC_size++; /* XXX WHY do we need this?!!
6080                                     For large programs it seems to be required
6081                                     but I can't figure out why. -- dmq*/
6082                     return ret;
6083                 }
6084                 else {
6085                     vFAIL2("Unknown switch condition (?(%.2s", RExC_parse);
6086                 }
6087             }
6088             case 0:
6089                 RExC_parse--; /* for vFAIL to print correctly */
6090                 vFAIL("Sequence (? incomplete");
6091                 break;
6092             default:
6093                 --RExC_parse;
6094                 parse_flags:      /* (?i) */  
6095             {
6096                 U32 posflags = 0, negflags = 0;
6097                 U32 *flagsp = &posflags;
6098
6099                 while (*RExC_parse) {
6100                     /* && strchr("iogcmsx", *RExC_parse) */
6101                     /* (?g), (?gc) and (?o) are useless here
6102                        and must be globally applied -- japhy */
6103                     switch (*RExC_parse) {
6104                     CASE_STD_PMMOD_FLAGS_PARSE_SET(flagsp);
6105                     case ONCE_PAT_MOD: /* 'o' */
6106                     case GLOBAL_PAT_MOD: /* 'g' */
6107                         if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
6108                             const I32 wflagbit = *RExC_parse == 'o' ? WASTED_O : WASTED_G;
6109                             if (! (wastedflags & wflagbit) ) {
6110                                 wastedflags |= wflagbit;
6111                                 vWARN5(
6112                                     RExC_parse + 1,
6113                                     "Useless (%s%c) - %suse /%c modifier",
6114                                     flagsp == &negflags ? "?-" : "?",
6115                                     *RExC_parse,
6116                                     flagsp == &negflags ? "don't " : "",
6117                                     *RExC_parse
6118                                 );
6119                             }
6120                         }
6121                         break;
6122                         
6123                     case CONTINUE_PAT_MOD: /* 'c' */
6124                         if (SIZE_ONLY && ckWARN(WARN_REGEXP)) {
6125                             if (! (wastedflags & WASTED_C) ) {
6126                                 wastedflags |= WASTED_GC;
6127                                 vWARN3(
6128                                     RExC_parse + 1,
6129                                     "Useless (%sc) - %suse /gc modifier",
6130                                     flagsp == &negflags ? "?-" : "?",
6131                                     flagsp == &negflags ? "don't " : ""
6132                                 );
6133                             }
6134                         }
6135                         break;
6136                     case KEEPCOPY_PAT_MOD: /* 'p' */
6137                         if (flagsp == &negflags) {
6138                             if (SIZE_ONLY)
6139                                 ckWARNreg(RExC_parse + 1,"Useless use of (?-p)");
6140                         } else {
6141                             *flagsp |= RXf_PMf_KEEPCOPY;
6142                         }
6143                         break;
6144                     case '-':
6145                         if (flagsp == &negflags) {
6146                             RExC_parse++;
6147                             vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
6148                             /*NOTREACHED*/
6149                         }
6150                         flagsp = &negflags;
6151                         wastedflags = 0;  /* reset so (?g-c) warns twice */
6152                         break;
6153                     case ':':
6154                         paren = ':';
6155                         /*FALLTHROUGH*/
6156                     case ')':
6157                         RExC_flags |= posflags;
6158                         RExC_flags &= ~negflags;
6159                         if (paren != ':') {
6160                             oregflags |= posflags;
6161                             oregflags &= ~negflags;
6162                         }
6163                         nextchar(pRExC_state);
6164                         if (paren != ':') {
6165                             *flagp = TRYAGAIN;
6166                             return NULL;
6167                         } else {
6168                             ret = NULL;
6169                             goto parse_rest;
6170                         }
6171                         /*NOTREACHED*/
6172                     default:
6173                         RExC_parse++;
6174                         vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
6175                         /*NOTREACHED*/
6176                     }                           
6177                     ++RExC_parse;
6178                 }
6179             }} /* one for the default block, one for the switch */
6180         }
6181         else {                  /* (...) */
6182           capturing_parens:
6183             parno = RExC_npar;
6184             RExC_npar++;
6185             
6186             ret = reganode(pRExC_state, OPEN, parno);
6187             if (!SIZE_ONLY ){
6188                 if (!RExC_nestroot) 
6189                     RExC_nestroot = parno;
6190                 if (RExC_seen & REG_SEEN_RECURSE
6191                     && !RExC_open_parens[parno-1])
6192                 {
6193                     DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
6194                         "Setting open paren #%"IVdf" to %d\n", 
6195                         (IV)parno, REG_NODE_NUM(ret)));
6196                     RExC_open_parens[parno-1]= ret;
6197                 }
6198             }
6199             Set_Node_Length(ret, 1); /* MJD */
6200             Set_Node_Offset(ret, RExC_parse); /* MJD */
6201             is_open = 1;
6202         }
6203     }
6204     else                        /* ! paren */
6205         ret = NULL;
6206    
6207    parse_rest:
6208     /* Pick up the branches, linking them together. */
6209     parse_start = RExC_parse;   /* MJD */
6210     br = regbranch(pRExC_state, &flags, 1,depth+1);
6211
6212     if (freeze_paren) {
6213         if (RExC_npar > after_freeze)
6214             after_freeze = RExC_npar;
6215         RExC_npar = freeze_paren;
6216     }
6217
6218     /*     branch_len = (paren != 0); */
6219
6220     if (br == NULL)
6221         return(NULL);
6222     if (*RExC_parse == '|') {
6223         if (!SIZE_ONLY && RExC_extralen) {
6224             reginsert(pRExC_state, BRANCHJ, br, depth+1);
6225         }
6226         else {                  /* MJD */
6227             reginsert(pRExC_state, BRANCH, br, depth+1);
6228             Set_Node_Length(br, paren != 0);
6229             Set_Node_Offset_To_R(br-RExC_emit_start, parse_start-RExC_start);
6230         }
6231         have_branch = 1;
6232         if (SIZE_ONLY)
6233             RExC_extralen += 1;         /* For BRANCHJ-BRANCH. */
6234     }
6235     else if (paren == ':') {
6236         *flagp |= flags&SIMPLE;
6237     }
6238     if (is_open) {                              /* Starts with OPEN. */
6239         REGTAIL(pRExC_state, ret, br);          /* OPEN -> first. */
6240     }
6241     else if (paren != '?')              /* Not Conditional */
6242         ret = br;
6243     *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
6244     lastbr = br;
6245     while (*RExC_parse == '|') {
6246         if (!SIZE_ONLY && RExC_extralen) {
6247             ender = reganode(pRExC_state, LONGJMP,0);
6248             REGTAIL(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender); /* Append to the previous. */
6249         }
6250         if (SIZE_ONLY)
6251             RExC_extralen += 2;         /* Account for LONGJMP. */
6252         nextchar(pRExC_state);
6253         if (freeze_paren) {
6254             if (RExC_npar > after_freeze)
6255                 after_freeze = RExC_npar;
6256             RExC_npar = freeze_paren;       
6257         }
6258         br = regbranch(pRExC_state, &flags, 0, depth+1);
6259
6260         if (br == NULL)
6261             return(NULL);
6262         REGTAIL(pRExC_state, lastbr, br);               /* BRANCH -> BRANCH. */
6263         lastbr = br;
6264         *flagp |= flags & (SPSTART | HASWIDTH | POSTPONED);
6265     }
6266
6267     if (have_branch || paren != ':') {
6268         /* Make a closing node, and hook it on the end. */
6269         switch (paren) {
6270         case ':':
6271             ender = reg_node(pRExC_state, TAIL);
6272             break;
6273         case 1:
6274             ender = reganode(pRExC_state, CLOSE, parno);
6275             if (!SIZE_ONLY && RExC_seen & REG_SEEN_RECURSE) {
6276                 DEBUG_OPTIMISE_MORE_r(PerlIO_printf(Perl_debug_log,
6277                         "Setting close paren #%"IVdf" to %d\n", 
6278                         (IV)parno, REG_NODE_NUM(ender)));
6279                 RExC_close_parens[parno-1]= ender;
6280                 if (RExC_nestroot == parno) 
6281                     RExC_nestroot = 0;
6282             }       
6283             Set_Node_Offset(ender,RExC_parse+1); /* MJD */
6284             Set_Node_Length(ender,1); /* MJD */
6285             break;
6286         case '<':
6287         case ',':
6288         case '=':
6289         case '!':
6290             *flagp &= ~HASWIDTH;
6291             /* FALL THROUGH */
6292         case '>':
6293             ender = reg_node(pRExC_state, SUCCEED);
6294             break;
6295         case 0:
6296             ender = reg_node(pRExC_state, END);
6297             if (!SIZE_ONLY) {
6298                 assert(!RExC_opend); /* there can only be one! */
6299                 RExC_opend = ender;
6300             }
6301             break;
6302         }
6303         REGTAIL(pRExC_state, lastbr, ender);
6304
6305         if (have_branch && !SIZE_ONLY) {
6306             if (depth==1)
6307                 RExC_seen |= REG_TOP_LEVEL_BRANCHES;
6308
6309             /* Hook the tails of the branches to the closing node. */
6310             for (br = ret; br; br = regnext(br)) {
6311                 const U8 op = PL_regkind[OP(br)];
6312                 if (op == BRANCH) {
6313                     REGTAIL_STUDY(pRExC_state, NEXTOPER(br), ender);
6314                 }
6315                 else if (op == BRANCHJ) {
6316                     REGTAIL_STUDY(pRExC_state, NEXTOPER(NEXTOPER(br)), ender);
6317                 }
6318             }
6319         }
6320     }
6321
6322     {
6323         const char *p;
6324         static const char parens[] = "=!<,>";
6325
6326         if (paren && (p = strchr(parens, paren))) {
6327             U8 node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
6328             int flag = (p - parens) > 1;
6329
6330             if (paren == '>')
6331                 node = SUSPEND, flag = 0;
6332             reginsert(pRExC_state, node,ret, depth+1);
6333             Set_Node_Cur_Length(ret);
6334             Set_Node_Offset(ret, parse_start + 1);
6335             ret->flags = flag;
6336             REGTAIL_STUDY(pRExC_state, ret, reg_node(pRExC_state, TAIL));
6337         }
6338     }
6339
6340     /* Check for proper termination. */
6341     if (paren) {
6342         RExC_flags = oregflags;
6343         if (RExC_parse >= RExC_end || *nextchar(pRExC_state) != ')') {
6344             RExC_parse = oregcomp_parse;
6345             vFAIL("Unmatched (");
6346         }
6347     }
6348     else if (!paren && RExC_parse < RExC_end) {
6349         if (*RExC_parse == ')') {
6350             RExC_parse++;
6351             vFAIL("Unmatched )");
6352         }
6353         else
6354             FAIL("Junk on end of regexp");      /* "Can't happen". */
6355         /* NOTREACHED */
6356     }
6357     if (after_freeze)
6358         RExC_npar = after_freeze;
6359     return(ret);
6360 }
6361
6362 /*
6363  - regbranch - one alternative of an | operator
6364  *
6365  * Implements the concatenation operator.
6366  */
6367 STATIC regnode *
6368 S_regbranch(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, I32 first, U32 depth)
6369 {
6370     dVAR;
6371     register regnode *ret;
6372     register regnode *chain = NULL;
6373     register regnode *latest;
6374     I32 flags = 0, c = 0;
6375     GET_RE_DEBUG_FLAGS_DECL;
6376
6377     PERL_ARGS_ASSERT_REGBRANCH;
6378
6379     DEBUG_PARSE("brnc");
6380
6381     if (first)
6382         ret = NULL;
6383     else {
6384         if (!SIZE_ONLY && RExC_extralen)
6385             ret = reganode(pRExC_state, BRANCHJ,0);
6386         else {
6387             ret = reg_node(pRExC_state, BRANCH);
6388             Set_Node_Length(ret, 1);
6389         }
6390     }
6391         
6392     if (!first && SIZE_ONLY)
6393         RExC_extralen += 1;                     /* BRANCHJ */
6394
6395     *flagp = WORST;                     /* Tentatively. */
6396
6397     RExC_parse--;
6398     nextchar(pRExC_state);
6399     while (RExC_parse < RExC_end && *RExC_parse != '|' && *RExC_parse != ')') {
6400         flags &= ~TRYAGAIN;
6401         latest = regpiece(pRExC_state, &flags,depth+1);
6402         if (latest == NULL) {
6403             if (flags & TRYAGAIN)
6404                 continue;
6405             return(NULL);
6406         }
6407         else if (ret == NULL)
6408             ret = latest;
6409         *flagp |= flags&(HASWIDTH|POSTPONED);
6410         if (chain == NULL)      /* First piece. */
6411             *flagp |= flags&SPSTART;
6412         else {
6413             RExC_naughty++;
6414             REGTAIL(pRExC_state, chain, latest);
6415         }
6416         chain = latest;
6417         c++;
6418     }
6419     if (chain == NULL) {        /* Loop ran zero times. */
6420         chain = reg_node(pRExC_state, NOTHING);
6421         if (ret == NULL)
6422             ret = chain;
6423     }
6424     if (c == 1) {
6425         *flagp |= flags&SIMPLE;
6426     }
6427
6428     return ret;
6429 }
6430
6431 /*
6432  - regpiece - something followed by possible [*+?]
6433  *
6434  * Note that the branching code sequences used for ? and the general cases
6435  * of * and + are somewhat optimized:  they use the same NOTHING node as
6436  * both the endmarker for their branch list and the body of the last branch.
6437  * It might seem that this node could be dispensed with entirely, but the
6438  * endmarker role is not redundant.
6439  */
6440 STATIC regnode *
6441 S_regpiece(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
6442 {
6443     dVAR;
6444     register regnode *ret;
6445     register char op;
6446     register char *next;
6447     I32 flags;
6448     const char * const origparse = RExC_parse;
6449     I32 min;
6450     I32 max = REG_INFTY;
6451     char *parse_start;
6452     const char *maxpos = NULL;
6453     GET_RE_DEBUG_FLAGS_DECL;
6454
6455     PERL_ARGS_ASSERT_REGPIECE;
6456
6457     DEBUG_PARSE("piec");
6458
6459     ret = regatom(pRExC_state, &flags,depth+1);
6460     if (ret == NULL) {
6461         if (flags & TRYAGAIN)
6462             *flagp |= TRYAGAIN;
6463         return(NULL);
6464     }
6465
6466     op = *RExC_parse;
6467
6468     if (op == '{' && regcurly(RExC_parse)) {
6469         maxpos = NULL;
6470         parse_start = RExC_parse; /* MJD */
6471         next = RExC_parse + 1;
6472         while (isDIGIT(*next) || *next == ',') {
6473             if (*next == ',') {
6474                 if (maxpos)
6475                     break;
6476                 else
6477                     maxpos = next;
6478             }
6479             next++;
6480         }
6481         if (*next == '}') {             /* got one */
6482             if (!maxpos)
6483                 maxpos = next;
6484             RExC_parse++;
6485             min = atoi(RExC_parse);
6486             if (*maxpos == ',')
6487                 maxpos++;
6488             else
6489                 maxpos = RExC_parse;
6490             max = atoi(maxpos);
6491             if (!max && *maxpos != '0')
6492                 max = REG_INFTY;                /* meaning "infinity" */
6493             else if (max >= REG_INFTY)
6494                 vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
6495             RExC_parse = next;
6496             nextchar(pRExC_state);
6497
6498         do_curly:
6499             if ((flags&SIMPLE)) {
6500                 RExC_naughty += 2 + RExC_naughty / 2;
6501                 reginsert(pRExC_state, CURLY, ret, depth+1);
6502                 Set_Node_Offset(ret, parse_start+1); /* MJD */
6503                 Set_Node_Cur_Length(ret);
6504             }
6505             else {
6506                 regnode * const w = reg_node(pRExC_state, WHILEM);
6507
6508                 w->flags = 0;
6509                 REGTAIL(pRExC_state, ret, w);
6510                 if (!SIZE_ONLY && RExC_extralen) {
6511                     reginsert(pRExC_state, LONGJMP,ret, depth+1);
6512                     reginsert(pRExC_state, NOTHING,ret, depth+1);
6513                     NEXT_OFF(ret) = 3;  /* Go over LONGJMP. */
6514                 }
6515                 reginsert(pRExC_state, CURLYX,ret, depth+1);
6516                                 /* MJD hk */
6517                 Set_Node_Offset(ret, parse_start+1);
6518                 Set_Node_Length(ret,
6519                                 op == '{' ? (RExC_parse - parse_start) : 1);
6520
6521                 if (!SIZE_ONLY && RExC_extralen)
6522                     NEXT_OFF(ret) = 3;  /* Go over NOTHING to LONGJMP. */
6523                 REGTAIL(pRExC_state, ret, reg_node(pRExC_state, NOTHING));
6524                 if (SIZE_ONLY)
6525                     RExC_whilem_seen++, RExC_extralen += 3;
6526                 RExC_naughty += 4 + RExC_naughty;       /* compound interest */
6527             }
6528             ret->flags = 0;
6529
6530             if (min > 0)
6531                 *flagp = WORST;
6532             if (max > 0)
6533                 *flagp |= HASWIDTH;
6534             if (max < min)
6535                 vFAIL("Can't do {n,m} with n > m");
6536             if (!SIZE_ONLY) {
6537                 ARG1_SET(ret, (U16)min);
6538                 ARG2_SET(ret, (U16)max);
6539             }
6540
6541             goto nest_check;
6542         }
6543     }
6544
6545     if (!ISMULT1(op)) {
6546         *flagp = flags;
6547         return(ret);
6548     }
6549
6550 #if 0                           /* Now runtime fix should be reliable. */
6551
6552     /* if this is reinstated, don't forget to put this back into perldiag:
6553
6554             =item Regexp *+ operand could be empty at {#} in regex m/%s/
6555
6556            (F) The part of the regexp subject to either the * or + quantifier
6557            could match an empty string. The {#} shows in the regular
6558            expression about where the problem was discovered.
6559
6560     */
6561
6562     if (!(flags&HASWIDTH) && op != '?')
6563       vFAIL("Regexp *+ operand could be empty");
6564 #endif
6565
6566     parse_start = RExC_parse;
6567     nextchar(pRExC_state);
6568
6569     *flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
6570
6571     if (op == '*' && (flags&SIMPLE)) {
6572         reginsert(pRExC_state, STAR, ret, depth+1);
6573         ret->flags = 0;
6574         RExC_naughty += 4;
6575     }
6576     else if (op == '*') {
6577         min = 0;
6578         goto do_curly;
6579     }
6580     else if (op == '+' && (flags&SIMPLE)) {
6581         reginsert(pRExC_state, PLUS, ret, depth+1);
6582         ret->flags = 0;
6583         RExC_naughty += 3;
6584     }
6585     else if (op == '+') {
6586         min = 1;
6587         goto do_curly;
6588     }
6589     else if (op == '?') {
6590         min = 0; max = 1;
6591         goto do_curly;
6592     }
6593   nest_check:
6594     if (!SIZE_ONLY && !(flags&(HASWIDTH|POSTPONED)) && max > REG_INFTY/3) {
6595         ckWARN3reg(RExC_parse,
6596                    "%.*s matches null string many times",
6597                    (int)(RExC_parse >= origparse ? RExC_parse - origparse : 0),
6598                    origparse);
6599     }
6600
6601     if (RExC_parse < RExC_end && *RExC_parse == '?') {
6602         nextchar(pRExC_state);
6603         reginsert(pRExC_state, MINMOD, ret, depth+1);
6604         REGTAIL(pRExC_state, ret, ret + NODE_STEP_REGNODE);
6605     }
6606 #ifndef REG_ALLOW_MINMOD_SUSPEND
6607     else
6608 #endif
6609     if (RExC_parse < RExC_end && *RExC_parse == '+') {
6610         regnode *ender;
6611         nextchar(pRExC_state);
6612         ender = reg_node(pRExC_state, SUCCEED);
6613         REGTAIL(pRExC_state, ret, ender);
6614         reginsert(pRExC_state, SUSPEND, ret, depth+1);
6615         ret->flags = 0;
6616         ender = reg_node(pRExC_state, TAIL);
6617         REGTAIL(pRExC_state, ret, ender);
6618         /*ret= ender;*/
6619     }
6620
6621     if (RExC_parse < RExC_end && ISMULT2(RExC_parse)) {
6622         RExC_parse++;
6623         vFAIL("Nested quantifiers");
6624     }
6625
6626     return(ret);
6627 }
6628
6629
6630 /* reg_namedseq(pRExC_state,UVp)
6631    
6632    This is expected to be called by a parser routine that has 
6633    recognized '\N' and needs to handle the rest. RExC_parse is
6634    expected to point at the first char following the N at the time
6635    of the call.
6636
6637    The \N may be inside (indicated by valuep not being NULL) or outside a
6638    character class.
6639
6640    \N may begin either a named sequence, or if outside a character class, mean
6641    to match a non-newline.  For non single-quoted regexes, the tokenizer has
6642    attempted to decide which, and in the case of a named sequence converted it
6643    into one of the forms: \N{} (if the sequence is null), or \N{U+c1.c2...},
6644    where c1... are the characters in the sequence.  For single-quoted regexes,
6645    the tokenizer passes the \N sequence through unchanged; this code will not
6646    attempt to determine this nor expand those.  The net effect is that if the
6647    beginning of the passed-in pattern isn't '{U+' or there is no '}', it
6648    signals that this \N occurrence means to match a non-newline.
6649    
6650    Only the \N{U+...} form should occur in a character class, for the same
6651    reason that '.' inside a character class means to just match a period: it
6652    just doesn't make sense.
6653    
6654    If valuep is non-null then it is assumed that we are parsing inside 
6655    of a charclass definition and the first codepoint in the resolved
6656    string is returned via *valuep and the routine will return NULL. 
6657    In this mode if a multichar string is returned from the charnames 
6658    handler, a warning will be issued, and only the first char in the 
6659    sequence will be examined. If the string returned is zero length
6660    then the value of *valuep is undefined and NON-NULL will 
6661    be returned to indicate failure. (This will NOT be a valid pointer 
6662    to a regnode.)
6663    
6664    If valuep is null then it is assumed that we are parsing normal text and a
6665    new EXACT node is inserted into the program containing the resolved string,
6666    and a pointer to the new node is returned.  But if the string is zero length
6667    a NOTHING node is emitted instead.
6668
6669    On success RExC_parse is set to the char following the endbrace.
6670    Parsing failures will generate a fatal error via vFAIL(...)
6671  */
6672 STATIC regnode *
6673 S_reg_namedseq(pTHX_ RExC_state_t *pRExC_state, UV *valuep, I32 *flagp)
6674 {
6675     char * endbrace;    /* '}' following the name */
6676     regnode *ret = NULL;
6677 #ifdef DEBUGGING
6678     char* parse_start = RExC_parse - 2;     /* points to the '\N' */
6679 #endif
6680     char* p;
6681
6682     GET_RE_DEBUG_FLAGS_DECL;
6683  
6684     PERL_ARGS_ASSERT_REG_NAMEDSEQ;
6685
6686     GET_RE_DEBUG_FLAGS;
6687
6688     /* The [^\n] meaning of \N ignores spaces and comments under the /x
6689      * modifier.  The other meaning does not */
6690     p = (RExC_flags & RXf_PMf_EXTENDED)
6691         ? regwhite( pRExC_state, RExC_parse )
6692         : RExC_parse;
6693    
6694     /* Disambiguate between \N meaning a named character versus \N meaning
6695      * [^\n].  The former is assumed when it can't be the latter. */
6696     if (*p != '{' || regcurly(p)) {
6697         RExC_parse = p;
6698         if (valuep) {
6699             /* no bare \N in a charclass */
6700             vFAIL("\\N in a character class must be a named character: \\N{...}");
6701         }
6702         nextchar(pRExC_state);
6703         ret = reg_node(pRExC_state, REG_ANY);
6704         *flagp |= HASWIDTH|SIMPLE;
6705         RExC_naughty++;
6706         RExC_parse--;
6707         Set_Node_Length(ret, 1); /* MJD */
6708         return ret;
6709     }
6710
6711     /* Here, we have decided it should be a named sequence */
6712
6713     /* The test above made sure that the next real character is a '{', but
6714      * under the /x modifier, it could be separated by space (or a comment and
6715      * \n) and this is not allowed (for consistency with \x{...} and the
6716      * tokenizer handling of \N{NAME}). */
6717     if (*RExC_parse != '{') {
6718         vFAIL("Missing braces on \\N{}");
6719     }
6720
6721     RExC_parse++;       /* Skip past the '{' */
6722
6723     if (! (endbrace = strchr(RExC_parse, '}')) /* no trailing brace */
6724         || ! (endbrace == RExC_parse            /* nothing between the {} */
6725               || (endbrace - RExC_parse >= 2    /* U+ (bad hex is checked below */
6726                   && strnEQ(RExC_parse, "U+", 2)))) /* for a better error msg) */
6727     {
6728         if (endbrace) RExC_parse = endbrace;    /* position msg's '<--HERE' */
6729         vFAIL("\\N{NAME} must be resolved by the lexer");
6730     }
6731
6732     if (endbrace == RExC_parse) {   /* empty: \N{} */
6733         if (! valuep) {
6734             RExC_parse = endbrace + 1;  
6735             return reg_node(pRExC_state,NOTHING);
6736         }
6737
6738         if (SIZE_ONLY) {
6739             ckWARNreg(RExC_parse,
6740                     "Ignoring zero length \\N{} in character class"
6741             );
6742             RExC_parse = endbrace + 1;  
6743         }
6744         *valuep = 0;
6745         return (regnode *) &RExC_parse; /* Invalid regnode pointer */
6746     }
6747
6748     RExC_utf8 = 1;      /* named sequences imply Unicode semantics */
6749     RExC_parse += 2;    /* Skip past the 'U+' */
6750
6751     if (valuep) {   /* In a bracketed char class */
6752         /* We only pay attention to the first char of 
6753         multichar strings being returned. I kinda wonder
6754         if this makes sense as it does change the behaviour
6755         from earlier versions, OTOH that behaviour was broken
6756         as well. XXX Solution is to recharacterize as
6757         [rest-of-class]|multi1|multi2... */
6758
6759         STRLEN length_of_hex;
6760         I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
6761             | PERL_SCAN_DISALLOW_PREFIX
6762             | (SIZE_ONLY ? PERL_SCAN_SILENT_ILLDIGIT : 0);
6763     
6764         char * endchar = RExC_parse + strcspn(RExC_parse, ".}");
6765         if (endchar < endbrace) {
6766             ckWARNreg(endchar, "Using just the first character returned by \\N{} in character class");
6767         }
6768
6769         length_of_hex = (STRLEN)(endchar - RExC_parse);
6770         *valuep = grok_hex(RExC_parse, &length_of_hex, &flags, NULL);
6771
6772         /* The tokenizer should have guaranteed validity, but it's possible to
6773          * bypass it by using single quoting, so check */
6774         if (length_of_hex == 0
6775             || length_of_hex != (STRLEN)(endchar - RExC_parse) )
6776         {
6777             RExC_parse += length_of_hex;        /* Includes all the valid */
6778             RExC_parse += (RExC_orig_utf8)      /* point to after 1st invalid */
6779                             ? UTF8SKIP(RExC_parse)
6780                             : 1;
6781             /* Guard against malformed utf8 */
6782             if (RExC_parse >= endchar) RExC_parse = endchar;
6783             vFAIL("Invalid hexadecimal number in \\N{U+...}");
6784         }    
6785
6786         RExC_parse = endbrace + 1;
6787         if (endchar == endbrace) return NULL;
6788
6789         ret = (regnode *) &RExC_parse;  /* Invalid regnode pointer */
6790     }
6791     else {      /* Not a char class */
6792         char *s;            /* String to put in generated EXACT node */
6793         STRLEN len = 0;     /* Its current length */
6794         char *endchar;      /* Points to '.' or '}' ending cur char in the input
6795                                stream */
6796
6797         ret = reg_node(pRExC_state,
6798                         (U8)(FOLD ? (LOC ? EXACTFL : EXACTF) : EXACT));
6799         s= STRING(ret);
6800
6801         /* Exact nodes can hold only a U8 length's of text = 255.  Loop through
6802          * the input which is of the form now 'c1.c2.c3...}' until find the
6803          * ending brace or exeed length 255.  The characters that exceed this
6804          * limit are dropped.  The limit could be relaxed should it become
6805          * desirable by reparsing this as (?:\N{NAME}), so could generate
6806          * multiple EXACT nodes, as is done for just regular input.  But this
6807          * is primarily a named character, and not intended to be a huge long
6808          * string, so 255 bytes should be good enough */
6809         while (1) {
6810             STRLEN length_of_hex;
6811             I32 grok_flags = PERL_SCAN_ALLOW_UNDERSCORES
6812                             | PERL_SCAN_DISALLOW_PREFIX
6813                             | (SIZE_ONLY ? PERL_SCAN_SILENT_ILLDIGIT : 0);
6814             UV cp;  /* Ord of current character */
6815
6816             /* Code points are separated by dots.  If none, there is only one
6817              * code point, and is terminated by the brace */
6818             endchar = RExC_parse + strcspn(RExC_parse, ".}");
6819
6820             /* The values are Unicode even on EBCDIC machines */
6821             length_of_hex = (STRLEN)(endchar - RExC_parse);
6822             cp = grok_hex(RExC_parse, &length_of_hex, &grok_flags, NULL);
6823             if ( length_of_hex == 0 
6824                 || length_of_hex != (STRLEN)(endchar - RExC_parse) )
6825             {
6826                 RExC_parse += length_of_hex;        /* Includes all the valid */
6827                 RExC_parse += (RExC_orig_utf8)  /* point to after 1st invalid */
6828                                 ? UTF8SKIP(RExC_parse)
6829                                 : 1;
6830                 /* Guard against malformed utf8 */
6831                 if (RExC_parse >= endchar) RExC_parse = endchar;
6832                 vFAIL("Invalid hexadecimal number in \\N{U+...}");
6833             }    
6834
6835             if (! FOLD) {       /* Not folding, just append to the string */
6836                 STRLEN unilen;
6837
6838                 /* Quit before adding this character if would exceed limit */
6839                 if (len + UNISKIP(cp) > U8_MAX) break;
6840
6841                 unilen = reguni(pRExC_state, cp, s);
6842                 if (unilen > 0) {
6843                     s   += unilen;
6844                     len += unilen;
6845                 }
6846             } else {    /* Folding, output the folded equivalent */
6847                 STRLEN foldlen,numlen;
6848                 U8 tmpbuf[UTF8_MAXBYTES_CASE+1], *foldbuf;
6849                 cp = toFOLD_uni(cp, tmpbuf, &foldlen);
6850
6851                 /* Quit before exceeding size limit */
6852                 if (len + foldlen > U8_MAX) break;
6853                 
6854                 for (foldbuf = tmpbuf;
6855                     foldlen;
6856                     foldlen -= numlen) 
6857                 {
6858                     cp = utf8_to_uvchr(foldbuf, &numlen);
6859                     if (numlen > 0) {
6860                         const STRLEN unilen = reguni(pRExC_state, cp, s);
6861                         s       += unilen;
6862                         len     += unilen;
6863                         /* In EBCDIC the numlen and unilen can differ. */
6864                         foldbuf += numlen;
6865                         if (numlen >= foldlen)
6866                             break;
6867                     }
6868                     else
6869                         break; /* "Can't happen." */
6870                 }                          
6871             }
6872
6873             /* Point to the beginning of the next character in the sequence. */
6874             RExC_parse = endchar + 1;
6875
6876             /* Quit if no more characters */
6877             if (RExC_parse >= endbrace) break;
6878         }
6879
6880
6881         if (SIZE_ONLY) {
6882             if (RExC_parse < endbrace) {
6883                 ckWARNreg(RExC_parse - 1,
6884                           "Using just the first characters returned by \\N{}");
6885             }
6886
6887             RExC_size += STR_SZ(len);
6888         } else {
6889             STR_LEN(ret) = len;
6890             RExC_emit += STR_SZ(len);
6891         }
6892
6893         RExC_parse = endbrace + 1;
6894
6895         *flagp |= HASWIDTH; /* Not SIMPLE, as that causes the engine to fail
6896                                with malformed in t/re/pat_advanced.t */
6897         RExC_parse --;
6898         Set_Node_Cur_Length(ret); /* MJD */
6899         nextchar(pRExC_state);
6900     }
6901
6902     return ret;
6903 }
6904
6905
6906 /*
6907  * reg_recode
6908  *
6909  * It returns the code point in utf8 for the value in *encp.
6910  *    value: a code value in the source encoding
6911  *    encp:  a pointer to an Encode object
6912  *
6913  * If the result from Encode is not a single character,
6914  * it returns U+FFFD (Replacement character) and sets *encp to NULL.
6915  */
6916 STATIC UV
6917 S_reg_recode(pTHX_ const char value, SV **encp)
6918 {
6919     STRLEN numlen = 1;
6920     SV * const sv = newSVpvn_flags(&value, numlen, SVs_TEMP);
6921     const char * const s = *encp ? sv_recode_to_utf8(sv, *encp) : SvPVX(sv);
6922     const STRLEN newlen = SvCUR(sv);
6923     UV uv = UNICODE_REPLACEMENT;
6924
6925     PERL_ARGS_ASSERT_REG_RECODE;
6926
6927     if (newlen)
6928         uv = SvUTF8(sv)
6929              ? utf8n_to_uvchr((U8*)s, newlen, &numlen, UTF8_ALLOW_DEFAULT)
6930              : *(U8*)s;
6931
6932     if (!newlen || numlen != newlen) {
6933         uv = UNICODE_REPLACEMENT;
6934         *encp = NULL;
6935     }
6936     return uv;
6937 }
6938
6939
6940 /*
6941  - regatom - the lowest level
6942
6943    Try to identify anything special at the start of the pattern. If there
6944    is, then handle it as required. This may involve generating a single regop,
6945    such as for an assertion; or it may involve recursing, such as to
6946    handle a () structure.
6947
6948    If the string doesn't start with something special then we gobble up
6949    as much literal text as we can.
6950
6951    Once we have been able to handle whatever type of thing started the
6952    sequence, we return.
6953
6954    Note: we have to be careful with escapes, as they can be both literal
6955    and special, and in the case of \10 and friends can either, depending
6956    on context. Specifically there are two seperate switches for handling
6957    escape sequences, with the one for handling literal escapes requiring
6958    a dummy entry for all of the special escapes that are actually handled
6959    by the other.
6960 */
6961
6962 STATIC regnode *
6963 S_regatom(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, U32 depth)
6964 {
6965     dVAR;
6966     register regnode *ret = NULL;
6967     I32 flags;
6968     char *parse_start = RExC_parse;
6969     GET_RE_DEBUG_FLAGS_DECL;
6970     DEBUG_PARSE("atom");
6971     *flagp = WORST;             /* Tentatively. */
6972
6973     PERL_ARGS_ASSERT_REGATOM;
6974
6975 tryagain:
6976     switch ((U8)*RExC_parse) {
6977     case '^':
6978         RExC_seen_zerolen++;
6979         nextchar(pRExC_state);
6980         if (RExC_flags & RXf_PMf_MULTILINE)
6981             ret = reg_node(pRExC_state, MBOL);
6982         else if (RExC_flags & RXf_PMf_SINGLELINE)
6983             ret = reg_node(pRExC_state, SBOL);
6984         else
6985             ret = reg_node(pRExC_state, BOL);
6986         Set_Node_Length(ret, 1); /* MJD */
6987         break;
6988     case '$':
6989         nextchar(pRExC_state);
6990         if (*RExC_parse)
6991             RExC_seen_zerolen++;
6992         if (RExC_flags & RXf_PMf_MULTILINE)
6993             ret = reg_node(pRExC_state, MEOL);
6994         else if (RExC_flags & RXf_PMf_SINGLELINE)
6995             ret = reg_node(pRExC_state, SEOL);
6996         else
6997             ret = reg_node(pRExC_state, EOL);
6998         Set_Node_Length(ret, 1); /* MJD */
6999         break;
7000     case '.':
7001         nextchar(pRExC_state);
7002         if (RExC_flags & RXf_PMf_SINGLELINE)
7003             ret = reg_node(pRExC_state, SANY);
7004         else
7005             ret = reg_node(pRExC_state, REG_ANY);
7006         *flagp |= HASWIDTH|SIMPLE;
7007         RExC_naughty++;
7008         Set_Node_Length(ret, 1); /* MJD */
7009         break;
7010     case '[':
7011     {
7012         char * const oregcomp_parse = ++RExC_parse;
7013         ret = regclass(pRExC_state,depth+1);
7014         if (*RExC_parse != ']') {
7015             RExC_parse = oregcomp_parse;
7016             vFAIL("Unmatched [");
7017         }
7018         nextchar(pRExC_state);
7019         *flagp |= HASWIDTH|SIMPLE;
7020         Set_Node_Length(ret, RExC_parse - oregcomp_parse + 1); /* MJD */
7021         break;
7022     }
7023     case '(':
7024         nextchar(pRExC_state);
7025         ret = reg(pRExC_state, 1, &flags,depth+1);
7026         if (ret == NULL) {
7027                 if (flags & TRYAGAIN) {
7028                     if (RExC_parse == RExC_end) {
7029                          /* Make parent create an empty node if needed. */
7030                         *flagp |= TRYAGAIN;
7031                         return(NULL);
7032                     }
7033                     goto tryagain;
7034                 }
7035                 return(NULL);
7036         }
7037         *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE|POSTPONED);
7038         break;
7039     case '|':
7040     case ')':
7041         if (flags & TRYAGAIN) {
7042             *flagp |= TRYAGAIN;
7043             return NULL;
7044         }
7045         vFAIL("Internal urp");
7046                                 /* Supposed to be caught earlier. */
7047         break;
7048     case '{':
7049         if (!regcurly(RExC_parse)) {
7050             RExC_parse++;
7051             goto defchar;
7052         }
7053         /* FALL THROUGH */
7054     case '?':
7055     case '+':
7056     case '*':
7057         RExC_parse++;
7058         vFAIL("Quantifier follows nothing");
7059         break;
7060     case 0xDF:
7061     case 0xC3:
7062     case 0xCE:
7063         do_foldchar:
7064         if (!LOC && FOLD) {
7065             U32 len,cp;
7066             len=0; /* silence a spurious compiler warning */
7067             if ((cp = what_len_TRICKYFOLD_safe(RExC_parse,RExC_end,UTF,len))) {
7068                 *flagp |= HASWIDTH; /* could be SIMPLE too, but needs a handler in regexec.regrepeat */
7069                 RExC_parse+=len-1; /* we get one from nextchar() as well. :-( */
7070                 ret = reganode(pRExC_state, FOLDCHAR, cp);
7071                 Set_Node_Length(ret, 1); /* MJD */
7072                 nextchar(pRExC_state); /* kill whitespace under /x */
7073                 return ret;
7074             }
7075         }
7076         goto outer_default;
7077     case '\\':
7078         /* Special Escapes
7079
7080            This switch handles escape sequences that resolve to some kind
7081            of special regop and not to literal text. Escape sequnces that
7082            resolve to literal text are handled below in the switch marked
7083            "Literal Escapes".
7084
7085            Every entry in this switch *must* have a corresponding entry
7086            in the literal escape switch. However, the opposite is not
7087            required, as the default for this switch is to jump to the
7088            literal text handling code.
7089         */
7090         switch ((U8)*++RExC_parse) {
7091         case 0xDF:
7092         case 0xC3:
7093         case 0xCE:
7094                    goto do_foldchar;        
7095         /* Special Escapes */
7096         case 'A':
7097             RExC_seen_zerolen++;
7098             ret = reg_node(pRExC_state, SBOL);
7099             *flagp |= SIMPLE;
7100             goto finish_meta_pat;
7101         case 'G':
7102             ret = reg_node(pRExC_state, GPOS);
7103             RExC_seen |= REG_SEEN_GPOS;
7104             *flagp |= SIMPLE;
7105             goto finish_meta_pat;
7106         case 'K':
7107             RExC_seen_zerolen++;
7108             ret = reg_node(pRExC_state, KEEPS);
7109             *flagp |= SIMPLE;
7110             /* XXX:dmq : disabling in-place substitution seems to
7111              * be necessary here to avoid cases of memory corruption, as
7112              * with: C<$_="x" x 80; s/x\K/y/> -- rgs
7113              */
7114             RExC_seen |= REG_SEEN_LOOKBEHIND;
7115             goto finish_meta_pat;
7116         case 'Z':
7117             ret = reg_node(pRExC_state, SEOL);
7118             *flagp |= SIMPLE;
7119             RExC_seen_zerolen++;                /* Do not optimize RE away */
7120             goto finish_meta_pat;
7121         case 'z':
7122             ret = reg_node(pRExC_state, EOS);
7123             *flagp |= SIMPLE;
7124             RExC_seen_zerolen++;                /* Do not optimize RE away */
7125             goto finish_meta_pat;
7126         case 'C':
7127             ret = reg_node(pRExC_state, CANY);
7128             RExC_seen |= REG_SEEN_CANY;
7129             *flagp |= HASWIDTH|SIMPLE;
7130             goto finish_meta_pat;
7131         case 'X':
7132             ret = reg_node(pRExC_state, CLUMP);
7133             *flagp |= HASWIDTH;
7134             goto finish_meta_pat;
7135         case 'w':
7136             ret = reg_node(pRExC_state, (U8)(LOC ? ALNUML     : ALNUM));
7137             *flagp |= HASWIDTH|SIMPLE;
7138             goto finish_meta_pat;
7139         case 'W':
7140             ret = reg_node(pRExC_state, (U8)(LOC ? NALNUML    : NALNUM));
7141             *flagp |= HASWIDTH|SIMPLE;
7142             goto finish_meta_pat;
7143         case 'b':
7144             RExC_seen_zerolen++;
7145             RExC_seen |= REG_SEEN_LOOKBEHIND;
7146             ret = reg_node(pRExC_state, (U8)(LOC ? BOUNDL     : BOUND));
7147             *flagp |= SIMPLE;
7148             goto finish_meta_pat;
7149         case 'B':
7150             RExC_seen_zerolen++;
7151             RExC_seen |= REG_SEEN_LOOKBEHIND;
7152             ret = reg_node(pRExC_state, (U8)(LOC ? NBOUNDL    : NBOUND));
7153             *flagp |= SIMPLE;
7154             goto finish_meta_pat;
7155         case 's':
7156             ret = reg_node(pRExC_state, (U8)(LOC ? SPACEL     : SPACE));
7157             *flagp |= HASWIDTH|SIMPLE;
7158             goto finish_meta_pat;
7159         case 'S':
7160             ret = reg_node(pRExC_state, (U8)(LOC ? NSPACEL    : NSPACE));
7161             *flagp |= HASWIDTH|SIMPLE;
7162             goto finish_meta_pat;
7163         case 'd':
7164             ret = reg_node(pRExC_state, DIGIT);
7165             *flagp |= HASWIDTH|SIMPLE;
7166             goto finish_meta_pat;
7167         case 'D':
7168             ret = reg_node(pRExC_state, NDIGIT);
7169             *flagp |= HASWIDTH|SIMPLE;
7170             goto finish_meta_pat;
7171         case 'R':
7172             ret = reg_node(pRExC_state, LNBREAK);
7173             *flagp |= HASWIDTH|SIMPLE;
7174             goto finish_meta_pat;
7175         case 'h':
7176             ret = reg_node(pRExC_state, HORIZWS);
7177             *flagp |= HASWIDTH|SIMPLE;
7178             goto finish_meta_pat;
7179         case 'H':
7180             ret = reg_node(pRExC_state, NHORIZWS);
7181             *flagp |= HASWIDTH|SIMPLE;
7182             goto finish_meta_pat;
7183         case 'v':
7184             ret = reg_node(pRExC_state, VERTWS);
7185             *flagp |= HASWIDTH|SIMPLE;
7186             goto finish_meta_pat;
7187         case 'V':
7188             ret = reg_node(pRExC_state, NVERTWS);
7189             *flagp |= HASWIDTH|SIMPLE;
7190          finish_meta_pat:           
7191             nextchar(pRExC_state);
7192             Set_Node_Length(ret, 2); /* MJD */
7193             break;          
7194         case 'p':
7195         case 'P':
7196             {   
7197                 char* const oldregxend = RExC_end;
7198 #ifdef DEBUGGING
7199                 char* parse_start = RExC_parse - 2;
7200 #endif
7201
7202                 if (RExC_parse[1] == '{') {
7203                   /* a lovely hack--pretend we saw [\pX] instead */
7204                     RExC_end = strchr(RExC_parse, '}');
7205                     if (!RExC_end) {
7206                         const U8 c = (U8)*RExC_parse;
7207                         RExC_parse += 2;
7208                         RExC_end = oldregxend;
7209                         vFAIL2("Missing right brace on \\%c{}", c);
7210                     }
7211                     RExC_end++;
7212                 }
7213                 else {
7214                     RExC_end = RExC_parse + 2;
7215                     if (RExC_end > oldregxend)
7216                         RExC_end = oldregxend;
7217                 }
7218                 RExC_parse--;
7219
7220                 ret = regclass(pRExC_state,depth+1);
7221
7222                 RExC_end = oldregxend;
7223                 RExC_parse--;
7224
7225                 Set_Node_Offset(ret, parse_start + 2);
7226                 Set_Node_Cur_Length(ret);
7227                 nextchar(pRExC_state);
7228                 *flagp |= HASWIDTH|SIMPLE;
7229             }
7230             break;
7231         case 'N': 
7232             /* Handle \N and \N{NAME} here and not below because it can be
7233             multicharacter. join_exact() will join them up later on. 
7234             Also this makes sure that things like /\N{BLAH}+/ and 
7235             \N{BLAH} being multi char Just Happen. dmq*/
7236             ++RExC_parse;
7237             ret= reg_namedseq(pRExC_state, NULL, flagp); 
7238             break;
7239         case 'k':    /* Handle \k<NAME> and \k'NAME' */
7240         parse_named_seq:
7241         {   
7242             char ch= RExC_parse[1];         
7243             if (ch != '<' && ch != '\'' && ch != '{') {
7244                 RExC_parse++;
7245                 vFAIL2("Sequence %.2s... not terminated",parse_start);
7246             } else {
7247                 /* this pretty much dupes the code for (?P=...) in reg(), if
7248                    you change this make sure you change that */
7249                 char* name_start = (RExC_parse += 2);
7250                 U32 num = 0;
7251                 SV *sv_dat = reg_scan_name(pRExC_state,
7252                     SIZE_ONLY ? REG_RSN_RETURN_NULL : REG_RSN_RETURN_DATA);
7253                 ch= (ch == '<') ? '>' : (ch == '{') ? '}' : '\'';
7254                 if (RExC_parse == name_start || *RExC_parse != ch)
7255                     vFAIL2("Sequence %.3s... not terminated",parse_start);
7256
7257                 if (!SIZE_ONLY) {
7258                     num = add_data( pRExC_state, 1, "S" );
7259                     RExC_rxi->data->data[num]=(void*)sv_dat;
7260                     SvREFCNT_inc_simple_void(sv_dat);
7261                 }
7262
7263                 RExC_sawback = 1;
7264                 ret = reganode(pRExC_state,
7265                            (U8)(FOLD ? (LOC ? NREFFL : NREFF) : NREF),
7266                            num);
7267                 *flagp |= HASWIDTH;
7268
7269                 /* override incorrect value set in reganode MJD */
7270                 Set_Node_Offset(ret, parse_start+1);
7271                 Set_Node_Cur_Length(ret); /* MJD */
7272                 nextchar(pRExC_state);
7273
7274             }
7275             break;
7276         }
7277         case 'g': 
7278         case '1': case '2': case '3': case '4':
7279         case '5': case '6': case '7': case '8': case '9':
7280             {
7281                 I32 num;
7282                 bool isg = *RExC_parse == 'g';
7283                 bool isrel = 0; 
7284                 bool hasbrace = 0;
7285                 if (isg) {
7286                     RExC_parse++;
7287                     if (*RExC_parse == '{') {
7288                         RExC_parse++;
7289                         hasbrace = 1;
7290                     }
7291                     if (*RExC_parse == '-') {
7292                         RExC_parse++;
7293                         isrel = 1;
7294                     }
7295                     if (hasbrace && !isDIGIT(*RExC_parse)) {
7296                         if (isrel) RExC_parse--;
7297                         RExC_parse -= 2;                            
7298                         goto parse_named_seq;
7299                 }   }
7300                 num = atoi(RExC_parse);
7301                 if (isg && num == 0)
7302                     vFAIL("Reference to invalid group 0");
7303                 if (isrel) {
7304                     num = RExC_npar - num;
7305                     if (num < 1)
7306                         vFAIL("Reference to nonexistent or unclosed group");
7307                 }
7308                 if (!isg && num > 9 && num >= RExC_npar)
7309                     goto defchar;
7310                 else {
7311                     char * const parse_start = RExC_parse - 1; /* MJD */
7312                     while (isDIGIT(*RExC_parse))
7313                         RExC_parse++;
7314                     if (parse_start == RExC_parse - 1) 
7315                         vFAIL("Unterminated \\g... pattern");
7316                     if (hasbrace) {
7317                         if (*RExC_parse != '}') 
7318                             vFAIL("Unterminated \\g{...} pattern");
7319                         RExC_parse++;
7320                     }    
7321                     if (!SIZE_ONLY) {
7322                         if (num > (I32)RExC_rx->nparens)
7323                             vFAIL("Reference to nonexistent group");
7324                     }
7325                     RExC_sawback = 1;
7326                     ret = reganode(pRExC_state,
7327                                    (U8)(FOLD ? (LOC ? REFFL : REFF) : REF),
7328                                    num);
7329                     *flagp |= HASWIDTH;
7330
7331                     /* override incorrect value set in reganode MJD */
7332                     Set_Node_Offset(ret, parse_start+1);
7333                     Set_Node_Cur_Length(ret); /* MJD */
7334                     RExC_parse--;
7335                     nextchar(pRExC_state);
7336                 }
7337             }
7338             break;
7339         case '\0':
7340             if (RExC_parse >= RExC_end)
7341                 FAIL("Trailing \\");
7342             /* FALL THROUGH */
7343         default:
7344             /* Do not generate "unrecognized" warnings here, we fall
7345                back into the quick-grab loop below */
7346             parse_start--;
7347             goto defchar;
7348         }
7349         break;
7350
7351     case '#':
7352         if (RExC_flags & RXf_PMf_EXTENDED) {
7353             if ( reg_skipcomment( pRExC_state ) )
7354                 goto tryagain;
7355         }
7356         /* FALL THROUGH */
7357
7358     default:
7359         outer_default:{
7360             register STRLEN len;
7361             register UV ender;
7362             register char *p;
7363             char *s;
7364             STRLEN foldlen;
7365             U8 tmpbuf[UTF8_MAXBYTES_CASE+1], *foldbuf;
7366
7367             parse_start = RExC_parse - 1;
7368
7369             RExC_parse++;
7370
7371         defchar:
7372             ender = 0;
7373             ret = reg_node(pRExC_state,
7374                            (U8)(FOLD ? (LOC ? EXACTFL : EXACTF) : EXACT));
7375             s = STRING(ret);
7376             for (len = 0, p = RExC_parse - 1;
7377               len < 127 && p < RExC_end;
7378               len++)
7379             {
7380                 char * const oldp = p;
7381
7382                 if (RExC_flags & RXf_PMf_EXTENDED)
7383                     p = regwhite( pRExC_state, p );
7384                 switch ((U8)*p) {
7385                 case 0xDF:
7386                 case 0xC3:
7387                 case 0xCE:
7388                            if (LOC || !FOLD || !is_TRICKYFOLD_safe(p,RExC_end,UTF))
7389                                 goto normal_default;
7390                 case '^':
7391                 case '$':
7392                 case '.':
7393                 case '[':
7394                 case '(':
7395                 case ')':
7396                 case '|':
7397                     goto loopdone;
7398                 case '\\':
7399                     /* Literal Escapes Switch
7400
7401                        This switch is meant to handle escape sequences that
7402                        resolve to a literal character.
7403
7404                        Every escape sequence that represents something
7405                        else, like an assertion or a char class, is handled
7406                        in the switch marked 'Special Escapes' above in this
7407                        routine, but also has an entry here as anything that
7408                        isn't explicitly mentioned here will be treated as
7409                        an unescaped equivalent literal.
7410                     */
7411
7412                     switch ((U8)*++p) {
7413                     /* These are all the special escapes. */
7414                     case 0xDF:
7415                     case 0xC3:
7416                     case 0xCE:
7417                            if (LOC || !FOLD || !is_TRICKYFOLD_safe(p,RExC_end,UTF))
7418                                 goto normal_default;                
7419                     case 'A':             /* Start assertion */
7420                     case 'b': case 'B':   /* Word-boundary assertion*/
7421                     case 'C':             /* Single char !DANGEROUS! */
7422                     case 'd': case 'D':   /* digit class */
7423                     case 'g': case 'G':   /* generic-backref, pos assertion */
7424                     case 'h': case 'H':   /* HORIZWS */
7425                     case 'k': case 'K':   /* named backref, keep marker */
7426                     case 'N':             /* named char sequence */
7427                     case 'p': case 'P':   /* Unicode property */
7428                               case 'R':   /* LNBREAK */
7429                     case 's': case 'S':   /* space class */
7430                     case 'v': case 'V':   /* VERTWS */
7431                     case 'w': case 'W':   /* word class */
7432                     case 'X':             /* eXtended Unicode "combining character sequence" */
7433                     case 'z': case 'Z':   /* End of line/string assertion */
7434                         --p;
7435                         goto loopdone;
7436
7437                     /* Anything after here is an escape that resolves to a
7438                        literal. (Except digits, which may or may not)
7439                      */
7440                     case 'n':
7441                         ender = '\n';
7442                         p++;
7443                         break;
7444                     case 'r':
7445                         ender = '\r';
7446                         p++;
7447                         break;
7448                     case 't':
7449                         ender = '\t';
7450                         p++;
7451                         break;
7452                     case 'f':
7453                         ender = '\f';
7454                         p++;
7455                         break;
7456                     case 'e':
7457                           ender = ASCII_TO_NATIVE('\033');
7458                         p++;
7459                         break;
7460                     case 'a':
7461                           ender = ASCII_TO_NATIVE('\007');
7462                         p++;
7463                         break;
7464                     case 'o':
7465                         {
7466                             STRLEN brace_len = len;
7467                             UV result;
7468                             const char* error_msg;
7469
7470                             bool valid = grok_bslash_o(p,
7471                                                        &result,
7472                                                        &brace_len,
7473                                                        &error_msg,
7474                                                        1);
7475                             p += brace_len;
7476                             if (! valid) {
7477                                 RExC_parse = p; /* going to die anyway; point
7478                                                    to exact spot of failure */
7479                                 vFAIL(error_msg);
7480                             }
7481                             else
7482                             {
7483                                 ender = result;
7484                             }
7485                             if (PL_encoding && ender < 0x100) {
7486                                 goto recode_encoding;
7487                             }
7488                             if (ender > 0xff) {
7489                                 RExC_utf8 = 1;
7490                             }
7491                             break;
7492                         }
7493                     case 'x':
7494                         if (*++p == '{') {
7495                             char* const e = strchr(p, '}');
7496         
7497                             if (!e) {
7498                                 RExC_parse = p + 1;
7499                                 vFAIL("Missing right brace on \\x{}");
7500                             }
7501                             else {
7502                                 I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
7503                                     | PERL_SCAN_DISALLOW_PREFIX;
7504                                 STRLEN numlen = e - p - 1;
7505                                 ender = grok_hex(p + 1, &numlen, &flags, NULL);
7506                                 if (ender > 0xff)
7507                                     RExC_utf8 = 1;
7508                                 p = e + 1;
7509                             }
7510                         }
7511                         else {
7512                             I32 flags = PERL_SCAN_DISALLOW_PREFIX;
7513                             STRLEN numlen = 2;
7514                             ender = grok_hex(p, &numlen, &flags, NULL);
7515                             p += numlen;
7516                         }
7517                         if (PL_encoding && ender < 0x100)
7518                             goto recode_encoding;
7519                         break;
7520                     case 'c':
7521                         p++;
7522                         ender = grok_bslash_c(*p++, SIZE_ONLY);
7523                         break;
7524                     case '0': case '1': case '2': case '3':case '4':
7525                     case '5': case '6': case '7': case '8':case '9':
7526                         if (*p == '0' ||
7527                           (isDIGIT(p[1]) && atoi(p) >= RExC_npar) ) {
7528                             I32 flags = 0;
7529                             STRLEN numlen = 3;
7530                             ender = grok_oct(p, &numlen, &flags, NULL);
7531                             if (ender > 0xff) {
7532                                 RExC_utf8 = 1;
7533                             }
7534                             p += numlen;
7535                         }
7536                         else {
7537                             --p;
7538                             goto loopdone;
7539                         }
7540                         if (PL_encoding && ender < 0x100)
7541                             goto recode_encoding;
7542                         break;
7543                     recode_encoding:
7544                         {
7545                             SV* enc = PL_encoding;
7546                             ender = reg_recode((const char)(U8)ender, &enc);
7547                             if (!enc && SIZE_ONLY)
7548                                 ckWARNreg(p, "Invalid escape in the specified encoding");
7549                             RExC_utf8 = 1;
7550                         }
7551                         break;
7552                     case '\0':
7553                         if (p >= RExC_end)
7554                             FAIL("Trailing \\");
7555                         /* FALL THROUGH */
7556                     default:
7557                         if (!SIZE_ONLY&& isALPHA(*p))
7558                             ckWARN2reg(p + 1, "Unrecognized escape \\%c passed through", UCHARAT(p));
7559                         goto normal_default;
7560                     }
7561                     break;
7562                 default:
7563                   normal_default:
7564                     if (UTF8_IS_START(*p) && UTF) {
7565                         STRLEN numlen;
7566                         ender = utf8n_to_uvchr((U8*)p, RExC_end - p,
7567                                                &numlen, UTF8_ALLOW_DEFAULT);
7568                         p += numlen;
7569                     }
7570                     else
7571                         ender = *p++;
7572                     break;
7573                 }
7574                 if ( RExC_flags & RXf_PMf_EXTENDED)
7575                     p = regwhite( pRExC_state, p );
7576                 if (UTF && FOLD) {
7577                     /* Prime the casefolded buffer. */
7578                     ender = toFOLD_uni(ender, tmpbuf, &foldlen);
7579                 }
7580                 if (p < RExC_end && ISMULT2(p)) { /* Back off on ?+*. */
7581                     if (len)
7582                         p = oldp;
7583                     else if (UTF) {
7584                          if (FOLD) {
7585                               /* Emit all the Unicode characters. */
7586                               STRLEN numlen;
7587                               for (foldbuf = tmpbuf;
7588                                    foldlen;
7589                                    foldlen -= numlen) {
7590                                    ender = utf8_to_uvchr(foldbuf, &numlen);
7591                                    if (numlen > 0) {
7592                                         const STRLEN unilen = reguni(pRExC_state, ender, s);
7593                                         s       += unilen;
7594                                         len     += unilen;
7595                                         /* In EBCDIC the numlen
7596                                          * and unilen can differ. */
7597                                         foldbuf += numlen;
7598                                         if (numlen >= foldlen)
7599                                              break;
7600                                    }
7601                                    else
7602                                         break; /* "Can't happen." */
7603                               }
7604                          }
7605                          else {
7606                               const STRLEN unilen = reguni(pRExC_state, ender, s);
7607                               if (unilen > 0) {
7608                                    s   += unilen;
7609                                    len += unilen;
7610                               }
7611                          }
7612                     }
7613                     else {
7614                         len++;
7615                         REGC((char)ender, s++);
7616                     }
7617                     break;
7618                 }
7619                 if (UTF) {
7620                      if (FOLD) {
7621                           /* Emit all the Unicode characters. */
7622                           STRLEN numlen;
7623                           for (foldbuf = tmpbuf;
7624                                foldlen;
7625                                foldlen -= numlen) {
7626                                ender = utf8_to_uvchr(foldbuf, &numlen);
7627                                if (numlen > 0) {
7628                                     const STRLEN unilen = reguni(pRExC_state, ender, s);
7629                                     len     += unilen;
7630                                     s       += unilen;
7631                                     /* In EBCDIC the numlen
7632                                      * and unilen can differ. */
7633                                     foldbuf += numlen;
7634                                     if (numlen >= foldlen)
7635                                          break;
7636                                }
7637                                else
7638                                     break;
7639                           }
7640                      }
7641                      else {
7642                           const STRLEN unilen = reguni(pRExC_state, ender, s);
7643                           if (unilen > 0) {
7644                                s   += unilen;
7645                                len += unilen;
7646                           }
7647                      }
7648                      len--;
7649                 }
7650                 else
7651                     REGC((char)ender, s++);
7652             }
7653         loopdone:
7654             RExC_parse = p - 1;
7655             Set_Node_Cur_Length(ret); /* MJD */
7656             nextchar(pRExC_state);
7657             {
7658                 /* len is STRLEN which is unsigned, need to copy to signed */
7659                 IV iv = len;
7660                 if (iv < 0)
7661                     vFAIL("Internal disaster");
7662             }
7663             if (len > 0)
7664                 *flagp |= HASWIDTH;
7665             if (len == 1 && UNI_IS_INVARIANT(ender))
7666                 *flagp |= SIMPLE;
7667                 
7668             if (SIZE_ONLY)
7669                 RExC_size += STR_SZ(len);
7670             else {
7671                 STR_LEN(ret) = len;
7672                 RExC_emit += STR_SZ(len);
7673             }
7674         }
7675         break;
7676     }
7677
7678     return(ret);
7679 }
7680
7681 STATIC char *
7682 S_regwhite( RExC_state_t *pRExC_state, char *p )
7683 {
7684     const char *e = RExC_end;
7685
7686     PERL_ARGS_ASSERT_REGWHITE;
7687
7688     while (p < e) {
7689         if (isSPACE(*p))
7690             ++p;
7691         else if (*p == '#') {
7692             bool ended = 0;
7693             do {
7694                 if (*p++ == '\n') {
7695                     ended = 1;
7696                     break;
7697                 }
7698             } while (p < e);
7699             if (!ended)
7700                 RExC_seen |= REG_SEEN_RUN_ON_COMMENT;
7701         }
7702         else
7703             break;
7704     }
7705     return p;
7706 }
7707
7708 /* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
7709    Character classes ([:foo:]) can also be negated ([:^foo:]).
7710    Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
7711    Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
7712    but trigger failures because they are currently unimplemented. */
7713
7714 #define POSIXCC_DONE(c)   ((c) == ':')
7715 #define POSIXCC_NOTYET(c) ((c) == '=' || (c) == '.')
7716 #define POSIXCC(c) (POSIXCC_DONE(c) || POSIXCC_NOTYET(c))
7717
7718 STATIC I32
7719 S_regpposixcc(pTHX_ RExC_state_t *pRExC_state, I32 value)
7720 {
7721     dVAR;
7722     I32 namedclass = OOB_NAMEDCLASS;
7723
7724     PERL_ARGS_ASSERT_REGPPOSIXCC;
7725
7726     if (value == '[' && RExC_parse + 1 < RExC_end &&
7727         /* I smell either [: or [= or [. -- POSIX has been here, right? */
7728         POSIXCC(UCHARAT(RExC_parse))) {
7729         const char c = UCHARAT(RExC_parse);
7730         char* const s = RExC_parse++;
7731         
7732         while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != c)
7733             RExC_parse++;
7734         if (RExC_parse == RExC_end)
7735             /* Grandfather lone [:, [=, [. */
7736             RExC_parse = s;
7737         else {
7738             const char* const t = RExC_parse++; /* skip over the c */
7739             assert(*t == c);
7740
7741             if (UCHARAT(RExC_parse) == ']') {
7742                 const char *posixcc = s + 1;
7743                 RExC_parse++; /* skip over the ending ] */
7744
7745                 if (*s == ':') {
7746                     const I32 complement = *posixcc == '^' ? *posixcc++ : 0;
7747                     const I32 skip = t - posixcc;
7748
7749                     /* Initially switch on the length of the name.  */
7750                     switch (skip) {
7751                     case 4:
7752                         if (memEQ(posixcc, "word", 4)) /* this is not POSIX, this is the Perl \w */
7753                             namedclass = complement ? ANYOF_NALNUM : ANYOF_ALNUM;
7754                         break;
7755                     case 5:
7756                         /* Names all of length 5.  */
7757                         /* alnum alpha ascii blank cntrl digit graph lower
7758                            print punct space upper  */
7759                         /* Offset 4 gives the best switch position.  */
7760                         switch (posixcc[4]) {
7761                         case 'a':
7762                             if (memEQ(posixcc, "alph", 4)) /* alpha */
7763                                 namedclass = complement ? ANYOF_NALPHA : ANYOF_ALPHA;
7764                             break;
7765                         case 'e':
7766                             if (memEQ(posixcc, "spac", 4)) /* space */
7767                                 namedclass = complement ? ANYOF_NPSXSPC : ANYOF_PSXSPC;
7768                             break;
7769                         case 'h':
7770                             if (memEQ(posixcc, "grap", 4)) /* graph */
7771                                 namedclass = complement ? ANYOF_NGRAPH : ANYOF_GRAPH;
7772                             break;
7773                         case 'i':
7774                             if (memEQ(posixcc, "asci", 4)) /* ascii */
7775                                 namedclass = complement ? ANYOF_NASCII : ANYOF_ASCII;
7776                             break;
7777                         case 'k':
7778                             if (memEQ(posixcc, "blan", 4)) /* blank */
7779                                 namedclass = complement ? ANYOF_NBLANK : ANYOF_BLANK;
7780                             break;
7781                         case 'l':
7782                             if (memEQ(posixcc, "cntr", 4)) /* cntrl */
7783                                 namedclass = complement ? ANYOF_NCNTRL : ANYOF_CNTRL;
7784                             break;
7785                         case 'm':
7786                             if (memEQ(posixcc, "alnu", 4)) /* alnum */
7787                                 namedclass = complement ? ANYOF_NALNUMC : ANYOF_ALNUMC;
7788                             break;
7789                         case 'r':
7790                             if (memEQ(posixcc, "lowe", 4)) /* lower */
7791                                 namedclass = complement ? ANYOF_NLOWER : ANYOF_LOWER;
7792                             else if (memEQ(posixcc, "uppe", 4)) /* upper */
7793                                 namedclass = complement ? ANYOF_NUPPER : ANYOF_UPPER;
7794                             break;
7795                         case 't':
7796                             if (memEQ(posixcc, "digi", 4)) /* digit */
7797                                 namedclass = complement ? ANYOF_NDIGIT : ANYOF_DIGIT;
7798                             else if (memEQ(posixcc, "prin", 4)) /* print */
7799                                 namedclass = complement ? ANYOF_NPRINT : ANYOF_PRINT;
7800                             else if (memEQ(posixcc, "punc", 4)) /* punct */
7801                                 namedclass = complement ? ANYOF_NPUNCT : ANYOF_PUNCT;
7802                             break;
7803                         }
7804                         break;
7805                     case 6:
7806                         if (memEQ(posixcc, "xdigit", 6))
7807                             namedclass = complement ? ANYOF_NXDIGIT : ANYOF_XDIGIT;
7808                         break;
7809                     }
7810
7811                     if (namedclass == OOB_NAMEDCLASS)
7812                         Simple_vFAIL3("POSIX class [:%.*s:] unknown",
7813                                       t - s - 1, s + 1);
7814                     assert (posixcc[skip] == ':');
7815                     assert (posixcc[skip+1] == ']');
7816                 } else if (!SIZE_ONLY) {
7817                     /* [[=foo=]] and [[.foo.]] are still future. */
7818
7819                     /* adjust RExC_parse so the warning shows after
7820                        the class closes */
7821                     while (UCHARAT(RExC_parse) && UCHARAT(RExC_parse) != ']')
7822                         RExC_parse++;
7823                     Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
7824                 }
7825             } else {
7826                 /* Maternal grandfather:
7827                  * "[:" ending in ":" but not in ":]" */
7828                 RExC_parse = s;
7829             }
7830         }
7831     }
7832
7833     return namedclass;
7834 }
7835
7836 STATIC void
7837 S_checkposixcc(pTHX_ RExC_state_t *pRExC_state)
7838 {
7839     dVAR;
7840
7841     PERL_ARGS_ASSERT_CHECKPOSIXCC;
7842
7843     if (POSIXCC(UCHARAT(RExC_parse))) {
7844         const char *s = RExC_parse;
7845         const char  c = *s++;
7846
7847         while (isALNUM(*s))
7848             s++;
7849         if (*s && c == *s && s[1] == ']') {
7850             ckWARN3reg(s+2,
7851                        "POSIX syntax [%c %c] belongs inside character classes",
7852                        c, c);
7853
7854             /* [[=foo=]] and [[.foo.]] are still future. */
7855             if (POSIXCC_NOTYET(c)) {
7856                 /* adjust RExC_parse so the error shows after
7857                    the class closes */
7858                 while (UCHARAT(RExC_parse) && UCHARAT(RExC_parse++) != ']')
7859                     NOOP;
7860                 Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
7861             }
7862         }
7863     }
7864 }
7865
7866
7867 #define _C_C_T_(NAME,TEST,WORD)                         \
7868 ANYOF_##NAME:                                           \
7869     if (LOC)                                            \
7870         ANYOF_CLASS_SET(ret, ANYOF_##NAME);             \
7871     else {                                              \
7872         for (value = 0; value < 256; value++)           \
7873             if (TEST)                                   \
7874                 ANYOF_BITMAP_SET(ret, value);           \
7875     }                                                   \
7876     yesno = '+';                                        \
7877     what = WORD;                                        \
7878     break;                                              \
7879 case ANYOF_N##NAME:                                     \
7880     if (LOC)                                            \
7881         ANYOF_CLASS_SET(ret, ANYOF_N##NAME);            \
7882     else {                                              \
7883         for (value = 0; value < 256; value++)           \
7884             if (!TEST)                                  \
7885                 ANYOF_BITMAP_SET(ret, value);           \
7886     }                                                   \
7887     yesno = '!';                                        \
7888     what = WORD;                                        \
7889     break
7890
7891 #define _C_C_T_NOLOC_(NAME,TEST,WORD)                   \
7892 ANYOF_##NAME:                                           \
7893         for (value = 0; value < 256; value++)           \
7894             if (TEST)                                   \
7895                 ANYOF_BITMAP_SET(ret, value);           \
7896     yesno = '+';                                        \
7897     what = WORD;                                        \
7898     break;                                              \
7899 case ANYOF_N##NAME:                                     \
7900         for (value = 0; value < 256; value++)           \
7901             if (!TEST)                                  \
7902                 ANYOF_BITMAP_SET(ret, value);           \
7903     yesno = '!';                                        \
7904     what = WORD;                                        \
7905     break
7906
7907 /* 
7908    We dont use PERL_LEGACY_UNICODE_CHARCLASS_MAPPINGS as the direct test
7909    so that it is possible to override the option here without having to 
7910    rebuild the entire core. as we are required to do if we change regcomp.h
7911    which is where PERL_LEGACY_UNICODE_CHARCLASS_MAPPINGS is defined.
7912 */
7913 #if PERL_LEGACY_UNICODE_CHARCLASS_MAPPINGS
7914 #define BROKEN_UNICODE_CHARCLASS_MAPPINGS
7915 #endif
7916
7917 #ifdef BROKEN_UNICODE_CHARCLASS_MAPPINGS
7918 #define POSIX_CC_UNI_NAME(CCNAME) CCNAME
7919 #else
7920 #define POSIX_CC_UNI_NAME(CCNAME) "Posix" CCNAME
7921 #endif
7922
7923 /*
7924    parse a class specification and produce either an ANYOF node that
7925    matches the pattern or if the pattern matches a single char only and
7926    that char is < 256 and we are case insensitive then we produce an 
7927    EXACT node instead.
7928 */
7929
7930 STATIC regnode *
7931 S_regclass(pTHX_ RExC_state_t *pRExC_state, U32 depth)
7932 {
7933     dVAR;
7934     register UV nextvalue;
7935     register IV prevvalue = OOB_UNICODE;
7936     register IV range = 0;
7937     UV value = 0; /* XXX:dmq: needs to be referenceable (unfortunately) */
7938     register regnode *ret;
7939     STRLEN numlen;
7940     IV namedclass;
7941     char *rangebegin = NULL;
7942     bool need_class = 0;
7943     SV *listsv = NULL;
7944     UV n;
7945     bool optimize_invert   = TRUE;
7946     AV* unicode_alternate  = NULL;
7947 #ifdef EBCDIC
7948     UV literal_endpoint = 0;
7949 #endif
7950     UV stored = 0;  /* number of chars stored in the class */
7951
7952     regnode * const orig_emit = RExC_emit; /* Save the original RExC_emit in
7953         case we need to change the emitted regop to an EXACT. */
7954     const char * orig_parse = RExC_parse;
7955     GET_RE_DEBUG_FLAGS_DECL;
7956
7957     PERL_ARGS_ASSERT_REGCLASS;
7958 #ifndef DEBUGGING
7959     PERL_UNUSED_ARG(depth);
7960 #endif
7961
7962     DEBUG_PARSE("clas");
7963
7964     /* Assume we are going to generate an ANYOF node. */
7965     ret = reganode(pRExC_state, ANYOF, 0);
7966
7967     if (!SIZE_ONLY)
7968         ANYOF_FLAGS(ret) = 0;
7969
7970     if (UCHARAT(RExC_parse) == '^') {   /* Complement of range. */
7971         RExC_naughty++;
7972         RExC_parse++;
7973         if (!SIZE_ONLY)
7974             ANYOF_FLAGS(ret) |= ANYOF_INVERT;
7975     }
7976
7977     if (SIZE_ONLY) {
7978         RExC_size += ANYOF_SKIP;
7979         listsv = &PL_sv_undef; /* For code scanners: listsv always non-NULL. */
7980     }
7981     else {
7982         RExC_emit += ANYOF_SKIP;
7983         if (FOLD)
7984             ANYOF_FLAGS(ret) |= ANYOF_FOLD;
7985         if (LOC)
7986             ANYOF_FLAGS(ret) |= ANYOF_LOCALE;
7987         ANYOF_BITMAP_ZERO(ret);
7988         listsv = newSVpvs("# comment\n");
7989     }
7990
7991     nextvalue = RExC_parse < RExC_end ? UCHARAT(RExC_parse) : 0;
7992
7993     if (!SIZE_ONLY && POSIXCC(nextvalue))
7994         checkposixcc(pRExC_state);
7995
7996     /* allow 1st char to be ] (allowing it to be - is dealt with later) */
7997     if (UCHARAT(RExC_parse) == ']')
7998         goto charclassloop;
7999
8000 parseit:
8001     while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != ']') {
8002
8003     charclassloop:
8004
8005         namedclass = OOB_NAMEDCLASS; /* initialize as illegal */
8006
8007         if (!range)
8008             rangebegin = RExC_parse;
8009         if (UTF) {
8010             value = utf8n_to_uvchr((U8*)RExC_parse,
8011                                    RExC_end - RExC_parse,
8012                                    &numlen, UTF8_ALLOW_DEFAULT);
8013             RExC_parse += numlen;
8014         }
8015         else
8016             value = UCHARAT(RExC_parse++);
8017
8018         nextvalue = RExC_parse < RExC_end ? UCHARAT(RExC_parse) : 0;
8019         if (value == '[' && POSIXCC(nextvalue))
8020             namedclass = regpposixcc(pRExC_state, value);
8021         else if (value == '\\') {
8022             if (UTF) {
8023                 value = utf8n_to_uvchr((U8*)RExC_parse,
8024                                    RExC_end - RExC_parse,
8025                                    &numlen, UTF8_ALLOW_DEFAULT);
8026                 RExC_parse += numlen;
8027             }
8028             else
8029                 value = UCHARAT(RExC_parse++);
8030             /* Some compilers cannot handle switching on 64-bit integer
8031              * values, therefore value cannot be an UV.  Yes, this will
8032              * be a problem later if we want switch on Unicode.
8033              * A similar issue a little bit later when switching on
8034              * namedclass. --jhi */
8035             switch ((I32)value) {
8036             case 'w':   namedclass = ANYOF_ALNUM;       break;
8037             case 'W':   namedclass = ANYOF_NALNUM;      break;
8038             case 's':   namedclass = ANYOF_SPACE;       break;
8039             case 'S':   namedclass = ANYOF_NSPACE;      break;
8040             case 'd':   namedclass = ANYOF_DIGIT;       break;
8041             case 'D':   namedclass = ANYOF_NDIGIT;      break;
8042             case 'v':   namedclass = ANYOF_VERTWS;      break;
8043             case 'V':   namedclass = ANYOF_NVERTWS;     break;
8044             case 'h':   namedclass = ANYOF_HORIZWS;     break;
8045             case 'H':   namedclass = ANYOF_NHORIZWS;    break;
8046             case 'N':  /* Handle \N{NAME} in class */
8047                 {
8048                     /* We only pay attention to the first char of 
8049                     multichar strings being returned. I kinda wonder
8050                     if this makes sense as it does change the behaviour
8051                     from earlier versions, OTOH that behaviour was broken
8052                     as well. */
8053                     UV v; /* value is register so we cant & it /grrr */
8054                     if (reg_namedseq(pRExC_state, &v, NULL)) {
8055                         goto parseit;
8056                     }
8057                     value= v; 
8058                 }
8059                 break;
8060             case 'p':
8061             case 'P':
8062                 {
8063                 char *e;
8064                 if (RExC_parse >= RExC_end)
8065                     vFAIL2("Empty \\%c{}", (U8)value);
8066                 if (*RExC_parse == '{') {
8067                     const U8 c = (U8)value;
8068                     e = strchr(RExC_parse++, '}');
8069                     if (!e)
8070                         vFAIL2("Missing right brace on \\%c{}", c);
8071                     while (isSPACE(UCHARAT(RExC_parse)))
8072                         RExC_parse++;
8073                     if (e == RExC_parse)
8074                         vFAIL2("Empty \\%c{}", c);
8075                     n = e - RExC_parse;
8076                     while (isSPACE(UCHARAT(RExC_parse + n - 1)))
8077                         n--;
8078                 }
8079                 else {
8080                     e = RExC_parse;
8081                     n = 1;
8082                 }
8083                 if (!SIZE_ONLY) {
8084                     if (UCHARAT(RExC_parse) == '^') {
8085                          RExC_parse++;
8086                          n--;
8087                          value = value == 'p' ? 'P' : 'p'; /* toggle */
8088                          while (isSPACE(UCHARAT(RExC_parse))) {
8089                               RExC_parse++;
8090                               n--;
8091                          }
8092                     }
8093                     Perl_sv_catpvf(aTHX_ listsv, "%cutf8::%.*s\n",
8094                         (value=='p' ? '+' : '!'), (int)n, RExC_parse);
8095                 }
8096                 RExC_parse = e + 1;
8097                 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
8098                 namedclass = ANYOF_MAX;  /* no official name, but it's named */
8099                 }
8100                 break;
8101             case 'n':   value = '\n';                   break;
8102             case 'r':   value = '\r';                   break;
8103             case 't':   value = '\t';                   break;
8104             case 'f':   value = '\f';                   break;
8105             case 'b':   value = '\b';                   break;
8106             case 'e':   value = ASCII_TO_NATIVE('\033');break;
8107             case 'a':   value = ASCII_TO_NATIVE('\007');break;
8108             case 'o':
8109                 RExC_parse--;   /* function expects to be pointed at the 'o' */
8110                 {
8111                     const char* error_msg;
8112                     bool valid = grok_bslash_o(RExC_parse,
8113                                                &value,
8114                                                &numlen,
8115                                                &error_msg,
8116                                                SIZE_ONLY);
8117                     RExC_parse += numlen;
8118                     if (! valid) {
8119                         vFAIL(error_msg);
8120                     }
8121                 }
8122                 if (PL_encoding && value < 0x100) {
8123                     goto recode_encoding;
8124                 }
8125                 break;
8126             case 'x':
8127                 if (*RExC_parse == '{') {
8128                     I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
8129                         | PERL_SCAN_DISALLOW_PREFIX;
8130                     char * const e = strchr(RExC_parse++, '}');
8131                     if (!e)
8132                         vFAIL("Missing right brace on \\x{}");
8133
8134                     numlen = e - RExC_parse;
8135                     value = grok_hex(RExC_parse, &numlen, &flags, NULL);
8136                     RExC_parse = e + 1;
8137                 }
8138                 else {
8139                     I32 flags = PERL_SCAN_DISALLOW_PREFIX;
8140                     numlen = 2;
8141                     value = grok_hex(RExC_parse, &numlen, &flags, NULL);
8142                     RExC_parse += numlen;
8143                 }
8144                 if (PL_encoding && value < 0x100)
8145                     goto recode_encoding;
8146                 break;
8147             case 'c':
8148                 value = grok_bslash_c(*RExC_parse++, SIZE_ONLY);
8149                 break;
8150             case '0': case '1': case '2': case '3': case '4':
8151             case '5': case '6': case '7': case '8': case '9':
8152                 {
8153                     I32 flags = 0;
8154                     numlen = 3;
8155                     value = grok_oct(--RExC_parse, &numlen, &flags, NULL);
8156                     RExC_parse += numlen;
8157                     if (PL_encoding && value < 0x100)
8158                         goto recode_encoding;
8159                     break;
8160                 }
8161             recode_encoding:
8162                 {
8163                     SV* enc = PL_encoding;
8164                     value = reg_recode((const char)(U8)value, &enc);
8165                     if (!enc && SIZE_ONLY)
8166                         ckWARNreg(RExC_parse,
8167                                   "Invalid escape in the specified encoding");
8168                     break;
8169                 }
8170             default:
8171                 if (!SIZE_ONLY && isALPHA(value))
8172                     ckWARN2reg(RExC_parse,
8173                                "Unrecognized escape \\%c in character class passed through",
8174                                (int)value);
8175                 break;
8176             }
8177         } /* end of \blah */
8178 #ifdef EBCDIC
8179         else
8180             literal_endpoint++;
8181 #endif
8182
8183         if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */
8184
8185             if (!SIZE_ONLY && !need_class)
8186                 ANYOF_CLASS_ZERO(ret);
8187
8188             need_class = 1;
8189
8190             /* a bad range like a-\d, a-[:digit:] ? */
8191             if (range) {
8192                 if (!SIZE_ONLY) {
8193                     const int w =
8194                         RExC_parse >= rangebegin ?
8195                         RExC_parse - rangebegin : 0;
8196                     ckWARN4reg(RExC_parse,
8197                                "False [] range \"%*.*s\"",
8198                                w, w, rangebegin);
8199
8200                     if (prevvalue < 256) {
8201                         ANYOF_BITMAP_SET(ret, prevvalue);
8202                         ANYOF_BITMAP_SET(ret, '-');
8203                     }
8204                     else {
8205                         ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
8206                         Perl_sv_catpvf(aTHX_ listsv,
8207                                        "%04"UVxf"\n%04"UVxf"\n", (UV)prevvalue, (UV) '-');
8208                     }
8209                 }
8210
8211                 range = 0; /* this was not a true range */
8212             }
8213
8214
8215     
8216             if (!SIZE_ONLY) {
8217                 const char *what = NULL;
8218                 char yesno = 0;
8219
8220                 if (namedclass > OOB_NAMEDCLASS)
8221                     optimize_invert = FALSE;
8222                 /* Possible truncation here but in some 64-bit environments
8223                  * the compiler gets heartburn about switch on 64-bit values.
8224                  * A similar issue a little earlier when switching on value.
8225                  * --jhi */
8226                 switch ((I32)namedclass) {
8227                 
8228                 case _C_C_T_(ALNUMC, isALNUMC(value), POSIX_CC_UNI_NAME("Alnum"));
8229                 case _C_C_T_(ALPHA, isALPHA(value), POSIX_CC_UNI_NAME("Alpha"));
8230                 case _C_C_T_(BLANK, isBLANK(value), POSIX_CC_UNI_NAME("Blank"));
8231                 case _C_C_T_(CNTRL, isCNTRL(value), POSIX_CC_UNI_NAME("Cntrl"));
8232                 case _C_C_T_(GRAPH, isGRAPH(value), POSIX_CC_UNI_NAME("Graph"));
8233                 case _C_C_T_(LOWER, isLOWER(value), POSIX_CC_UNI_NAME("Lower"));
8234                 case _C_C_T_(PRINT, isPRINT(value), POSIX_CC_UNI_NAME("Print"));
8235                 case _C_C_T_(PSXSPC, isPSXSPC(value), POSIX_CC_UNI_NAME("Space"));
8236                 case _C_C_T_(PUNCT, isPUNCT(value), POSIX_CC_UNI_NAME("Punct"));
8237                 case _C_C_T_(UPPER, isUPPER(value), POSIX_CC_UNI_NAME("Upper"));
8238 #ifdef BROKEN_UNICODE_CHARCLASS_MAPPINGS
8239                 case _C_C_T_(ALNUM, isALNUM(value), "Word");
8240                 case _C_C_T_(SPACE, isSPACE(value), "SpacePerl");
8241 #else
8242                 case _C_C_T_(SPACE, isSPACE(value), "PerlSpace");
8243                 case _C_C_T_(ALNUM, isALNUM(value), "PerlWord");
8244 #endif          
8245                 case _C_C_T_(XDIGIT, isXDIGIT(value), "XDigit");
8246                 case _C_C_T_NOLOC_(VERTWS, is_VERTWS_latin1(&value), "VertSpace");
8247                 case _C_C_T_NOLOC_(HORIZWS, is_HORIZWS_latin1(&value), "HorizSpace");
8248                 case ANYOF_ASCII:
8249                     if (LOC)
8250                         ANYOF_CLASS_SET(ret, ANYOF_ASCII);
8251                     else {
8252 #ifndef EBCDIC
8253                         for (value = 0; value < 128; value++)
8254                             ANYOF_BITMAP_SET(ret, value);
8255 #else  /* EBCDIC */
8256                         for (value = 0; value < 256; value++) {
8257                             if (isASCII(value))
8258                                 ANYOF_BITMAP_SET(ret, value);
8259                         }
8260 #endif /* EBCDIC */
8261                     }
8262                     yesno = '+';
8263                     what = "ASCII";
8264                     break;
8265                 case ANYOF_NASCII:
8266                     if (LOC)
8267                         ANYOF_CLASS_SET(ret, ANYOF_NASCII);
8268                     else {
8269 #ifndef EBCDIC
8270                         for (value = 128; value < 256; value++)
8271                             ANYOF_BITMAP_SET(ret, value);
8272 #else  /* EBCDIC */
8273                         for (value = 0; value < 256; value++) {
8274                             if (!isASCII(value))
8275                                 ANYOF_BITMAP_SET(ret, value);
8276                         }
8277 #endif /* EBCDIC */
8278                     }
8279                     yesno = '!';
8280                     what = "ASCII";
8281                     break;              
8282                 case ANYOF_DIGIT:
8283                     if (LOC)
8284                         ANYOF_CLASS_SET(ret, ANYOF_DIGIT);
8285                     else {
8286                         /* consecutive digits assumed */
8287                         for (value = '0'; value <= '9'; value++)
8288                             ANYOF_BITMAP_SET(ret, value);
8289                     }
8290                     yesno = '+';
8291                     what = POSIX_CC_UNI_NAME("Digit");
8292                     break;
8293                 case ANYOF_NDIGIT:
8294                     if (LOC)
8295                         ANYOF_CLASS_SET(ret, ANYOF_NDIGIT);
8296                     else {
8297                         /* consecutive digits assumed */
8298                         for (value = 0; value < '0'; value++)
8299                             ANYOF_BITMAP_SET(ret, value);
8300                         for (value = '9' + 1; value < 256; value++)
8301                             ANYOF_BITMAP_SET(ret, value);
8302                     }
8303                     yesno = '!';
8304                     what = POSIX_CC_UNI_NAME("Digit");
8305                     break;              
8306                 case ANYOF_MAX:
8307                     /* this is to handle \p and \P */
8308                     break;
8309                 default:
8310                     vFAIL("Invalid [::] class");
8311                     break;
8312                 }
8313                 if (what) {
8314                     /* Strings such as "+utf8::isWord\n" */
8315                     Perl_sv_catpvf(aTHX_ listsv, "%cutf8::Is%s\n", yesno, what);
8316                 }
8317                 if (LOC)
8318                     ANYOF_FLAGS(ret) |= ANYOF_CLASS;
8319                 continue;
8320             }
8321         } /* end of namedclass \blah */
8322
8323         if (range) {
8324             if (prevvalue > (IV)value) /* b-a */ {
8325                 const int w = RExC_parse - rangebegin;
8326                 Simple_vFAIL4("Invalid [] range \"%*.*s\"", w, w, rangebegin);
8327                 range = 0; /* not a valid range */
8328             }
8329         }
8330         else {
8331             prevvalue = value; /* save the beginning of the range */
8332             if (*RExC_parse == '-' && RExC_parse+1 < RExC_end &&
8333                 RExC_parse[1] != ']') {
8334                 RExC_parse++;
8335
8336                 /* a bad range like \w-, [:word:]- ? */
8337                 if (namedclass > OOB_NAMEDCLASS) {
8338                     if (ckWARN(WARN_REGEXP)) {
8339                         const int w =
8340                             RExC_parse >= rangebegin ?
8341                             RExC_parse - rangebegin : 0;
8342                         vWARN4(RExC_parse,
8343                                "False [] range \"%*.*s\"",
8344                                w, w, rangebegin);
8345                     }
8346                     if (!SIZE_ONLY)
8347                         ANYOF_BITMAP_SET(ret, '-');
8348                 } else
8349                     range = 1;  /* yeah, it's a range! */
8350                 continue;       /* but do it the next time */
8351             }
8352         }
8353
8354         /* now is the next time */
8355         /*stored += (value - prevvalue + 1);*/
8356         if (!SIZE_ONLY) {
8357             if (prevvalue < 256) {
8358                 const IV ceilvalue = value < 256 ? value : 255;
8359                 IV i;
8360 #ifdef EBCDIC
8361                 /* In EBCDIC [\x89-\x91] should include
8362                  * the \x8e but [i-j] should not. */
8363                 if (literal_endpoint == 2 &&
8364                     ((isLOWER(prevvalue) && isLOWER(ceilvalue)) ||
8365                      (isUPPER(prevvalue) && isUPPER(ceilvalue))))
8366                 {
8367                     if (isLOWER(prevvalue)) {
8368                         for (i = prevvalue; i <= ceilvalue; i++)
8369                             if (isLOWER(i) && !ANYOF_BITMAP_TEST(ret,i)) {
8370                                 stored++;
8371                                 ANYOF_BITMAP_SET(ret, i);
8372                             }
8373                     } else {
8374                         for (i = prevvalue; i <= ceilvalue; i++)
8375                             if (isUPPER(i) && !ANYOF_BITMAP_TEST(ret,i)) {
8376                                 stored++;
8377                                 ANYOF_BITMAP_SET(ret, i);
8378                             }
8379                     }
8380                 }
8381                 else
8382 #endif
8383                       for (i = prevvalue; i <= ceilvalue; i++) {
8384                         if (!ANYOF_BITMAP_TEST(ret,i)) {
8385                             stored++;  
8386                             ANYOF_BITMAP_SET(ret, i);
8387                         }
8388                       }
8389           }
8390           if (value > 255 || UTF) {
8391                 const UV prevnatvalue  = NATIVE_TO_UNI(prevvalue);
8392                 const UV natvalue      = NATIVE_TO_UNI(value);
8393                 stored+=2; /* can't optimize this class */
8394                 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
8395                 if (prevnatvalue < natvalue) { /* what about > ? */
8396                     Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\t%04"UVxf"\n",
8397                                    prevnatvalue, natvalue);
8398                 }
8399                 else if (prevnatvalue == natvalue) {
8400                     Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n", natvalue);
8401                     if (FOLD) {
8402                          U8 foldbuf[UTF8_MAXBYTES_CASE+1];
8403                          STRLEN foldlen;
8404                          const UV f = to_uni_fold(natvalue, foldbuf, &foldlen);
8405
8406 #ifdef EBCDIC /* RD t/uni/fold ff and 6b */
8407                          if (RExC_precomp[0] == ':' &&
8408                              RExC_precomp[1] == '[' &&
8409                              (f == 0xDF || f == 0x92)) {
8410                              f = NATIVE_TO_UNI(f);
8411                         }
8412 #endif
8413                          /* If folding and foldable and a single
8414                           * character, insert also the folded version
8415                           * to the charclass. */
8416                          if (f != value) {
8417 #ifdef EBCDIC /* RD tunifold ligatures s,t fb05, fb06 */
8418                              if ((RExC_precomp[0] == ':' &&
8419                                   RExC_precomp[1] == '[' &&
8420                                   (f == 0xA2 &&
8421                                    (value == 0xFB05 || value == 0xFB06))) ?
8422                                  foldlen == ((STRLEN)UNISKIP(f) - 1) :
8423                                  foldlen == (STRLEN)UNISKIP(f) )
8424 #else
8425                               if (foldlen == (STRLEN)UNISKIP(f))
8426 #endif
8427                                   Perl_sv_catpvf(aTHX_ listsv,
8428                                                  "%04"UVxf"\n", f);
8429                               else {
8430                                   /* Any multicharacter foldings
8431                                    * require the following transform:
8432                                    * [ABCDEF] -> (?:[ABCabcDEFd]|pq|rst)
8433                                    * where E folds into "pq" and F folds
8434                                    * into "rst", all other characters
8435                                    * fold to single characters.  We save
8436                                    * away these multicharacter foldings,
8437                                    * to be later saved as part of the
8438                                    * additional "s" data. */
8439                                   SV *sv;
8440
8441                                   if (!unicode_alternate)
8442                                       unicode_alternate = newAV();
8443                                   sv = newSVpvn_utf8((char*)foldbuf, foldlen,
8444                                                      TRUE);
8445                                   av_push(unicode_alternate, sv);
8446                               }
8447                          }
8448
8449                          /* If folding and the value is one of the Greek
8450                           * sigmas insert a few more sigmas to make the
8451                           * folding rules of the sigmas to work right.
8452                           * Note that not all the possible combinations
8453                           * are handled here: some of them are handled
8454                           * by the standard folding rules, and some of
8455                           * them (literal or EXACTF cases) are handled
8456                           * during runtime in regexec.c:S_find_byclass(). */
8457                          if (value == UNICODE_GREEK_SMALL_LETTER_FINAL_SIGMA) {
8458                               Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
8459                                              (UV)UNICODE_GREEK_CAPITAL_LETTER_SIGMA);
8460                               Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
8461                                              (UV)UNICODE_GREEK_SMALL_LETTER_SIGMA);
8462                          }
8463                          else if (value == UNICODE_GREEK_CAPITAL_LETTER_SIGMA)
8464                               Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
8465                                              (UV)UNICODE_GREEK_SMALL_LETTER_SIGMA);
8466                     }
8467                 }
8468             }
8469 #ifdef EBCDIC
8470             literal_endpoint = 0;
8471 #endif
8472         }
8473
8474         range = 0; /* this range (if it was one) is done now */
8475     }
8476
8477     if (need_class) {
8478         ANYOF_FLAGS(ret) |= ANYOF_LARGE;
8479         if (SIZE_ONLY)
8480             RExC_size += ANYOF_CLASS_ADD_SKIP;
8481         else
8482             RExC_emit += ANYOF_CLASS_ADD_SKIP;
8483     }
8484
8485
8486     if (SIZE_ONLY)
8487         return ret;
8488     /****** !SIZE_ONLY AFTER HERE *********/
8489
8490     if( stored == 1 && (value < 128 || (value < 256 && !UTF))
8491         && !( ANYOF_FLAGS(ret) & ( ANYOF_FLAGS_ALL ^ ANYOF_FOLD ) )
8492     ) {
8493         /* optimize single char class to an EXACT node
8494            but *only* when its not a UTF/high char  */
8495         const char * cur_parse= RExC_parse;
8496         RExC_emit = (regnode *)orig_emit;
8497         RExC_parse = (char *)orig_parse;
8498         ret = reg_node(pRExC_state,
8499                        (U8)((ANYOF_FLAGS(ret) & ANYOF_FOLD) ? EXACTF : EXACT));
8500         RExC_parse = (char *)cur_parse;
8501         *STRING(ret)= (char)value;
8502         STR_LEN(ret)= 1;
8503         RExC_emit += STR_SZ(1);
8504         SvREFCNT_dec(listsv);
8505         return ret;
8506     }
8507     /* optimize case-insensitive simple patterns (e.g. /[a-z]/i) */
8508     if ( /* If the only flag is folding (plus possibly inversion). */
8509         ((ANYOF_FLAGS(ret) & (ANYOF_FLAGS_ALL ^ ANYOF_INVERT)) == ANYOF_FOLD)
8510        ) {
8511         for (value = 0; value < 256; ++value) {
8512             if (ANYOF_BITMAP_TEST(ret, value)) {
8513                 UV fold = PL_fold[value];
8514
8515                 if (fold != value)
8516                     ANYOF_BITMAP_SET(ret, fold);
8517             }
8518         }
8519         ANYOF_FLAGS(ret) &= ~ANYOF_FOLD;
8520     }
8521
8522     /* optimize inverted simple patterns (e.g. [^a-z]) */
8523     if (optimize_invert &&
8524         /* If the only flag is inversion. */
8525         (ANYOF_FLAGS(ret) & ANYOF_FLAGS_ALL) == ANYOF_INVERT) {
8526         for (value = 0; value < ANYOF_BITMAP_SIZE; ++value)
8527             ANYOF_BITMAP(ret)[value] ^= ANYOF_FLAGS_ALL;
8528         ANYOF_FLAGS(ret) = ANYOF_UNICODE_ALL;
8529     }
8530     {
8531         AV * const av = newAV();
8532         SV *rv;
8533         /* The 0th element stores the character class description
8534          * in its textual form: used later (regexec.c:Perl_regclass_swash())
8535          * to initialize the appropriate swash (which gets stored in
8536          * the 1st element), and also useful for dumping the regnode.
8537          * The 2nd element stores the multicharacter foldings,
8538          * used later (regexec.c:S_reginclass()). */
8539         av_store(av, 0, listsv);
8540         av_store(av, 1, NULL);
8541         av_store(av, 2, MUTABLE_SV(unicode_alternate));
8542         rv = newRV_noinc(MUTABLE_SV(av));
8543         n = add_data(pRExC_state, 1, "s");
8544         RExC_rxi->data->data[n] = (void*)rv;
8545         ARG_SET(ret, n);
8546     }
8547     return ret;
8548 }
8549 #undef _C_C_T_
8550
8551
8552 /* reg_skipcomment()
8553
8554    Absorbs an /x style # comments from the input stream.
8555    Returns true if there is more text remaining in the stream.
8556    Will set the REG_SEEN_RUN_ON_COMMENT flag if the comment
8557    terminates the pattern without including a newline.
8558
8559    Note its the callers responsibility to ensure that we are
8560    actually in /x mode
8561
8562 */
8563
8564 STATIC bool
8565 S_reg_skipcomment(pTHX_ RExC_state_t *pRExC_state)
8566 {
8567     bool ended = 0;
8568
8569     PERL_ARGS_ASSERT_REG_SKIPCOMMENT;
8570
8571     while (RExC_parse < RExC_end)
8572         if (*RExC_parse++ == '\n') {
8573             ended = 1;
8574             break;
8575         }
8576     if (!ended) {
8577         /* we ran off the end of the pattern without ending
8578            the comment, so we have to add an \n when wrapping */
8579         RExC_seen |= REG_SEEN_RUN_ON_COMMENT;
8580         return 0;
8581     } else
8582         return 1;
8583 }
8584
8585 /* nextchar()
8586
8587    Advance that parse position, and optionall absorbs
8588    "whitespace" from the inputstream.
8589
8590    Without /x "whitespace" means (?#...) style comments only,
8591    with /x this means (?#...) and # comments and whitespace proper.
8592
8593    Returns the RExC_parse point from BEFORE the scan occurs.
8594
8595    This is the /x friendly way of saying RExC_parse++.
8596 */
8597
8598 STATIC char*
8599 S_nextchar(pTHX_ RExC_state_t *pRExC_state)
8600 {
8601     char* const retval = RExC_parse++;
8602
8603     PERL_ARGS_ASSERT_NEXTCHAR;
8604
8605     for (;;) {
8606         if (*RExC_parse == '(' && RExC_parse[1] == '?' &&
8607                 RExC_parse[2] == '#') {
8608             while (*RExC_parse != ')') {
8609                 if (RExC_parse == RExC_end)
8610                     FAIL("Sequence (?#... not terminated");
8611                 RExC_parse++;
8612             }
8613             RExC_parse++;
8614             continue;
8615         }
8616         if (RExC_flags & RXf_PMf_EXTENDED) {
8617             if (isSPACE(*RExC_parse)) {
8618                 RExC_parse++;
8619                 continue;
8620             }
8621             else if (*RExC_parse == '#') {
8622                 if ( reg_skipcomment( pRExC_state ) )
8623                     continue;
8624             }
8625         }
8626         return retval;
8627     }
8628 }
8629
8630 /*
8631 - reg_node - emit a node
8632 */
8633 STATIC regnode *                        /* Location. */
8634 S_reg_node(pTHX_ RExC_state_t *pRExC_state, U8 op)
8635 {
8636     dVAR;
8637     register regnode *ptr;
8638     regnode * const ret = RExC_emit;
8639     GET_RE_DEBUG_FLAGS_DECL;
8640
8641     PERL_ARGS_ASSERT_REG_NODE;
8642
8643     if (SIZE_ONLY) {
8644         SIZE_ALIGN(RExC_size);
8645         RExC_size += 1;
8646         return(ret);
8647     }
8648     if (RExC_emit >= RExC_emit_bound)
8649         Perl_croak(aTHX_ "panic: reg_node overrun trying to emit %d", op);
8650
8651     NODE_ALIGN_FILL(ret);
8652     ptr = ret;
8653     FILL_ADVANCE_NODE(ptr, op);
8654     REH_CALL_REGCOMP_HOOK(pRExC_state->rx, (ptr) - 1);
8655 #ifdef RE_TRACK_PATTERN_OFFSETS
8656     if (RExC_offsets) {         /* MJD */
8657         MJD_OFFSET_DEBUG(("%s:%d: (op %s) %s %"UVuf" (len %"UVuf") (max %"UVuf").\n", 
8658               "reg_node", __LINE__, 
8659               PL_reg_name[op],
8660               (UV)(RExC_emit - RExC_emit_start) > RExC_offsets[0] 
8661                 ? "Overwriting end of array!\n" : "OK",
8662               (UV)(RExC_emit - RExC_emit_start),
8663               (UV)(RExC_parse - RExC_start),
8664               (UV)RExC_offsets[0])); 
8665         Set_Node_Offset(RExC_emit, RExC_parse + (op == END));
8666     }
8667 #endif
8668     RExC_emit = ptr;
8669     return(ret);
8670 }
8671
8672 /*
8673 - reganode - emit a node with an argument
8674 */
8675 STATIC regnode *                        /* Location. */
8676 S_reganode(pTHX_ RExC_state_t *pRExC_state, U8 op, U32 arg)
8677 {
8678     dVAR;
8679     register regnode *ptr;
8680     regnode * const ret = RExC_emit;
8681     GET_RE_DEBUG_FLAGS_DECL;
8682
8683     PERL_ARGS_ASSERT_REGANODE;
8684
8685     if (SIZE_ONLY) {
8686         SIZE_ALIGN(RExC_size);
8687         RExC_size += 2;
8688         /* 
8689            We can't do this:
8690            
8691            assert(2==regarglen[op]+1); 
8692         
8693            Anything larger than this has to allocate the extra amount.
8694            If we changed this to be:
8695            
8696            RExC_size += (1 + regarglen[op]);
8697            
8698            then it wouldn't matter. Its not clear what side effect
8699            might come from that so its not done so far.
8700            -- dmq
8701         */
8702         return(ret);
8703     }
8704     if (RExC_emit >= RExC_emit_bound)
8705         Perl_croak(aTHX_ "panic: reg_node overrun trying to emit %d", op);
8706
8707     NODE_ALIGN_FILL(ret);
8708     ptr = ret;
8709     FILL_ADVANCE_NODE_ARG(ptr, op, arg);
8710     REH_CALL_REGCOMP_HOOK(pRExC_state->rx, (ptr) - 2);
8711 #ifdef RE_TRACK_PATTERN_OFFSETS
8712     if (RExC_offsets) {         /* MJD */
8713         MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s %"UVuf" <- %"UVuf" (max %"UVuf").\n", 
8714               "reganode",
8715               __LINE__,
8716               PL_reg_name[op],
8717               (UV)(RExC_emit - RExC_emit_start) > RExC_offsets[0] ? 
8718               "Overwriting end of array!\n" : "OK",
8719               (UV)(RExC_emit - RExC_emit_start),
8720               (UV)(RExC_parse - RExC_start),
8721               (UV)RExC_offsets[0])); 
8722         Set_Cur_Node_Offset;
8723     }
8724 #endif            
8725     RExC_emit = ptr;
8726     return(ret);
8727 }
8728
8729 /*
8730 - reguni - emit (if appropriate) a Unicode character
8731 */
8732 STATIC STRLEN
8733 S_reguni(pTHX_ const RExC_state_t *pRExC_state, UV uv, char* s)
8734 {
8735     dVAR;
8736
8737     PERL_ARGS_ASSERT_REGUNI;
8738
8739     return SIZE_ONLY ? UNISKIP(uv) : (uvchr_to_utf8((U8*)s, uv) - (U8*)s);
8740 }
8741
8742 /*
8743 - reginsert - insert an operator in front of already-emitted operand
8744 *
8745 * Means relocating the operand.
8746 */
8747 STATIC void
8748 S_reginsert(pTHX_ RExC_state_t *pRExC_state, U8 op, regnode *opnd, U32 depth)
8749 {
8750     dVAR;
8751     register regnode *src;
8752     register regnode *dst;
8753     register regnode *place;
8754     const int offset = regarglen[(U8)op];
8755     const int size = NODE_STEP_REGNODE + offset;
8756     GET_RE_DEBUG_FLAGS_DECL;
8757
8758     PERL_ARGS_ASSERT_REGINSERT;
8759     PERL_UNUSED_ARG(depth);
8760 /* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
8761     DEBUG_PARSE_FMT("inst"," - %s",PL_reg_name[op]);
8762     if (SIZE_ONLY) {
8763         RExC_size += size;
8764         return;
8765     }
8766
8767     src = RExC_emit;
8768     RExC_emit += size;
8769     dst = RExC_emit;
8770     if (RExC_open_parens) {
8771         int paren;
8772         /*DEBUG_PARSE_FMT("inst"," - %"IVdf, (IV)RExC_npar);*/
8773         for ( paren=0 ; paren < RExC_npar ; paren++ ) {
8774             if ( RExC_open_parens[paren] >= opnd ) {
8775                 /*DEBUG_PARSE_FMT("open"," - %d",size);*/
8776                 RExC_open_parens[paren] += size;
8777             } else {
8778                 /*DEBUG_PARSE_FMT("open"," - %s","ok");*/
8779             }
8780             if ( RExC_close_parens[paren] >= opnd ) {
8781                 /*DEBUG_PARSE_FMT("close"," - %d",size);*/
8782                 RExC_close_parens[paren] += size;
8783             } else {
8784                 /*DEBUG_PARSE_FMT("close"," - %s","ok");*/
8785             }
8786         }
8787     }
8788
8789     while (src > opnd) {
8790         StructCopy(--src, --dst, regnode);
8791 #ifdef RE_TRACK_PATTERN_OFFSETS
8792         if (RExC_offsets) {     /* MJD 20010112 */
8793             MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s copy %"UVuf" -> %"UVuf" (max %"UVuf").\n",
8794                   "reg_insert",
8795                   __LINE__,
8796                   PL_reg_name[op],
8797                   (UV)(dst - RExC_emit_start) > RExC_offsets[0] 
8798                     ? "Overwriting end of array!\n" : "OK",
8799                   (UV)(src - RExC_emit_start),
8800                   (UV)(dst - RExC_emit_start),
8801                   (UV)RExC_offsets[0])); 
8802             Set_Node_Offset_To_R(dst-RExC_emit_start, Node_Offset(src));
8803             Set_Node_Length_To_R(dst-RExC_emit_start, Node_Length(src));
8804         }
8805 #endif
8806     }
8807     
8808
8809     place = opnd;               /* Op node, where operand used to be. */
8810 #ifdef RE_TRACK_PATTERN_OFFSETS
8811     if (RExC_offsets) {         /* MJD */
8812         MJD_OFFSET_DEBUG(("%s(%d): (op %s) %s %"UVuf" <- %"UVuf" (max %"UVuf").\n", 
8813               "reginsert",
8814               __LINE__,
8815               PL_reg_name[op],
8816               (UV)(place - RExC_emit_start) > RExC_offsets[0] 
8817               ? "Overwriting end of array!\n" : "OK",
8818               (UV)(place - RExC_emit_start),
8819               (UV)(RExC_parse - RExC_start),
8820               (UV)RExC_offsets[0]));
8821         Set_Node_Offset(place, RExC_parse);
8822         Set_Node_Length(place, 1);
8823     }
8824 #endif    
8825     src = NEXTOPER(place);
8826     FILL_ADVANCE_NODE(place, op);
8827     REH_CALL_REGCOMP_HOOK(pRExC_state->rx, (place) - 1);
8828     Zero(src, offset, regnode);
8829 }
8830
8831 /*
8832 - regtail - set the next-pointer at the end of a node chain of p to val.
8833 - SEE ALSO: regtail_study
8834 */
8835 /* TODO: All three parms should be const */
8836 STATIC void
8837 S_regtail(pTHX_ RExC_state_t *pRExC_state, regnode *p, const regnode *val,U32 depth)
8838 {
8839     dVAR;
8840     register regnode *scan;
8841     GET_RE_DEBUG_FLAGS_DECL;
8842
8843     PERL_ARGS_ASSERT_REGTAIL;
8844 #ifndef DEBUGGING
8845     PERL_UNUSED_ARG(depth);
8846 #endif
8847
8848     if (SIZE_ONLY)
8849         return;
8850
8851     /* Find last node. */
8852     scan = p;
8853     for (;;) {
8854         regnode * const temp = regnext(scan);
8855         DEBUG_PARSE_r({
8856             SV * const mysv=sv_newmortal();
8857             DEBUG_PARSE_MSG((scan==p ? "tail" : ""));
8858             regprop(RExC_rx, mysv, scan);
8859             PerlIO_printf(Perl_debug_log, "~ %s (%d) %s %s\n",
8860                 SvPV_nolen_const(mysv), REG_NODE_NUM(scan),
8861                     (temp == NULL ? "->" : ""),
8862                     (temp == NULL ? PL_reg_name[OP(val)] : "")
8863             );
8864         });
8865         if (temp == NULL)
8866             break;
8867         scan = temp;
8868     }
8869
8870     if (reg_off_by_arg[OP(scan)]) {
8871         ARG_SET(scan, val - scan);
8872     }
8873     else {
8874         NEXT_OFF(scan) = val - scan;
8875     }
8876 }
8877
8878 #ifdef DEBUGGING
8879 /*
8880 - regtail_study - set the next-pointer at the end of a node chain of p to val.
8881 - Look for optimizable sequences at the same time.
8882 - currently only looks for EXACT chains.
8883
8884 This is expermental code. The idea is to use this routine to perform 
8885 in place optimizations on branches and groups as they are constructed,
8886 with the long term intention of removing optimization from study_chunk so
8887 that it is purely analytical.
8888
8889 Currently only used when in DEBUG mode. The macro REGTAIL_STUDY() is used
8890 to control which is which.
8891
8892 */
8893 /* TODO: All four parms should be const */
8894
8895 STATIC U8
8896 S_regtail_study(pTHX_ RExC_state_t *pRExC_state, regnode *p, const regnode *val,U32 depth)
8897 {
8898     dVAR;
8899     register regnode *scan;
8900     U8 exact = PSEUDO;
8901 #ifdef EXPERIMENTAL_INPLACESCAN
8902     I32 min = 0;
8903 #endif
8904     GET_RE_DEBUG_FLAGS_DECL;
8905
8906     PERL_ARGS_ASSERT_REGTAIL_STUDY;
8907
8908
8909     if (SIZE_ONLY)
8910         return exact;
8911
8912     /* Find last node. */
8913
8914     scan = p;
8915     for (;;) {
8916         regnode * const temp = regnext(scan);
8917 #ifdef EXPERIMENTAL_INPLACESCAN
8918         if (PL_regkind[OP(scan)] == EXACT)
8919             if (join_exact(pRExC_state,scan,&min,1,val,depth+1))
8920                 return EXACT;
8921 #endif
8922         if ( exact ) {
8923             switch (OP(scan)) {
8924                 case EXACT:
8925                 case EXACTF:
8926                 case EXACTFL:
8927                         if( exact == PSEUDO )
8928                             exact= OP(scan);
8929                         else if ( exact != OP(scan) )
8930                             exact= 0;
8931                 case NOTHING:
8932                     break;
8933                 default:
8934                     exact= 0;
8935             }
8936         }
8937         DEBUG_PARSE_r({
8938             SV * const mysv=sv_newmortal();
8939             DEBUG_PARSE_MSG((scan==p ? "tsdy" : ""));
8940             regprop(RExC_rx, mysv, scan);
8941             PerlIO_printf(Perl_debug_log, "~ %s (%d) -> %s\n",
8942                 SvPV_nolen_const(mysv),
8943                 REG_NODE_NUM(scan),
8944                 PL_reg_name[exact]);
8945         });
8946         if (temp == NULL)
8947             break;
8948         scan = temp;
8949     }
8950     DEBUG_PARSE_r({
8951         SV * const mysv_val=sv_newmortal();
8952         DEBUG_PARSE_MSG("");
8953         regprop(RExC_rx, mysv_val, val);
8954         PerlIO_printf(Perl_debug_log, "~ attach to %s (%"IVdf") offset to %"IVdf"\n",
8955                       SvPV_nolen_const(mysv_val),
8956                       (IV)REG_NODE_NUM(val),
8957                       (IV)(val - scan)
8958         );
8959     });
8960     if (reg_off_by_arg[OP(scan)]) {
8961         ARG_SET(scan, val - scan);
8962     }
8963     else {
8964         NEXT_OFF(scan) = val - scan;
8965     }
8966
8967     return exact;
8968 }
8969 #endif
8970
8971 /*
8972  - regcurly - a little FSA that accepts {\d+,?\d*}
8973  */
8974 #ifndef PERL_IN_XSUB_RE
8975 I32
8976 Perl_regcurly(register const char *s)
8977 {
8978     PERL_ARGS_ASSERT_REGCURLY;
8979
8980     if (*s++ != '{')
8981         return FALSE;
8982     if (!isDIGIT(*s))
8983         return FALSE;
8984     while (isDIGIT(*s))
8985         s++;
8986     if (*s == ',')
8987         s++;
8988     while (isDIGIT(*s))
8989         s++;
8990     if (*s != '}')
8991         return FALSE;
8992     return TRUE;
8993 }
8994 #endif
8995
8996 /*
8997  - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
8998  */
8999 #ifdef DEBUGGING
9000 static void 
9001 S_regdump_extflags(pTHX_ const char *lead, const U32 flags)
9002 {
9003     int bit;
9004     int set=0;
9005
9006     for (bit=0; bit<32; bit++) {
9007         if (flags & (1<<bit)) {
9008             if (!set++ && lead) 
9009                 PerlIO_printf(Perl_debug_log, "%s",lead);
9010             PerlIO_printf(Perl_debug_log, "%s ",PL_reg_extflags_name[bit]);
9011         }               
9012     }      
9013     if (lead)  {
9014         if (set) 
9015             PerlIO_printf(Perl_debug_log, "\n");
9016         else 
9017             PerlIO_printf(Perl_debug_log, "%s[none-set]\n",lead);
9018     }            
9019 }   
9020 #endif
9021
9022 void
9023 Perl_regdump(pTHX_ const regexp *r)
9024 {
9025 #ifdef DEBUGGING
9026     dVAR;
9027     SV * const sv = sv_newmortal();
9028     SV *dsv= sv_newmortal();
9029     RXi_GET_DECL(r,ri);
9030     GET_RE_DEBUG_FLAGS_DECL;
9031
9032     PERL_ARGS_ASSERT_REGDUMP;
9033
9034     (void)dumpuntil(r, ri->program, ri->program + 1, NULL, NULL, sv, 0, 0);
9035
9036     /* Header fields of interest. */
9037     if (r->anchored_substr) {
9038         RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->anchored_substr), 
9039             RE_SV_DUMPLEN(r->anchored_substr), 30);
9040         PerlIO_printf(Perl_debug_log,
9041                       "anchored %s%s at %"IVdf" ",
9042                       s, RE_SV_TAIL(r->anchored_substr),
9043                       (IV)r->anchored_offset);
9044     } else if (r->anchored_utf8) {
9045         RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->anchored_utf8), 
9046             RE_SV_DUMPLEN(r->anchored_utf8), 30);
9047         PerlIO_printf(Perl_debug_log,
9048                       "anchored utf8 %s%s at %"IVdf" ",
9049                       s, RE_SV_TAIL(r->anchored_utf8),
9050                       (IV)r->anchored_offset);
9051     }                 
9052     if (r->float_substr) {
9053         RE_PV_QUOTED_DECL(s, 0, dsv, SvPVX_const(r->float_substr), 
9054             RE_SV_DUMPLEN(r->float_substr), 30);
9055         PerlIO_printf(Perl_debug_log,
9056                       "floating %s%s at %"IVdf"..%"UVuf" ",
9057                       s, RE_SV_TAIL(r->float_substr),
9058                       (IV)r->float_min_offset, (UV)r->float_max_offset);
9059     } else if (r->float_utf8) {
9060         RE_PV_QUOTED_DECL(s, 1, dsv, SvPVX_const(r->float_utf8), 
9061             RE_SV_DUMPLEN(r->float_utf8), 30);
9062         PerlIO_printf(Perl_debug_log,
9063                       "floating utf8 %s%s at %"IVdf"..%"UVuf" ",
9064                       s, RE_SV_TAIL(r->float_utf8),
9065                       (IV)r->float_min_offset, (UV)r->float_max_offset);
9066     }
9067     if (r->check_substr || r->check_utf8)
9068         PerlIO_printf(Perl_debug_log,
9069                       (const char *)
9070                       (r->check_substr == r->float_substr
9071                        && r->check_utf8 == r->float_utf8
9072                        ? "(checking floating" : "(checking anchored"));
9073     if (r->extflags & RXf_NOSCAN)
9074         PerlIO_printf(Perl_debug_log, " noscan");
9075     if (r->extflags & RXf_CHECK_ALL)
9076         PerlIO_printf(Perl_debug_log, " isall");
9077     if (r->check_substr || r->check_utf8)
9078         PerlIO_printf(Perl_debug_log, ") ");
9079
9080     if (ri->regstclass) {
9081         regprop(r, sv, ri->regstclass);
9082         PerlIO_printf(Perl_debug_log, "stclass %s ", SvPVX_const(sv));
9083     }
9084     if (r->extflags & RXf_ANCH) {
9085         PerlIO_printf(Perl_debug_log, "anchored");
9086         if (r->extflags & RXf_ANCH_BOL)
9087             PerlIO_printf(Perl_debug_log, "(BOL)");
9088         if (r->extflags & RXf_ANCH_MBOL)
9089             PerlIO_printf(Perl_debug_log, "(MBOL)");
9090         if (r->extflags & RXf_ANCH_SBOL)
9091             PerlIO_printf(Perl_debug_log, "(SBOL)");
9092         if (r->extflags & RXf_ANCH_GPOS)
9093             PerlIO_printf(Perl_debug_log, "(GPOS)");
9094         PerlIO_putc(Perl_debug_log, ' ');
9095     }
9096     if (r->extflags & RXf_GPOS_SEEN)
9097         PerlIO_printf(Perl_debug_log, "GPOS:%"UVuf" ", (UV)r->gofs);
9098     if (r->intflags & PREGf_SKIP)
9099         PerlIO_printf(Perl_debug_log, "plus ");
9100     if (r->intflags & PREGf_IMPLICIT)
9101         PerlIO_printf(Perl_debug_log, "implicit ");
9102     PerlIO_printf(Perl_debug_log, "minlen %"IVdf" ", (IV)r->minlen);
9103     if (r->extflags & RXf_EVAL_SEEN)
9104         PerlIO_printf(Perl_debug_log, "with eval ");
9105     PerlIO_printf(Perl_debug_log, "\n");
9106     DEBUG_FLAGS_r(regdump_extflags("r->extflags: ",r->extflags));            
9107 #else
9108     PERL_ARGS_ASSERT_REGDUMP;
9109     PERL_UNUSED_CONTEXT;
9110     PERL_UNUSED_ARG(r);
9111 #endif  /* DEBUGGING */
9112 }
9113
9114 /*
9115 - regprop - printable representation of opcode
9116 */
9117 #define EMIT_ANYOF_TEST_SEPARATOR(do_sep,sv,flags) \
9118 STMT_START { \
9119         if (do_sep) {                           \
9120             Perl_sv_catpvf(aTHX_ sv,"%s][%s",PL_colors[1],PL_colors[0]); \
9121             if (flags & ANYOF_INVERT)           \
9122                 /*make sure the invert info is in each */ \
9123                 sv_catpvs(sv, "^");             \
9124             do_sep = 0;                         \
9125         }                                       \
9126 } STMT_END
9127
9128 void
9129 Perl_regprop(pTHX_ const regexp *prog, SV *sv, const regnode *o)
9130 {
9131 #ifdef DEBUGGING
9132     dVAR;
9133     register int k;
9134     RXi_GET_DECL(prog,progi);
9135     GET_RE_DEBUG_FLAGS_DECL;
9136     
9137     PERL_ARGS_ASSERT_REGPROP;
9138
9139     sv_setpvs(sv, "");
9140
9141     if (OP(o) > REGNODE_MAX)            /* regnode.type is unsigned */
9142         /* It would be nice to FAIL() here, but this may be called from
9143            regexec.c, and it would be hard to supply pRExC_state. */
9144         Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d", (int)OP(o), (int)REGNODE_MAX);
9145     sv_catpv(sv, PL_reg_name[OP(o)]); /* Take off const! */
9146
9147     k = PL_regkind[OP(o)];
9148
9149     if (k == EXACT) {
9150         sv_catpvs(sv, " ");
9151         /* Using is_utf8_string() (via PERL_PV_UNI_DETECT) 
9152          * is a crude hack but it may be the best for now since 
9153          * we have no flag "this EXACTish node was UTF-8" 
9154          * --jhi */
9155         pv_pretty(sv, STRING(o), STR_LEN(o), 60, PL_colors[0], PL_colors[1],
9156                   PERL_PV_ESCAPE_UNI_DETECT |
9157                   PERL_PV_PRETTY_ELLIPSES   |
9158                   PERL_PV_PRETTY_LTGT       |
9159                   PERL_PV_PRETTY_NOCLEAR
9160                   );
9161     } else if (k == TRIE) {
9162         /* print the details of the trie in dumpuntil instead, as
9163          * progi->data isn't available here */
9164         const char op = OP(o);
9165         const U32 n = ARG(o);
9166         const reg_ac_data * const ac = IS_TRIE_AC(op) ?
9167                (reg_ac_data *)progi->data->data[n] :
9168                NULL;
9169         const reg_trie_data * const trie
9170             = (reg_trie_data*)progi->data->data[!IS_TRIE_AC(op) ? n : ac->trie];
9171         
9172         Perl_sv_catpvf(aTHX_ sv, "-%s",PL_reg_name[o->flags]);
9173         DEBUG_TRIE_COMPILE_r(
9174             Perl_sv_catpvf(aTHX_ sv,
9175                 "<S:%"UVuf"/%"IVdf" W:%"UVuf" L:%"UVuf"/%"UVuf" C:%"UVuf"/%"UVuf">",
9176                 (UV)trie->startstate,
9177                 (IV)trie->statecount-1, /* -1 because of the unused 0 element */
9178                 (UV)trie->wordcount,
9179                 (UV)trie->minlen,
9180                 (UV)trie->maxlen,
9181                 (UV)TRIE_CHARCOUNT(trie),
9182                 (UV)trie->uniquecharcount
9183             )
9184         );
9185         if ( IS_ANYOF_TRIE(op) || trie->bitmap ) {
9186             int i;
9187             int rangestart = -1;
9188             U8* bitmap = IS_ANYOF_TRIE(op) ? (U8*)ANYOF_BITMAP(o) : (U8*)TRIE_BITMAP(trie);
9189             sv_catpvs(sv, "[");
9190             for (i = 0; i <= 256; i++) {
9191                 if (i < 256 && BITMAP_TEST(bitmap,i)) {
9192                     if (rangestart == -1)
9193                         rangestart = i;
9194                 } else if (rangestart != -1) {
9195                     if (i <= rangestart + 3)
9196                         for (; rangestart < i; rangestart++)
9197                             put_byte(sv, rangestart);
9198                     else {
9199                         put_byte(sv, rangestart);
9200                         sv_catpvs(sv, "-");
9201                         put_byte(sv, i - 1);
9202                     }
9203                     rangestart = -1;
9204                 }
9205             }
9206             sv_catpvs(sv, "]");
9207         } 
9208          
9209     } else if (k == CURLY) {
9210         if (OP(o) == CURLYM || OP(o) == CURLYN || OP(o) == CURLYX)
9211             Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
9212         Perl_sv_catpvf(aTHX_ sv, " {%d,%d}", ARG1(o), ARG2(o));
9213     }
9214     else if (k == WHILEM && o->flags)                   /* Ordinal/of */
9215         Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
9216     else if (k == REF || k == OPEN || k == CLOSE || k == GROUPP || OP(o)==ACCEPT) {
9217         Perl_sv_catpvf(aTHX_ sv, "%d", (int)ARG(o));    /* Parenth number */
9218         if ( RXp_PAREN_NAMES(prog) ) {
9219             if ( k != REF || OP(o) < NREF) {        
9220                 AV *list= MUTABLE_AV(progi->data->data[progi->name_list_idx]);
9221                 SV **name= av_fetch(list, ARG(o), 0 );
9222                 if (name)
9223                     Perl_sv_catpvf(aTHX_ sv, " '%"SVf"'", SVfARG(*name));
9224             }       
9225             else {
9226                 AV *list= MUTABLE_AV(progi->data->data[ progi->name_list_idx ]);
9227                 SV *sv_dat= MUTABLE_SV(progi->data->data[ ARG( o ) ]);
9228                 I32 *nums=(I32*)SvPVX(sv_dat);
9229                 SV **name= av_fetch(list, nums[0], 0 );
9230                 I32 n;
9231                 if (name) {
9232                     for ( n=0; n<SvIVX(sv_dat); n++ ) {
9233                         Perl_sv_catpvf(aTHX_ sv, "%s%"IVdf,
9234                                     (n ? "," : ""), (IV)nums[n]);
9235                     }
9236                     Perl_sv_catpvf(aTHX_ sv, " '%"SVf"'", SVfARG(*name));
9237                 }
9238             }
9239         }            
9240     } else if (k == GOSUB) 
9241         Perl_sv_catpvf(aTHX_ sv, "%d[%+d]", (int)ARG(o),(int)ARG2L(o)); /* Paren and offset */
9242     else if (k == VERB) {
9243         if (!o->flags) 
9244             Perl_sv_catpvf(aTHX_ sv, ":%"SVf, 
9245                            SVfARG((MUTABLE_SV(progi->data->data[ ARG( o ) ]))));
9246     } else if (k == LOGICAL)
9247         Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags);     /* 2: embedded, otherwise 1 */
9248     else if (k == FOLDCHAR)
9249         Perl_sv_catpvf(aTHX_ sv, "[0x%"UVXf"]", PTR2UV(ARG(o)) );
9250     else if (k == ANYOF) {
9251         int i, rangestart = -1;
9252         const U8 flags = ANYOF_FLAGS(o);
9253         int do_sep = 0;
9254
9255         /* Should be synchronized with * ANYOF_ #xdefines in regcomp.h */
9256         static const char * const anyofs[] = {
9257             "\\w",
9258             "\\W",
9259             "\\s",
9260             "\\S",
9261             "\\d",
9262             "\\D",
9263             "[:alnum:]",
9264             "[:^alnum:]",
9265             "[:alpha:]",
9266             "[:^alpha:]",
9267             "[:ascii:]",
9268             "[:^ascii:]",
9269             "[:cntrl:]",
9270             "[:^cntrl:]",
9271             "[:graph:]",
9272             "[:^graph:]",
9273             "[:lower:]",
9274             "[:^lower:]",
9275             "[:print:]",
9276             "[:^print:]",
9277             "[:punct:]",
9278             "[:^punct:]",
9279             "[:upper:]",
9280             "[:^upper:]",
9281             "[:xdigit:]",
9282             "[:^xdigit:]",
9283             "[:space:]",
9284             "[:^space:]",
9285             "[:blank:]",
9286             "[:^blank:]"
9287         };
9288
9289         if (flags & ANYOF_LOCALE)
9290             sv_catpvs(sv, "{loc}");
9291         if (flags & ANYOF_FOLD)
9292             sv_catpvs(sv, "{i}");
9293         Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
9294         if (flags & ANYOF_INVERT)
9295             sv_catpvs(sv, "^");
9296         
9297         /* output what the standard cp 0-255 bitmap matches */
9298         for (i = 0; i <= 256; i++) {
9299             if (i < 256 && ANYOF_BITMAP_TEST(o,i)) {
9300                 if (rangestart == -1)
9301                     rangestart = i;
9302             } else if (rangestart != -1) {
9303                 if (i <= rangestart + 3)
9304                     for (; rangestart < i; rangestart++)
9305                         put_byte(sv, rangestart);
9306                 else {
9307                     put_byte(sv, rangestart);
9308                     sv_catpvs(sv, "-");
9309                     put_byte(sv, i - 1);
9310                 }
9311                 do_sep = 1;
9312                 rangestart = -1;
9313             }
9314         }
9315         
9316         EMIT_ANYOF_TEST_SEPARATOR(do_sep,sv,flags);
9317         /* output any special charclass tests (used mostly under use locale) */
9318         if (o->flags & ANYOF_CLASS)
9319             for (i = 0; i < (int)(sizeof(anyofs)/sizeof(char*)); i++)
9320                 if (ANYOF_CLASS_TEST(o,i)) {
9321                     sv_catpv(sv, anyofs[i]);
9322                     do_sep = 1;
9323                 }
9324         
9325         EMIT_ANYOF_TEST_SEPARATOR(do_sep,sv,flags);
9326         
9327         /* output information about the unicode matching */
9328         if (flags & ANYOF_UNICODE)
9329             sv_catpvs(sv, "{unicode}");
9330         else if (flags & ANYOF_UNICODE_ALL)
9331             sv_catpvs(sv, "{unicode_all}");
9332
9333         {
9334             SV *lv;
9335             SV * const sw = regclass_swash(prog, o, FALSE, &lv, 0);
9336         
9337             if (lv) {
9338                 if (sw) {
9339                     U8 s[UTF8_MAXBYTES_CASE+1];
9340
9341                     for (i = 0; i <= 256; i++) { /* just the first 256 */
9342                         uvchr_to_utf8(s, i);
9343                         
9344                         if (i < 256 && swash_fetch(sw, s, TRUE)) {
9345                             if (rangestart == -1)
9346                                 rangestart = i;
9347                         } else if (rangestart != -1) {
9348                             if (i <= rangestart + 3)
9349                                 for (; rangestart < i; rangestart++) {
9350                                     const U8 * const e = uvchr_to_utf8(s,rangestart);
9351                                     U8 *p;
9352                                     for(p = s; p < e; p++)
9353                                         put_byte(sv, *p);
9354                                 }
9355                             else {
9356                                 const U8 *e = uvchr_to_utf8(s,rangestart);
9357                                 U8 *p;
9358                                 for (p = s; p < e; p++)
9359                                     put_byte(sv, *p);
9360                                 sv_catpvs(sv, "-");
9361                                 e = uvchr_to_utf8(s, i-1);
9362                                 for (p = s; p < e; p++)
9363                                     put_byte(sv, *p);
9364                                 }
9365                                 rangestart = -1;
9366                             }
9367                         }
9368                         
9369                     sv_catpvs(sv, "..."); /* et cetera */
9370                 }
9371
9372                 {
9373                     char *s = savesvpv(lv);
9374                     char * const origs = s;
9375                 
9376                     while (*s && *s != '\n')
9377                         s++;
9378                 
9379                     if (*s == '\n') {
9380                         const char * const t = ++s;
9381                         
9382                         while (*s) {
9383                             if (*s == '\n')
9384                                 *s = ' ';
9385                             s++;
9386                         }
9387                         if (s[-1] == ' ')
9388                             s[-1] = 0;
9389                         
9390                         sv_catpv(sv, t);
9391                     }
9392                 
9393                     Safefree(origs);
9394                 }
9395             }
9396         }
9397
9398         Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
9399     }
9400     else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH))
9401         Perl_sv_catpvf(aTHX_ sv, "[%d]", -(o->flags));
9402 #else
9403     PERL_UNUSED_CONTEXT;
9404     PERL_UNUSED_ARG(sv);
9405     PERL_UNUSED_ARG(o);
9406     PERL_UNUSED_ARG(prog);
9407 #endif  /* DEBUGGING */
9408 }
9409
9410 SV *
9411 Perl_re_intuit_string(pTHX_ REGEXP * const r)
9412 {                               /* Assume that RE_INTUIT is set */
9413     dVAR;
9414     struct regexp *const prog = (struct regexp *)SvANY(r);
9415     GET_RE_DEBUG_FLAGS_DECL;
9416
9417     PERL_ARGS_ASSERT_RE_INTUIT_STRING;
9418     PERL_UNUSED_CONTEXT;
9419
9420     DEBUG_COMPILE_r(
9421         {
9422             const char * const s = SvPV_nolen_const(prog->check_substr
9423                       ? prog->check_substr : prog->check_utf8);
9424
9425             if (!PL_colorset) reginitcolors();
9426             PerlIO_printf(Perl_debug_log,
9427                       "%sUsing REx %ssubstr:%s \"%s%.60s%s%s\"\n",
9428                       PL_colors[4],
9429                       prog->check_substr ? "" : "utf8 ",
9430                       PL_colors[5],PL_colors[0],
9431                       s,
9432                       PL_colors[1],
9433                       (strlen(s) > 60 ? "..." : ""));
9434         } );
9435
9436     return prog->check_substr ? prog->check_substr : prog->check_utf8;
9437 }
9438
9439 /* 
9440    pregfree() 
9441    
9442    handles refcounting and freeing the perl core regexp structure. When 
9443    it is necessary to actually free the structure the first thing it 
9444    does is call the 'free' method of the regexp_engine associated to to 
9445    the regexp, allowing the handling of the void *pprivate; member 
9446    first. (This routine is not overridable by extensions, which is why 
9447    the extensions free is called first.)
9448    
9449    See regdupe and regdupe_internal if you change anything here. 
9450 */
9451 #ifndef PERL_IN_XSUB_RE
9452 void
9453 Perl_pregfree(pTHX_ REGEXP *r)
9454 {
9455     SvREFCNT_dec(r);
9456 }
9457
9458 void
9459 Perl_pregfree2(pTHX_ REGEXP *rx)
9460 {
9461     dVAR;
9462     struct regexp *const r = (struct regexp *)SvANY(rx);
9463     GET_RE_DEBUG_FLAGS_DECL;
9464
9465     PERL_ARGS_ASSERT_PREGFREE2;
9466
9467     if (r->mother_re) {
9468         ReREFCNT_dec(r->mother_re);
9469     } else {
9470         CALLREGFREE_PVT(rx); /* free the private data */
9471         SvREFCNT_dec(RXp_PAREN_NAMES(r));
9472     }        
9473     if (r->substrs) {
9474         SvREFCNT_dec(r->anchored_substr);
9475         SvREFCNT_dec(r->anchored_utf8);
9476         SvREFCNT_dec(r->float_substr);
9477         SvREFCNT_dec(r->float_utf8);
9478         Safefree(r->substrs);
9479     }
9480     RX_MATCH_COPY_FREE(rx);
9481 #ifdef PERL_OLD_COPY_ON_WRITE
9482     SvREFCNT_dec(r->saved_copy);
9483 #endif
9484     Safefree(r->offs);
9485 }
9486
9487 /*  reg_temp_copy()
9488     
9489     This is a hacky workaround to the structural issue of match results
9490     being stored in the regexp structure which is in turn stored in
9491     PL_curpm/PL_reg_curpm. The problem is that due to qr// the pattern
9492     could be PL_curpm in multiple contexts, and could require multiple
9493     result sets being associated with the pattern simultaneously, such
9494     as when doing a recursive match with (??{$qr})
9495     
9496     The solution is to make a lightweight copy of the regexp structure 
9497     when a qr// is returned from the code executed by (??{$qr}) this
9498     lightweight copy doesnt actually own any of its data except for
9499     the starp/end and the actual regexp structure itself. 
9500     
9501 */    
9502     
9503     
9504 REGEXP *
9505 Perl_reg_temp_copy (pTHX_ REGEXP *ret_x, REGEXP *rx)
9506 {
9507     struct regexp *ret;
9508     struct regexp *const r = (struct regexp *)SvANY(rx);
9509     register const I32 npar = r->nparens+1;
9510
9511     PERL_ARGS_ASSERT_REG_TEMP_COPY;
9512
9513     if (!ret_x)
9514         ret_x = (REGEXP*) newSV_type(SVt_REGEXP);
9515     ret = (struct regexp *)SvANY(ret_x);
9516     
9517     (void)ReREFCNT_inc(rx);
9518     /* We can take advantage of the existing "copied buffer" mechanism in SVs
9519        by pointing directly at the buffer, but flagging that the allocated
9520        space in the copy is zero. As we've just done a struct copy, it's now
9521        a case of zero-ing that, rather than copying the current length.  */
9522     SvPV_set(ret_x, RX_WRAPPED(rx));
9523     SvFLAGS(ret_x) |= SvFLAGS(rx) & (SVf_POK|SVp_POK|SVf_UTF8);
9524     memcpy(&(ret->xpv_cur), &(r->xpv_cur),
9525            sizeof(regexp) - STRUCT_OFFSET(regexp, xpv_cur));
9526     SvLEN_set(ret_x, 0);
9527     SvSTASH_set(ret_x, NULL);
9528     SvMAGIC_set(ret_x, NULL);
9529     Newx(ret->offs, npar, regexp_paren_pair);
9530     Copy(r->offs, ret->offs, npar, regexp_paren_pair);
9531     if (r->substrs) {
9532         Newx(ret->substrs, 1, struct reg_substr_data);
9533         StructCopy(r->substrs, ret->substrs, struct reg_substr_data);
9534
9535         SvREFCNT_inc_void(ret->anchored_substr);
9536         SvREFCNT_inc_void(ret->anchored_utf8);
9537         SvREFCNT_inc_void(ret->float_substr);
9538         SvREFCNT_inc_void(ret->float_utf8);
9539
9540         /* check_substr and check_utf8, if non-NULL, point to either their
9541            anchored or float namesakes, and don't hold a second reference.  */
9542     }
9543     RX_MATCH_COPIED_off(ret_x);
9544 #ifdef PERL_OLD_COPY_ON_WRITE
9545     ret->saved_copy = NULL;
9546 #endif
9547     ret->mother_re = rx;
9548     
9549     return ret_x;
9550 }
9551 #endif
9552
9553 /* regfree_internal() 
9554
9555    Free the private data in a regexp. This is overloadable by 
9556    extensions. Perl takes care of the regexp structure in pregfree(), 
9557    this covers the *pprivate pointer which technically perldoesnt 
9558    know about, however of course we have to handle the 
9559    regexp_internal structure when no extension is in use. 
9560    
9561    Note this is called before freeing anything in the regexp 
9562    structure. 
9563  */
9564  
9565 void
9566 Perl_regfree_internal(pTHX_ REGEXP * const rx)
9567 {
9568     dVAR;
9569     struct regexp *const r = (struct regexp *)SvANY(rx);
9570     RXi_GET_DECL(r,ri);
9571     GET_RE_DEBUG_FLAGS_DECL;
9572
9573     PERL_ARGS_ASSERT_REGFREE_INTERNAL;
9574
9575     DEBUG_COMPILE_r({
9576         if (!PL_colorset)
9577             reginitcolors();
9578         {
9579             SV *dsv= sv_newmortal();
9580             RE_PV_QUOTED_DECL(s, RX_UTF8(rx),
9581                 dsv, RX_PRECOMP(rx), RX_PRELEN(rx), 60);
9582             PerlIO_printf(Perl_debug_log,"%sFreeing REx:%s %s\n", 
9583                 PL_colors[4],PL_colors[5],s);
9584         }
9585     });
9586 #ifdef RE_TRACK_PATTERN_OFFSETS
9587     if (ri->u.offsets)
9588         Safefree(ri->u.offsets);             /* 20010421 MJD */
9589 #endif
9590     if (ri->data) {
9591         int n = ri->data->count;
9592         PAD* new_comppad = NULL;
9593         PAD* old_comppad;
9594         PADOFFSET refcnt;
9595
9596         while (--n >= 0) {
9597           /* If you add a ->what type here, update the comment in regcomp.h */
9598             switch (ri->data->what[n]) {
9599             case 'a':
9600             case 's':
9601             case 'S':
9602             case 'u':
9603                 SvREFCNT_dec(MUTABLE_SV(ri->data->data[n]));
9604                 break;
9605             case 'f':
9606                 Safefree(ri->data->data[n]);
9607                 break;
9608             case 'p':
9609                 new_comppad = MUTABLE_AV(ri->data->data[n]);
9610                 break;
9611             case 'o':
9612                 if (new_comppad == NULL)
9613                     Perl_croak(aTHX_ "panic: pregfree comppad");
9614                 PAD_SAVE_LOCAL(old_comppad,
9615                     /* Watch out for global destruction's random ordering. */
9616                     (SvTYPE(new_comppad) == SVt_PVAV) ? new_comppad : NULL
9617                 );
9618                 OP_REFCNT_LOCK;
9619                 refcnt = OpREFCNT_dec((OP_4tree*)ri->data->data[n]);
9620                 OP_REFCNT_UNLOCK;
9621                 if (!refcnt)
9622                     op_free((OP_4tree*)ri->data->data[n]);
9623
9624                 PAD_RESTORE_LOCAL(old_comppad);
9625                 SvREFCNT_dec(MUTABLE_SV(new_comppad));
9626                 new_comppad = NULL;
9627                 break;
9628             case 'n':
9629                 break;
9630             case 'T':           
9631                 { /* Aho Corasick add-on structure for a trie node.
9632                      Used in stclass optimization only */
9633                     U32 refcount;
9634                     reg_ac_data *aho=(reg_ac_data*)ri->data->data[n];
9635                     OP_REFCNT_LOCK;
9636                     refcount = --aho->refcount;
9637                     OP_REFCNT_UNLOCK;
9638                     if ( !refcount ) {
9639                         PerlMemShared_free(aho->states);
9640                         PerlMemShared_free(aho->fail);
9641                          /* do this last!!!! */
9642                         PerlMemShared_free(ri->data->data[n]);
9643                         PerlMemShared_free(ri->regstclass);
9644                     }
9645                 }
9646                 break;
9647             case 't':
9648                 {
9649                     /* trie structure. */
9650                     U32 refcount;
9651                     reg_trie_data *trie=(reg_trie_data*)ri->data->data[n];
9652                     OP_REFCNT_LOCK;
9653                     refcount = --trie->refcount;
9654                     OP_REFCNT_UNLOCK;
9655                     if ( !refcount ) {
9656                         PerlMemShared_free(trie->charmap);
9657                         PerlMemShared_free(trie->states);
9658                         PerlMemShared_free(trie->trans);
9659                         if (trie->bitmap)
9660                             PerlMemShared_free(trie->bitmap);
9661                         if (trie->jump)
9662                             PerlMemShared_free(trie->jump);
9663                         PerlMemShared_free(trie->wordinfo);
9664                         /* do this last!!!! */
9665                         PerlMemShared_free(ri->data->data[n]);
9666                     }
9667                 }
9668                 break;
9669             default:
9670                 Perl_croak(aTHX_ "panic: regfree data code '%c'", ri->data->what[n]);
9671             }
9672         }
9673         Safefree(ri->data->what);
9674         Safefree(ri->data);
9675     }
9676
9677     Safefree(ri);
9678 }
9679
9680 #define av_dup_inc(s,t) MUTABLE_AV(sv_dup_inc((const SV *)s,t))
9681 #define hv_dup_inc(s,t) MUTABLE_HV(sv_dup_inc((const SV *)s,t))
9682 #define SAVEPVN(p,n)    ((p) ? savepvn(p,n) : NULL)
9683
9684 /* 
9685    re_dup - duplicate a regexp. 
9686    
9687    This routine is expected to clone a given regexp structure. It is only
9688    compiled under USE_ITHREADS.
9689
9690    After all of the core data stored in struct regexp is duplicated
9691    the regexp_engine.dupe method is used to copy any private data
9692    stored in the *pprivate pointer. This allows extensions to handle
9693    any duplication it needs to do.
9694
9695    See pregfree() and regfree_internal() if you change anything here. 
9696 */
9697 #if defined(USE_ITHREADS)
9698 #ifndef PERL_IN_XSUB_RE
9699 void
9700 Perl_re_dup_guts(pTHX_ const REGEXP *sstr, REGEXP *dstr, CLONE_PARAMS *param)
9701 {
9702     dVAR;
9703     I32 npar;
9704     const struct regexp *r = (const struct regexp *)SvANY(sstr);
9705     struct regexp *ret = (struct regexp *)SvANY(dstr);
9706     
9707     PERL_ARGS_ASSERT_RE_DUP_GUTS;
9708
9709     npar = r->nparens+1;
9710     Newx(ret->offs, npar, regexp_paren_pair);
9711     Copy(r->offs, ret->offs, npar, regexp_paren_pair);
9712     if(ret->swap) {
9713         /* no need to copy these */
9714         Newx(ret->swap, npar, regexp_paren_pair);
9715     }
9716
9717     if (ret->substrs) {
9718         /* Do it this way to avoid reading from *r after the StructCopy().
9719            That way, if any of the sv_dup_inc()s dislodge *r from the L1
9720            cache, it doesn't matter.  */
9721         const bool anchored = r->check_substr
9722             ? r->check_substr == r->anchored_substr
9723             : r->check_utf8 == r->anchored_utf8;
9724         Newx(ret->substrs, 1, struct reg_substr_data);
9725         StructCopy(r->substrs, ret->substrs, struct reg_substr_data);
9726
9727         ret->anchored_substr = sv_dup_inc(ret->anchored_substr, param);
9728         ret->anchored_utf8 = sv_dup_inc(ret->anchored_utf8, param);
9729         ret->float_substr = sv_dup_inc(ret->float_substr, param);
9730         ret->float_utf8 = sv_dup_inc(ret->float_utf8, param);
9731
9732         /* check_substr and check_utf8, if non-NULL, point to either their
9733            anchored or float namesakes, and don't hold a second reference.  */
9734
9735         if (ret->check_substr) {
9736             if (anchored) {
9737                 assert(r->check_utf8 == r->anchored_utf8);
9738                 ret->check_substr = ret->anchored_substr;
9739                 ret->check_utf8 = ret->anchored_utf8;
9740             } else {
9741                 assert(r->check_substr == r->float_substr);
9742                 assert(r->check_utf8 == r->float_utf8);
9743                 ret->check_substr = ret->float_substr;
9744                 ret->check_utf8 = ret->float_utf8;
9745             }
9746         } else if (ret->check_utf8) {
9747             if (anchored) {
9748                 ret->check_utf8 = ret->anchored_utf8;
9749             } else {
9750                 ret->check_utf8 = ret->float_utf8;
9751             }
9752         }
9753     }
9754
9755     RXp_PAREN_NAMES(ret) = hv_dup_inc(RXp_PAREN_NAMES(ret), param);
9756
9757     if (ret->pprivate)
9758         RXi_SET(ret,CALLREGDUPE_PVT(dstr,param));
9759
9760     if (RX_MATCH_COPIED(dstr))
9761         ret->subbeg  = SAVEPVN(ret->subbeg, ret->sublen);
9762     else
9763         ret->subbeg = NULL;
9764 #ifdef PERL_OLD_COPY_ON_WRITE
9765     ret->saved_copy = NULL;
9766 #endif
9767
9768     if (ret->mother_re) {
9769         if (SvPVX_const(dstr) == SvPVX_const(ret->mother_re)) {
9770             /* Our storage points directly to our mother regexp, but that's
9771                1: a buffer in a different thread
9772                2: something we no longer hold a reference on
9773                so we need to copy it locally.  */
9774             /* Note we need to sue SvCUR() on our mother_re, because it, in
9775                turn, may well be pointing to its own mother_re.  */
9776             SvPV_set(dstr, SAVEPVN(SvPVX_const(ret->mother_re),
9777                                    SvCUR(ret->mother_re)+1));
9778             SvLEN_set(dstr, SvCUR(ret->mother_re)+1);
9779         }
9780         ret->mother_re      = NULL;
9781     }
9782     ret->gofs = 0;
9783 }
9784 #endif /* PERL_IN_XSUB_RE */
9785
9786 /*
9787    regdupe_internal()
9788    
9789    This is the internal complement to regdupe() which is used to copy
9790    the structure pointed to by the *pprivate pointer in the regexp.
9791    This is the core version of the extension overridable cloning hook.
9792    The regexp structure being duplicated will be copied by perl prior
9793    to this and will be provided as the regexp *r argument, however 
9794    with the /old/ structures pprivate pointer value. Thus this routine
9795    may override any copying normally done by perl.
9796    
9797    It returns a pointer to the new regexp_internal structure.
9798 */
9799
9800 void *
9801 Perl_regdupe_internal(pTHX_ REGEXP * const rx, CLONE_PARAMS *param)
9802 {
9803     dVAR;
9804     struct regexp *const r = (struct regexp *)SvANY(rx);
9805     regexp_internal *reti;
9806     int len, npar;
9807     RXi_GET_DECL(r,ri);
9808
9809     PERL_ARGS_ASSERT_REGDUPE_INTERNAL;
9810     
9811     npar = r->nparens+1;
9812     len = ProgLen(ri);
9813     
9814     Newxc(reti, sizeof(regexp_internal) + len*sizeof(regnode), char, regexp_internal);
9815     Copy(ri->program, reti->program, len+1, regnode);
9816     
9817
9818     reti->regstclass = NULL;
9819
9820     if (ri->data) {
9821         struct reg_data *d;
9822         const int count = ri->data->count;
9823         int i;
9824
9825         Newxc(d, sizeof(struct reg_data) + count*sizeof(void *),
9826                 char, struct reg_data);
9827         Newx(d->what, count, U8);
9828
9829         d->count = count;
9830         for (i = 0; i < count; i++) {
9831             d->what[i] = ri->data->what[i];
9832             switch (d->what[i]) {
9833                 /* legal options are one of: sSfpontTua
9834                    see also regcomp.h and pregfree() */
9835             case 'a': /* actually an AV, but the dup function is identical.  */
9836             case 's':
9837             case 'S':
9838             case 'p': /* actually an AV, but the dup function is identical.  */
9839             case 'u': /* actually an HV, but the dup function is identical.  */
9840                 d->data[i] = sv_dup_inc((const SV *)ri->data->data[i], param);
9841                 break;
9842             case 'f':
9843                 /* This is cheating. */
9844                 Newx(d->data[i], 1, struct regnode_charclass_class);
9845                 StructCopy(ri->data->data[i], d->data[i],
9846                             struct regnode_charclass_class);
9847                 reti->regstclass = (regnode*)d->data[i];
9848                 break;
9849             case 'o':
9850                 /* Compiled op trees are readonly and in shared memory,
9851                    and can thus be shared without duplication. */
9852                 OP_REFCNT_LOCK;
9853                 d->data[i] = (void*)OpREFCNT_inc((OP*)ri->data->data[i]);
9854                 OP_REFCNT_UNLOCK;
9855                 break;
9856             case 'T':
9857                 /* Trie stclasses are readonly and can thus be shared
9858                  * without duplication. We free the stclass in pregfree
9859                  * when the corresponding reg_ac_data struct is freed.
9860                  */
9861                 reti->regstclass= ri->regstclass;
9862                 /* Fall through */
9863             case 't':
9864                 OP_REFCNT_LOCK;
9865                 ((reg_trie_data*)ri->data->data[i])->refcount++;
9866                 OP_REFCNT_UNLOCK;
9867                 /* Fall through */
9868             case 'n':
9869                 d->data[i] = ri->data->data[i];
9870                 break;
9871             default:
9872                 Perl_croak(aTHX_ "panic: re_dup unknown data code '%c'", ri->data->what[i]);
9873             }
9874         }
9875
9876         reti->data = d;
9877     }
9878     else
9879         reti->data = NULL;
9880
9881     reti->name_list_idx = ri->name_list_idx;
9882
9883 #ifdef RE_TRACK_PATTERN_OFFSETS
9884     if (ri->u.offsets) {
9885         Newx(reti->u.offsets, 2*len+1, U32);
9886         Copy(ri->u.offsets, reti->u.offsets, 2*len+1, U32);
9887     }
9888 #else
9889     SetProgLen(reti,len);
9890 #endif
9891
9892     return (void*)reti;
9893 }
9894
9895 #endif    /* USE_ITHREADS */
9896
9897 #ifndef PERL_IN_XSUB_RE
9898
9899 /*
9900  - regnext - dig the "next" pointer out of a node
9901  */
9902 regnode *
9903 Perl_regnext(pTHX_ register regnode *p)
9904 {
9905     dVAR;
9906     register I32 offset;
9907
9908     if (!p)
9909         return(NULL);
9910
9911     if (OP(p) > REGNODE_MAX) {          /* regnode.type is unsigned */
9912         Perl_croak(aTHX_ "Corrupted regexp opcode %d > %d", (int)OP(p), (int)REGNODE_MAX);
9913     }
9914
9915     offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
9916     if (offset == 0)
9917         return(NULL);
9918
9919     return(p+offset);
9920 }
9921 #endif
9922
9923 STATIC void     
9924 S_re_croak2(pTHX_ const char* pat1,const char* pat2,...)
9925 {
9926     va_list args;
9927     STRLEN l1 = strlen(pat1);
9928     STRLEN l2 = strlen(pat2);
9929     char buf[512];
9930     SV *msv;
9931     const char *message;
9932
9933     PERL_ARGS_ASSERT_RE_CROAK2;
9934
9935     if (l1 > 510)
9936         l1 = 510;
9937     if (l1 + l2 > 510)
9938         l2 = 510 - l1;
9939     Copy(pat1, buf, l1 , char);
9940     Copy(pat2, buf + l1, l2 , char);
9941     buf[l1 + l2] = '\n';
9942     buf[l1 + l2 + 1] = '\0';
9943 #ifdef I_STDARG
9944     /* ANSI variant takes additional second argument */
9945     va_start(args, pat2);
9946 #else
9947     va_start(args);
9948 #endif
9949     msv = vmess(buf, &args);
9950     va_end(args);
9951     message = SvPV_const(msv,l1);
9952     if (l1 > 512)
9953         l1 = 512;
9954     Copy(message, buf, l1 , char);
9955     buf[l1-1] = '\0';                   /* Overwrite \n */
9956     Perl_croak(aTHX_ "%s", buf);
9957 }
9958
9959 /* XXX Here's a total kludge.  But we need to re-enter for swash routines. */
9960
9961 #ifndef PERL_IN_XSUB_RE
9962 void
9963 Perl_save_re_context(pTHX)
9964 {
9965     dVAR;
9966
9967     struct re_save_state *state;
9968
9969     SAVEVPTR(PL_curcop);
9970     SSGROW(SAVESTACK_ALLOC_FOR_RE_SAVE_STATE + 1);
9971
9972     state = (struct re_save_state *)(PL_savestack + PL_savestack_ix);
9973     PL_savestack_ix += SAVESTACK_ALLOC_FOR_RE_SAVE_STATE;
9974     SSPUSHUV(SAVEt_RE_STATE);
9975
9976     Copy(&PL_reg_state, state, 1, struct re_save_state);
9977
9978     PL_reg_start_tmp = 0;
9979     PL_reg_start_tmpl = 0;
9980     PL_reg_oldsaved = NULL;
9981     PL_reg_oldsavedlen = 0;
9982     PL_reg_maxiter = 0;
9983     PL_reg_leftiter = 0;
9984     PL_reg_poscache = NULL;
9985     PL_reg_poscache_size = 0;
9986 #ifdef PERL_OLD_COPY_ON_WRITE
9987     PL_nrs = NULL;
9988 #endif
9989
9990     /* Save $1..$n (#18107: UTF-8 s/(\w+)/uc($1)/e); AMS 20021106. */
9991     if (PL_curpm) {
9992         const REGEXP * const rx = PM_GETRE(PL_curpm);
9993         if (rx) {
9994             U32 i;
9995             for (i = 1; i <= RX_NPARENS(rx); i++) {
9996                 char digits[TYPE_CHARS(long)];
9997                 const STRLEN len = my_snprintf(digits, sizeof(digits), "%lu", (long)i);
9998                 GV *const *const gvp
9999                     = (GV**)hv_fetch(PL_defstash, digits, len, 0);
10000
10001                 if (gvp) {
10002                     GV * const gv = *gvp;
10003                     if (SvTYPE(gv) == SVt_PVGV && GvSV(gv))
10004                         save_scalar(gv);
10005                 }
10006             }
10007         }
10008     }
10009 }
10010 #endif
10011
10012 static void
10013 clear_re(pTHX_ void *r)
10014 {
10015     dVAR;
10016     ReREFCNT_dec((REGEXP *)r);
10017 }
10018
10019 #ifdef DEBUGGING
10020
10021 STATIC void
10022 S_put_byte(pTHX_ SV *sv, int c)
10023 {
10024     PERL_ARGS_ASSERT_PUT_BYTE;
10025
10026     /* Our definition of isPRINT() ignores locales, so only bytes that are
10027        not part of UTF-8 are considered printable. I assume that the same
10028        holds for UTF-EBCDIC.
10029        Also, code point 255 is not printable in either (it's E0 in EBCDIC,
10030        which Wikipedia says:
10031
10032        EO, or Eight Ones, is an 8-bit EBCDIC character code represented as all
10033        ones (binary 1111 1111, hexadecimal FF). It is similar, but not
10034        identical, to the ASCII delete (DEL) or rubout control character.
10035        ) So the old condition can be simplified to !isPRINT(c)  */
10036     if (!isPRINT(c))
10037         Perl_sv_catpvf(aTHX_ sv, "\\%o", c);
10038     else {
10039         const char string = c;
10040         if (c == '-' || c == ']' || c == '\\' || c == '^')
10041             sv_catpvs(sv, "\\");
10042         sv_catpvn(sv, &string, 1);
10043     }
10044 }
10045
10046
10047 #define CLEAR_OPTSTART \
10048     if (optstart) STMT_START { \
10049             DEBUG_OPTIMISE_r(PerlIO_printf(Perl_debug_log, " (%"IVdf" nodes)\n", (IV)(node - optstart))); \
10050             optstart=NULL; \
10051     } STMT_END
10052
10053 #define DUMPUNTIL(b,e) CLEAR_OPTSTART; node=dumpuntil(r,start,(b),(e),last,sv,indent+1,depth+1);
10054
10055 STATIC const regnode *
10056 S_dumpuntil(pTHX_ const regexp *r, const regnode *start, const regnode *node,
10057             const regnode *last, const regnode *plast, 
10058             SV* sv, I32 indent, U32 depth)
10059 {
10060     dVAR;
10061     register U8 op = PSEUDO;    /* Arbitrary non-END op. */
10062     register const regnode *next;
10063     const regnode *optstart= NULL;
10064     
10065     RXi_GET_DECL(r,ri);
10066     GET_RE_DEBUG_FLAGS_DECL;
10067
10068     PERL_ARGS_ASSERT_DUMPUNTIL;
10069
10070 #ifdef DEBUG_DUMPUNTIL
10071     PerlIO_printf(Perl_debug_log, "--- %d : %d - %d - %d\n",indent,node-start,
10072         last ? last-start : 0,plast ? plast-start : 0);
10073 #endif
10074             
10075     if (plast && plast < last) 
10076         last= plast;
10077
10078     while (PL_regkind[op] != END && (!last || node < last)) {
10079         /* While that wasn't END last time... */
10080         NODE_ALIGN(node);
10081         op = OP(node);
10082         if (op == CLOSE || op == WHILEM)
10083             indent--;
10084         next = regnext((regnode *)node);
10085
10086         /* Where, what. */
10087         if (OP(node) == OPTIMIZED) {
10088             if (!optstart && RE_DEBUG_FLAG(RE_DEBUG_COMPILE_OPTIMISE))
10089                 optstart = node;
10090             else
10091                 goto after_print;
10092         } else
10093             CLEAR_OPTSTART;
10094         
10095         regprop(r, sv, node);
10096         PerlIO_printf(Perl_debug_log, "%4"IVdf":%*s%s", (IV)(node - start),
10097                       (int)(2*indent + 1), "", SvPVX_const(sv));
10098         
10099         if (OP(node) != OPTIMIZED) {                  
10100             if (next == NULL)           /* Next ptr. */
10101                 PerlIO_printf(Perl_debug_log, " (0)");
10102             else if (PL_regkind[(U8)op] == BRANCH && PL_regkind[OP(next)] != BRANCH )
10103                 PerlIO_printf(Perl_debug_log, " (FAIL)");
10104             else 
10105                 PerlIO_printf(Perl_debug_log, " (%"IVdf")", (IV)(next - start));
10106             (void)PerlIO_putc(Perl_debug_log, '\n'); 
10107         }
10108         
10109       after_print:
10110         if (PL_regkind[(U8)op] == BRANCHJ) {
10111             assert(next);
10112             {
10113                 register const regnode *nnode = (OP(next) == LONGJMP
10114                                              ? regnext((regnode *)next)
10115                                              : next);
10116                 if (last && nnode > last)
10117                     nnode = last;
10118                 DUMPUNTIL(NEXTOPER(NEXTOPER(node)), nnode);
10119             }
10120         }
10121         else if (PL_regkind[(U8)op] == BRANCH) {
10122             assert(next);
10123             DUMPUNTIL(NEXTOPER(node), next);
10124         }
10125         else if ( PL_regkind[(U8)op]  == TRIE ) {
10126             const regnode *this_trie = node;
10127             const char op = OP(node);
10128             const U32 n = ARG(node);
10129             const reg_ac_data * const ac = op>=AHOCORASICK ?
10130                (reg_ac_data *)ri->data->data[n] :
10131                NULL;
10132             const reg_trie_data * const trie =
10133                 (reg_trie_data*)ri->data->data[op<AHOCORASICK ? n : ac->trie];
10134 #ifdef DEBUGGING
10135             AV *const trie_words = MUTABLE_AV(ri->data->data[n + TRIE_WORDS_OFFSET]);
10136 #endif
10137             const regnode *nextbranch= NULL;
10138             I32 word_idx;
10139             sv_setpvs(sv, "");
10140             for (word_idx= 0; word_idx < (I32)trie->wordcount; word_idx++) {
10141                 SV ** const elem_ptr = av_fetch(trie_words,word_idx,0);
10142                 
10143                 PerlIO_printf(Perl_debug_log, "%*s%s ",
10144                    (int)(2*(indent+3)), "",
10145                     elem_ptr ? pv_pretty(sv, SvPV_nolen_const(*elem_ptr), SvCUR(*elem_ptr), 60,
10146                             PL_colors[0], PL_colors[1],
10147                             (SvUTF8(*elem_ptr) ? PERL_PV_ESCAPE_UNI : 0) |
10148                             PERL_PV_PRETTY_ELLIPSES    |
10149                             PERL_PV_PRETTY_LTGT
10150                             )
10151                             : "???"
10152                 );
10153                 if (trie->jump) {
10154                     U16 dist= trie->jump[word_idx+1];
10155                     PerlIO_printf(Perl_debug_log, "(%"UVuf")\n",
10156                                   (UV)((dist ? this_trie + dist : next) - start));
10157                     if (dist) {
10158                         if (!nextbranch)
10159                             nextbranch= this_trie + trie->jump[0];    
10160                         DUMPUNTIL(this_trie + dist, nextbranch);
10161                     }
10162                     if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
10163                         nextbranch= regnext((regnode *)nextbranch);
10164                 } else {
10165                     PerlIO_printf(Perl_debug_log, "\n");
10166                 }
10167             }
10168             if (last && next > last)
10169                 node= last;
10170             else
10171                 node= next;
10172         }
10173         else if ( op == CURLY ) {   /* "next" might be very big: optimizer */
10174             DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS,
10175                     NEXTOPER(node) + EXTRA_STEP_2ARGS + 1);
10176         }
10177         else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
10178             assert(next);
10179             DUMPUNTIL(NEXTOPER(node) + EXTRA_STEP_2ARGS, next);
10180         }
10181         else if ( op == PLUS || op == STAR) {
10182             DUMPUNTIL(NEXTOPER(node), NEXTOPER(node) + 1);
10183         }
10184         else if (op == ANYOF) {
10185             /* arglen 1 + class block */
10186             node += 1 + ((ANYOF_FLAGS(node) & ANYOF_LARGE)
10187                     ? ANYOF_CLASS_SKIP : ANYOF_SKIP);
10188             node = NEXTOPER(node);
10189         }
10190         else if (PL_regkind[(U8)op] == EXACT) {
10191             /* Literal string, where present. */
10192             node += NODE_SZ_STR(node) - 1;
10193             node = NEXTOPER(node);
10194         }
10195         else {
10196             node = NEXTOPER(node);
10197             node += regarglen[(U8)op];
10198         }
10199         if (op == CURLYX || op == OPEN)
10200             indent++;
10201     }
10202     CLEAR_OPTSTART;
10203 #ifdef DEBUG_DUMPUNTIL    
10204     PerlIO_printf(Perl_debug_log, "--- %d\n", (int)indent);
10205 #endif
10206     return node;
10207 }
10208
10209 #endif  /* DEBUGGING */
10210
10211 /*
10212  * Local variables:
10213  * c-indentation-style: bsd
10214  * c-basic-offset: 4
10215  * indent-tabs-mode: t
10216  * End:
10217  *
10218  * ex: set ts=8 sts=4 sw=4 noet:
10219  */