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