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