Update to Switch 2.02.
[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 /* NOTE: this is derived from Henry Spencer's regexp code, and should not
9  * confused with the original package (see point 3 below).  Thanks, Henry!
10  */
11
12 /* Additional note: this code is very heavily munged from Henry's version
13  * in places.  In some spots I've traded clarity for efficiency, so don't
14  * blame Henry for some of the lack of readability.
15  */
16
17 /* The names of the functions have been changed from regcomp and
18  * regexec to  pregcomp and pregexec in order to avoid conflicts
19  * with the POSIX routines of the same names.
20 */
21
22 #ifdef PERL_EXT_RE_BUILD
23 /* need to replace pregcomp et al, so enable that */
24 #  ifndef PERL_IN_XSUB_RE
25 #    define PERL_IN_XSUB_RE
26 #  endif
27 /* need access to debugger hooks */
28 #  if defined(PERL_EXT_RE_DEBUG) && !defined(DEBUGGING)
29 #    define DEBUGGING
30 #  endif
31 #endif
32
33 #ifdef PERL_IN_XSUB_RE
34 /* We *really* need to overwrite these symbols: */
35 #  define Perl_pregcomp my_regcomp
36 #  define Perl_regdump my_regdump
37 #  define Perl_regprop my_regprop
38 #  define Perl_pregfree my_regfree
39 #  define Perl_re_intuit_string my_re_intuit_string
40 /* *These* symbols are masked to allow static link. */
41 #  define Perl_regnext my_regnext
42 #  define Perl_save_re_context my_save_re_context
43 #  define Perl_reginitcolors my_reginitcolors
44
45 #  define PERL_NO_GET_CONTEXT
46 #endif
47
48 /*SUPPRESS 112*/
49 /*
50  * pregcomp and pregexec -- regsub and regerror are not used in perl
51  *
52  *      Copyright (c) 1986 by University of Toronto.
53  *      Written by Henry Spencer.  Not derived from licensed software.
54  *
55  *      Permission is granted to anyone to use this software for any
56  *      purpose on any computer system, and to redistribute it freely,
57  *      subject to the following restrictions:
58  *
59  *      1. The author is not responsible for the consequences of use of
60  *              this software, no matter how awful, even if they arise
61  *              from defects in it.
62  *
63  *      2. The origin of this software must not be misrepresented, either
64  *              by explicit claim or by omission.
65  *
66  *      3. Altered versions must be plainly marked as such, and must not
67  *              be misrepresented as being the original software.
68  *
69  *
70  ****    Alterations to Henry's code are...
71  ****
72  ****    Copyright (c) 1991-2001, Larry Wall
73  ****
74  ****    You may distribute under the terms of either the GNU General Public
75  ****    License or the Artistic License, as specified in the README file.
76
77  *
78  * Beware that some of this code is subtly aware of the way operator
79  * precedence is structured in regular expressions.  Serious changes in
80  * regular-expression syntax might require a total rethink.
81  */
82 #include "EXTERN.h"
83 #define PERL_IN_REGCOMP_C
84 #include "perl.h"
85
86 #ifdef PERL_IN_XSUB_RE
87 #  if defined(PERL_CAPI) || defined(PERL_OBJECT)
88 #    include "XSUB.h"
89 #  endif
90 #else
91 #  include "INTERN.h"
92 #endif
93
94 #define REG_COMP_C
95 #include "regcomp.h"
96
97 #ifdef op
98 #undef op
99 #endif /* op */
100
101 #ifdef MSDOS
102 # if defined(BUGGY_MSC6)
103  /* MSC 6.00A breaks on op/regexp.t test 85 unless we turn this off */
104  # pragma optimize("a",off)
105  /* But MSC 6.00A is happy with 'w', for aliases only across function calls*/
106  # pragma optimize("w",on )
107 # endif /* BUGGY_MSC6 */
108 #endif /* MSDOS */
109
110 #ifndef STATIC
111 #define STATIC  static
112 #endif
113
114 typedef struct RExC_state_t {
115     U16         flags16;                /* are we folding, multilining? */
116     char        *precomp;               /* uncompiled string. */
117     regexp      *rx;
118     char        *start;                 /* Start of input for compile */
119     char        *end;                   /* End of input for compile */
120     char        *parse;                 /* Input-scan pointer. */
121     I32         whilem_seen;            /* number of WHILEM in this expr */
122     regnode     *emit_start;            /* Start of emitted-code area */
123     regnode     *emit;                  /* Code-emit pointer; &regdummy = don't = compiling */
124     I32         naughty;                /* How bad is this pattern? */
125     I32         sawback;                /* Did we see \1, ...? */
126     U32         seen;
127     I32         size;                   /* Code size. */
128     I32         npar;                   /* () count. */
129     I32         extralen;
130     I32         seen_zerolen;
131     I32         seen_evals;
132     I32         utf8;
133 #if ADD_TO_REGEXEC
134     char        *starttry;              /* -Dr: where regtry was called. */
135 #define RExC_starttry   (pRExC_state->starttry)
136 #endif
137 } RExC_state_t;
138
139 #define RExC_flags16    (pRExC_state->flags16)
140 #define RExC_precomp    (pRExC_state->precomp)
141 #define RExC_rx         (pRExC_state->rx)
142 #define RExC_start      (pRExC_state->start)
143 #define RExC_end        (pRExC_state->end)
144 #define RExC_parse      (pRExC_state->parse)
145 #define RExC_whilem_seen        (pRExC_state->whilem_seen)
146 #define RExC_offsets    (pRExC_state->rx->offsets) /* I am not like the others */
147 #define RExC_emit       (pRExC_state->emit)
148 #define RExC_emit_start (pRExC_state->emit_start)
149 #define RExC_naughty    (pRExC_state->naughty)
150 #define RExC_sawback    (pRExC_state->sawback)
151 #define RExC_seen       (pRExC_state->seen)
152 #define RExC_size       (pRExC_state->size)
153 #define RExC_npar       (pRExC_state->npar)
154 #define RExC_extralen   (pRExC_state->extralen)
155 #define RExC_seen_zerolen       (pRExC_state->seen_zerolen)
156 #define RExC_seen_evals (pRExC_state->seen_evals)
157 #define RExC_utf8       (pRExC_state->utf8)
158
159 #define ISMULT1(c)      ((c) == '*' || (c) == '+' || (c) == '?')
160 #define ISMULT2(s)      ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
161         ((*s) == '{' && regcurly(s)))
162
163 #ifdef SPSTART
164 #undef SPSTART          /* dratted cpp namespace... */
165 #endif
166 /*
167  * Flags to be passed up and down.
168  */
169 #define WORST           0       /* Worst case. */
170 #define HASWIDTH        0x1     /* Known to match non-null strings. */
171 #define SIMPLE          0x2     /* Simple enough to be STAR/PLUS operand. */
172 #define SPSTART         0x4     /* Starts with * or +. */
173 #define TRYAGAIN        0x8     /* Weeded out a declaration. */
174
175 /* Length of a variant. */
176
177 typedef struct scan_data_t {
178     I32 len_min;
179     I32 len_delta;
180     I32 pos_min;
181     I32 pos_delta;
182     SV *last_found;
183     I32 last_end;                       /* min value, <0 unless valid. */
184     I32 last_start_min;
185     I32 last_start_max;
186     SV **longest;                       /* Either &l_fixed, or &l_float. */
187     SV *longest_fixed;
188     I32 offset_fixed;
189     SV *longest_float;
190     I32 offset_float_min;
191     I32 offset_float_max;
192     I32 flags;
193     I32 whilem_c;
194     I32 *last_closep;
195     struct regnode_charclass_class *start_class;
196 } scan_data_t;
197
198 /*
199  * Forward declarations for pregcomp()'s friends.
200  */
201
202 static scan_data_t zero_scan_data = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
203                                       0, 0, 0, 0, 0, 0};
204
205 #define SF_BEFORE_EOL           (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
206 #define SF_BEFORE_SEOL          0x1
207 #define SF_BEFORE_MEOL          0x2
208 #define SF_FIX_BEFORE_EOL       (SF_FIX_BEFORE_SEOL|SF_FIX_BEFORE_MEOL)
209 #define SF_FL_BEFORE_EOL        (SF_FL_BEFORE_SEOL|SF_FL_BEFORE_MEOL)
210
211 #ifdef NO_UNARY_PLUS
212 #  define SF_FIX_SHIFT_EOL      (0+2)
213 #  define SF_FL_SHIFT_EOL               (0+4)
214 #else
215 #  define SF_FIX_SHIFT_EOL      (+2)
216 #  define SF_FL_SHIFT_EOL               (+4)
217 #endif
218
219 #define SF_FIX_BEFORE_SEOL      (SF_BEFORE_SEOL << SF_FIX_SHIFT_EOL)
220 #define SF_FIX_BEFORE_MEOL      (SF_BEFORE_MEOL << SF_FIX_SHIFT_EOL)
221
222 #define SF_FL_BEFORE_SEOL       (SF_BEFORE_SEOL << SF_FL_SHIFT_EOL)
223 #define SF_FL_BEFORE_MEOL       (SF_BEFORE_MEOL << SF_FL_SHIFT_EOL) /* 0x20 */
224 #define SF_IS_INF               0x40
225 #define SF_HAS_PAR              0x80
226 #define SF_IN_PAR               0x100
227 #define SF_HAS_EVAL             0x200
228 #define SCF_DO_SUBSTR           0x400
229 #define SCF_DO_STCLASS_AND      0x0800
230 #define SCF_DO_STCLASS_OR       0x1000
231 #define SCF_DO_STCLASS          (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
232 #define SCF_WHILEM_VISITED_POS  0x2000
233
234 #define UTF RExC_utf8
235 #define LOC (RExC_flags16 & PMf_LOCALE)
236 #define FOLD (RExC_flags16 & PMf_FOLD)
237
238 #define OOB_UNICODE             12345678
239 #define OOB_NAMEDCLASS          -1
240
241 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
242 #define CHR_DIST(a,b) (UTF ? utf8_distance(a,b) : a - b)
243
244
245 /* length of regex to show in messages that don't mark a position within */
246 #define RegexLengthToShowInErrorMessages 127
247
248 /*
249  * If MARKER[12] are adjusted, be sure to adjust the constants at the top
250  * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
251  * op/pragma/warn/regcomp.
252  */
253 #define MARKER1 "HERE"      /* marker as it appears in the description */
254 #define MARKER2 " << HERE "  /* marker as it appears within the regex */
255
256 #define REPORT_LOCATION " before " MARKER1 " mark in regex m/%.*s" MARKER2 "%s/"
257
258 /*
259  * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
260  * arg. Show regex, up to a maximum length. If it's too long, chop and add
261  * "...".
262  */
263 #define FAIL(msg)                                                             \
264     STMT_START {                                                             \
265         char *ellipses = "";                                                 \
266         unsigned len = strlen(RExC_precomp);                                \
267                                                                              \
268         if (!SIZE_ONLY)                                                      \
269             SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx);                 \
270                                                                              \
271         if (len > RegexLengthToShowInErrorMessages) {                        \
272             /* chop 10 shorter than the max, to ensure meaning of "..." */   \
273             len = RegexLengthToShowInErrorMessages - 10;                     \
274             ellipses = "...";                                                \
275         }                                                                    \
276         Perl_croak(aTHX_ "%s in regex m/%.*s%s/",                            \
277                    msg, (int)len, RExC_precomp, ellipses);                  \
278     } STMT_END
279
280 /*
281  * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
282  * args. Show regex, up to a maximum length. If it's too long, chop and add
283  * "...".
284  */
285 #define FAIL2(pat,msg)                                                        \
286     STMT_START {                                                             \
287         char *ellipses = "";                                                 \
288         unsigned len = strlen(RExC_precomp);                                \
289                                                                              \
290         if (!SIZE_ONLY)                                                      \
291             SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx);                 \
292                                                                              \
293         if (len > RegexLengthToShowInErrorMessages) {                        \
294             /* chop 10 shorter than the max, to ensure meaning of "..." */   \
295             len = RegexLengthToShowInErrorMessages - 10;                     \
296             ellipses = "...";                                                \
297         }                                                                    \
298         S_re_croak2(aTHX_ pat, " in regex m/%.*s%s/",                        \
299                     msg, (int)len, RExC_precomp, ellipses);                \
300     } STMT_END
301
302
303 /*
304  * Simple_vFAIL -- like FAIL, but marks the current location in the scan
305  */
306 #define Simple_vFAIL(m)                                                      \
307     STMT_START {                                                             \
308       unsigned offset = strlen(RExC_precomp)-(RExC_end-RExC_parse); \
309                                                                              \
310       Perl_croak(aTHX_ "%s" REPORT_LOCATION,               \
311                  m, (int)offset, RExC_precomp, RExC_precomp + offset);     \
312     } STMT_END
313
314 /*
315  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
316  */
317 #define vFAIL(m)                                                             \
318     STMT_START {                                                             \
319       if (!SIZE_ONLY)                                                        \
320             SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx);                 \
321       Simple_vFAIL(m);                                                       \
322     } STMT_END
323
324 /*
325  * Like Simple_vFAIL(), but accepts two arguments.
326  */
327 #define Simple_vFAIL2(m,a1)                                                  \
328     STMT_START {                                                             \
329       unsigned offset = strlen(RExC_precomp)-(RExC_end-RExC_parse); \
330                                                                              \
331       S_re_croak2(aTHX_ m, REPORT_LOCATION, a1,       \
332                   (int)offset, RExC_precomp, RExC_precomp + offset);       \
333     } STMT_END
334
335 /*
336  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
337  */
338 #define vFAIL2(m,a1)                                                         \
339     STMT_START {                                                             \
340       if (!SIZE_ONLY)                                                        \
341             SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx);                 \
342       Simple_vFAIL2(m, a1);                                                  \
343     } STMT_END
344
345
346 /*
347  * Like Simple_vFAIL(), but accepts three arguments.
348  */
349 #define Simple_vFAIL3(m, a1, a2)                                             \
350     STMT_START {                                                             \
351       unsigned offset = strlen(RExC_precomp)-(RExC_end-RExC_parse); \
352                                                                              \
353       S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2,   \
354                   (int)offset, RExC_precomp, RExC_precomp + offset);       \
355     } STMT_END
356
357 /*
358  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
359  */
360 #define vFAIL3(m,a1,a2)                                                      \
361     STMT_START {                                                             \
362       if (!SIZE_ONLY)                                                        \
363             SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx);                 \
364       Simple_vFAIL3(m, a1, a2);                                              \
365     } STMT_END
366
367 /*
368  * Like Simple_vFAIL(), but accepts four arguments.
369  */
370 #define Simple_vFAIL4(m, a1, a2, a3)                                         \
371     STMT_START {                                                             \
372       unsigned offset = strlen(RExC_precomp)-(RExC_end-RExC_parse); \
373                                                                              \
374       S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, a3,\
375                   (int)offset, RExC_precomp, RExC_precomp + offset);       \
376     } STMT_END
377
378 /*
379  * Like Simple_vFAIL(), but accepts five arguments.
380  */
381 #define Simple_vFAIL5(m, a1, a2, a3, a4)                                     \
382     STMT_START {                                                             \
383       unsigned offset = strlen(RExC_precomp)-(RExC_end-RExC_parse); \
384       S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, a3, a4,\
385                   (int)offset, RExC_precomp, RExC_precomp + offset);       \
386     } STMT_END
387
388
389 #define vWARN(loc,m)                                                         \
390     STMT_START {                                                             \
391         unsigned offset = strlen(RExC_precomp)-(RExC_end-(loc));          \
392         Perl_warner(aTHX_ WARN_REGEXP, "%s" REPORT_LOCATION,\
393                  m, (int)offset, RExC_precomp, RExC_precomp + offset);          \
394     } STMT_END                                                               \
395
396
397 #define vWARN2(loc, m, a1)                                                   \
398     STMT_START {                                                             \
399         unsigned offset = strlen(RExC_precomp)-(RExC_end-(loc));          \
400         Perl_warner(aTHX_ WARN_REGEXP, m REPORT_LOCATION,\
401                  a1,                                                         \
402                  (int)offset, RExC_precomp, RExC_precomp + offset);        \
403     } STMT_END
404
405 #define vWARN3(loc, m, a1, a2)                                               \
406     STMT_START {                                                             \
407       unsigned offset = strlen(RExC_precomp) - (RExC_end - (loc));        \
408         Perl_warner(aTHX_ WARN_REGEXP, m REPORT_LOCATION,                    \
409                  a1, a2,                                                     \
410                  (int)offset, RExC_precomp, RExC_precomp + offset);        \
411     } STMT_END
412
413 #define vWARN4(loc, m, a1, a2, a3)                                           \
414     STMT_START {                                                             \
415       unsigned offset = strlen(RExC_precomp)-(RExC_end-(loc));            \
416         Perl_warner(aTHX_ WARN_REGEXP, m REPORT_LOCATION,\
417                  a1, a2, a3,                                                 \
418                  (int)offset, RExC_precomp, RExC_precomp + offset);        \
419     } STMT_END
420
421
422 /* Allow for side effects in s */
423 #define REGC(c,s) STMT_START { if (!SIZE_ONLY) *(s) = (c); else (s);} STMT_END
424
425 /* Macros for recording node offsets.   20001227 mjd@plover.com 
426  * Nodes are numbered 1, 2, 3, 4.  Node #n's position is recorded in
427  * element 2*n-1 of the array.  Element #2n holds the byte length node #n.
428  * Element 0 holds the number n.
429  */
430
431 #define MJD_OFFSET_DEBUG(x)
432 /* #define MJD_OFFSET_DEBUG(x) fprintf x */
433
434
435 #  define Set_Node_Offset_To_R(node,byte)                           \
436    STMT_START {                                        \
437      if (! SIZE_ONLY) {                                  \
438        if((node) < 0) {                   \
439          Perl_croak(aTHX_ "value of node is %d in Offset macro", node); \
440        } else {                                                        \
441          RExC_offsets[2*(node)-1] = (byte);                               \
442        }                                                               \
443      }                                                                 \
444    } STMT_END
445
446 #  define Set_Node_Offset(node,byte) Set_Node_Offset_To_R((node)-RExC_emit_start, (byte)-RExC_start)
447 #  define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
448
449 #  define Set_Node_Length_To_R(node,len)                            \
450    STMT_START {                                        \
451      if (! SIZE_ONLY) {                                  \
452        MJD_OFFSET_DEBUG((stderr, "** (%d) size of node %d is %d.\n", __LINE__, (node), (len))); \
453        if((node) < 0) {                   \
454          Perl_croak(aTHX_ "value of node is %d in Length macro", node); \
455        } else {                                                        \
456          RExC_offsets[2*(node)] = (len);                               \
457        }                                                               \
458      }                                                                 \
459    } STMT_END
460
461 #  define Set_Node_Length(node,len) Set_Node_Length_To_R((node)-RExC_emit_start, len)
462 #  define Set_Cur_Node_Length(len)  Set_Node_Length(RExC_emit, len)
463 #  define Set_Node_Cur_Length(node)   Set_Node_Length(node, RExC_parse - parse_start)
464
465 /* Get offsets and lengths */
466 #define Node_Offset(n) (RExC_offsets[2*((n)-RExC_emit_start)-1])
467 #define Node_Length(n) (RExC_offsets[2*((n)-RExC_emit_start)])
468
469 static void clear_re(pTHXo_ void *r);
470
471 /* Mark that we cannot extend a found fixed substring at this point.
472    Updata the longest found anchored substring and the longest found
473    floating substrings if needed. */
474
475 STATIC void
476 S_scan_commit(pTHX_ RExC_state_t *pRExC_state, scan_data_t *data)
477 {
478     STRLEN l = CHR_SVLEN(data->last_found);
479     STRLEN old_l = CHR_SVLEN(*data->longest);
480
481     if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
482         sv_setsv(*data->longest, data->last_found);
483         if (*data->longest == data->longest_fixed) {
484             data->offset_fixed = l ? data->last_start_min : data->pos_min;
485             if (data->flags & SF_BEFORE_EOL)
486                 data->flags
487                     |= ((data->flags & SF_BEFORE_EOL) << SF_FIX_SHIFT_EOL);
488             else
489                 data->flags &= ~SF_FIX_BEFORE_EOL;
490         }
491         else {
492             data->offset_float_min = l ? data->last_start_min : data->pos_min;
493             data->offset_float_max = (l
494                                       ? data->last_start_max
495                                       : data->pos_min + data->pos_delta);
496             if (data->flags & SF_BEFORE_EOL)
497                 data->flags
498                     |= ((data->flags & SF_BEFORE_EOL) << SF_FL_SHIFT_EOL);
499             else
500                 data->flags &= ~SF_FL_BEFORE_EOL;
501         }
502     }
503     SvCUR_set(data->last_found, 0);
504     data->last_end = -1;
505     data->flags &= ~SF_BEFORE_EOL;
506 }
507
508 /* Can match anything (initialization) */
509 STATIC void
510 S_cl_anything(pTHX_ RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
511 {
512     int value;
513
514     ANYOF_CLASS_ZERO(cl);
515     for (value = 0; value < 256; ++value)
516         ANYOF_BITMAP_SET(cl, value);
517     cl->flags = ANYOF_EOS|ANYOF_UNICODE_ALL;
518     if (LOC)
519         cl->flags |= ANYOF_LOCALE;
520 }
521
522 /* Can match anything (initialization) */
523 STATIC int
524 S_cl_is_anything(pTHX_ struct regnode_charclass_class *cl)
525 {
526     int value;
527
528     for (value = 0; value <= ANYOF_MAX; value += 2)
529         if (ANYOF_CLASS_TEST(cl, value) && ANYOF_CLASS_TEST(cl, value + 1))
530             return 1;
531     if (!(cl->flags & ANYOF_UNICODE_ALL))
532         return 0;
533     for (value = 0; value < 256; ++value)
534         if (!ANYOF_BITMAP_TEST(cl, value))
535             return 0;
536     return 1;
537 }
538
539 /* Can match anything (initialization) */
540 STATIC void
541 S_cl_init(pTHX_ RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
542 {
543     Zero(cl, 1, struct regnode_charclass_class);
544     cl->type = ANYOF;
545     cl_anything(pRExC_state, cl);
546 }
547
548 STATIC void
549 S_cl_init_zero(pTHX_ RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
550 {
551     Zero(cl, 1, struct regnode_charclass_class);
552     cl->type = ANYOF;
553     cl_anything(pRExC_state, cl);
554     if (LOC)
555         cl->flags |= ANYOF_LOCALE;
556 }
557
558 /* 'And' a given class with another one.  Can create false positives */
559 /* We assume that cl is not inverted */
560 STATIC void
561 S_cl_and(pTHX_ struct regnode_charclass_class *cl,
562          struct regnode_charclass_class *and_with)
563 {
564     if (!(and_with->flags & ANYOF_CLASS)
565         && !(cl->flags & ANYOF_CLASS)
566         && (and_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
567         && !(and_with->flags & ANYOF_FOLD)
568         && !(cl->flags & ANYOF_FOLD)) {
569         int i;
570
571         if (and_with->flags & ANYOF_INVERT)
572             for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
573                 cl->bitmap[i] &= ~and_with->bitmap[i];
574         else
575             for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
576                 cl->bitmap[i] &= and_with->bitmap[i];
577     } /* XXXX: logic is complicated otherwise, leave it along for a moment. */
578     if (!(and_with->flags & ANYOF_EOS))
579         cl->flags &= ~ANYOF_EOS;
580
581     if (cl->flags & ANYOF_UNICODE_ALL && and_with->flags & ANYOF_UNICODE) {
582         cl->flags &= ~ANYOF_UNICODE_ALL;
583         cl->flags |= ANYOF_UNICODE;
584         ARG_SET(cl, ARG(and_with));
585     }
586     if (!(and_with->flags & ANYOF_UNICODE_ALL))
587         cl->flags &= ~ANYOF_UNICODE_ALL;
588     if (!(and_with->flags & (ANYOF_UNICODE|ANYOF_UNICODE_ALL)))
589         cl->flags &= ~ANYOF_UNICODE;
590 }
591
592 /* 'OR' a given class with another one.  Can create false positives */
593 /* We assume that cl is not inverted */
594 STATIC void
595 S_cl_or(pTHX_ RExC_state_t *pRExC_state, struct regnode_charclass_class *cl, struct regnode_charclass_class *or_with)
596 {
597     if (or_with->flags & ANYOF_INVERT) {
598         /* We do not use
599          * (B1 | CL1) | (!B2 & !CL2) = (B1 | !B2 & !CL2) | (CL1 | (!B2 & !CL2))
600          *   <= (B1 | !B2) | (CL1 | !CL2)
601          * which is wasteful if CL2 is small, but we ignore CL2:
602          *   (B1 | CL1) | (!B2 & !CL2) <= (B1 | CL1) | !B2 = (B1 | !B2) | CL1
603          * XXXX Can we handle case-fold?  Unclear:
604          *   (OK1(i) | OK1(i')) | !(OK1(i) | OK1(i')) =
605          *   (OK1(i) | OK1(i')) | (!OK1(i) & !OK1(i'))
606          */
607         if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
608              && !(or_with->flags & ANYOF_FOLD)
609              && !(cl->flags & ANYOF_FOLD) ) {
610             int i;
611
612             for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
613                 cl->bitmap[i] |= ~or_with->bitmap[i];
614         } /* XXXX: logic is complicated otherwise */
615         else {
616             cl_anything(pRExC_state, cl);
617         }
618     } else {
619         /* (B1 | CL1) | (B2 | CL2) = (B1 | B2) | (CL1 | CL2)) */
620         if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
621              && (!(or_with->flags & ANYOF_FOLD)
622                  || (cl->flags & ANYOF_FOLD)) ) {
623             int i;
624
625             /* OR char bitmap and class bitmap separately */
626             for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
627                 cl->bitmap[i] |= or_with->bitmap[i];
628             if (or_with->flags & ANYOF_CLASS) {
629                 for (i = 0; i < ANYOF_CLASSBITMAP_SIZE; i++)
630                     cl->classflags[i] |= or_with->classflags[i];
631                 cl->flags |= ANYOF_CLASS;
632             }
633         }
634         else { /* XXXX: logic is complicated, leave it along for a moment. */
635             cl_anything(pRExC_state, cl);
636         }
637     }
638     if (or_with->flags & ANYOF_EOS)
639         cl->flags |= ANYOF_EOS;
640
641     if (cl->flags & ANYOF_UNICODE && or_with->flags & ANYOF_UNICODE &&
642         ARG(cl) != ARG(or_with)) {
643         cl->flags |= ANYOF_UNICODE_ALL;
644         cl->flags &= ~ANYOF_UNICODE;
645     }
646     if (or_with->flags & ANYOF_UNICODE_ALL) {
647         cl->flags |= ANYOF_UNICODE_ALL;
648         cl->flags &= ~ANYOF_UNICODE;
649     }
650 }
651
652 /* REx optimizer.  Converts nodes into quickier variants "in place".
653    Finds fixed substrings.  */
654
655 /* Stops at toplevel WHILEM as well as at `last'. At end *scanp is set
656    to the position after last scanned or to NULL. */
657
658 STATIC I32
659 S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp, I32 *deltap, regnode *last, scan_data_t *data, U32 flags)
660                         /* scanp: Start here (read-write). */
661                         /* deltap: Write maxlen-minlen here. */
662                         /* last: Stop before this one. */
663 {
664     I32 min = 0, pars = 0, code;
665     regnode *scan = *scanp, *next;
666     I32 delta = 0;
667     int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
668     int is_inf_internal = 0;            /* The studied chunk is infinite */
669     I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
670     scan_data_t data_fake;
671     struct regnode_charclass_class and_with; /* Valid if flags & SCF_DO_STCLASS_OR */
672
673     while (scan && OP(scan) != END && scan < last) {
674         /* Peephole optimizer: */
675
676         if (PL_regkind[(U8)OP(scan)] == EXACT) {
677             /* Merge several consecutive EXACTish nodes into one. */
678             regnode *n = regnext(scan);
679             U32 stringok = 1;
680 #ifdef DEBUGGING
681             regnode *stop = scan;
682 #endif
683
684             next = scan + NODE_SZ_STR(scan);
685             /* Skip NOTHING, merge EXACT*. */
686             while (n &&
687                    ( PL_regkind[(U8)OP(n)] == NOTHING ||
688                      (stringok && (OP(n) == OP(scan))))
689                    && NEXT_OFF(n)
690                    && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX) {
691                 if (OP(n) == TAIL || n > next)
692                     stringok = 0;
693                 if (PL_regkind[(U8)OP(n)] == NOTHING) {
694                     NEXT_OFF(scan) += NEXT_OFF(n);
695                     next = n + NODE_STEP_REGNODE;
696 #ifdef DEBUGGING
697                     if (stringok)
698                         stop = n;
699 #endif
700                     n = regnext(n);
701                 }
702                 else if (stringok) {
703                     int oldl = STR_LEN(scan);
704                     regnode *nnext = regnext(n);
705
706                     if (oldl + STR_LEN(n) > U8_MAX)
707                         break;
708                     NEXT_OFF(scan) += NEXT_OFF(n);
709                     STR_LEN(scan) += STR_LEN(n);
710                     next = n + NODE_SZ_STR(n);
711                     /* Now we can overwrite *n : */
712                     Move(STRING(n), STRING(scan) + oldl, STR_LEN(n), char);
713 #ifdef DEBUGGING
714                     stop = next - 1;
715 #endif
716                     n = nnext;
717                 }
718             }
719 #ifdef DEBUGGING
720             /* Allow dumping */
721             n = scan + NODE_SZ_STR(scan);
722             while (n <= stop) {
723                 if (PL_regkind[(U8)OP(n)] != NOTHING || OP(n) == NOTHING) {
724                     OP(n) = OPTIMIZED;
725                     NEXT_OFF(n) = 0;
726                 }
727                 n++;
728             }
729 #endif
730         }
731         /* Follow the next-chain of the current node and optimize
732            away all the NOTHINGs from it.  */
733         if (OP(scan) != CURLYX) {
734             int max = (reg_off_by_arg[OP(scan)]
735                        ? I32_MAX
736                        /* I32 may be smaller than U16 on CRAYs! */
737                        : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
738             int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
739             int noff;
740             regnode *n = scan;
741         
742             /* Skip NOTHING and LONGJMP. */
743             while ((n = regnext(n))
744                    && ((PL_regkind[(U8)OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
745                        || ((OP(n) == LONGJMP) && (noff = ARG(n))))
746                    && off + noff < max)
747                 off += noff;
748             if (reg_off_by_arg[OP(scan)])
749                 ARG(scan) = off;
750             else
751                 NEXT_OFF(scan) = off;
752         }
753         /* The principal pseudo-switch.  Cannot be a switch, since we
754            look into several different things.  */
755         if (OP(scan) == BRANCH || OP(scan) == BRANCHJ
756                    || OP(scan) == IFTHEN || OP(scan) == SUSPEND) {
757             next = regnext(scan);
758             code = OP(scan);
759         
760             if (OP(next) == code || code == IFTHEN || code == SUSPEND) {
761                 I32 max1 = 0, min1 = I32_MAX, num = 0;
762                 struct regnode_charclass_class accum;
763                 
764                 if (flags & SCF_DO_SUBSTR) /* XXXX Add !SUSPEND? */
765                     scan_commit(pRExC_state, data); /* Cannot merge strings after this. */
766                 if (flags & SCF_DO_STCLASS)
767                     cl_init_zero(pRExC_state, &accum);
768                 while (OP(scan) == code) {
769                     I32 deltanext, minnext, f = 0, fake;
770                     struct regnode_charclass_class this_class;
771
772                     num++;
773                     data_fake.flags = 0;
774                     if (data) {         
775                         data_fake.whilem_c = data->whilem_c;
776                         data_fake.last_closep = data->last_closep;
777                     }
778                     else
779                         data_fake.last_closep = &fake;
780                     next = regnext(scan);
781                     scan = NEXTOPER(scan);
782                     if (code != BRANCH)
783                         scan = NEXTOPER(scan);
784                     if (flags & SCF_DO_STCLASS) {
785                         cl_init(pRExC_state, &this_class);
786                         data_fake.start_class = &this_class;
787                         f = SCF_DO_STCLASS_AND;
788                     }           
789                     if (flags & SCF_WHILEM_VISITED_POS)
790                         f |= SCF_WHILEM_VISITED_POS;
791                     /* we suppose the run is continuous, last=next...*/
792                     minnext = study_chunk(pRExC_state, &scan, &deltanext,
793                                           next, &data_fake, f);
794                     if (min1 > minnext)
795                         min1 = minnext;
796                     if (max1 < minnext + deltanext)
797                         max1 = minnext + deltanext;
798                     if (deltanext == I32_MAX)
799                         is_inf = is_inf_internal = 1;
800                     scan = next;
801                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
802                         pars++;
803                     if (data && (data_fake.flags & SF_HAS_EVAL))
804                         data->flags |= SF_HAS_EVAL;
805                     if (data)
806                         data->whilem_c = data_fake.whilem_c;
807                     if (flags & SCF_DO_STCLASS)
808                         cl_or(pRExC_state, &accum, &this_class);
809                     if (code == SUSPEND)
810                         break;
811                 }
812                 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
813                     min1 = 0;
814                 if (flags & SCF_DO_SUBSTR) {
815                     data->pos_min += min1;
816                     data->pos_delta += max1 - min1;
817                     if (max1 != min1 || is_inf)
818                         data->longest = &(data->longest_float);
819                 }
820                 min += min1;
821                 delta += max1 - min1;
822                 if (flags & SCF_DO_STCLASS_OR) {
823                     cl_or(pRExC_state, data->start_class, &accum);
824                     if (min1) {
825                         cl_and(data->start_class, &and_with);
826                         flags &= ~SCF_DO_STCLASS;
827                     }
828                 }
829                 else if (flags & SCF_DO_STCLASS_AND) {
830                     if (min1) {
831                         cl_and(data->start_class, &accum);
832                         flags &= ~SCF_DO_STCLASS;
833                     }
834                     else {
835                         /* Switch to OR mode: cache the old value of
836                          * data->start_class */
837                         StructCopy(data->start_class, &and_with,
838                                    struct regnode_charclass_class);
839                         flags &= ~SCF_DO_STCLASS_AND;
840                         StructCopy(&accum, data->start_class,
841                                    struct regnode_charclass_class);
842                         flags |= SCF_DO_STCLASS_OR;
843                         data->start_class->flags |= ANYOF_EOS;
844                     }
845                 }
846             }
847             else if (code == BRANCHJ)   /* single branch is optimized. */
848                 scan = NEXTOPER(NEXTOPER(scan));
849             else                        /* single branch is optimized. */
850                 scan = NEXTOPER(scan);
851             continue;
852         }
853         else if (OP(scan) == EXACT) {
854             I32 l = STR_LEN(scan);
855             UV uc = *((U8*)STRING(scan));
856             if (UTF) {
857                 U8 *s = (U8*)STRING(scan);
858                 l = utf8_length(s, s + l);
859                 uc = utf8_to_uvchr(s, NULL);
860             }
861             min += l;
862             if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
863                 /* The code below prefers earlier match for fixed
864                    offset, later match for variable offset.  */
865                 if (data->last_end == -1) { /* Update the start info. */
866                     data->last_start_min = data->pos_min;
867                     data->last_start_max = is_inf
868                         ? I32_MAX : data->pos_min + data->pos_delta;
869                 }
870                 sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));
871                 data->last_end = data->pos_min + l;
872                 data->pos_min += l; /* As in the first entry. */
873                 data->flags &= ~SF_BEFORE_EOL;
874             }
875             if (flags & SCF_DO_STCLASS_AND) {
876                 /* Check whether it is compatible with what we know already! */
877                 int compat = 1;
878
879                 if (uc >= 0x100 ||
880                     !(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
881                     && !ANYOF_BITMAP_TEST(data->start_class, uc)
882                     && (!(data->start_class->flags & ANYOF_FOLD)
883                         || !ANYOF_BITMAP_TEST(data->start_class, PL_fold[uc])))
884                     compat = 0;
885                 ANYOF_CLASS_ZERO(data->start_class);
886                 ANYOF_BITMAP_ZERO(data->start_class);
887                 if (compat)
888                     ANYOF_BITMAP_SET(data->start_class, uc);
889                 data->start_class->flags &= ~ANYOF_EOS;
890                 if (uc < 0x100)
891                   data->start_class->flags &= ~ANYOF_UNICODE_ALL;
892             }
893             else if (flags & SCF_DO_STCLASS_OR) {
894                 /* false positive possible if the class is case-folded */
895                 if (uc < 0x100)
896                     ANYOF_BITMAP_SET(data->start_class, uc);
897                 else
898                     data->start_class->flags |= ANYOF_UNICODE_ALL;
899                 data->start_class->flags &= ~ANYOF_EOS;
900                 cl_and(data->start_class, &and_with);
901             }
902             flags &= ~SCF_DO_STCLASS;
903         }
904         else if (PL_regkind[(U8)OP(scan)] == EXACT) { /* But OP != EXACT! */
905             I32 l = STR_LEN(scan);
906             UV uc = *((U8*)STRING(scan));
907
908             /* Search for fixed substrings supports EXACT only. */
909             if (flags & SCF_DO_SUBSTR)
910                 scan_commit(pRExC_state, data);
911             if (UTF) {
912                 U8 *s = (U8 *)STRING(scan);
913                 l = utf8_length(s, s + l);
914                 uc = utf8_to_uvchr(s, NULL);
915             }
916             min += l;
917             if (data && (flags & SCF_DO_SUBSTR))
918                 data->pos_min += l;
919             if (flags & SCF_DO_STCLASS_AND) {
920                 /* Check whether it is compatible with what we know already! */
921                 int compat = 1;
922
923                 if (uc >= 0x100 ||
924                     !(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
925                     && !ANYOF_BITMAP_TEST(data->start_class, uc)
926                     && !ANYOF_BITMAP_TEST(data->start_class, PL_fold[uc]))
927                     compat = 0;
928                 ANYOF_CLASS_ZERO(data->start_class);
929                 ANYOF_BITMAP_ZERO(data->start_class);
930                 if (compat) {
931                     ANYOF_BITMAP_SET(data->start_class, uc);
932                     data->start_class->flags &= ~ANYOF_EOS;
933                     data->start_class->flags |= ANYOF_FOLD;
934                     if (OP(scan) == EXACTFL)
935                         data->start_class->flags |= ANYOF_LOCALE;
936                 }
937             }
938             else if (flags & SCF_DO_STCLASS_OR) {
939                 if (data->start_class->flags & ANYOF_FOLD) {
940                     /* false positive possible if the class is case-folded.
941                        Assume that the locale settings are the same... */
942                     if (uc < 0x100)
943                         ANYOF_BITMAP_SET(data->start_class, uc);
944                     data->start_class->flags &= ~ANYOF_EOS;
945                 }
946                 cl_and(data->start_class, &and_with);
947             }
948             flags &= ~SCF_DO_STCLASS;
949         }
950         else if (strchr((char*)PL_varies,OP(scan))) {
951             I32 mincount, maxcount, minnext, deltanext, fl;
952             I32 f = flags, pos_before = 0;
953             regnode *oscan = scan;
954             struct regnode_charclass_class this_class;
955             struct regnode_charclass_class *oclass = NULL;
956
957             switch (PL_regkind[(U8)OP(scan)]) {
958             case WHILEM:                /* End of (?:...)* . */
959                 scan = NEXTOPER(scan);
960                 goto finish;
961             case PLUS:
962                 if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
963                     next = NEXTOPER(scan);
964                     if (OP(next) == EXACT || (flags & SCF_DO_STCLASS)) {
965                         mincount = 1;
966                         maxcount = REG_INFTY;
967                         next = regnext(scan);
968                         scan = NEXTOPER(scan);
969                         goto do_curly;
970                     }
971                 }
972                 if (flags & SCF_DO_SUBSTR)
973                     data->pos_min++;
974                 min++;
975                 /* Fall through. */
976             case STAR:
977                 if (flags & SCF_DO_STCLASS) {
978                     mincount = 0;
979                     maxcount = REG_INFTY;
980                     next = regnext(scan);
981                     scan = NEXTOPER(scan);
982                     goto do_curly;
983                 }
984                 is_inf = is_inf_internal = 1;
985                 scan = regnext(scan);
986                 if (flags & SCF_DO_SUBSTR) {
987                     scan_commit(pRExC_state, data); /* Cannot extend fixed substrings */
988                     data->longest = &(data->longest_float);
989                 }
990                 goto optimize_curly_tail;
991             case CURLY:
992                 mincount = ARG1(scan);
993                 maxcount = ARG2(scan);
994                 next = regnext(scan);
995                 if (OP(scan) == CURLYX) {
996                     I32 lp = (data ? *(data->last_closep) : 0);
997
998                     scan->flags = ((lp <= U8_MAX) ? lp : U8_MAX);
999                 }
1000                 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
1001               do_curly:
1002                 if (flags & SCF_DO_SUBSTR) {
1003                     if (mincount == 0) scan_commit(pRExC_state,data); /* Cannot extend fixed substrings */
1004                     pos_before = data->pos_min;
1005                 }
1006                 if (data) {
1007                     fl = data->flags;
1008                     data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
1009                     if (is_inf)
1010                         data->flags |= SF_IS_INF;
1011                 }
1012                 if (flags & SCF_DO_STCLASS) {
1013                     cl_init(pRExC_state, &this_class);
1014                     oclass = data->start_class;
1015                     data->start_class = &this_class;
1016                     f |= SCF_DO_STCLASS_AND;
1017                     f &= ~SCF_DO_STCLASS_OR;
1018                 }
1019                 /* These are the cases when once a subexpression
1020                    fails at a particular position, it cannot succeed
1021                    even after backtracking at the enclosing scope.
1022                 
1023                    XXXX what if minimal match and we are at the
1024                         initial run of {n,m}? */
1025                 if ((mincount != maxcount - 1) && (maxcount != REG_INFTY))
1026                     f &= ~SCF_WHILEM_VISITED_POS;
1027
1028                 /* This will finish on WHILEM, setting scan, or on NULL: */
1029                 minnext = study_chunk(pRExC_state, &scan, &deltanext, last, data,
1030                                       mincount == 0
1031                                         ? (f & ~SCF_DO_SUBSTR) : f);
1032
1033                 if (flags & SCF_DO_STCLASS)
1034                     data->start_class = oclass;
1035                 if (mincount == 0 || minnext == 0) {
1036                     if (flags & SCF_DO_STCLASS_OR) {
1037                         cl_or(pRExC_state, data->start_class, &this_class);
1038                     }
1039                     else if (flags & SCF_DO_STCLASS_AND) {
1040                         /* Switch to OR mode: cache the old value of
1041                          * data->start_class */
1042                         StructCopy(data->start_class, &and_with,
1043                                    struct regnode_charclass_class);
1044                         flags &= ~SCF_DO_STCLASS_AND;
1045                         StructCopy(&this_class, data->start_class,
1046                                    struct regnode_charclass_class);
1047                         flags |= SCF_DO_STCLASS_OR;
1048                         data->start_class->flags |= ANYOF_EOS;
1049                     }
1050                 } else {                /* Non-zero len */
1051                     if (flags & SCF_DO_STCLASS_OR) {
1052                         cl_or(pRExC_state, data->start_class, &this_class);
1053                         cl_and(data->start_class, &and_with);
1054                     }
1055                     else if (flags & SCF_DO_STCLASS_AND)
1056                         cl_and(data->start_class, &this_class);
1057                     flags &= ~SCF_DO_STCLASS;
1058                 }
1059                 if (!scan)              /* It was not CURLYX, but CURLY. */
1060                     scan = next;
1061                 if (ckWARN(WARN_REGEXP) && (minnext + deltanext == 0)
1062                     && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
1063                     && maxcount <= REG_INFTY/3) /* Complement check for big count */
1064                 {
1065                     vWARN(RExC_parse,
1066                           "Quantifier unexpected on zero-length expression");
1067                 }
1068
1069                 min += minnext * mincount;
1070                 is_inf_internal |= ((maxcount == REG_INFTY
1071                                      && (minnext + deltanext) > 0)
1072                                     || deltanext == I32_MAX);
1073                 is_inf |= is_inf_internal;
1074                 delta += (minnext + deltanext) * maxcount - minnext * mincount;
1075
1076                 /* Try powerful optimization CURLYX => CURLYN. */
1077                 if (  OP(oscan) == CURLYX && data
1078                       && data->flags & SF_IN_PAR
1079                       && !(data->flags & SF_HAS_EVAL)
1080                       && !deltanext && minnext == 1 ) {
1081                     /* Try to optimize to CURLYN.  */
1082                     regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
1083                     regnode *nxt1 = nxt, *nxt2;
1084
1085                     /* Skip open. */
1086                     nxt = regnext(nxt);
1087                     if (!strchr((char*)PL_simple,OP(nxt))
1088                         && !(PL_regkind[(U8)OP(nxt)] == EXACT
1089                              && STR_LEN(nxt) == 1))
1090                         goto nogo;
1091                     nxt2 = nxt;
1092                     nxt = regnext(nxt);
1093                     if (OP(nxt) != CLOSE)
1094                         goto nogo;
1095                     /* Now we know that nxt2 is the only contents: */
1096                     oscan->flags = ARG(nxt);
1097                     OP(oscan) = CURLYN;
1098                     OP(nxt1) = NOTHING; /* was OPEN. */
1099 #ifdef DEBUGGING
1100                     OP(nxt1 + 1) = OPTIMIZED; /* was count. */
1101                     NEXT_OFF(nxt1+ 1) = 0; /* just for consistancy. */
1102                     NEXT_OFF(nxt2) = 0; /* just for consistancy with CURLY. */
1103                     OP(nxt) = OPTIMIZED;        /* was CLOSE. */
1104                     OP(nxt + 1) = OPTIMIZED; /* was count. */
1105                     NEXT_OFF(nxt+ 1) = 0; /* just for consistancy. */
1106 #endif
1107                 }
1108               nogo:
1109
1110                 /* Try optimization CURLYX => CURLYM. */
1111                 if (  OP(oscan) == CURLYX && data
1112                       && !(data->flags & SF_HAS_PAR)
1113                       && !(data->flags & SF_HAS_EVAL)
1114                       && !deltanext  ) {
1115                     /* XXXX How to optimize if data == 0? */
1116                     /* Optimize to a simpler form.  */
1117                     regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
1118                     regnode *nxt2;
1119
1120                     OP(oscan) = CURLYM;
1121                     while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
1122                             && (OP(nxt2) != WHILEM))
1123                         nxt = nxt2;
1124                     OP(nxt2)  = SUCCEED; /* Whas WHILEM */
1125                     /* Need to optimize away parenths. */
1126                     if (data->flags & SF_IN_PAR) {
1127                         /* Set the parenth number.  */
1128                         regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
1129
1130                         if (OP(nxt) != CLOSE)
1131                             FAIL("Panic opt close");
1132                         oscan->flags = ARG(nxt);
1133                         OP(nxt1) = OPTIMIZED;   /* was OPEN. */
1134                         OP(nxt) = OPTIMIZED;    /* was CLOSE. */
1135 #ifdef DEBUGGING
1136                         OP(nxt1 + 1) = OPTIMIZED; /* was count. */
1137                         OP(nxt + 1) = OPTIMIZED; /* was count. */
1138                         NEXT_OFF(nxt1 + 1) = 0; /* just for consistancy. */
1139                         NEXT_OFF(nxt + 1) = 0; /* just for consistancy. */
1140 #endif
1141 #if 0
1142                         while ( nxt1 && (OP(nxt1) != WHILEM)) {
1143                             regnode *nnxt = regnext(nxt1);
1144                         
1145                             if (nnxt == nxt) {
1146                                 if (reg_off_by_arg[OP(nxt1)])
1147                                     ARG_SET(nxt1, nxt2 - nxt1);
1148                                 else if (nxt2 - nxt1 < U16_MAX)
1149                                     NEXT_OFF(nxt1) = nxt2 - nxt1;
1150                                 else
1151                                     OP(nxt) = NOTHING;  /* Cannot beautify */
1152                             }
1153                             nxt1 = nnxt;
1154                         }
1155 #endif
1156                         /* Optimize again: */
1157                         study_chunk(pRExC_state, &nxt1, &deltanext, nxt,
1158                                     NULL, 0);
1159                     }
1160                     else
1161                         oscan->flags = 0;
1162                 }
1163                 else if ((OP(oscan) == CURLYX)
1164                          && (flags & SCF_WHILEM_VISITED_POS)
1165                          /* See the comment on a similar expression above.
1166                             However, this time it not a subexpression
1167                             we care about, but the expression itself. */
1168                          && (maxcount == REG_INFTY)
1169                          && data && ++data->whilem_c < 16) {
1170                     /* This stays as CURLYX, we can put the count/of pair. */
1171                     /* Find WHILEM (as in regexec.c) */
1172                     regnode *nxt = oscan + NEXT_OFF(oscan);
1173
1174                     if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
1175                         nxt += ARG(nxt);
1176                     PREVOPER(nxt)->flags = data->whilem_c
1177                         | (RExC_whilem_seen << 4); /* On WHILEM */
1178                 }
1179                 if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
1180                     pars++;
1181                 if (flags & SCF_DO_SUBSTR) {
1182                     SV *last_str = Nullsv;
1183                     int counted = mincount != 0;
1184
1185                     if (data->last_end > 0 && mincount != 0) { /* Ends with a string. */
1186                         I32 b = pos_before >= data->last_start_min
1187                             ? pos_before : data->last_start_min;
1188                         STRLEN l;
1189                         char *s = SvPV(data->last_found, l);
1190                         I32 old = b - data->last_start_min;
1191
1192                         if (UTF)
1193                             old = utf8_hop((U8*)s, old) - (U8*)s;
1194                         
1195                         l -= old;
1196                         /* Get the added string: */
1197                         last_str = newSVpvn(s  + old, l);
1198                         if (deltanext == 0 && pos_before == b) {
1199                             /* What was added is a constant string */
1200                             if (mincount > 1) {
1201                                 SvGROW(last_str, (mincount * l) + 1);
1202                                 repeatcpy(SvPVX(last_str) + l,
1203                                           SvPVX(last_str), l, mincount - 1);
1204                                 SvCUR(last_str) *= mincount;
1205                                 /* Add additional parts. */
1206                                 SvCUR_set(data->last_found,
1207                                           SvCUR(data->last_found) - l);
1208                                 sv_catsv(data->last_found, last_str);
1209                                 data->last_end += l * (mincount - 1);
1210                             }
1211                         } else {
1212                             /* start offset must point into the last copy */
1213                             data->last_start_min += minnext * (mincount - 1);
1214                             data->last_start_max += is_inf ? 0 : (maxcount - 1)
1215                                 * (minnext + data->pos_delta);
1216                         }
1217                     }
1218                     /* It is counted once already... */
1219                     data->pos_min += minnext * (mincount - counted);
1220                     data->pos_delta += - counted * deltanext +
1221                         (minnext + deltanext) * maxcount - minnext * mincount;
1222                     if (mincount != maxcount) {
1223                          /* Cannot extend fixed substrings found inside
1224                             the group.  */
1225                         scan_commit(pRExC_state,data);
1226                         if (mincount && last_str) {
1227                             sv_setsv(data->last_found, last_str);
1228                             data->last_end = data->pos_min;
1229                             data->last_start_min =
1230                                 data->pos_min - CHR_SVLEN(last_str);
1231                             data->last_start_max = is_inf
1232                                 ? I32_MAX
1233                                 : data->pos_min + data->pos_delta
1234                                 - CHR_SVLEN(last_str);
1235                         }
1236                         data->longest = &(data->longest_float);
1237                     }
1238                     SvREFCNT_dec(last_str);
1239                 }
1240                 if (data && (fl & SF_HAS_EVAL))
1241                     data->flags |= SF_HAS_EVAL;
1242               optimize_curly_tail:
1243                 if (OP(oscan) != CURLYX) {
1244                     while (PL_regkind[(U8)OP(next = regnext(oscan))] == NOTHING
1245                            && NEXT_OFF(next))
1246                         NEXT_OFF(oscan) += NEXT_OFF(next);
1247                 }
1248                 continue;
1249             default:                    /* REF and CLUMP only? */
1250                 if (flags & SCF_DO_SUBSTR) {
1251                     scan_commit(pRExC_state,data);      /* Cannot expect anything... */
1252                     data->longest = &(data->longest_float);
1253                 }
1254                 is_inf = is_inf_internal = 1;
1255                 if (flags & SCF_DO_STCLASS_OR)
1256                     cl_anything(pRExC_state, data->start_class);
1257                 flags &= ~SCF_DO_STCLASS;
1258                 break;
1259             }
1260         }
1261         else if (strchr((char*)PL_simple,OP(scan))) {
1262             int value;
1263
1264             if (flags & SCF_DO_SUBSTR) {
1265                 scan_commit(pRExC_state,data);
1266                 data->pos_min++;
1267             }
1268             min++;
1269             if (flags & SCF_DO_STCLASS) {
1270                 data->start_class->flags &= ~ANYOF_EOS; /* No match on empty */
1271
1272                 /* Some of the logic below assumes that switching
1273                    locale on will only add false positives. */
1274                 switch (PL_regkind[(U8)OP(scan)]) {
1275                 case SANY:
1276                 default:
1277                   do_default:
1278                     /* Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d", OP(scan)); */
1279                     if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
1280                         cl_anything(pRExC_state, data->start_class);
1281                     break;
1282                 case REG_ANY:
1283                     if (OP(scan) == SANY)
1284                         goto do_default;
1285                     if (flags & SCF_DO_STCLASS_OR) { /* Everything but \n */
1286                         value = (ANYOF_BITMAP_TEST(data->start_class,'\n')
1287                                  || (data->start_class->flags & ANYOF_CLASS));
1288                         cl_anything(pRExC_state, data->start_class);
1289                     }
1290                     if (flags & SCF_DO_STCLASS_AND || !value)
1291                         ANYOF_BITMAP_CLEAR(data->start_class,'\n');
1292                     break;
1293                 case ANYOF:
1294                     if (flags & SCF_DO_STCLASS_AND)
1295                         cl_and(data->start_class,
1296                                (struct regnode_charclass_class*)scan);
1297                     else
1298                         cl_or(pRExC_state, data->start_class,
1299                               (struct regnode_charclass_class*)scan);
1300                     break;
1301                 case ALNUM:
1302                     if (flags & SCF_DO_STCLASS_AND) {
1303                         if (!(data->start_class->flags & ANYOF_LOCALE)) {
1304                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
1305                             for (value = 0; value < 256; value++)
1306                                 if (!isALNUM(value))
1307                                     ANYOF_BITMAP_CLEAR(data->start_class, value);
1308                         }
1309                     }
1310                     else {
1311                         if (data->start_class->flags & ANYOF_LOCALE)
1312                             ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
1313                         else {
1314                             for (value = 0; value < 256; value++)
1315                                 if (isALNUM(value))
1316                                     ANYOF_BITMAP_SET(data->start_class, value);                 
1317                         }
1318                     }
1319                     break;
1320                 case ALNUML:
1321                     if (flags & SCF_DO_STCLASS_AND) {
1322                         if (data->start_class->flags & ANYOF_LOCALE)
1323                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
1324                     }
1325                     else {
1326                         ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
1327                         data->start_class->flags |= ANYOF_LOCALE;
1328                     }
1329                     break;
1330                 case NALNUM:
1331                     if (flags & SCF_DO_STCLASS_AND) {
1332                         if (!(data->start_class->flags & ANYOF_LOCALE)) {
1333                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
1334                             for (value = 0; value < 256; value++)
1335                                 if (isALNUM(value))
1336                                     ANYOF_BITMAP_CLEAR(data->start_class, value);
1337                         }
1338                     }
1339                     else {
1340                         if (data->start_class->flags & ANYOF_LOCALE)
1341                             ANYOF_CLASS_SET(data->start_class,ANYOF_NALNUM);
1342                         else {
1343                             for (value = 0; value < 256; value++)
1344                                 if (!isALNUM(value))
1345                                     ANYOF_BITMAP_SET(data->start_class, value);                 
1346                         }
1347                     }
1348                     break;
1349                 case NALNUML:
1350                     if (flags & SCF_DO_STCLASS_AND) {
1351                         if (data->start_class->flags & ANYOF_LOCALE)
1352                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
1353                     }
1354                     else {
1355                         data->start_class->flags |= ANYOF_LOCALE;
1356                         ANYOF_CLASS_SET(data->start_class,ANYOF_NALNUM);
1357                     }
1358                     break;
1359                 case SPACE:
1360                     if (flags & SCF_DO_STCLASS_AND) {
1361                         if (!(data->start_class->flags & ANYOF_LOCALE)) {
1362                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NSPACE);
1363                             for (value = 0; value < 256; value++)
1364                                 if (!isSPACE(value))
1365                                     ANYOF_BITMAP_CLEAR(data->start_class, value);
1366                         }
1367                     }
1368                     else {
1369                         if (data->start_class->flags & ANYOF_LOCALE)
1370                             ANYOF_CLASS_SET(data->start_class,ANYOF_SPACE);
1371                         else {
1372                             for (value = 0; value < 256; value++)
1373                                 if (isSPACE(value))
1374                                     ANYOF_BITMAP_SET(data->start_class, value);                 
1375                         }
1376                     }
1377                     break;
1378                 case SPACEL:
1379                     if (flags & SCF_DO_STCLASS_AND) {
1380                         if (data->start_class->flags & ANYOF_LOCALE)
1381                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NSPACE);
1382                     }
1383                     else {
1384                         data->start_class->flags |= ANYOF_LOCALE;
1385                         ANYOF_CLASS_SET(data->start_class,ANYOF_SPACE);
1386                     }
1387                     break;
1388                 case NSPACE:
1389                     if (flags & SCF_DO_STCLASS_AND) {
1390                         if (!(data->start_class->flags & ANYOF_LOCALE)) {
1391                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_SPACE);
1392                             for (value = 0; value < 256; value++)
1393                                 if (isSPACE(value))
1394                                     ANYOF_BITMAP_CLEAR(data->start_class, value);
1395                         }
1396                     }
1397                     else {
1398                         if (data->start_class->flags & ANYOF_LOCALE)
1399                             ANYOF_CLASS_SET(data->start_class,ANYOF_NSPACE);
1400                         else {
1401                             for (value = 0; value < 256; value++)
1402                                 if (!isSPACE(value))
1403                                     ANYOF_BITMAP_SET(data->start_class, value);                 
1404                         }
1405                     }
1406                     break;
1407                 case NSPACEL:
1408                     if (flags & SCF_DO_STCLASS_AND) {
1409                         if (data->start_class->flags & ANYOF_LOCALE) {
1410                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_SPACE);
1411                             for (value = 0; value < 256; value++)
1412                                 if (!isSPACE(value))
1413                                     ANYOF_BITMAP_CLEAR(data->start_class, value);
1414                         }
1415                     }
1416                     else {
1417                         data->start_class->flags |= ANYOF_LOCALE;
1418                         ANYOF_CLASS_SET(data->start_class,ANYOF_NSPACE);
1419                     }
1420                     break;
1421                 case DIGIT:
1422                     if (flags & SCF_DO_STCLASS_AND) {
1423                         ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NDIGIT);
1424                         for (value = 0; value < 256; value++)
1425                             if (!isDIGIT(value))
1426                                 ANYOF_BITMAP_CLEAR(data->start_class, value);
1427                     }
1428                     else {
1429                         if (data->start_class->flags & ANYOF_LOCALE)
1430                             ANYOF_CLASS_SET(data->start_class,ANYOF_DIGIT);
1431                         else {
1432                             for (value = 0; value < 256; value++)
1433                                 if (isDIGIT(value))
1434                                     ANYOF_BITMAP_SET(data->start_class, value);                 
1435                         }
1436                     }
1437                     break;
1438                 case NDIGIT:
1439                     if (flags & SCF_DO_STCLASS_AND) {
1440                         ANYOF_CLASS_CLEAR(data->start_class,ANYOF_DIGIT);
1441                         for (value = 0; value < 256; value++)
1442                             if (isDIGIT(value))
1443                                 ANYOF_BITMAP_CLEAR(data->start_class, value);
1444                     }
1445                     else {
1446                         if (data->start_class->flags & ANYOF_LOCALE)
1447                             ANYOF_CLASS_SET(data->start_class,ANYOF_NDIGIT);
1448                         else {
1449                             for (value = 0; value < 256; value++)
1450                                 if (!isDIGIT(value))
1451                                     ANYOF_BITMAP_SET(data->start_class, value);                 
1452                         }
1453                     }
1454                     break;
1455                 }
1456                 if (flags & SCF_DO_STCLASS_OR)
1457                     cl_and(data->start_class, &and_with);
1458                 flags &= ~SCF_DO_STCLASS;
1459             }
1460         }
1461         else if (PL_regkind[(U8)OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
1462             data->flags |= (OP(scan) == MEOL
1463                             ? SF_BEFORE_MEOL
1464                             : SF_BEFORE_SEOL);
1465         }
1466         else if (  PL_regkind[(U8)OP(scan)] == BRANCHJ
1467                  /* Lookbehind, or need to calculate parens/evals/stclass: */
1468                    && (scan->flags || data || (flags & SCF_DO_STCLASS))
1469                    && (OP(scan) == IFMATCH || OP(scan) == UNLESSM)) {
1470             /* Lookahead/lookbehind */
1471             I32 deltanext, minnext, fake = 0;
1472             regnode *nscan;
1473             struct regnode_charclass_class intrnl;
1474             int f = 0;
1475
1476             data_fake.flags = 0;
1477             if (data) {         
1478                 data_fake.whilem_c = data->whilem_c;
1479                 data_fake.last_closep = data->last_closep;
1480             }
1481             else
1482                 data_fake.last_closep = &fake;
1483             if ( flags & SCF_DO_STCLASS && !scan->flags
1484                  && OP(scan) == IFMATCH ) { /* Lookahead */
1485                 cl_init(pRExC_state, &intrnl);
1486                 data_fake.start_class = &intrnl;
1487                 f |= SCF_DO_STCLASS_AND;
1488             }
1489             if (flags & SCF_WHILEM_VISITED_POS)
1490                 f |= SCF_WHILEM_VISITED_POS;
1491             next = regnext(scan);
1492             nscan = NEXTOPER(NEXTOPER(scan));
1493             minnext = study_chunk(pRExC_state, &nscan, &deltanext, last, &data_fake, f);
1494             if (scan->flags) {
1495                 if (deltanext) {
1496                     vFAIL("Variable length lookbehind not implemented");
1497                 }
1498                 else if (minnext > U8_MAX) {
1499                     vFAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
1500                 }
1501                 scan->flags = minnext;
1502             }
1503             if (data && data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
1504                 pars++;
1505             if (data && (data_fake.flags & SF_HAS_EVAL))
1506                 data->flags |= SF_HAS_EVAL;
1507             if (data)
1508                 data->whilem_c = data_fake.whilem_c;
1509             if (f & SCF_DO_STCLASS_AND) {
1510                 int was = (data->start_class->flags & ANYOF_EOS);
1511
1512                 cl_and(data->start_class, &intrnl);
1513                 if (was)
1514                     data->start_class->flags |= ANYOF_EOS;
1515             }
1516         }
1517         else if (OP(scan) == OPEN) {
1518             pars++;
1519         }
1520         else if (OP(scan) == CLOSE) {
1521             if (ARG(scan) == is_par) {
1522                 next = regnext(scan);
1523
1524                 if ( next && (OP(next) != WHILEM) && next < last)
1525                     is_par = 0;         /* Disable optimization */
1526             }
1527             if (data)
1528                 *(data->last_closep) = ARG(scan);
1529         }
1530         else if (OP(scan) == EVAL) {
1531                 if (data)
1532                     data->flags |= SF_HAS_EVAL;
1533         }
1534         else if (OP(scan) == LOGICAL && scan->flags == 2) { /* Embedded follows */
1535                 if (flags & SCF_DO_SUBSTR) {
1536                     scan_commit(pRExC_state,data);
1537                     data->longest = &(data->longest_float);
1538                 }
1539                 is_inf = is_inf_internal = 1;
1540                 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
1541                     cl_anything(pRExC_state, data->start_class);
1542                 flags &= ~SCF_DO_STCLASS;
1543         }
1544         /* Else: zero-length, ignore. */
1545         scan = regnext(scan);
1546     }
1547
1548   finish:
1549     *scanp = scan;
1550     *deltap = is_inf_internal ? I32_MAX : delta;
1551     if (flags & SCF_DO_SUBSTR && is_inf)
1552         data->pos_delta = I32_MAX - data->pos_min;
1553     if (is_par > U8_MAX)
1554         is_par = 0;
1555     if (is_par && pars==1 && data) {
1556         data->flags |= SF_IN_PAR;
1557         data->flags &= ~SF_HAS_PAR;
1558     }
1559     else if (pars && data) {
1560         data->flags |= SF_HAS_PAR;
1561         data->flags &= ~SF_IN_PAR;
1562     }
1563     if (flags & SCF_DO_STCLASS_OR)
1564         cl_and(data->start_class, &and_with);
1565     return min;
1566 }
1567
1568 STATIC I32
1569 S_add_data(pTHX_ RExC_state_t *pRExC_state, I32 n, char *s)
1570 {
1571     if (RExC_rx->data) {
1572         Renewc(RExC_rx->data,
1573                sizeof(*RExC_rx->data) + sizeof(void*) * (RExC_rx->data->count + n - 1),
1574                char, struct reg_data);
1575         Renew(RExC_rx->data->what, RExC_rx->data->count + n, U8);
1576         RExC_rx->data->count += n;
1577     }
1578     else {
1579         Newc(1207, RExC_rx->data, sizeof(*RExC_rx->data) + sizeof(void*) * (n - 1),
1580              char, struct reg_data);
1581         New(1208, RExC_rx->data->what, n, U8);
1582         RExC_rx->data->count = n;
1583     }
1584     Copy(s, RExC_rx->data->what + RExC_rx->data->count - n, n, U8);
1585     return RExC_rx->data->count - n;
1586 }
1587
1588 void
1589 Perl_reginitcolors(pTHX)
1590 {
1591     int i = 0;
1592     char *s = PerlEnv_getenv("PERL_RE_COLORS");
1593         
1594     if (s) {
1595         PL_colors[0] = s = savepv(s);
1596         while (++i < 6) {
1597             s = strchr(s, '\t');
1598             if (s) {
1599                 *s = '\0';
1600                 PL_colors[i] = ++s;
1601             }
1602             else
1603                 PL_colors[i] = s = "";
1604         }
1605     } else {
1606         while (i < 6)
1607             PL_colors[i++] = "";
1608     }
1609     PL_colorset = 1;
1610 }
1611
1612
1613 /*
1614  - pregcomp - compile a regular expression into internal code
1615  *
1616  * We can't allocate space until we know how big the compiled form will be,
1617  * but we can't compile it (and thus know how big it is) until we've got a
1618  * place to put the code.  So we cheat:  we compile it twice, once with code
1619  * generation turned off and size counting turned on, and once "for real".
1620  * This also means that we don't allocate space until we are sure that the
1621  * thing really will compile successfully, and we never have to move the
1622  * code and thus invalidate pointers into it.  (Note that it has to be in
1623  * one piece because free() must be able to free it all.) [NB: not true in perl]
1624  *
1625  * Beware that the optimization-preparation code in here knows about some
1626  * of the structure of the compiled regexp.  [I'll say.]
1627  */
1628 regexp *
1629 Perl_pregcomp(pTHX_ char *exp, char *xend, PMOP *pm)
1630 {
1631     register regexp *r;
1632     regnode *scan;
1633     regnode *first;
1634     I32 flags;
1635     I32 minlen = 0;
1636     I32 sawplus = 0;
1637     I32 sawopen = 0;
1638     scan_data_t data;
1639     RExC_state_t RExC_state;
1640     RExC_state_t *pRExC_state = &RExC_state;
1641
1642     if (exp == NULL)
1643         FAIL("NULL regexp argument");
1644
1645     /* XXXX This looks very suspicious... */
1646     if (pm->op_pmdynflags & PMdf_CMP_UTF8)
1647         RExC_utf8 = 1;
1648     else
1649         RExC_utf8 = 0;
1650
1651     RExC_precomp = exp;
1652     DEBUG_r(if (!PL_colorset) reginitcolors());
1653     DEBUG_r(PerlIO_printf(Perl_debug_log, "%sCompiling REx%s `%s%*s%s'\n",
1654                       PL_colors[4],PL_colors[5],PL_colors[0],
1655                       (int)(xend - exp), RExC_precomp, PL_colors[1]));
1656     RExC_flags16 = pm->op_pmflags;
1657     RExC_sawback = 0;
1658
1659     RExC_seen = 0;
1660     RExC_seen_zerolen = *exp == '^' ? -1 : 0;
1661     RExC_seen_evals = 0;
1662     RExC_extralen = 0;
1663
1664     /* First pass: determine size, legality. */
1665     RExC_parse = exp;
1666     RExC_start = exp;
1667     RExC_end = xend;
1668     RExC_naughty = 0;
1669     RExC_npar = 1;
1670     RExC_size = 0L;
1671     RExC_emit = &PL_regdummy;
1672     RExC_whilem_seen = 0;
1673 #if 0 /* REGC() is (currently) a NOP at the first pass.
1674        * Clever compilers notice this and complain. --jhi */
1675     REGC((U8)REG_MAGIC, (char*)RExC_emit);
1676 #endif
1677     if (reg(pRExC_state, 0, &flags) == NULL) {
1678         RExC_precomp = Nullch;
1679         return(NULL);
1680     }
1681     DEBUG_r(PerlIO_printf(Perl_debug_log, "size %"IVdf" ", (IV)RExC_size));
1682
1683     /* Small enough for pointer-storage convention?
1684        If extralen==0, this means that we will not need long jumps. */
1685     if (RExC_size >= 0x10000L && RExC_extralen)
1686         RExC_size += RExC_extralen;
1687     else
1688         RExC_extralen = 0;
1689     if (RExC_whilem_seen > 15)
1690         RExC_whilem_seen = 15;
1691
1692     /* Allocate space and initialize. */
1693     Newc(1001, r, sizeof(regexp) + (unsigned)RExC_size * sizeof(regnode),
1694          char, regexp);
1695     if (r == NULL)
1696         FAIL("Regexp out of space");
1697
1698 #ifdef DEBUGGING
1699     /* avoid reading uninitialized memory in DEBUGGING code in study_chunk() */
1700     Zero(r, sizeof(regexp) + (unsigned)RExC_size * sizeof(regnode), char);
1701 #endif
1702     r->refcnt = 1;
1703     r->prelen = xend - exp;
1704     r->precomp = savepvn(RExC_precomp, r->prelen);
1705     r->subbeg = NULL;
1706     r->reganch = pm->op_pmflags & PMf_COMPILETIME;
1707     r->nparens = RExC_npar - 1; /* set early to validate backrefs */
1708
1709     r->substrs = 0;                     /* Useful during FAIL. */
1710     r->startp = 0;                      /* Useful during FAIL. */
1711     r->endp = 0;                        /* Useful during FAIL. */
1712
1713     Newz(1304, r->offsets, 2*RExC_size+1, U32); /* MJD 20001228 */
1714     if (r->offsets) {
1715       r->offsets[0] = RExC_size; 
1716     }
1717     DEBUG_r(PerlIO_printf(Perl_debug_log, 
1718                           "%s %u bytes for offset annotations.\n", 
1719                           r->offsets ? "Got" : "Couldn't get", 
1720                           (2*RExC_size+1) * sizeof(U32)));
1721
1722     RExC_rx = r;
1723
1724     /* Second pass: emit code. */
1725     RExC_parse = exp;
1726     RExC_end = xend;
1727     RExC_naughty = 0;
1728     RExC_npar = 1;
1729     RExC_emit_start = r->program;
1730     RExC_emit = r->program;
1731     /* Store the count of eval-groups for security checks: */
1732     RExC_emit->next_off = ((RExC_seen_evals > U16_MAX) ? U16_MAX : RExC_seen_evals);
1733     REGC((U8)REG_MAGIC, (char*) RExC_emit++);
1734     r->data = 0;
1735     if (reg(pRExC_state, 0, &flags) == NULL)
1736         return(NULL);
1737
1738     /* Dig out information for optimizations. */
1739     r->reganch = pm->op_pmflags & PMf_COMPILETIME; /* Again? */
1740     pm->op_pmflags = RExC_flags16;
1741     if (UTF)
1742         r->reganch |= ROPT_UTF8;
1743     r->regstclass = NULL;
1744     if (RExC_naughty >= 10)     /* Probably an expensive pattern. */
1745         r->reganch |= ROPT_NAUGHTY;
1746     scan = r->program + 1;              /* First BRANCH. */
1747
1748     /* XXXX To minimize changes to RE engine we always allocate
1749        3-units-long substrs field. */
1750     Newz(1004, r->substrs, 1, struct reg_substr_data);
1751
1752     StructCopy(&zero_scan_data, &data, scan_data_t);
1753     /* XXXX Should not we check for something else?  Usually it is OPEN1... */
1754     if (OP(scan) != BRANCH) {   /* Only one top-level choice. */
1755         I32 fake;
1756         STRLEN longest_float_length, longest_fixed_length;
1757         struct regnode_charclass_class ch_class;
1758         int stclass_flag;
1759         I32 last_close = 0;
1760
1761         first = scan;
1762         /* Skip introductions and multiplicators >= 1. */
1763         while ((OP(first) == OPEN && (sawopen = 1)) ||
1764                /* An OR of *one* alternative - should not happen now. */
1765             (OP(first) == BRANCH && OP(regnext(first)) != BRANCH) ||
1766             (OP(first) == PLUS) ||
1767             (OP(first) == MINMOD) ||
1768                /* An {n,m} with n>0 */
1769             (PL_regkind[(U8)OP(first)] == CURLY && ARG1(first) > 0) ) {
1770                 if (OP(first) == PLUS)
1771                     sawplus = 1;
1772                 else
1773                     first += regarglen[(U8)OP(first)];
1774                 first = NEXTOPER(first);
1775         }
1776
1777         /* Starting-point info. */
1778       again:
1779         if (PL_regkind[(U8)OP(first)] == EXACT) {
1780             if (OP(first) == EXACT)
1781                 ;       /* Empty, get anchored substr later. */
1782             else if ((OP(first) == EXACTF || OP(first) == EXACTFL))
1783                 r->regstclass = first;
1784         }
1785         else if (strchr((char*)PL_simple,OP(first)))
1786             r->regstclass = first;
1787         else if (PL_regkind[(U8)OP(first)] == BOUND ||
1788                  PL_regkind[(U8)OP(first)] == NBOUND)
1789             r->regstclass = first;
1790         else if (PL_regkind[(U8)OP(first)] == BOL) {
1791             r->reganch |= (OP(first) == MBOL
1792                            ? ROPT_ANCH_MBOL
1793                            : (OP(first) == SBOL
1794                               ? ROPT_ANCH_SBOL
1795                               : ROPT_ANCH_BOL));
1796             first = NEXTOPER(first);
1797             goto again;
1798         }
1799         else if (OP(first) == GPOS) {
1800             r->reganch |= ROPT_ANCH_GPOS;
1801             first = NEXTOPER(first);
1802             goto again;
1803         }
1804         else if ((OP(first) == STAR &&
1805             PL_regkind[(U8)OP(NEXTOPER(first))] == REG_ANY) &&
1806             !(r->reganch & ROPT_ANCH) )
1807         {
1808             /* turn .* into ^.* with an implied $*=1 */
1809             int type = OP(NEXTOPER(first));
1810
1811             if (type == REG_ANY)
1812                 type = ROPT_ANCH_MBOL;
1813             else
1814                 type = ROPT_ANCH_SBOL;
1815
1816             r->reganch |= type | ROPT_IMPLICIT;
1817             first = NEXTOPER(first);
1818             goto again;
1819         }
1820         if (sawplus && (!sawopen || !RExC_sawback)
1821             && !(RExC_seen & REG_SEEN_EVAL)) /* May examine pos and $& */
1822             /* x+ must match at the 1st pos of run of x's */
1823             r->reganch |= ROPT_SKIP;
1824
1825         /* Scan is after the zeroth branch, first is atomic matcher. */
1826         DEBUG_r(PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
1827                               (IV)(first - scan + 1)));
1828         /*
1829         * If there's something expensive in the r.e., find the
1830         * longest literal string that must appear and make it the
1831         * regmust.  Resolve ties in favor of later strings, since
1832         * the regstart check works with the beginning of the r.e.
1833         * and avoiding duplication strengthens checking.  Not a
1834         * strong reason, but sufficient in the absence of others.
1835         * [Now we resolve ties in favor of the earlier string if
1836         * it happens that c_offset_min has been invalidated, since the
1837         * earlier string may buy us something the later one won't.]
1838         */
1839         minlen = 0;
1840
1841         data.longest_fixed = newSVpvn("",0);
1842         data.longest_float = newSVpvn("",0);
1843         data.last_found = newSVpvn("",0);
1844         data.longest = &(data.longest_fixed);
1845         first = scan;
1846         if (!r->regstclass) {
1847             cl_init(pRExC_state, &ch_class);
1848             data.start_class = &ch_class;
1849             stclass_flag = SCF_DO_STCLASS_AND;
1850         } else                          /* XXXX Check for BOUND? */
1851             stclass_flag = 0;
1852         data.last_closep = &last_close;
1853
1854         minlen = study_chunk(pRExC_state, &first, &fake, scan + RExC_size, /* Up to end */
1855                              &data, SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag);
1856         if ( RExC_npar == 1 && data.longest == &(data.longest_fixed)
1857              && data.last_start_min == 0 && data.last_end > 0
1858              && !RExC_seen_zerolen
1859              && (!(RExC_seen & REG_SEEN_GPOS) || (r->reganch & ROPT_ANCH_GPOS)))
1860             r->reganch |= ROPT_CHECK_ALL;
1861         scan_commit(pRExC_state, &data);
1862         SvREFCNT_dec(data.last_found);
1863
1864         longest_float_length = CHR_SVLEN(data.longest_float);
1865         if (longest_float_length
1866             || (data.flags & SF_FL_BEFORE_EOL
1867                 && (!(data.flags & SF_FL_BEFORE_MEOL)
1868                     || (RExC_flags16 & PMf_MULTILINE)))) {
1869             int t;
1870
1871             if (SvCUR(data.longest_fixed)                       /* ok to leave SvCUR */
1872                 && data.offset_fixed == data.offset_float_min
1873                 && SvCUR(data.longest_fixed) == SvCUR(data.longest_float))
1874                     goto remove_float;          /* As in (a)+. */
1875
1876             r->float_substr = data.longest_float;
1877             r->float_min_offset = data.offset_float_min;
1878             r->float_max_offset = data.offset_float_max;
1879             t = (data.flags & SF_FL_BEFORE_EOL /* Can't have SEOL and MULTI */
1880                        && (!(data.flags & SF_FL_BEFORE_MEOL)
1881                            || (RExC_flags16 & PMf_MULTILINE)));
1882             fbm_compile(r->float_substr, t ? FBMcf_TAIL : 0);
1883         }
1884         else {
1885           remove_float:
1886             r->float_substr = Nullsv;
1887             SvREFCNT_dec(data.longest_float);
1888             longest_float_length = 0;
1889         }
1890
1891         longest_fixed_length = CHR_SVLEN(data.longest_fixed);
1892         if (longest_fixed_length
1893             || (data.flags & SF_FIX_BEFORE_EOL /* Cannot have SEOL and MULTI */
1894                 && (!(data.flags & SF_FIX_BEFORE_MEOL)
1895                     || (RExC_flags16 & PMf_MULTILINE)))) {
1896             int t;
1897
1898             r->anchored_substr = data.longest_fixed;
1899             r->anchored_offset = data.offset_fixed;
1900             t = (data.flags & SF_FIX_BEFORE_EOL /* Can't have SEOL and MULTI */
1901                  && (!(data.flags & SF_FIX_BEFORE_MEOL)
1902                      || (RExC_flags16 & PMf_MULTILINE)));
1903             fbm_compile(r->anchored_substr, t ? FBMcf_TAIL : 0);
1904         }
1905         else {
1906             r->anchored_substr = Nullsv;
1907             SvREFCNT_dec(data.longest_fixed);
1908             longest_fixed_length = 0;
1909         }
1910         if (r->regstclass
1911             && (OP(r->regstclass) == REG_ANY || OP(r->regstclass) == SANY))
1912             r->regstclass = NULL;
1913         if ((!r->anchored_substr || r->anchored_offset) && stclass_flag
1914             && !(data.start_class->flags & ANYOF_EOS)
1915             && !cl_is_anything(data.start_class)) {
1916             SV *sv;
1917             I32 n = add_data(pRExC_state, 1, "f");
1918
1919             New(1006, RExC_rx->data->data[n], 1,
1920                 struct regnode_charclass_class);
1921             StructCopy(data.start_class,
1922                        (struct regnode_charclass_class*)RExC_rx->data->data[n],
1923                        struct regnode_charclass_class);
1924             r->regstclass = (regnode*)RExC_rx->data->data[n];
1925             r->reganch &= ~ROPT_SKIP;   /* Used in find_byclass(). */
1926             PL_regdata = r->data; /* for regprop() */
1927             DEBUG_r((sv = sv_newmortal(),
1928                      regprop(sv, (regnode*)data.start_class),
1929                      PerlIO_printf(Perl_debug_log, "synthetic stclass `%s'.\n",
1930                                    SvPVX(sv))));
1931         }
1932
1933         /* A temporary algorithm prefers floated substr to fixed one to dig more info. */
1934         if (longest_fixed_length > longest_float_length) {
1935             r->check_substr = r->anchored_substr;
1936             r->check_offset_min = r->check_offset_max = r->anchored_offset;
1937             if (r->reganch & ROPT_ANCH_SINGLE)
1938                 r->reganch |= ROPT_NOSCAN;
1939         }
1940         else {
1941             r->check_substr = r->float_substr;
1942             r->check_offset_min = data.offset_float_min;
1943             r->check_offset_max = data.offset_float_max;
1944         }
1945         /* XXXX Currently intuiting is not compatible with ANCH_GPOS.
1946            This should be changed ASAP!  */
1947         if (r->check_substr && !(r->reganch & ROPT_ANCH_GPOS)) {
1948             r->reganch |= RE_USE_INTUIT;
1949             if (SvTAIL(r->check_substr))
1950                 r->reganch |= RE_INTUIT_TAIL;
1951         }
1952     }
1953     else {
1954         /* Several toplevels. Best we can is to set minlen. */
1955         I32 fake;
1956         struct regnode_charclass_class ch_class;
1957         I32 last_close = 0;
1958         
1959         DEBUG_r(PerlIO_printf(Perl_debug_log, "\n"));
1960         scan = r->program + 1;
1961         cl_init(pRExC_state, &ch_class);
1962         data.start_class = &ch_class;
1963         data.last_closep = &last_close;
1964         minlen = study_chunk(pRExC_state, &scan, &fake, scan + RExC_size, &data, SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS);
1965         r->check_substr = r->anchored_substr = r->float_substr = Nullsv;
1966         if (!(data.start_class->flags & ANYOF_EOS)
1967             && !cl_is_anything(data.start_class)) {
1968             SV *sv;
1969             I32 n = add_data(pRExC_state, 1, "f");
1970
1971             New(1006, RExC_rx->data->data[n], 1,
1972                 struct regnode_charclass_class);
1973             StructCopy(data.start_class,
1974                        (struct regnode_charclass_class*)RExC_rx->data->data[n],
1975                        struct regnode_charclass_class);
1976             r->regstclass = (regnode*)RExC_rx->data->data[n];
1977             r->reganch &= ~ROPT_SKIP;   /* Used in find_byclass(). */
1978             DEBUG_r((sv = sv_newmortal(),
1979                      regprop(sv, (regnode*)data.start_class),
1980                      PerlIO_printf(Perl_debug_log, "synthetic stclass `%s'.\n",
1981                                    SvPVX(sv))));
1982         }
1983     }
1984
1985     r->minlen = minlen;
1986     if (RExC_seen & REG_SEEN_GPOS)
1987         r->reganch |= ROPT_GPOS_SEEN;
1988     if (RExC_seen & REG_SEEN_LOOKBEHIND)
1989         r->reganch |= ROPT_LOOKBEHIND_SEEN;
1990     if (RExC_seen & REG_SEEN_EVAL)
1991         r->reganch |= ROPT_EVAL_SEEN;
1992     if (RExC_seen & REG_SEEN_SANY)
1993         r->reganch |= ROPT_SANY_SEEN;
1994     Newz(1002, r->startp, RExC_npar, I32);
1995     Newz(1002, r->endp, RExC_npar, I32);
1996     PL_regdata = r->data; /* for regprop() */
1997     DEBUG_r(regdump(r));
1998     return(r);
1999 }
2000
2001 /*
2002  - reg - regular expression, i.e. main body or parenthesized thing
2003  *
2004  * Caller must absorb opening parenthesis.
2005  *
2006  * Combining parenthesis handling with the base level of regular expression
2007  * is a trifle forced, but the need to tie the tails of the branches to what
2008  * follows makes it hard to avoid.
2009  */
2010 STATIC regnode *
2011 S_reg(pTHX_ RExC_state_t *pRExC_state, I32 paren, I32 *flagp)
2012     /* paren: Parenthesized? 0=top, 1=(, inside: changed to letter. */
2013 {
2014     register regnode *ret;              /* Will be the head of the group. */
2015     register regnode *br;
2016     register regnode *lastbr;
2017     register regnode *ender = 0;
2018     register I32 parno = 0;
2019     I32 flags, oregflags = RExC_flags16, have_branch = 0, open = 0;
2020     char * parse_start = RExC_parse; /* MJD */
2021     char *oregcomp_parse = RExC_parse;
2022     char c;
2023
2024     *flagp = 0;                         /* Tentatively. */
2025
2026     /* Make an OPEN node, if parenthesized. */
2027     if (paren) {
2028         if (*RExC_parse == '?') { /* (?...) */
2029             U16 posflags = 0, negflags = 0;
2030             U16 *flagsp = &posflags;
2031             int logical = 0;
2032             char *seqstart = RExC_parse;
2033
2034             RExC_parse++;
2035             paren = *RExC_parse++;
2036             ret = NULL;                 /* For look-ahead/behind. */
2037             switch (paren) {
2038             case '<':           /* (?<...) */
2039                 RExC_seen |= REG_SEEN_LOOKBEHIND;
2040                 if (*RExC_parse == '!')
2041                     paren = ',';
2042                 if (*RExC_parse != '=' && *RExC_parse != '!')
2043                     goto unknown;
2044                 RExC_parse++;
2045             case '=':           /* (?=...) */
2046             case '!':           /* (?!...) */
2047                 RExC_seen_zerolen++;
2048             case ':':           /* (?:...) */
2049             case '>':           /* (?>...) */
2050                 break;
2051             case '$':           /* (?$...) */
2052             case '@':           /* (?@...) */
2053                 vFAIL2("Sequence (?%c...) not implemented", (int)paren);
2054                 break;
2055             case '#':           /* (?#...) */
2056                 while (*RExC_parse && *RExC_parse != ')')
2057                     RExC_parse++;
2058                 if (*RExC_parse != ')')
2059                     FAIL("Sequence (?#... not terminated");
2060                 nextchar(pRExC_state);
2061                 *flagp = TRYAGAIN;
2062                 return NULL;
2063             case 'p':           /* (?p...) */
2064                 if (SIZE_ONLY)
2065                     vWARN(RExC_parse, "(?p{}) is deprecated - use (??{})");
2066                 /* FALL THROUGH*/
2067             case '?':           /* (??...) */
2068                 logical = 1;
2069                 paren = *RExC_parse++;
2070                 /* FALL THROUGH */
2071             case '{':           /* (?{...}) */
2072             {
2073                 I32 count = 1, n = 0;
2074                 char c;
2075                 char *s = RExC_parse;
2076                 SV *sv;
2077                 OP_4tree *sop, *rop;
2078
2079                 RExC_seen_zerolen++;
2080                 RExC_seen |= REG_SEEN_EVAL;
2081                 while (count && (c = *RExC_parse)) {
2082                     if (c == '\\' && RExC_parse[1])
2083                         RExC_parse++;
2084                     else if (c == '{')
2085                         count++;
2086                     else if (c == '}')
2087                         count--;
2088                     RExC_parse++;
2089                 }
2090                 if (*RExC_parse != ')')
2091                 {
2092                     RExC_parse = s;             
2093                     vFAIL("Sequence (?{...}) not terminated or not {}-balanced");
2094                 }
2095                 if (!SIZE_ONLY) {
2096                     AV *av;
2097                 
2098                     if (RExC_parse - 1 - s)
2099                         sv = newSVpvn(s, RExC_parse - 1 - s);
2100                     else
2101                         sv = newSVpvn("", 0);
2102
2103                     ENTER;
2104                     Perl_save_re_context(aTHX);
2105                     rop = sv_compile_2op(sv, &sop, "re", &av);
2106                     LEAVE;
2107
2108                     n = add_data(pRExC_state, 3, "nop");
2109                     RExC_rx->data->data[n] = (void*)rop;
2110                     RExC_rx->data->data[n+1] = (void*)sop;
2111                     RExC_rx->data->data[n+2] = (void*)av;
2112                     SvREFCNT_dec(sv);
2113                 }
2114                 else {                                          /* First pass */
2115                     if (PL_reginterp_cnt < ++RExC_seen_evals
2116                         && PL_curcop != &PL_compiling)
2117                         /* No compiled RE interpolated, has runtime
2118                            components ===> unsafe.  */
2119                         FAIL("Eval-group not allowed at runtime, use re 'eval'");
2120                     if (PL_tainted)
2121                         FAIL("Eval-group in insecure regular expression");
2122                 }
2123                 
2124                 nextchar(pRExC_state);
2125                 if (logical) {
2126                     ret = reg_node(pRExC_state, LOGICAL);
2127                     if (!SIZE_ONLY)
2128                         ret->flags = 2;
2129                     regtail(pRExC_state, ret, reganode(pRExC_state, EVAL, n));
2130                     /* deal with the length of this later - MJD */
2131                     return ret;
2132                 }
2133                 return reganode(pRExC_state, EVAL, n);
2134             }
2135             case '(':           /* (?(?{...})...) and (?(?=...)...) */
2136             {
2137                 if (RExC_parse[0] == '?') {        /* (?(?...)) */
2138                     if (RExC_parse[1] == '=' || RExC_parse[1] == '!'
2139                         || RExC_parse[1] == '<'
2140                         || RExC_parse[1] == '{') { /* Lookahead or eval. */
2141                         I32 flag;
2142                         
2143                         ret = reg_node(pRExC_state, LOGICAL);
2144                         if (!SIZE_ONLY)
2145                             ret->flags = 1;
2146                         regtail(pRExC_state, ret, reg(pRExC_state, 1, &flag));
2147                         goto insert_if;
2148                     }
2149                 }
2150                 else if (RExC_parse[0] >= '1' && RExC_parse[0] <= '9' ) {
2151                     /* (?(1)...) */
2152                     parno = atoi(RExC_parse++);
2153
2154                     while (isDIGIT(*RExC_parse))
2155                         RExC_parse++;
2156                     ret = reganode(pRExC_state, GROUPP, parno);
2157                     
2158                     if ((c = *nextchar(pRExC_state)) != ')')
2159                         vFAIL("Switch condition not recognized");
2160                   insert_if:
2161                     regtail(pRExC_state, ret, reganode(pRExC_state, IFTHEN, 0));
2162                     br = regbranch(pRExC_state, &flags, 1);
2163                     if (br == NULL)
2164                         br = reganode(pRExC_state, LONGJMP, 0);
2165                     else
2166                         regtail(pRExC_state, br, reganode(pRExC_state, LONGJMP, 0));
2167                     c = *nextchar(pRExC_state);
2168                     if (flags&HASWIDTH)
2169                         *flagp |= HASWIDTH;
2170                     if (c == '|') {
2171                         lastbr = reganode(pRExC_state, IFTHEN, 0); /* Fake one for optimizer. */
2172                         regbranch(pRExC_state, &flags, 1);
2173                         regtail(pRExC_state, ret, lastbr);
2174                         if (flags&HASWIDTH)
2175                             *flagp |= HASWIDTH;
2176                         c = *nextchar(pRExC_state);
2177                     }
2178                     else
2179                         lastbr = NULL;
2180                     if (c != ')')
2181                         vFAIL("Switch (?(condition)... contains too many branches");
2182                     ender = reg_node(pRExC_state, TAIL);
2183                     regtail(pRExC_state, br, ender);
2184                     if (lastbr) {
2185                         regtail(pRExC_state, lastbr, ender);
2186                         regtail(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender);
2187                     }
2188                     else
2189                         regtail(pRExC_state, ret, ender);
2190                     return ret;
2191                 }
2192                 else {
2193                     vFAIL2("Unknown switch condition (?(%.2s", RExC_parse);
2194                 }
2195             }
2196             case 0:
2197                 RExC_parse--; /* for vFAIL to print correctly */
2198                 vFAIL("Sequence (? incomplete");
2199                 break;
2200             default:
2201                 --RExC_parse;
2202               parse_flags:      /* (?i) */
2203                 while (*RExC_parse && strchr("iogcmsx", *RExC_parse)) {
2204                     if (*RExC_parse != 'o')
2205                         pmflag(flagsp, *RExC_parse);
2206                     ++RExC_parse;
2207                 }
2208                 if (*RExC_parse == '-') {
2209                     flagsp = &negflags;
2210                     ++RExC_parse;
2211                     goto parse_flags;
2212                 }
2213                 RExC_flags16 |= posflags;
2214                 RExC_flags16 &= ~negflags;
2215                 if (*RExC_parse == ':') {
2216                     RExC_parse++;
2217                     paren = ':';
2218                     break;
2219                 }               
2220               unknown:
2221                 if (*RExC_parse != ')') {
2222                     RExC_parse++;
2223                     vFAIL3("Sequence (%.*s...) not recognized", RExC_parse-seqstart, seqstart);
2224                 }
2225                 nextchar(pRExC_state);
2226                 *flagp = TRYAGAIN;
2227                 return NULL;
2228             }
2229         }
2230         else {                  /* (...) */
2231             parno = RExC_npar;
2232             RExC_npar++;
2233             ret = reganode(pRExC_state, OPEN, parno);
2234             Set_Node_Length(ret, 1); /* MJD */
2235             Set_Node_Offset(ret, RExC_parse); /* MJD */
2236             open = 1;
2237         }
2238     }
2239     else                        /* ! paren */
2240         ret = NULL;
2241
2242     /* Pick up the branches, linking them together. */
2243     parse_start = RExC_parse;   /* MJD */
2244     br = regbranch(pRExC_state, &flags, 1);
2245     /*     branch_len = (paren != 0); */
2246     
2247     if (br == NULL)
2248         return(NULL);
2249     if (*RExC_parse == '|') {
2250         if (!SIZE_ONLY && RExC_extralen) {
2251             reginsert(pRExC_state, BRANCHJ, br);
2252         }
2253         else {                  /* MJD */
2254             reginsert(pRExC_state, BRANCH, br);
2255             Set_Node_Length(br, paren != 0);
2256             Set_Node_Offset_To_R(br-RExC_emit_start, parse_start-RExC_start);
2257         }
2258         have_branch = 1;
2259         if (SIZE_ONLY)
2260             RExC_extralen += 1;         /* For BRANCHJ-BRANCH. */
2261     }
2262     else if (paren == ':') {
2263         *flagp |= flags&SIMPLE;
2264     }
2265     if (open) {                         /* Starts with OPEN. */
2266         regtail(pRExC_state, ret, br);          /* OPEN -> first. */
2267     }
2268     else if (paren != '?')              /* Not Conditional */
2269         ret = br;
2270     if (flags&HASWIDTH)
2271         *flagp |= HASWIDTH;
2272     *flagp |= flags&SPSTART;
2273     lastbr = br;
2274     while (*RExC_parse == '|') {
2275         if (!SIZE_ONLY && RExC_extralen) {
2276             ender = reganode(pRExC_state, LONGJMP,0);
2277             regtail(pRExC_state, NEXTOPER(NEXTOPER(lastbr)), ender); /* Append to the previous. */
2278         }
2279         if (SIZE_ONLY)
2280             RExC_extralen += 2;         /* Account for LONGJMP. */
2281         nextchar(pRExC_state);
2282         br = regbranch(pRExC_state, &flags, 0);
2283         
2284         if (br == NULL)
2285             return(NULL);
2286         regtail(pRExC_state, lastbr, br);               /* BRANCH -> BRANCH. */
2287         lastbr = br;
2288         if (flags&HASWIDTH)
2289             *flagp |= HASWIDTH;
2290         *flagp |= flags&SPSTART;
2291     }
2292
2293     if (have_branch || paren != ':') {
2294         /* Make a closing node, and hook it on the end. */
2295         switch (paren) {
2296         case ':':
2297             ender = reg_node(pRExC_state, TAIL);
2298             break;
2299         case 1:
2300             ender = reganode(pRExC_state, CLOSE, parno);
2301             Set_Node_Offset(ender,RExC_parse+1); /* MJD */
2302             Set_Node_Length(ender,1); /* MJD */
2303             break;
2304         case '<':
2305         case ',':
2306         case '=':
2307         case '!':
2308             *flagp &= ~HASWIDTH;
2309             /* FALL THROUGH */
2310         case '>':
2311             ender = reg_node(pRExC_state, SUCCEED);
2312             break;
2313         case 0:
2314             ender = reg_node(pRExC_state, END);
2315             break;
2316         }
2317         regtail(pRExC_state, lastbr, ender);
2318
2319         if (have_branch) {
2320             /* Hook the tails of the branches to the closing node. */
2321             for (br = ret; br != NULL; br = regnext(br)) {
2322                 regoptail(pRExC_state, br, ender);
2323             }
2324         }
2325     }
2326
2327     {
2328         char *p;
2329         static char parens[] = "=!<,>";
2330
2331         if (paren && (p = strchr(parens, paren))) {
2332             int node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
2333             int flag = (p - parens) > 1;
2334
2335             if (paren == '>')
2336                 node = SUSPEND, flag = 0;
2337             reginsert(pRExC_state, node,ret);
2338             ret->flags = flag;
2339             regtail(pRExC_state, ret, reg_node(pRExC_state, TAIL));
2340         }
2341     }
2342
2343     /* Check for proper termination. */
2344     if (paren) {
2345         RExC_flags16 = oregflags;
2346         if (RExC_parse >= RExC_end || *nextchar(pRExC_state) != ')') {
2347             RExC_parse = oregcomp_parse;
2348             vFAIL("Unmatched (");
2349         }
2350     }
2351     else if (!paren && RExC_parse < RExC_end) {
2352         if (*RExC_parse == ')') {
2353             RExC_parse++;
2354             vFAIL("Unmatched )");
2355         }
2356         else
2357             FAIL("Junk on end of regexp");      /* "Can't happen". */
2358         /* NOTREACHED */
2359     }
2360
2361     return(ret);
2362 }
2363
2364 /*
2365  - regbranch - one alternative of an | operator
2366  *
2367  * Implements the concatenation operator.
2368  */
2369 STATIC regnode *
2370 S_regbranch(pTHX_ RExC_state_t *pRExC_state, I32 *flagp, I32 first)
2371 {
2372     register regnode *ret;
2373     register regnode *chain = NULL;
2374     register regnode *latest;
2375     I32 flags = 0, c = 0;
2376
2377     if (first)
2378         ret = NULL;
2379     else {
2380         if (!SIZE_ONLY && RExC_extralen)
2381             ret = reganode(pRExC_state, BRANCHJ,0);
2382         else {
2383             ret = reg_node(pRExC_state, BRANCH);
2384             Set_Node_Length(ret, 1);
2385         }
2386     }
2387         
2388     if (!first && SIZE_ONLY)
2389         RExC_extralen += 1;                     /* BRANCHJ */
2390
2391     *flagp = WORST;                     /* Tentatively. */
2392
2393     RExC_parse--;
2394     nextchar(pRExC_state);
2395     while (RExC_parse < RExC_end && *RExC_parse != '|' && *RExC_parse != ')') {
2396         flags &= ~TRYAGAIN;
2397         latest = regpiece(pRExC_state, &flags);
2398         if (latest == NULL) {
2399             if (flags & TRYAGAIN)
2400                 continue;
2401             return(NULL);
2402         }
2403         else if (ret == NULL)
2404             ret = latest;
2405         *flagp |= flags&HASWIDTH;
2406         if (chain == NULL)      /* First piece. */
2407             *flagp |= flags&SPSTART;
2408         else {
2409             RExC_naughty++;
2410             regtail(pRExC_state, chain, latest);
2411         }
2412         chain = latest;
2413         c++;
2414     }
2415     if (chain == NULL) {        /* Loop ran zero times. */
2416         chain = reg_node(pRExC_state, NOTHING);
2417         if (ret == NULL)
2418             ret = chain;
2419     }
2420     if (c == 1) {
2421         *flagp |= flags&SIMPLE;
2422     }
2423
2424     return(ret);
2425 }
2426
2427 /*
2428  - regpiece - something followed by possible [*+?]
2429  *
2430  * Note that the branching code sequences used for ? and the general cases
2431  * of * and + are somewhat optimized:  they use the same NOTHING node as
2432  * both the endmarker for their branch list and the body of the last branch.
2433  * It might seem that this node could be dispensed with entirely, but the
2434  * endmarker role is not redundant.
2435  */
2436 STATIC regnode *
2437 S_regpiece(pTHX_ RExC_state_t *pRExC_state, I32 *flagp)
2438 {
2439     register regnode *ret;
2440     register char op;
2441     register char *next;
2442     I32 flags;
2443     char *origparse = RExC_parse;
2444     char *maxpos;
2445     I32 min;
2446     I32 max = REG_INFTY;
2447     char *parse_start;
2448
2449     ret = regatom(pRExC_state, &flags);
2450     if (ret == NULL) {
2451         if (flags & TRYAGAIN)
2452             *flagp |= TRYAGAIN;
2453         return(NULL);
2454     }
2455
2456     op = *RExC_parse;
2457
2458     if (op == '{' && regcurly(RExC_parse)) {
2459         parse_start = RExC_parse; /* MJD */
2460         next = RExC_parse + 1;
2461         maxpos = Nullch;
2462         while (isDIGIT(*next) || *next == ',') {
2463             if (*next == ',') {
2464                 if (maxpos)
2465                     break;
2466                 else
2467                     maxpos = next;
2468             }
2469             next++;
2470         }
2471         if (*next == '}') {             /* got one */
2472             if (!maxpos)
2473                 maxpos = next;
2474             RExC_parse++;
2475             min = atoi(RExC_parse);
2476             if (*maxpos == ',')
2477                 maxpos++;
2478             else
2479                 maxpos = RExC_parse;
2480             max = atoi(maxpos);
2481             if (!max && *maxpos != '0')
2482                 max = REG_INFTY;                /* meaning "infinity" */
2483             else if (max >= REG_INFTY)
2484                 vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
2485             RExC_parse = next;
2486             nextchar(pRExC_state);
2487
2488         do_curly:
2489             if ((flags&SIMPLE)) {
2490                 RExC_naughty += 2 + RExC_naughty / 2;
2491                 reginsert(pRExC_state, CURLY, ret);
2492                 Set_Node_Offset(ret, parse_start+1); /* MJD */
2493                 Set_Node_Cur_Length(ret);
2494             }
2495             else {
2496                 regnode *w = reg_node(pRExC_state, WHILEM);
2497
2498                 w->flags = 0;
2499                 regtail(pRExC_state, ret, w);
2500                 if (!SIZE_ONLY && RExC_extralen) {
2501                     reginsert(pRExC_state, LONGJMP,ret);
2502                     reginsert(pRExC_state, NOTHING,ret);
2503                     NEXT_OFF(ret) = 3;  /* Go over LONGJMP. */
2504                 }
2505                 reginsert(pRExC_state, CURLYX,ret);
2506                                 /* MJD hk */
2507                 Set_Node_Offset(ret, parse_start+1);
2508                 Set_Node_Length(ret, 
2509                                 op == '{' ? (RExC_parse - parse_start) : 1);
2510                 
2511                 if (!SIZE_ONLY && RExC_extralen)
2512                     NEXT_OFF(ret) = 3;  /* Go over NOTHING to LONGJMP. */
2513                 regtail(pRExC_state, ret, reg_node(pRExC_state, NOTHING));
2514                 if (SIZE_ONLY)
2515                     RExC_whilem_seen++, RExC_extralen += 3;
2516                 RExC_naughty += 4 + RExC_naughty;       /* compound interest */
2517             }
2518             ret->flags = 0;
2519
2520             if (min > 0)
2521                 *flagp = WORST;
2522             if (max > 0)
2523                 *flagp |= HASWIDTH;
2524             if (max && max < min)
2525                 vFAIL("Can't do {n,m} with n > m");
2526             if (!SIZE_ONLY) {
2527                 ARG1_SET(ret, min);
2528                 ARG2_SET(ret, max);
2529             }
2530
2531             goto nest_check;
2532         }
2533     }
2534
2535     if (!ISMULT1(op)) {
2536         *flagp = flags;
2537         return(ret);
2538     }
2539
2540 #if 0                           /* Now runtime fix should be reliable. */
2541
2542     /* if this is reinstated, don't forget to put this back into perldiag:
2543
2544             =item Regexp *+ operand could be empty at {#} in regex m/%s/
2545
2546            (F) The part of the regexp subject to either the * or + quantifier
2547            could match an empty string. The {#} shows in the regular
2548            expression about where the problem was discovered.
2549
2550     */
2551
2552     if (!(flags&HASWIDTH) && op != '?')
2553       vFAIL("Regexp *+ operand could be empty");
2554 #endif
2555
2556     parse_start = RExC_parse;
2557     nextchar(pRExC_state);
2558
2559     *flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
2560
2561     if (op == '*' && (flags&SIMPLE)) {
2562         reginsert(pRExC_state, STAR, ret);
2563         ret->flags = 0;
2564         RExC_naughty += 4;
2565     }
2566     else if (op == '*') {
2567         min = 0;
2568         goto do_curly;
2569     }
2570     else if (op == '+' && (flags&SIMPLE)) {
2571         reginsert(pRExC_state, PLUS, ret);
2572         ret->flags = 0;
2573         RExC_naughty += 3;
2574     }
2575     else if (op == '+') {
2576         min = 1;
2577         goto do_curly;
2578     }
2579     else if (op == '?') {
2580         min = 0; max = 1;
2581         goto do_curly;
2582     }
2583   nest_check:
2584     if (ckWARN(WARN_REGEXP) && !SIZE_ONLY && !(flags&HASWIDTH) && max > REG_INFTY/3) {
2585         vWARN3(RExC_parse,
2586                "%.*s matches null string many times",
2587                RExC_parse - origparse,
2588                origparse);
2589     }
2590
2591     if (*RExC_parse == '?') {
2592         nextchar(pRExC_state);
2593         reginsert(pRExC_state, MINMOD, ret);
2594         regtail(pRExC_state, ret, ret + NODE_STEP_REGNODE);
2595     }
2596     if (ISMULT2(RExC_parse)) {
2597         RExC_parse++;
2598         vFAIL("Nested quantifiers");
2599     }
2600
2601     return(ret);
2602 }
2603
2604 /*
2605  - regatom - the lowest level
2606  *
2607  * Optimization:  gobbles an entire sequence of ordinary characters so that
2608  * it can turn them into a single node, which is smaller to store and
2609  * faster to run.  Backslashed characters are exceptions, each becoming a
2610  * separate node; the code is simpler that way and it's not worth fixing.
2611  *
2612  * [Yes, it is worth fixing, some scripts can run twice the speed.] */
2613 STATIC regnode *
2614 S_regatom(pTHX_ RExC_state_t *pRExC_state, I32 *flagp)
2615 {
2616     register regnode *ret = 0;
2617     I32 flags;
2618     char *parse_start = RExC_parse;
2619
2620     *flagp = WORST;             /* Tentatively. */
2621
2622 tryagain:
2623     switch (*RExC_parse) {
2624     case '^':
2625         RExC_seen_zerolen++;
2626         nextchar(pRExC_state);
2627         if (RExC_flags16 & PMf_MULTILINE)
2628             ret = reg_node(pRExC_state, MBOL);
2629         else if (RExC_flags16 & PMf_SINGLELINE)
2630             ret = reg_node(pRExC_state, SBOL);
2631         else
2632             ret = reg_node(pRExC_state, BOL);
2633         Set_Node_Length(ret, 1); /* MJD */
2634         break;
2635     case '$':
2636         nextchar(pRExC_state);
2637         if (*RExC_parse)
2638             RExC_seen_zerolen++;
2639         if (RExC_flags16 & PMf_MULTILINE)
2640             ret = reg_node(pRExC_state, MEOL);
2641         else if (RExC_flags16 & PMf_SINGLELINE)
2642             ret = reg_node(pRExC_state, SEOL);
2643         else
2644             ret = reg_node(pRExC_state, EOL);
2645         Set_Node_Length(ret, 1); /* MJD */
2646         break;
2647     case '.':
2648         nextchar(pRExC_state);
2649         if (RExC_flags16 & PMf_SINGLELINE)
2650             ret = reg_node(pRExC_state, SANY);
2651         else
2652             ret = reg_node(pRExC_state, REG_ANY);
2653         *flagp |= HASWIDTH|SIMPLE;
2654         RExC_naughty++;
2655         Set_Node_Length(ret, 1); /* MJD */
2656         break;
2657     case '[':
2658     {
2659         char *oregcomp_parse = ++RExC_parse;
2660         ret = regclass(pRExC_state);
2661         if (*RExC_parse != ']') {
2662             RExC_parse = oregcomp_parse;
2663             vFAIL("Unmatched [");
2664         }
2665         nextchar(pRExC_state);
2666         *flagp |= HASWIDTH|SIMPLE;
2667         Set_Node_Length(ret, RExC_parse - oregcomp_parse + 1); /* MJD */
2668         break;
2669     }
2670     case '(':
2671         nextchar(pRExC_state);
2672         ret = reg(pRExC_state, 1, &flags);
2673         if (ret == NULL) {
2674                 if (flags & TRYAGAIN) {
2675                     if (RExC_parse == RExC_end) {
2676                          /* Make parent create an empty node if needed. */
2677                         *flagp |= TRYAGAIN;
2678                         return(NULL);
2679                     }
2680                     goto tryagain;
2681                 }
2682                 return(NULL);
2683         }
2684         *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE);
2685         break;
2686     case '|':
2687     case ')':
2688         if (flags & TRYAGAIN) {
2689             *flagp |= TRYAGAIN;
2690             return NULL;
2691         }
2692         vFAIL("Internal urp");
2693                                 /* Supposed to be caught earlier. */
2694         break;
2695     case '{':
2696         if (!regcurly(RExC_parse)) {
2697             RExC_parse++;
2698             goto defchar;
2699         }
2700         /* FALL THROUGH */
2701     case '?':
2702     case '+':
2703     case '*':
2704         RExC_parse++;
2705         vFAIL("Quantifier follows nothing");
2706         break;
2707     case '\\':
2708         switch (*++RExC_parse) {
2709         case 'A':
2710             RExC_seen_zerolen++;
2711             ret = reg_node(pRExC_state, SBOL);
2712             *flagp |= SIMPLE;
2713             nextchar(pRExC_state);
2714             Set_Node_Length(ret, 2); /* MJD */
2715             break;
2716         case 'G':
2717             ret = reg_node(pRExC_state, GPOS);
2718             RExC_seen |= REG_SEEN_GPOS;
2719             *flagp |= SIMPLE;
2720             nextchar(pRExC_state);
2721             Set_Node_Length(ret, 2); /* MJD */
2722             break;
2723         case 'Z':
2724             ret = reg_node(pRExC_state, SEOL);
2725             *flagp |= SIMPLE;
2726             nextchar(pRExC_state);
2727             break;
2728         case 'z':
2729             ret = reg_node(pRExC_state, EOS);
2730             *flagp |= SIMPLE;
2731             RExC_seen_zerolen++;                /* Do not optimize RE away */
2732             nextchar(pRExC_state);
2733             Set_Node_Length(ret, 2); /* MJD */
2734             break;
2735         case 'C':
2736             ret = reg_node(pRExC_state, SANY);
2737             RExC_seen |= REG_SEEN_SANY;
2738             *flagp |= HASWIDTH|SIMPLE;
2739             nextchar(pRExC_state);
2740             Set_Node_Length(ret, 2); /* MJD */
2741             break;
2742         case 'X':
2743             ret = reg_node(pRExC_state, CLUMP);
2744             *flagp |= HASWIDTH;
2745             nextchar(pRExC_state);
2746             Set_Node_Length(ret, 2); /* MJD */
2747             break;
2748         case 'w':
2749             ret = reg_node(pRExC_state, LOC ? ALNUML     : ALNUM);
2750             *flagp |= HASWIDTH|SIMPLE;
2751             nextchar(pRExC_state);
2752             Set_Node_Length(ret, 2); /* MJD */
2753             break;
2754         case 'W':
2755             ret = reg_node(pRExC_state, LOC ? NALNUML     : NALNUM);
2756             *flagp |= HASWIDTH|SIMPLE;
2757             nextchar(pRExC_state);
2758             Set_Node_Length(ret, 2); /* MJD */
2759             break;
2760         case 'b':
2761             RExC_seen_zerolen++;
2762             RExC_seen |= REG_SEEN_LOOKBEHIND;
2763             ret = reg_node(pRExC_state, LOC ? BOUNDL     : BOUND);
2764             *flagp |= SIMPLE;
2765             nextchar(pRExC_state);
2766             Set_Node_Length(ret, 2); /* MJD */
2767             break;
2768         case 'B':
2769             RExC_seen_zerolen++;
2770             RExC_seen |= REG_SEEN_LOOKBEHIND;
2771             ret = reg_node(pRExC_state, LOC ? NBOUNDL     : NBOUND);
2772             *flagp |= SIMPLE;
2773             nextchar(pRExC_state);
2774             Set_Node_Length(ret, 2); /* MJD */
2775             break;
2776         case 's':
2777             ret = reg_node(pRExC_state, LOC ? SPACEL     : SPACE);
2778             *flagp |= HASWIDTH|SIMPLE;
2779             nextchar(pRExC_state);
2780             Set_Node_Length(ret, 2); /* MJD */
2781             break;
2782         case 'S':
2783             ret = reg_node(pRExC_state, LOC ? NSPACEL     : NSPACE);
2784             *flagp |= HASWIDTH|SIMPLE;
2785             nextchar(pRExC_state);
2786             Set_Node_Length(ret, 2); /* MJD */
2787             break;
2788         case 'd':
2789             ret = reg_node(pRExC_state, DIGIT);
2790             *flagp |= HASWIDTH|SIMPLE;
2791             nextchar(pRExC_state);
2792             Set_Node_Length(ret, 2); /* MJD */
2793             break;
2794         case 'D':
2795             ret = reg_node(pRExC_state, NDIGIT);
2796             *flagp |= HASWIDTH|SIMPLE;
2797             nextchar(pRExC_state);
2798             Set_Node_Length(ret, 2); /* MJD */
2799             break;
2800         case 'p':
2801         case 'P':
2802             {   
2803                 char* oldregxend = RExC_end;
2804                 char* parse_start = RExC_parse;
2805
2806                 if (RExC_parse[1] == '{') {
2807                   /* a lovely hack--pretend we saw [\pX] instead */
2808                     RExC_end = strchr(RExC_parse, '}');
2809                     if (!RExC_end) {
2810                         RExC_parse += 2;
2811                         RExC_end = oldregxend;
2812                         vFAIL("Missing right brace on \\p{}");
2813                     }
2814                     RExC_end++;
2815                 }
2816                 else
2817                     RExC_end = RExC_parse + 2;
2818                 RExC_parse--;
2819
2820                 ret = regclass(pRExC_state);
2821
2822                 RExC_end = oldregxend;
2823                 RExC_parse--;
2824                 Set_Node_Cur_Length(ret); /* MJD */
2825                 nextchar(pRExC_state);
2826                 *flagp |= HASWIDTH|SIMPLE;
2827             }
2828             break;
2829         case 'n':
2830         case 'r':
2831         case 't':
2832         case 'f':
2833         case 'e':
2834         case 'a':
2835         case 'x':
2836         case 'c':
2837         case '0':
2838             goto defchar;
2839         case '1': case '2': case '3': case '4':
2840         case '5': case '6': case '7': case '8': case '9':
2841             {
2842                 I32 num = atoi(RExC_parse);
2843
2844                 if (num > 9 && num >= RExC_npar)
2845                     goto defchar;
2846                 else {
2847                     char * parse_start = RExC_parse - 1; /* MJD */
2848                     while (isDIGIT(*RExC_parse))
2849                         RExC_parse++;
2850
2851                     if (!SIZE_ONLY && num > RExC_rx->nparens)
2852                         vFAIL("Reference to nonexistent group");
2853                     RExC_sawback = 1;
2854                     ret = reganode(pRExC_state, FOLD
2855                                    ? (LOC ? REFFL : REFF)
2856                                    : REF, num);
2857                     *flagp |= HASWIDTH;
2858                     
2859                     /* override incorrect value set in reganode MJD */
2860                     Set_Node_Offset(ret, parse_start+1); 
2861                     Set_Node_Cur_Length(ret); /* MJD */
2862                     RExC_parse--;
2863                     nextchar(pRExC_state);
2864                 }
2865             }
2866             break;
2867         case '\0':
2868             if (RExC_parse >= RExC_end)
2869                 FAIL("Trailing \\");
2870             /* FALL THROUGH */
2871         default:
2872             /* Do not generate `unrecognized' warnings here, we fall
2873                back into the quick-grab loop below */
2874             goto defchar;
2875         }
2876         break;
2877
2878     case '#':
2879         if (RExC_flags16 & PMf_EXTENDED) {
2880             while (RExC_parse < RExC_end && *RExC_parse != '\n') RExC_parse++;
2881             if (RExC_parse < RExC_end)
2882                 goto tryagain;
2883         }
2884         /* FALL THROUGH */
2885
2886     default: {
2887             register STRLEN len;
2888             register UV ender;
2889             register char *p;
2890             char *oldp, *s;
2891             STRLEN numlen;
2892             char *parse_start = RExC_parse - 1;
2893
2894             RExC_parse++;
2895
2896         defchar:
2897             ret = reg_node(pRExC_state, FOLD
2898                           ? (LOC ? EXACTFL : EXACTF)
2899                           : EXACT);
2900             s = STRING(ret);
2901             for (len = 0, p = RExC_parse - 1;
2902               len < 127 && p < RExC_end;
2903               len++)
2904             {
2905                 oldp = p;
2906
2907                 if (RExC_flags16 & PMf_EXTENDED)
2908                     p = regwhite(p, RExC_end);
2909                 switch (*p) {
2910                 case '^':
2911                 case '$':
2912                 case '.':
2913                 case '[':
2914                 case '(':
2915                 case ')':
2916                 case '|':
2917                     goto loopdone;
2918                 case '\\':
2919                     switch (*++p) {
2920                     case 'A':
2921                     case 'G':
2922                     case 'Z':
2923                     case 'z':
2924                     case 'w':
2925                     case 'W':
2926                     case 'b':
2927                     case 'B':
2928                     case 's':
2929                     case 'S':
2930                     case 'd':
2931                     case 'D':
2932                     case 'p':
2933                     case 'P':
2934                         --p;
2935                         goto loopdone;
2936                     case 'n':
2937                         ender = '\n';
2938                         p++;
2939                         break;
2940                     case 'r':
2941                         ender = '\r';
2942                         p++;
2943                         break;
2944                     case 't':
2945                         ender = '\t';
2946                         p++;
2947                         break;
2948                     case 'f':
2949                         ender = '\f';
2950                         p++;
2951                         break;
2952                     case 'e':
2953                           ender = ASCII_TO_NATIVE('\033');
2954                         p++;
2955                         break;
2956                     case 'a':
2957                           ender = ASCII_TO_NATIVE('\007');
2958                         p++;
2959                         break;
2960                     case 'x':
2961                         if (*++p == '{') {
2962                             char* e = strchr(p, '}');
2963         
2964                             if (!e) {
2965                                 RExC_parse = p + 1;
2966                                 vFAIL("Missing right brace on \\x{}");
2967                             }
2968                             else {
2969                                 numlen = 1;     /* allow underscores */
2970                                 ender = (UV)scan_hex(p + 1, e - p - 1, &numlen);
2971                                 if (ender > 0xff)
2972                                     RExC_utf8 = 1;
2973                                 /* numlen is generous */
2974                                 if (numlen + len >= 127) {
2975                                     p--;
2976                                     goto loopdone;
2977                                 }
2978                                 p = e + 1;
2979                             }
2980                         }
2981                         else {
2982                             numlen = 0;         /* disallow underscores */
2983                             ender = (UV)scan_hex(p, 2, &numlen);
2984                             p += numlen;
2985                         }
2986                         break;
2987                     case 'c':
2988                         p++;
2989                         ender = UCHARAT(p++);
2990                         ender = toCTRL(ender);
2991                         break;
2992                     case '0': case '1': case '2': case '3':case '4':
2993                     case '5': case '6': case '7': case '8':case '9':
2994                         if (*p == '0' ||
2995                           (isDIGIT(p[1]) && atoi(p) >= RExC_npar) ) {
2996                             numlen = 0;         /* disallow underscores */
2997                             ender = (UV)scan_oct(p, 3, &numlen);
2998                             p += numlen;
2999                         }
3000                         else {
3001                             --p;
3002                             goto loopdone;
3003                         }
3004                         break;
3005                     case '\0':
3006                         if (p >= RExC_end)
3007                             FAIL("Trailing \\");
3008                         /* FALL THROUGH */
3009                     default:
3010                         if (!SIZE_ONLY && ckWARN(WARN_REGEXP) && isALPHA(*p))
3011                             vWARN2(p +1, "Unrecognized escape \\%c passed through", *p);
3012                         goto normal_default;
3013                     }
3014                     break;
3015                 default:
3016                   normal_default:
3017                     if (UTF8_IS_START(*p) && UTF) {
3018                         ender = utf8n_to_uvchr((U8*)p, RExC_end - p,
3019                                                &numlen, 0);
3020                         p += numlen;
3021                     }
3022                     else
3023                         ender = *p++;
3024                     break;
3025                 }
3026                 if (RExC_flags16 & PMf_EXTENDED)
3027                     p = regwhite(p, RExC_end);
3028                 if (UTF && FOLD) {
3029                     if (LOC)
3030                         ender = toLOWER_LC_uvchr(ender);
3031                     else
3032                         ender = toLOWER_uni(ender);
3033                 }
3034                 if (ISMULT2(p)) { /* Back off on ?+*. */
3035                     if (len)
3036                         p = oldp;
3037                     else if (!UNI_IS_INVARIANT(NATIVE_TO_UNI(ender)) && UTF) {
3038                         reguni(pRExC_state, ender, s, &numlen);
3039                         s += numlen;
3040                         len += numlen;
3041                     }
3042                     else {
3043                         len++;
3044                         REGC(ender, s++);
3045                     }
3046                     break;
3047                 }
3048                 if (!UNI_IS_INVARIANT(NATIVE_TO_UNI(ender)) && UTF) {
3049                     reguni(pRExC_state, ender, s, &numlen);
3050                     s += numlen;
3051                     len += numlen - 1;
3052                 }
3053                 else
3054                     REGC(ender, s++);
3055             }
3056         loopdone:
3057             RExC_parse = p - 1;
3058             Set_Node_Cur_Length(ret); /* MJD */
3059             nextchar(pRExC_state);
3060             {
3061                 /* len is STRLEN which is unsigned, need to copy to signed */
3062                 IV iv = len;
3063                 if (iv < 0)
3064                     vFAIL("Internal disaster");
3065             }
3066             if (len > 0)
3067                 *flagp |= HASWIDTH;
3068             if (len == 1)
3069                 *flagp |= SIMPLE;
3070             if (!SIZE_ONLY)
3071                 STR_LEN(ret) = len;
3072             if (SIZE_ONLY)
3073                 RExC_size += STR_SZ(len);
3074             else
3075                 RExC_emit += STR_SZ(len);
3076         }
3077         break;
3078     }
3079
3080     return(ret);
3081 }
3082
3083 STATIC char *
3084 S_regwhite(pTHX_ char *p, char *e)
3085 {
3086     while (p < e) {
3087         if (isSPACE(*p))
3088             ++p;
3089         else if (*p == '#') {
3090             do {
3091                 p++;
3092             } while (p < e && *p != '\n');
3093         }
3094         else
3095             break;
3096     }
3097     return p;
3098 }
3099
3100 /* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
3101    Character classes ([:foo:]) can also be negated ([:^foo:]).
3102    Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
3103    Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
3104    but trigger warnings because they are currently unimplemented. */
3105 STATIC I32
3106 S_regpposixcc(pTHX_ RExC_state_t *pRExC_state, I32 value)
3107 {
3108     char *posixcc = 0;
3109     I32 namedclass = OOB_NAMEDCLASS;
3110
3111     if (value == '[' && RExC_parse + 1 < RExC_end &&
3112         /* I smell either [: or [= or [. -- POSIX has been here, right? */
3113         (*RExC_parse == ':' ||
3114          *RExC_parse == '=' ||
3115          *RExC_parse == '.')) {
3116         char  c = *RExC_parse;
3117         char* s = RExC_parse++;
3118         
3119         while (RExC_parse < RExC_end && *RExC_parse != c)
3120             RExC_parse++;
3121         if (RExC_parse == RExC_end)
3122             /* Grandfather lone [:, [=, [. */
3123             RExC_parse = s;
3124         else {
3125             char* t = RExC_parse++; /* skip over the c */
3126
3127             if (*RExC_parse == ']') {
3128                 RExC_parse++; /* skip over the ending ] */
3129                 posixcc = s + 1;
3130                 if (*s == ':') {
3131                     I32 complement = *posixcc == '^' ? *posixcc++ : 0;
3132                     I32 skip = 5; /* the most common skip */
3133
3134                     switch (*posixcc) {
3135                     case 'a':
3136                         if (strnEQ(posixcc, "alnum", 5))
3137                             namedclass =
3138                                 complement ? ANYOF_NALNUMC : ANYOF_ALNUMC;
3139                         else if (strnEQ(posixcc, "alpha", 5))
3140                             namedclass =
3141                                 complement ? ANYOF_NALPHA : ANYOF_ALPHA;
3142                         else if (strnEQ(posixcc, "ascii", 5))
3143                             namedclass =
3144                                 complement ? ANYOF_NASCII : ANYOF_ASCII;
3145                         break;
3146                     case 'b':
3147                         if (strnEQ(posixcc, "blank", 5))
3148                             namedclass =
3149                                 complement ? ANYOF_NBLANK : ANYOF_BLANK;
3150                         break;
3151                     case 'c':
3152                         if (strnEQ(posixcc, "cntrl", 5))
3153                             namedclass =
3154                                 complement ? ANYOF_NCNTRL : ANYOF_CNTRL;
3155                         break;
3156                     case 'd':
3157                         if (strnEQ(posixcc, "digit", 5))
3158                             namedclass =
3159                                 complement ? ANYOF_NDIGIT : ANYOF_DIGIT;
3160                         break;
3161                     case 'g':
3162                         if (strnEQ(posixcc, "graph", 5))
3163                             namedclass =
3164                                 complement ? ANYOF_NGRAPH : ANYOF_GRAPH;
3165                         break;
3166                     case 'l':
3167                         if (strnEQ(posixcc, "lower", 5))
3168                             namedclass =
3169                                 complement ? ANYOF_NLOWER : ANYOF_LOWER;
3170                         break;
3171                     case 'p':
3172                         if (strnEQ(posixcc, "print", 5))
3173                             namedclass =
3174                                 complement ? ANYOF_NPRINT : ANYOF_PRINT;
3175                         else if (strnEQ(posixcc, "punct", 5))
3176                             namedclass =
3177                                 complement ? ANYOF_NPUNCT : ANYOF_PUNCT;
3178                         break;
3179                     case 's':
3180                         if (strnEQ(posixcc, "space", 5))
3181                             namedclass =
3182                                 complement ? ANYOF_NPSXSPC : ANYOF_PSXSPC;
3183                         break;
3184                     case 'u':
3185                         if (strnEQ(posixcc, "upper", 5))
3186                             namedclass =
3187                                 complement ? ANYOF_NUPPER : ANYOF_UPPER;
3188                         break;
3189                     case 'w': /* this is not POSIX, this is the Perl \w */
3190                         if (strnEQ(posixcc, "word", 4)) {
3191                             namedclass =
3192                                 complement ? ANYOF_NALNUM : ANYOF_ALNUM;
3193                             skip = 4;
3194                         }
3195                         break;
3196                     case 'x':
3197                         if (strnEQ(posixcc, "xdigit", 6)) {
3198                             namedclass =
3199                                 complement ? ANYOF_NXDIGIT : ANYOF_XDIGIT;
3200                             skip = 6;
3201                         }
3202                         break;
3203                     }
3204                     if (namedclass == OOB_NAMEDCLASS ||
3205                         posixcc[skip] != ':' ||
3206                         posixcc[skip+1] != ']')
3207                     {
3208                         Simple_vFAIL3("POSIX class [:%.*s:] unknown",
3209                                       t - s - 1, s + 1);
3210                     }
3211                 } else if (!SIZE_ONLY) {
3212                     /* [[=foo=]] and [[.foo.]] are still future. */
3213
3214                     /* adjust RExC_parse so the warning shows after
3215                        the class closes */
3216                     while (*RExC_parse && *RExC_parse != ']')
3217                         RExC_parse++;
3218                     Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
3219                 }
3220             } else {
3221                 /* Maternal grandfather:
3222                  * "[:" ending in ":" but not in ":]" */
3223                 RExC_parse = s;
3224             }
3225         }
3226     }
3227
3228     return namedclass;
3229 }
3230
3231 STATIC void
3232 S_checkposixcc(pTHX_ RExC_state_t *pRExC_state)
3233 {
3234     if (!SIZE_ONLY && ckWARN(WARN_REGEXP) &&
3235         (*RExC_parse == ':' ||
3236          *RExC_parse == '=' ||
3237          *RExC_parse == '.')) {
3238         char *s = RExC_parse;
3239         char  c = *s++;
3240
3241         while(*s && isALNUM(*s))
3242             s++;
3243         if (*s && c == *s && s[1] == ']') {
3244             vWARN3(s+2, "POSIX syntax [%c %c] belongs inside character classes", c, c);
3245
3246             /* [[=foo=]] and [[.foo.]] are still future. */
3247             if (c == '=' || c == '.')
3248             {
3249                 /* adjust RExC_parse so the error shows after
3250                    the class closes */
3251                 while (*RExC_parse && *RExC_parse++ != ']')
3252                     ;
3253                 Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
3254             }
3255         }
3256     }
3257 }
3258
3259 STATIC regnode *
3260 S_regclass(pTHX_ RExC_state_t *pRExC_state)
3261 {
3262     register UV value;
3263     register IV prevvalue = OOB_UNICODE;
3264     register IV range = 0;
3265     register regnode *ret;
3266     STRLEN numlen;
3267     IV namedclass;
3268     char *rangebegin;
3269     bool need_class = 0;
3270     SV *listsv;
3271     register char *e;
3272     char *parse_start = RExC_parse; /* MJD */
3273     UV n;
3274     bool optimize_invert = TRUE;
3275
3276     ret = reganode(pRExC_state, ANYOF, 0);
3277
3278     if (!SIZE_ONLY)
3279         ANYOF_FLAGS(ret) = 0;
3280
3281     if (*RExC_parse == '^') {   /* Complement of range. */
3282         RExC_naughty++;
3283         RExC_parse++;
3284         if (!SIZE_ONLY)
3285             ANYOF_FLAGS(ret) |= ANYOF_INVERT;
3286     }
3287
3288     if (SIZE_ONLY)
3289         RExC_size += ANYOF_SKIP;
3290     else {
3291         RExC_emit += ANYOF_SKIP;
3292         if (FOLD)
3293             ANYOF_FLAGS(ret) |= ANYOF_FOLD;
3294         if (LOC)
3295             ANYOF_FLAGS(ret) |= ANYOF_LOCALE;
3296         ANYOF_BITMAP_ZERO(ret);
3297         listsv = newSVpvn("# comment\n", 10);
3298     }
3299
3300     if (!SIZE_ONLY && ckWARN(WARN_REGEXP))
3301         checkposixcc(pRExC_state);
3302
3303     if (*RExC_parse == ']' || *RExC_parse == '-')
3304         goto charclassloop;             /* allow 1st char to be ] or - */
3305
3306     while (RExC_parse < RExC_end && *RExC_parse != ']') {
3307
3308     charclassloop:
3309
3310         namedclass = OOB_NAMEDCLASS; /* initialize as illegal */
3311
3312         if (!range)
3313             rangebegin = RExC_parse;
3314         if (UTF) {
3315             value = utf8n_to_uvchr((U8*)RExC_parse,
3316                                    RExC_end - RExC_parse,
3317                                    &numlen, 0);
3318             RExC_parse += numlen;
3319         }
3320         else
3321             value = UCHARAT(RExC_parse++);
3322         if (value == '[')
3323             namedclass = regpposixcc(pRExC_state, value);
3324         else if (value == '\\') {
3325             if (UTF) {
3326                 value = utf8n_to_uvchr((U8*)RExC_parse,
3327                                    RExC_end - RExC_parse,
3328                                    &numlen, 0);
3329                 RExC_parse += numlen;
3330             }
3331             else
3332                 value = UCHARAT(RExC_parse++);
3333             /* Some compilers cannot handle switching on 64-bit integer
3334              * values, therefore value cannot be an UV.  Yes, this will
3335              * be a problem later if we want switch on Unicode.
3336              * A similar issue a little bit later when switching on
3337              * namedclass. --jhi */
3338             switch ((I32)value) {
3339             case 'w':   namedclass = ANYOF_ALNUM;       break;
3340             case 'W':   namedclass = ANYOF_NALNUM;      break;
3341             case 's':   namedclass = ANYOF_SPACE;       break;
3342             case 'S':   namedclass = ANYOF_NSPACE;      break;
3343             case 'd':   namedclass = ANYOF_DIGIT;       break;
3344             case 'D':   namedclass = ANYOF_NDIGIT;      break;
3345             case 'p':
3346             case 'P':
3347                 if (*RExC_parse == '{') {
3348                     e = strchr(RExC_parse++, '}');
3349                     if (!e)
3350                         vFAIL("Missing right brace on \\p{}");
3351                     n = e - RExC_parse;
3352                 }
3353                 else {
3354                     e = RExC_parse;
3355                     n = 1;
3356                 }
3357                 if (!SIZE_ONLY) {
3358                     if (value == 'p')
3359                         Perl_sv_catpvf(aTHX_ listsv,
3360                                        "+utf8::%.*s\n", (int)n, RExC_parse);
3361                     else
3362                         Perl_sv_catpvf(aTHX_ listsv,
3363                                        "!utf8::%.*s\n", (int)n, RExC_parse);
3364                 }
3365                 RExC_parse = e + 1;
3366                 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
3367                 continue;
3368             case 'n':   value = '\n';                   break;
3369             case 'r':   value = '\r';                   break;
3370             case 't':   value = '\t';                   break;
3371             case 'f':   value = '\f';                   break;
3372             case 'b':   value = '\b';                   break;
3373             case 'e':   value = ASCII_TO_NATIVE('\033');break;
3374             case 'a':   value = ASCII_TO_NATIVE('\007');break;
3375             case 'x':
3376                 if (*RExC_parse == '{') {
3377                     e = strchr(RExC_parse++, '}');
3378                     if (!e)
3379                         vFAIL("Missing right brace on \\x{}");
3380                     numlen = 1;         /* allow underscores */
3381                     value = (UV)scan_hex(RExC_parse,
3382                                          e - RExC_parse,
3383                                          &numlen);
3384                     RExC_parse = e + 1;
3385                 }
3386                 else {
3387                     numlen = 0;         /* disallow underscores */
3388                     value = (UV)scan_hex(RExC_parse, 2, &numlen);
3389                     RExC_parse += numlen;
3390                 }
3391                 break;
3392             case 'c':
3393                 value = UCHARAT(RExC_parse++);
3394                 value = toCTRL(value);
3395                 break;
3396             case '0': case '1': case '2': case '3': case '4':
3397             case '5': case '6': case '7': case '8': case '9':
3398                 numlen = 0;             /* disallow underscores */
3399                 value = (UV)scan_oct(--RExC_parse, 3, &numlen);
3400                 RExC_parse += numlen;
3401                 break;
3402             default:
3403                 if (!SIZE_ONLY && ckWARN(WARN_REGEXP) && isALPHA(value))
3404                     vWARN2(RExC_parse,
3405                            "Unrecognized escape \\%c in character class passed through",
3406                            (int)value);
3407                 break;
3408             }
3409         } /* end of \blah */
3410
3411         if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */
3412
3413             if (!SIZE_ONLY && !need_class)
3414                 ANYOF_CLASS_ZERO(ret);
3415
3416             need_class = 1;
3417
3418             /* a bad range like a-\d, a-[:digit:] ? */
3419             if (range) {
3420                 if (!SIZE_ONLY) {
3421                     if (ckWARN(WARN_REGEXP))
3422                         vWARN4(RExC_parse,
3423                                "False [] range \"%*.*s\"",
3424                                RExC_parse - rangebegin,
3425                                RExC_parse - rangebegin,
3426                                rangebegin);
3427                     if (prevvalue < 256) {
3428                         ANYOF_BITMAP_SET(ret, prevvalue);
3429                         ANYOF_BITMAP_SET(ret, '-');
3430                     }
3431                     else {
3432                         ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
3433                         Perl_sv_catpvf(aTHX_ listsv,
3434                                        "%04"UVxf"\n%04"UVxf"\n", (UV)prevvalue, (UV) '-');
3435                     }
3436                 }
3437
3438                 range = 0; /* this was not a true range */
3439             }
3440
3441             if (!SIZE_ONLY) {
3442                 if (namedclass > OOB_NAMEDCLASS)
3443                     optimize_invert = FALSE;
3444                 /* Possible truncation here but in some 64-bit environments
3445                  * the compiler gets heartburn about switch on 64-bit values.
3446                  * A similar issue a little earlier when switching on value.
3447                  * --jhi */
3448                 switch ((I32)namedclass) {
3449                 case ANYOF_ALNUM:
3450                     if (LOC)
3451                         ANYOF_CLASS_SET(ret, ANYOF_ALNUM);
3452                     else {
3453                         for (value = 0; value < 256; value++)
3454                             if (isALNUM(value))
3455                                 ANYOF_BITMAP_SET(ret, value);
3456                     }
3457                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsWord\n");    
3458                     break;
3459                 case ANYOF_NALNUM:
3460                     if (LOC)
3461                         ANYOF_CLASS_SET(ret, ANYOF_NALNUM);
3462                     else {
3463                         for (value = 0; value < 256; value++)
3464                             if (!isALNUM(value))
3465                                 ANYOF_BITMAP_SET(ret, value);
3466                     }
3467                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsWord\n");
3468                     break;
3469                 case ANYOF_ALNUMC:
3470                     if (LOC)
3471                         ANYOF_CLASS_SET(ret, ANYOF_ALNUMC);
3472                     else {
3473                         for (value = 0; value < 256; value++)
3474                             if (isALNUMC(value))
3475                                 ANYOF_BITMAP_SET(ret, value);
3476                     }
3477                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsAlnum\n");
3478                     break;
3479                 case ANYOF_NALNUMC:
3480                     if (LOC)
3481                         ANYOF_CLASS_SET(ret, ANYOF_NALNUMC);
3482                     else {
3483                         for (value = 0; value < 256; value++)
3484                             if (!isALNUMC(value))
3485                                 ANYOF_BITMAP_SET(ret, value);
3486                     }
3487                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsAlnum\n");
3488                     break;
3489                 case ANYOF_ALPHA:
3490                     if (LOC)
3491                         ANYOF_CLASS_SET(ret, ANYOF_ALPHA);
3492                     else {
3493                         for (value = 0; value < 256; value++)
3494                             if (isALPHA(value))
3495                                 ANYOF_BITMAP_SET(ret, value);
3496                     }
3497                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsAlpha\n");
3498                     break;
3499                 case ANYOF_NALPHA:
3500                     if (LOC)
3501                         ANYOF_CLASS_SET(ret, ANYOF_NALPHA);
3502                     else {
3503                         for (value = 0; value < 256; value++)
3504                             if (!isALPHA(value))
3505                                 ANYOF_BITMAP_SET(ret, value);
3506                     }
3507                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsAlpha\n");
3508                     break;
3509                 case ANYOF_ASCII:
3510                     if (LOC)
3511                         ANYOF_CLASS_SET(ret, ANYOF_ASCII);
3512                     else {
3513 #ifndef EBCDIC
3514                         for (value = 0; value < 128; value++)
3515                             ANYOF_BITMAP_SET(ret, value);
3516 #else  /* EBCDIC */
3517                         for (value = 0; value < 256; value++) {
3518                             if (PL_hints & HINT_RE_ASCIIR) {
3519                                 if (NATIVE_TO_ASCII(value) < 128)
3520                                     ANYOF_BITMAP_SET(ret, value);
3521                             }
3522                             else {
3523                                 if (isASCII(value))
3524                                     ANYOF_BITMAP_SET(ret, value);
3525                             }
3526                         }
3527 #endif /* EBCDIC */
3528                     }
3529                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsASCII\n");
3530                     break;
3531                 case ANYOF_NASCII:
3532                     if (LOC)
3533                         ANYOF_CLASS_SET(ret, ANYOF_NASCII);
3534                     else {
3535 #ifndef EBCDIC
3536                         for (value = 128; value < 256; value++)
3537                             ANYOF_BITMAP_SET(ret, value);
3538 #else  /* EBCDIC */
3539                         for (value = 0; value < 256; value++) {
3540                             if (PL_hints & HINT_RE_ASCIIR) {
3541                                 if (NATIVE_TO_ASCII(value) >= 128)
3542                                     ANYOF_BITMAP_SET(ret, value);
3543                             }
3544                             else {
3545                                 if (!isASCII(value))
3546                                     ANYOF_BITMAP_SET(ret, value);
3547                             }
3548                         }
3549 #endif /* EBCDIC */
3550                     }
3551                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsASCII\n");
3552                     break;
3553                 case ANYOF_BLANK:
3554                     if (LOC)
3555                         ANYOF_CLASS_SET(ret, ANYOF_BLANK);
3556                     else {
3557                         for (value = 0; value < 256; value++)
3558                             if (isBLANK(value))
3559                                 ANYOF_BITMAP_SET(ret, value);
3560                     }
3561                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsBlank\n");
3562                     break;
3563                 case ANYOF_NBLANK:
3564                     if (LOC)
3565                         ANYOF_CLASS_SET(ret, ANYOF_NBLANK);
3566                     else {
3567                         for (value = 0; value < 256; value++)
3568                             if (!isBLANK(value))
3569                                 ANYOF_BITMAP_SET(ret, value);
3570                     }
3571                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsBlank\n");
3572                     break;
3573                 case ANYOF_CNTRL:
3574                     if (LOC)
3575                         ANYOF_CLASS_SET(ret, ANYOF_CNTRL);
3576                     else {
3577                         for (value = 0; value < 256; value++)
3578                             if (isCNTRL(value))
3579                                 ANYOF_BITMAP_SET(ret, value);
3580                     }
3581                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsCntrl\n");
3582                     break;
3583                 case ANYOF_NCNTRL:
3584                     if (LOC)
3585                         ANYOF_CLASS_SET(ret, ANYOF_NCNTRL);
3586                     else {
3587                         for (value = 0; value < 256; value++)
3588                             if (!isCNTRL(value))
3589                                 ANYOF_BITMAP_SET(ret, value);
3590                     }
3591                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsCntrl\n");
3592                     break;
3593                 case ANYOF_DIGIT:
3594                     if (LOC)
3595                         ANYOF_CLASS_SET(ret, ANYOF_DIGIT);
3596                     else {
3597                         /* consecutive digits assumed */
3598                         for (value = '0'; value <= '9'; value++)
3599                             ANYOF_BITMAP_SET(ret, value);
3600                     }
3601                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsDigit\n");
3602                     break;
3603                 case ANYOF_NDIGIT:
3604                     if (LOC)
3605                         ANYOF_CLASS_SET(ret, ANYOF_NDIGIT);
3606                     else {
3607                         /* consecutive digits assumed */
3608                         for (value = 0; value < '0'; value++)
3609                             ANYOF_BITMAP_SET(ret, value);
3610                         for (value = '9' + 1; value < 256; value++)
3611                             ANYOF_BITMAP_SET(ret, value);
3612                     }
3613                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsDigit\n");
3614                     break;
3615                 case ANYOF_GRAPH:
3616                     if (LOC)
3617                         ANYOF_CLASS_SET(ret, ANYOF_GRAPH);
3618                     else {
3619                         for (value = 0; value < 256; value++)
3620                             if (isGRAPH(value))
3621                                 ANYOF_BITMAP_SET(ret, value);
3622                     }
3623                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsGraph\n");
3624                     break;
3625                 case ANYOF_NGRAPH:
3626                     if (LOC)
3627                         ANYOF_CLASS_SET(ret, ANYOF_NGRAPH);
3628                     else {
3629                         for (value = 0; value < 256; value++)
3630                             if (!isGRAPH(value))
3631                                 ANYOF_BITMAP_SET(ret, value);
3632                     }
3633                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsGraph\n");
3634                     break;
3635                 case ANYOF_LOWER:
3636                     if (LOC)
3637                         ANYOF_CLASS_SET(ret, ANYOF_LOWER);
3638                     else {
3639                         for (value = 0; value < 256; value++)
3640                             if (isLOWER(value))
3641                                 ANYOF_BITMAP_SET(ret, value);
3642                     }
3643                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsLower\n");
3644                     break;
3645                 case ANYOF_NLOWER:
3646                     if (LOC)
3647                         ANYOF_CLASS_SET(ret, ANYOF_NLOWER);
3648                     else {
3649                         for (value = 0; value < 256; value++)
3650                             if (!isLOWER(value))
3651                                 ANYOF_BITMAP_SET(ret, value);
3652                     }
3653                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsLower\n");
3654                     break;
3655                 case ANYOF_PRINT:
3656                     if (LOC)
3657                         ANYOF_CLASS_SET(ret, ANYOF_PRINT);
3658                     else {
3659                         for (value = 0; value < 256; value++)
3660                             if (isPRINT(value))
3661                                 ANYOF_BITMAP_SET(ret, value);
3662                     }
3663                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsPrint\n");
3664                     break;
3665                 case ANYOF_NPRINT:
3666                     if (LOC)
3667                         ANYOF_CLASS_SET(ret, ANYOF_NPRINT);
3668                     else {
3669                         for (value = 0; value < 256; value++)
3670                             if (!isPRINT(value))
3671                                 ANYOF_BITMAP_SET(ret, value);
3672                     }
3673                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsPrint\n");
3674                     break;
3675                 case ANYOF_PSXSPC:
3676                     if (LOC)
3677                         ANYOF_CLASS_SET(ret, ANYOF_PSXSPC);
3678                     else {
3679                         for (value = 0; value < 256; value++)
3680                             if (isPSXSPC(value))
3681                                 ANYOF_BITMAP_SET(ret, value);
3682                     }
3683                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsSpace\n");
3684                     break;
3685                 case ANYOF_NPSXSPC:
3686                     if (LOC)
3687                         ANYOF_CLASS_SET(ret, ANYOF_NPSXSPC);
3688                     else {
3689                         for (value = 0; value < 256; value++)
3690                             if (!isPSXSPC(value))
3691                                 ANYOF_BITMAP_SET(ret, value);
3692                     }
3693                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsSpace\n");
3694                     break;
3695                 case ANYOF_PUNCT:
3696                     if (LOC)
3697                         ANYOF_CLASS_SET(ret, ANYOF_PUNCT);
3698                     else {
3699                         for (value = 0; value < 256; value++)
3700                             if (isPUNCT(value))
3701                                 ANYOF_BITMAP_SET(ret, value);
3702                     }
3703                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsPunct\n");
3704                     break;
3705                 case ANYOF_NPUNCT:
3706                     if (LOC)
3707                         ANYOF_CLASS_SET(ret, ANYOF_NPUNCT);
3708                     else {
3709                         for (value = 0; value < 256; value++)
3710                             if (!isPUNCT(value))
3711                                 ANYOF_BITMAP_SET(ret, value);
3712                     }
3713                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsPunct\n");
3714                     break;
3715                 case ANYOF_SPACE:
3716                     if (LOC)
3717                         ANYOF_CLASS_SET(ret, ANYOF_SPACE);
3718                     else {
3719                         for (value = 0; value < 256; value++)
3720                             if (isSPACE(value))
3721                                 ANYOF_BITMAP_SET(ret, value);
3722                     }
3723                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsSpacePerl\n");
3724                     break;
3725                 case ANYOF_NSPACE:
3726                     if (LOC)
3727                         ANYOF_CLASS_SET(ret, ANYOF_NSPACE);
3728                     else {
3729                         for (value = 0; value < 256; value++)
3730                             if (!isSPACE(value))
3731                                 ANYOF_BITMAP_SET(ret, value);
3732                     }
3733                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsSpacePerl\n");
3734                     break;
3735                 case ANYOF_UPPER:
3736                     if (LOC)
3737                         ANYOF_CLASS_SET(ret, ANYOF_UPPER);
3738                     else {
3739                         for (value = 0; value < 256; value++)
3740                             if (isUPPER(value))
3741                                 ANYOF_BITMAP_SET(ret, value);
3742                     }
3743                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsUpper\n");
3744                     break;
3745                 case ANYOF_NUPPER:
3746                     if (LOC)
3747                         ANYOF_CLASS_SET(ret, ANYOF_NUPPER);
3748                     else {
3749                         for (value = 0; value < 256; value++)
3750                             if (!isUPPER(value))
3751                                 ANYOF_BITMAP_SET(ret, value);
3752                     }
3753                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsUpper\n");
3754                     break;
3755                 case ANYOF_XDIGIT:
3756                     if (LOC)
3757                         ANYOF_CLASS_SET(ret, ANYOF_XDIGIT);
3758                     else {
3759                         for (value = 0; value < 256; value++)
3760                             if (isXDIGIT(value))
3761                                 ANYOF_BITMAP_SET(ret, value);
3762                     }
3763                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsXDigit\n");
3764                     break;
3765                 case ANYOF_NXDIGIT:
3766                     if (LOC)
3767                         ANYOF_CLASS_SET(ret, ANYOF_NXDIGIT);
3768                     else {
3769                         for (value = 0; value < 256; value++)
3770                             if (!isXDIGIT(value))
3771                                 ANYOF_BITMAP_SET(ret, value);
3772                     }
3773                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsXDigit\n");
3774                     break;
3775                 default:
3776                     vFAIL("Invalid [::] class");
3777                     break;
3778                 }
3779                 if (LOC)
3780                     ANYOF_FLAGS(ret) |= ANYOF_CLASS;
3781                 continue;
3782             }
3783         } /* end of namedclass \blah */
3784
3785         if (range) {
3786             if (((prevvalue > value) && !(PL_hints & HINT_RE_ASCIIR)) ||
3787                 ((NATIVE_TO_UNI(prevvalue) > NATIVE_TO_UNI(value)) &&
3788                  (PL_hints & HINT_RE_ASCIIR))) /* b-a */ {
3789                 Simple_vFAIL4("Invalid [] range \"%*.*s\"",
3790                               RExC_parse - rangebegin,
3791                               RExC_parse - rangebegin,
3792                               rangebegin);
3793                 range = 0; /* not a valid range */
3794             }
3795         }
3796         else {
3797             prevvalue = value; /* save the beginning of the range */
3798             if (*RExC_parse == '-' && RExC_parse+1 < RExC_end &&
3799                 RExC_parse[1] != ']') {
3800                 RExC_parse++;
3801
3802                 /* a bad range like \w-, [:word:]- ? */
3803                 if (namedclass > OOB_NAMEDCLASS) {
3804                     if (ckWARN(WARN_REGEXP))
3805                         vWARN4(RExC_parse,
3806                                "False [] range \"%*.*s\"",
3807                                RExC_parse - rangebegin,
3808                                RExC_parse - rangebegin,
3809                                rangebegin);
3810                     if (!SIZE_ONLY)
3811                         ANYOF_BITMAP_SET(ret, '-');
3812                 } else
3813                     range = 1;  /* yeah, it's a range! */
3814                 continue;       /* but do it the next time */
3815             }
3816         }
3817
3818         /* now is the next time */
3819         if (!SIZE_ONLY) {
3820             IV i;
3821
3822             if (prevvalue < 256) {
3823                 IV ceilvalue = value < 256 ? value : 255;
3824
3825 #ifdef EBCDIC
3826                     /* New style scheme for ranges:
3827                      * use re 'asciir';
3828                      * do ranges in ASCII/Unicode space
3829                      */
3830                     for (i  = NATIVE_TO_ASCII(prevvalue);
3831                          i <= NATIVE_TO_ASCII(ceilvalue);
3832                          i++)
3833                       ANYOF_BITMAP_SET(ret, ASCII_TO_NATIVE(i));
3834                 }
3835                 else if ((isLOWER(prevvalue) && isLOWER(ceilvalue)) ||
3836                          (isUPPER(prevvalue) && isUPPER(ceilvalue)))
3837                 {
3838                     if (isLOWER(prevvalue)) {
3839                         for (i = prevvalue; i <= ceilvalue; i++)
3840                             if (isLOWER(i))
3841                                 ANYOF_BITMAP_SET(ret, i);
3842                     } else {
3843                         for (i = prevvalue; i <= ceilvalue; i++)
3844                             if (isUPPER(i))
3845                                 ANYOF_BITMAP_SET(ret, i);
3846                     }
3847                 }
3848                 else
3849 #endif
3850                     for (i = prevvalue; i <= ceilvalue; i++)
3851                         ANYOF_BITMAP_SET(ret, i);
3852           }
3853           if (value > 255) {
3854                 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
3855                 if (prevvalue < value)
3856                     Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\t%04"UVxf"\n",
3857                                    (UV)prevvalue, (UV)value);
3858                 else if (prevvalue == value)
3859                     Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
3860                                    (UV)value);
3861             }
3862         }
3863
3864         range = 0; /* this range (if it was one) is done now */
3865     }
3866
3867     if (need_class) {
3868         ANYOF_FLAGS(ret) |= ANYOF_LARGE;
3869         if (SIZE_ONLY)
3870             RExC_size += ANYOF_CLASS_ADD_SKIP;
3871         else
3872             RExC_emit += ANYOF_CLASS_ADD_SKIP;
3873     }
3874
3875     /* optimize case-insensitive simple patterns (e.g. /[a-z]/i) */
3876     if (!SIZE_ONLY &&
3877         (ANYOF_FLAGS(ret) &
3878          /* If the only flag is folding (plus possibly inversion). */
3879          (ANYOF_FLAGS_ALL ^ ANYOF_INVERT) == ANYOF_FOLD)) {
3880         for (value = 0; value < 256; ++value) {
3881             if (ANYOF_BITMAP_TEST(ret, value)) {
3882                 IV fold = PL_fold[value];
3883
3884                 if (fold != value)
3885                     ANYOF_BITMAP_SET(ret, fold);
3886             }
3887         }
3888         ANYOF_FLAGS(ret) &= ~ANYOF_FOLD;
3889     }
3890
3891     /* optimize inverted simple patterns (e.g. [^a-z]) */
3892     if (!SIZE_ONLY && optimize_invert &&
3893         /* If the only flag is inversion. */
3894         (ANYOF_FLAGS(ret) & ANYOF_FLAGS_ALL) == ANYOF_INVERT) {
3895         for (value = 0; value < ANYOF_BITMAP_SIZE; ++value)
3896             ANYOF_BITMAP(ret)[value] ^= ANYOF_FLAGS_ALL;
3897         ANYOF_FLAGS(ret) = ANYOF_UNICODE_ALL;
3898     }
3899
3900     if (!SIZE_ONLY) {
3901         AV *av = newAV();
3902         SV *rv;
3903
3904         av_store(av, 0, listsv);
3905         av_store(av, 1, NULL);
3906         rv = newRV_noinc((SV*)av);
3907         n = add_data(pRExC_state, 1, "s");
3908         RExC_rx->data->data[n] = (void*)rv;
3909         ARG_SET(ret, n);
3910     }
3911
3912     return ret;
3913 }
3914
3915 STATIC char*
3916 S_nextchar(pTHX_ RExC_state_t *pRExC_state)
3917 {
3918     char* retval = RExC_parse++;
3919
3920     for (;;) {
3921         if (*RExC_parse == '(' && RExC_parse[1] == '?' &&
3922                 RExC_parse[2] == '#') {
3923             while (*RExC_parse && *RExC_parse != ')')
3924                 RExC_parse++;
3925             RExC_parse++;
3926             continue;
3927         }
3928         if (RExC_flags16 & PMf_EXTENDED) {
3929             if (isSPACE(*RExC_parse)) {
3930                 RExC_parse++;
3931                 continue;
3932             }
3933             else if (*RExC_parse == '#') {
3934                 while (*RExC_parse && *RExC_parse != '\n')
3935                     RExC_parse++;
3936                 RExC_parse++;
3937                 continue;
3938             }
3939         }
3940         return retval;
3941     }
3942 }
3943
3944 /*
3945 - reg_node - emit a node
3946 */
3947 STATIC regnode *                        /* Location. */
3948 S_reg_node(pTHX_ RExC_state_t *pRExC_state, U8 op)
3949 {
3950     register regnode *ret;
3951     register regnode *ptr;
3952
3953     ret = RExC_emit;
3954     if (SIZE_ONLY) {
3955         SIZE_ALIGN(RExC_size);
3956         RExC_size += 1;
3957         return(ret);
3958     }
3959
3960     NODE_ALIGN_FILL(ret);
3961     ptr = ret;
3962     FILL_ADVANCE_NODE(ptr, op);
3963     if (RExC_offsets) {         /* MJD */
3964       MJD_OFFSET_DEBUG((stderr, "%s:%u: (op %s) %s %u <- %u (len %u) (max %u).\n", 
3965               "reg_node", __LINE__, 
3966               reg_name[op],
3967               RExC_emit - RExC_emit_start > RExC_offsets[0] 
3968               ? "Overwriting end of array!\n" : "OK",
3969               RExC_emit - RExC_emit_start,
3970               RExC_parse - RExC_start,
3971               RExC_offsets[0])); 
3972       Set_Node_Offset(RExC_emit, RExC_parse + (op == END));
3973     }
3974             
3975     RExC_emit = ptr;
3976
3977     return(ret);
3978 }
3979
3980 /*
3981 - reganode - emit a node with an argument
3982 */
3983 STATIC regnode *                        /* Location. */
3984 S_reganode(pTHX_ RExC_state_t *pRExC_state, U8 op, U32 arg)
3985 {
3986     register regnode *ret;
3987     register regnode *ptr;
3988
3989     ret = RExC_emit;
3990     if (SIZE_ONLY) {
3991         SIZE_ALIGN(RExC_size);
3992         RExC_size += 2;
3993         return(ret);
3994     }
3995
3996     NODE_ALIGN_FILL(ret);
3997     ptr = ret;
3998     FILL_ADVANCE_NODE_ARG(ptr, op, arg);
3999     if (RExC_offsets) {         /* MJD */
4000       MJD_OFFSET_DEBUG((stderr, "%s: %s %u <- %u (max %u).\n", 
4001               "reganode",
4002               RExC_emit - RExC_emit_start > RExC_offsets[0] ? 
4003               "Overwriting end of array!\n" : "OK",
4004               RExC_emit - RExC_emit_start,
4005               RExC_parse - RExC_start,
4006               RExC_offsets[0])); 
4007       Set_Cur_Node_Offset;
4008     }
4009             
4010     RExC_emit = ptr;
4011
4012     return(ret);
4013 }
4014
4015 /*
4016 - reguni - emit (if appropriate) a Unicode character
4017 */
4018 STATIC void
4019 S_reguni(pTHX_ RExC_state_t *pRExC_state, UV uv, char* s, STRLEN* lenp)
4020 {
4021     *lenp = SIZE_ONLY ? UNISKIP(uv) : (uvchr_to_utf8((U8*)s, uv) - (U8*)s);
4022 }
4023
4024 /*
4025 - reginsert - insert an operator in front of already-emitted operand
4026 *
4027 * Means relocating the operand.
4028 */
4029 STATIC void
4030 S_reginsert(pTHX_ RExC_state_t *pRExC_state, U8 op, regnode *opnd)
4031 {
4032     register regnode *src;
4033     register regnode *dst;
4034     register regnode *place;
4035     register int offset = regarglen[(U8)op];
4036
4037 /* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
4038
4039     if (SIZE_ONLY) {
4040         RExC_size += NODE_STEP_REGNODE + offset;
4041         return;
4042     }
4043
4044     src = RExC_emit;
4045     RExC_emit += NODE_STEP_REGNODE + offset;
4046     dst = RExC_emit;
4047     while (src > opnd) {
4048         StructCopy(--src, --dst, regnode);
4049         if (RExC_offsets) {     /* MJD 20010112 */
4050           MJD_OFFSET_DEBUG((stderr, "%s: %s copy %u -> %u (max %u).\n", 
4051                   "reg_insert",
4052                   dst - RExC_emit_start > RExC_offsets[0] 
4053                   ? "Overwriting end of array!\n" : "OK",
4054                   src - RExC_emit_start,
4055                   dst - RExC_emit_start,
4056                   RExC_offsets[0])); 
4057           Set_Node_Offset_To_R(dst-RExC_emit_start, Node_Offset(src));
4058           Set_Node_Length_To_R(dst-RExC_emit_start, Node_Length(src));
4059         }
4060     }
4061     
4062
4063     place = opnd;               /* Op node, where operand used to be. */
4064     if (RExC_offsets) {         /* MJD */
4065       MJD_OFFSET_DEBUG((stderr, "%s: %s %u <- %u (max %u).\n", 
4066               "reginsert",
4067               place - RExC_emit_start > RExC_offsets[0] 
4068               ? "Overwriting end of array!\n" : "OK",
4069               place - RExC_emit_start,
4070               RExC_parse - RExC_start,
4071               RExC_offsets[0])); 
4072       Set_Node_Offset(place, RExC_parse);
4073     }
4074     src = NEXTOPER(place);
4075     FILL_ADVANCE_NODE(place, op);
4076     Zero(src, offset, regnode);
4077 }
4078
4079 /*
4080 - regtail - set the next-pointer at the end of a node chain of p to val.
4081 */
4082 STATIC void
4083 S_regtail(pTHX_ RExC_state_t *pRExC_state, regnode *p, regnode *val)
4084 {
4085     register regnode *scan;
4086     register regnode *temp;
4087
4088     if (SIZE_ONLY)
4089         return;
4090
4091     /* Find last node. */
4092     scan = p;
4093     for (;;) {
4094         temp = regnext(scan);
4095         if (temp == NULL)
4096             break;
4097         scan = temp;
4098     }
4099
4100     if (reg_off_by_arg[OP(scan)]) {
4101         ARG_SET(scan, val - scan);
4102     }
4103     else {
4104         NEXT_OFF(scan) = val - scan;
4105     }
4106 }
4107
4108 /*
4109 - regoptail - regtail on operand of first argument; nop if operandless
4110 */
4111 STATIC void
4112 S_regoptail(pTHX_ RExC_state_t *pRExC_state, regnode *p, regnode *val)
4113 {
4114     /* "Operandless" and "op != BRANCH" are synonymous in practice. */
4115     if (p == NULL || SIZE_ONLY)
4116         return;
4117     if (PL_regkind[(U8)OP(p)] == BRANCH) {
4118         regtail(pRExC_state, NEXTOPER(p), val);
4119     }
4120     else if ( PL_regkind[(U8)OP(p)] == BRANCHJ) {
4121         regtail(pRExC_state, NEXTOPER(NEXTOPER(p)), val);
4122     }
4123     else
4124         return;
4125 }
4126
4127 /*
4128  - regcurly - a little FSA that accepts {\d+,?\d*}
4129  */
4130 STATIC I32
4131 S_regcurly(pTHX_ register char *s)
4132 {
4133     if (*s++ != '{')
4134         return FALSE;
4135     if (!isDIGIT(*s))
4136         return FALSE;
4137     while (isDIGIT(*s))
4138         s++;
4139     if (*s == ',')
4140         s++;
4141     while (isDIGIT(*s))
4142         s++;
4143     if (*s != '}')
4144         return FALSE;
4145     return TRUE;
4146 }
4147
4148
4149 STATIC regnode *
4150 S_dumpuntil(pTHX_ regnode *start, regnode *node, regnode *last, SV* sv, I32 l)
4151 {
4152 #ifdef DEBUGGING
4153     register U8 op = EXACT;     /* Arbitrary non-END op. */
4154     register regnode *next;
4155
4156     while (op != END && (!last || node < last)) {
4157         /* While that wasn't END last time... */
4158
4159         NODE_ALIGN(node);
4160         op = OP(node);
4161         if (op == CLOSE)
4162             l--;        
4163         next = regnext(node);
4164         /* Where, what. */
4165         if (OP(node) == OPTIMIZED)
4166             goto after_print;
4167         regprop(sv, node);
4168         PerlIO_printf(Perl_debug_log, "%4"IVdf":%*s%s", (IV)(node - start),
4169                       (int)(2*l + 1), "", SvPVX(sv));
4170         if (next == NULL)               /* Next ptr. */
4171             PerlIO_printf(Perl_debug_log, "(0)");
4172         else
4173             PerlIO_printf(Perl_debug_log, "(%"IVdf")", (IV)(next - start));
4174         (void)PerlIO_putc(Perl_debug_log, '\n');
4175       after_print:
4176         if (PL_regkind[(U8)op] == BRANCHJ) {
4177             register regnode *nnode = (OP(next) == LONGJMP
4178                                        ? regnext(next)
4179                                        : next);
4180             if (last && nnode > last)
4181                 nnode = last;
4182             node = dumpuntil(start, NEXTOPER(NEXTOPER(node)), nnode, sv, l + 1);
4183         }
4184         else if (PL_regkind[(U8)op] == BRANCH) {
4185             node = dumpuntil(start, NEXTOPER(node), next, sv, l + 1);
4186         }
4187         else if ( op == CURLY) {   /* `next' might be very big: optimizer */
4188             node = dumpuntil(start, NEXTOPER(node) + EXTRA_STEP_2ARGS,
4189                              NEXTOPER(node) + EXTRA_STEP_2ARGS + 1, sv, l + 1);
4190         }
4191         else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
4192             node = dumpuntil(start, NEXTOPER(node) + EXTRA_STEP_2ARGS,
4193                              next, sv, l + 1);
4194         }
4195         else if ( op == PLUS || op == STAR) {
4196             node = dumpuntil(start, NEXTOPER(node), NEXTOPER(node) + 1, sv, l + 1);
4197         }
4198         else if (op == ANYOF) {
4199             /* arglen 1 + class block */
4200             node += 1 + ((ANYOF_FLAGS(node) & ANYOF_LARGE)
4201                     ? ANYOF_CLASS_SKIP : ANYOF_SKIP);
4202             node = NEXTOPER(node);
4203         }
4204         else if (PL_regkind[(U8)op] == EXACT) {
4205             /* Literal string, where present. */
4206             node += NODE_SZ_STR(node) - 1;
4207             node = NEXTOPER(node);
4208         }
4209         else {
4210             node = NEXTOPER(node);
4211             node += regarglen[(U8)op];
4212         }
4213         if (op == CURLYX || op == OPEN)
4214             l++;
4215         else if (op == WHILEM)
4216             l--;
4217     }
4218 #endif  /* DEBUGGING */
4219     return node;
4220 }
4221
4222 /*
4223  - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
4224  */
4225 void
4226 Perl_regdump(pTHX_ regexp *r)
4227 {
4228 #ifdef DEBUGGING
4229     SV *sv = sv_newmortal();
4230
4231     (void)dumpuntil(r->program, r->program + 1, NULL, sv, 0);
4232
4233     /* Header fields of interest. */
4234     if (r->anchored_substr)
4235         PerlIO_printf(Perl_debug_log,
4236                       "anchored `%s%.*s%s'%s at %"IVdf" ",
4237                       PL_colors[0],
4238                       (int)(SvCUR(r->anchored_substr) - (SvTAIL(r->anchored_substr)!=0)),
4239                       SvPVX(r->anchored_substr),
4240                       PL_colors[1],
4241                       SvTAIL(r->anchored_substr) ? "$" : "",
4242                       (IV)r->anchored_offset);
4243     if (r->float_substr)
4244         PerlIO_printf(Perl_debug_log,
4245                       "floating `%s%.*s%s'%s at %"IVdf"..%"UVuf" ",
4246                       PL_colors[0],
4247                       (int)(SvCUR(r->float_substr) - (SvTAIL(r->float_substr)!=0)),
4248                       SvPVX(r->float_substr),
4249                       PL_colors[1],
4250                       SvTAIL(r->float_substr) ? "$" : "",
4251                       (IV)r->float_min_offset, (UV)r->float_max_offset);
4252     if (r->check_substr)
4253         PerlIO_printf(Perl_debug_log,
4254                       r->check_substr == r->float_substr
4255                       ? "(checking floating" : "(checking anchored");
4256     if (r->reganch & ROPT_NOSCAN)
4257         PerlIO_printf(Perl_debug_log, " noscan");
4258     if (r->reganch & ROPT_CHECK_ALL)
4259         PerlIO_printf(Perl_debug_log, " isall");
4260     if (r->check_substr)
4261         PerlIO_printf(Perl_debug_log, ") ");
4262
4263     if (r->regstclass) {
4264         regprop(sv, r->regstclass);
4265         PerlIO_printf(Perl_debug_log, "stclass `%s' ", SvPVX(sv));
4266     }
4267     if (r->reganch & ROPT_ANCH) {
4268         PerlIO_printf(Perl_debug_log, "anchored");
4269         if (r->reganch & ROPT_ANCH_BOL)
4270             PerlIO_printf(Perl_debug_log, "(BOL)");
4271         if (r->reganch & ROPT_ANCH_MBOL)
4272             PerlIO_printf(Perl_debug_log, "(MBOL)");
4273         if (r->reganch & ROPT_ANCH_SBOL)
4274             PerlIO_printf(Perl_debug_log, "(SBOL)");
4275         if (r->reganch & ROPT_ANCH_GPOS)
4276             PerlIO_printf(Perl_debug_log, "(GPOS)");
4277         PerlIO_putc(Perl_debug_log, ' ');
4278     }
4279     if (r->reganch & ROPT_GPOS_SEEN)
4280         PerlIO_printf(Perl_debug_log, "GPOS ");
4281     if (r->reganch & ROPT_SKIP)
4282         PerlIO_printf(Perl_debug_log, "plus ");
4283     if (r->reganch & ROPT_IMPLICIT)
4284         PerlIO_printf(Perl_debug_log, "implicit ");
4285     PerlIO_printf(Perl_debug_log, "minlen %ld ", (long) r->minlen);
4286     if (r->reganch & ROPT_EVAL_SEEN)
4287         PerlIO_printf(Perl_debug_log, "with eval ");
4288     PerlIO_printf(Perl_debug_log, "\n");
4289     if (r->offsets) {
4290       U32 i;
4291       U32 len = r->offsets[0];
4292       PerlIO_printf(Perl_debug_log, "Offsets: [%u]\n\t", r->offsets[0]);
4293       for (i = 1; i <= len; i++)
4294         PerlIO_printf(Perl_debug_log, "%u[%u] ", 
4295                       r->offsets[i*2-1], 
4296                       r->offsets[i*2]);
4297       PerlIO_printf(Perl_debug_log, "\n");
4298     }
4299 #endif  /* DEBUGGING */
4300 }
4301
4302 STATIC void
4303 S_put_byte(pTHX_ SV *sv, int c)
4304 {
4305     if (isCNTRL(c) || c == 127 || c == 255 || !isPRINT(c))
4306         Perl_sv_catpvf(aTHX_ sv, "\\%o", c);
4307     else if (c == '-' || c == ']' || c == '\\' || c == '^')
4308         Perl_sv_catpvf(aTHX_ sv, "\\%c", c);
4309     else
4310         Perl_sv_catpvf(aTHX_ sv, "%c", c);
4311 }
4312
4313 /*
4314 - regprop - printable representation of opcode
4315 */
4316 void
4317 Perl_regprop(pTHX_ SV *sv, regnode *o)
4318 {
4319 #ifdef DEBUGGING
4320     register int k;
4321
4322     sv_setpvn(sv, "", 0);
4323     if (OP(o) >= reg_num)               /* regnode.type is unsigned */
4324         /* It would be nice to FAIL() here, but this may be called from
4325            regexec.c, and it would be hard to supply pRExC_state. */
4326         Perl_croak(aTHX_ "Corrupted regexp opcode");
4327     sv_catpv(sv, (char*)reg_name[OP(o)]); /* Take off const! */
4328
4329     k = PL_regkind[(U8)OP(o)];
4330
4331     if (k == EXACT)
4332         Perl_sv_catpvf(aTHX_ sv, " <%s%.*s%s>", PL_colors[0],
4333                        STR_LEN(o), STRING(o), PL_colors[1]);
4334     else if (k == CURLY) {
4335         if (OP(o) == CURLYM || OP(o) == CURLYN || OP(o) == CURLYX)
4336             Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
4337         Perl_sv_catpvf(aTHX_ sv, " {%d,%d}", ARG1(o), ARG2(o));
4338     }
4339     else if (k == WHILEM && o->flags)                   /* Ordinal/of */
4340         Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
4341     else if (k == REF || k == OPEN || k == CLOSE || k == GROUPP )
4342         Perl_sv_catpvf(aTHX_ sv, "%d", (int)ARG(o));    /* Parenth number */
4343     else if (k == LOGICAL)
4344         Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags);     /* 2: embedded, otherwise 1 */
4345     else if (k == ANYOF) {
4346         int i, rangestart = -1;
4347         U8 flags = ANYOF_FLAGS(o);
4348         const char * const anyofs[] = { /* Should be syncronized with
4349                                          * ANYOF_ #xdefines in regcomp.h */
4350             "\\w",
4351             "\\W",
4352             "\\s",
4353             "\\S",
4354             "\\d",
4355             "\\D",
4356             "[:alnum:]",
4357             "[:^alnum:]",
4358             "[:alpha:]",
4359             "[:^alpha:]",
4360             "[:ascii:]",
4361             "[:^ascii:]",
4362             "[:ctrl:]",
4363             "[:^ctrl:]",
4364             "[:graph:]",
4365             "[:^graph:]",
4366             "[:lower:]",
4367             "[:^lower:]",
4368             "[:print:]",
4369             "[:^print:]",
4370             "[:punct:]",
4371             "[:^punct:]",
4372             "[:upper:]",
4373             "[:^upper:]",
4374             "[:xdigit:]",
4375             "[:^xdigit:]",
4376             "[:space:]",
4377             "[:^space:]",
4378             "[:blank:]",
4379             "[:^blank:]"
4380         };
4381
4382         if (flags & ANYOF_LOCALE)
4383             sv_catpv(sv, "{loc}");
4384         if (flags & ANYOF_FOLD)
4385             sv_catpv(sv, "{i}");
4386         Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
4387         if (flags & ANYOF_INVERT)
4388             sv_catpv(sv, "^");
4389         for (i = 0; i <= 256; i++) {
4390             if (i < 256 && ANYOF_BITMAP_TEST(o,i)) {
4391                 if (rangestart == -1)
4392                     rangestart = i;
4393             } else if (rangestart != -1) {
4394                 if (i <= rangestart + 3)
4395                     for (; rangestart < i; rangestart++)
4396                         put_byte(sv, rangestart);
4397                 else {
4398                     put_byte(sv, rangestart);
4399                     sv_catpv(sv, "-");
4400                     put_byte(sv, i - 1);
4401                 }
4402                 rangestart = -1;
4403             }
4404         }
4405
4406         if (o->flags & ANYOF_CLASS)
4407             for (i = 0; i < sizeof(anyofs)/sizeof(char*); i++)
4408                 if (ANYOF_CLASS_TEST(o,i))
4409                     sv_catpv(sv, anyofs[i]);
4410
4411         if (flags & ANYOF_UNICODE)
4412             sv_catpv(sv, "{unicode}");
4413         else if (flags & ANYOF_UNICODE_ALL)
4414             sv_catpv(sv, "{all-unicode}");
4415
4416         {
4417             SV *lv;
4418             SV *sw = regclass_swash(o, FALSE, &lv);
4419         
4420             if (lv) {
4421                 if (sw) {
4422                     UV i;
4423                     U8 s[UTF8_MAXLEN+1];
4424                 
4425                     for (i = 0; i <= 256; i++) { /* just the first 256 */
4426                         U8 *e = uvchr_to_utf8(s, i);
4427                         
4428                         if (i < 256 && swash_fetch(sw, s, TRUE)) {
4429                             if (rangestart == -1)
4430                                 rangestart = i;
4431                         } else if (rangestart != -1) {
4432                             U8 *p;
4433                         
4434                             if (i <= rangestart + 3)
4435                                 for (; rangestart < i; rangestart++) {
4436                                     for(e = uvchr_to_utf8(s, rangestart), p = s; p < e; p++)
4437                                         put_byte(sv, *p);
4438                                 }
4439                             else {
4440                                 for (e = uvchr_to_utf8(s, rangestart), p = s; p < e; p++)
4441                                     put_byte(sv, *p);
4442                                 sv_catpv(sv, "-");
4443                                     for (e = uvchr_to_utf8(s, i - 1), p = s; p < e; p++)
4444                                         put_byte(sv, *p);
4445                                 }
4446                                 rangestart = -1;
4447                             }
4448                         }
4449                         
4450                     sv_catpv(sv, "..."); /* et cetera */
4451                 }
4452
4453                 {
4454                     char *s = savepv(SvPVX(lv));
4455                     char *origs = s;
4456                 
4457                     while(*s && *s != '\n') s++;
4458                 
4459                     if (*s == '\n') {
4460                         char *t = ++s;
4461                         
4462                         while (*s) {
4463                             if (*s == '\n')
4464                                 *s = ' ';
4465                             s++;
4466                         }
4467                         if (s[-1] == ' ')
4468                             s[-1] = 0;
4469                         
4470                         sv_catpv(sv, t);
4471                     }
4472                 
4473                     Safefree(origs);
4474                 }
4475             }
4476         }
4477
4478         Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
4479     }
4480     else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH))
4481         Perl_sv_catpvf(aTHX_ sv, "[-%d]", o->flags);
4482 #endif  /* DEBUGGING */
4483 }
4484
4485 SV *
4486 Perl_re_intuit_string(pTHX_ regexp *prog)
4487 {                               /* Assume that RE_INTUIT is set */
4488     DEBUG_r(
4489         {   STRLEN n_a;
4490             char *s = SvPV(prog->check_substr,n_a);
4491
4492             if (!PL_colorset) reginitcolors();
4493             PerlIO_printf(Perl_debug_log,
4494                       "%sUsing REx substr:%s `%s%.60s%s%s'\n",
4495                       PL_colors[4],PL_colors[5],PL_colors[0],
4496                       s,
4497                       PL_colors[1],
4498                       (strlen(s) > 60 ? "..." : ""));
4499         } );
4500
4501     return prog->check_substr;
4502 }
4503
4504 void
4505 Perl_pregfree(pTHX_ struct regexp *r)
4506 {
4507     DEBUG_r(if (!PL_colorset) reginitcolors());
4508
4509     if (!r || (--r->refcnt > 0))
4510         return;
4511     DEBUG_r(PerlIO_printf(Perl_debug_log,
4512                       "%sFreeing REx:%s `%s%.60s%s%s'\n",
4513                       PL_colors[4],PL_colors[5],PL_colors[0],
4514                       r->precomp,
4515                       PL_colors[1],
4516                       (strlen(r->precomp) > 60 ? "..." : "")));
4517
4518     if (r->precomp)
4519         Safefree(r->precomp);
4520     if (r->offsets)             /* 20010421 MJD */
4521         Safefree(r->offsets);
4522     if (RX_MATCH_COPIED(r))
4523         Safefree(r->subbeg);
4524     if (r->substrs) {
4525         if (r->anchored_substr)
4526             SvREFCNT_dec(r->anchored_substr);
4527         if (r->float_substr)
4528             SvREFCNT_dec(r->float_substr);
4529         Safefree(r->substrs);
4530     }
4531     if (r->data) {
4532         int n = r->data->count;
4533         AV* new_comppad = NULL;
4534         AV* old_comppad;
4535         SV** old_curpad;
4536
4537         while (--n >= 0) {
4538             switch (r->data->what[n]) {
4539             case 's':
4540                 SvREFCNT_dec((SV*)r->data->data[n]);
4541                 break;
4542             case 'f':
4543                 Safefree(r->data->data[n]);
4544                 break;
4545             case 'p':
4546                 new_comppad = (AV*)r->data->data[n];
4547                 break;
4548             case 'o':
4549                 if (new_comppad == NULL)
4550                     Perl_croak(aTHX_ "panic: pregfree comppad");
4551                 old_comppad = PL_comppad;
4552                 old_curpad = PL_curpad;
4553                 /* Watch out for global destruction's random ordering. */
4554                 if (SvTYPE(new_comppad) == SVt_PVAV) {
4555                     PL_comppad = new_comppad;
4556                     PL_curpad = AvARRAY(new_comppad);
4557                 }
4558                 else
4559                     PL_curpad = NULL;
4560                 op_free((OP_4tree*)r->data->data[n]);
4561                 PL_comppad = old_comppad;
4562                 PL_curpad = old_curpad;
4563                 SvREFCNT_dec((SV*)new_comppad);
4564                 new_comppad = NULL;
4565                 break;
4566             case 'n':
4567                 break;
4568             default:
4569                 Perl_croak(aTHX_ "panic: regfree data code '%c'", r->data->what[n]);
4570             }
4571         }
4572         Safefree(r->data->what);
4573         Safefree(r->data);
4574     }
4575     Safefree(r->startp);
4576     Safefree(r->endp);
4577     Safefree(r);
4578 }
4579
4580 /*
4581  - regnext - dig the "next" pointer out of a node
4582  *
4583  * [Note, when REGALIGN is defined there are two places in regmatch()
4584  * that bypass this code for speed.]
4585  */
4586 regnode *
4587 Perl_regnext(pTHX_ register regnode *p)
4588 {
4589     register I32 offset;
4590
4591     if (p == &PL_regdummy)
4592         return(NULL);
4593
4594     offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
4595     if (offset == 0)
4596         return(NULL);
4597
4598     return(p+offset);
4599 }
4600
4601 STATIC void     
4602 S_re_croak2(pTHX_ const char* pat1,const char* pat2,...)
4603 {
4604     va_list args;
4605     STRLEN l1 = strlen(pat1);
4606     STRLEN l2 = strlen(pat2);
4607     char buf[512];
4608     SV *msv;
4609     char *message;
4610
4611     if (l1 > 510)
4612         l1 = 510;
4613     if (l1 + l2 > 510)
4614         l2 = 510 - l1;
4615     Copy(pat1, buf, l1 , char);
4616     Copy(pat2, buf + l1, l2 , char);
4617     buf[l1 + l2] = '\n';
4618     buf[l1 + l2 + 1] = '\0';
4619 #ifdef I_STDARG
4620     /* ANSI variant takes additional second argument */
4621     va_start(args, pat2);
4622 #else
4623     va_start(args);
4624 #endif
4625     msv = vmess(buf, &args);
4626     va_end(args);
4627     message = SvPV(msv,l1);
4628     if (l1 > 512)
4629         l1 = 512;
4630     Copy(message, buf, l1 , char);
4631     buf[l1] = '\0';                     /* Overwrite \n */
4632     Perl_croak(aTHX_ "%s", buf);
4633 }
4634
4635 /* XXX Here's a total kludge.  But we need to re-enter for swash routines. */
4636
4637 void
4638 Perl_save_re_context(pTHX)
4639 {
4640 #if 0
4641     SAVEPPTR(RExC_precomp);             /* uncompiled string. */
4642     SAVEI32(RExC_npar);         /* () count. */
4643     SAVEI32(RExC_size);         /* Code size. */
4644     SAVEI16(RExC_flags16);              /* are we folding, multilining? */
4645     SAVEVPTR(RExC_rx);          /* from regcomp.c */
4646     SAVEI32(RExC_seen);         /* from regcomp.c */
4647     SAVEI32(RExC_sawback);              /* Did we see \1, ...? */
4648     SAVEI32(RExC_naughty);              /* How bad is this pattern? */
4649     SAVEVPTR(RExC_emit);                /* Code-emit pointer; &regdummy = don't */
4650     SAVEPPTR(RExC_end);         /* End of input for compile */
4651     SAVEPPTR(RExC_parse);               /* Input-scan pointer. */
4652 #endif
4653
4654     SAVEI32(PL_reg_flags);              /* from regexec.c */
4655     SAVEPPTR(PL_bostr);
4656     SAVEPPTR(PL_reginput);              /* String-input pointer. */
4657     SAVEPPTR(PL_regbol);                /* Beginning of input, for ^ check. */
4658     SAVEPPTR(PL_regeol);                /* End of input, for $ check. */
4659     SAVEVPTR(PL_regstartp);             /* Pointer to startp array. */
4660     SAVEVPTR(PL_regendp);               /* Ditto for endp. */
4661     SAVEVPTR(PL_reglastparen);          /* Similarly for lastparen. */
4662     SAVEPPTR(PL_regtill);               /* How far we are required to go. */
4663     SAVEGENERICPV(PL_reg_start_tmp);            /* from regexec.c */
4664     PL_reg_start_tmp = 0;
4665     SAVEI32(PL_reg_start_tmpl);         /* from regexec.c */
4666     PL_reg_start_tmpl = 0;
4667     SAVEVPTR(PL_regdata);
4668     SAVEI32(PL_reg_eval_set);           /* from regexec.c */
4669     SAVEI32(PL_regnarrate);             /* from regexec.c */
4670     SAVEVPTR(PL_regprogram);            /* from regexec.c */
4671     SAVEINT(PL_regindent);              /* from regexec.c */
4672     SAVEVPTR(PL_regcc);                 /* from regexec.c */
4673     SAVEVPTR(PL_curcop);
4674     SAVEVPTR(PL_reg_call_cc);           /* from regexec.c */
4675     SAVEVPTR(PL_reg_re);                /* from regexec.c */
4676     SAVEPPTR(PL_reg_ganch);             /* from regexec.c */
4677     SAVESPTR(PL_reg_sv);                /* from regexec.c */
4678     SAVEVPTR(PL_reg_magic);             /* from regexec.c */
4679     SAVEI32(PL_reg_oldpos);                     /* from regexec.c */
4680     SAVEVPTR(PL_reg_oldcurpm);          /* from regexec.c */
4681     SAVEVPTR(PL_reg_curpm);             /* from regexec.c */
4682     SAVEI32(PL_regnpar);                /* () count. */
4683 #ifdef DEBUGGING
4684     SAVEPPTR(PL_reg_starttry);          /* from regexec.c */
4685 #endif
4686 }
4687
4688 #ifdef PERL_OBJECT
4689 #include "XSUB.h"
4690 #undef this
4691 #define this pPerl
4692 #endif
4693
4694 static void
4695 clear_re(pTHXo_ void *r)
4696 {
4697     ReREFCNT_dec((regexp *)r);
4698 }
4699