provide EBCDIC CGI::Util::escape() and test
[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 {
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,
664                          STR_LEN(n), char);
665 #ifdef DEBUGGING
666                     if (stringok)
667                         stop = next - 1;
668 #endif
669                     n = nnext;
670                 }
671             }
672 #ifdef DEBUGGING
673             /* Allow dumping */
674             n = scan + NODE_SZ_STR(scan);
675             while (n <= stop) {
676                 if (PL_regkind[(U8)OP(n)] != NOTHING || OP(n) == NOTHING) {
677                     OP(n) = OPTIMIZED;
678                     NEXT_OFF(n) = 0;
679                 }
680                 n++;
681             }
682 #endif
683         }
684         /* Follow the next-chain of the current node and optimize
685            away all the NOTHINGs from it.  */
686         if (OP(scan) != CURLYX) {
687             int max = (reg_off_by_arg[OP(scan)]
688                        ? I32_MAX
689                        /* I32 may be smaller than U16 on CRAYs! */
690                        : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
691             int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
692             int noff;
693             regnode *n = scan;
694         
695             /* Skip NOTHING and LONGJMP. */
696             while ((n = regnext(n))
697                    && ((PL_regkind[(U8)OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
698                        || ((OP(n) == LONGJMP) && (noff = ARG(n))))
699                    && off + noff < max)
700                 off += noff;
701             if (reg_off_by_arg[OP(scan)])
702                 ARG(scan) = off;
703             else
704                 NEXT_OFF(scan) = off;
705         }
706         /* The principal pseudo-switch.  Cannot be a switch, since we
707            look into several different things.  */
708         if (OP(scan) == BRANCH || OP(scan) == BRANCHJ
709                    || OP(scan) == IFTHEN || OP(scan) == SUSPEND) {
710             next = regnext(scan);
711             code = OP(scan);
712         
713             if (OP(next) == code || code == IFTHEN || code == SUSPEND) {
714                 I32 max1 = 0, min1 = I32_MAX, num = 0;
715                 struct regnode_charclass_class accum;
716                 
717                 if (flags & SCF_DO_SUBSTR) /* XXXX Add !SUSPEND? */
718                     scan_commit(pRExC_state, data); /* Cannot merge strings after this. */
719                 if (flags & SCF_DO_STCLASS)
720                     cl_init_zero(pRExC_state, &accum);
721                 while (OP(scan) == code) {
722                     I32 deltanext, minnext, f = 0, fake;
723                     struct regnode_charclass_class this_class;
724
725                     num++;
726                     data_fake.flags = 0;
727                     if (data) {         
728                         data_fake.whilem_c = data->whilem_c;
729                         data_fake.last_closep = data->last_closep;
730                     }
731                     else
732                         data_fake.last_closep = &fake;
733                     next = regnext(scan);
734                     scan = NEXTOPER(scan);
735                     if (code != BRANCH)
736                         scan = NEXTOPER(scan);
737                     if (flags & SCF_DO_STCLASS) {
738                         cl_init(pRExC_state, &this_class);
739                         data_fake.start_class = &this_class;
740                         f = SCF_DO_STCLASS_AND;
741                     }           
742                     if (flags & SCF_WHILEM_VISITED_POS)
743                         f |= SCF_WHILEM_VISITED_POS;
744                     /* we suppose the run is continuous, last=next...*/
745                     minnext = study_chunk(pRExC_state, &scan, &deltanext,
746                                           next, &data_fake, f);
747                     if (min1 > minnext)
748                         min1 = minnext;
749                     if (max1 < minnext + deltanext)
750                         max1 = minnext + deltanext;
751                     if (deltanext == I32_MAX)
752                         is_inf = is_inf_internal = 1;
753                     scan = next;
754                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
755                         pars++;
756                     if (data && (data_fake.flags & SF_HAS_EVAL))
757                         data->flags |= SF_HAS_EVAL;
758                     if (data)
759                         data->whilem_c = data_fake.whilem_c;
760                     if (flags & SCF_DO_STCLASS)
761                         cl_or(pRExC_state, &accum, &this_class);
762                     if (code == SUSPEND)
763                         break;
764                 }
765                 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
766                     min1 = 0;
767                 if (flags & SCF_DO_SUBSTR) {
768                     data->pos_min += min1;
769                     data->pos_delta += max1 - min1;
770                     if (max1 != min1 || is_inf)
771                         data->longest = &(data->longest_float);
772                 }
773                 min += min1;
774                 delta += max1 - min1;
775                 if (flags & SCF_DO_STCLASS_OR) {
776                     cl_or(pRExC_state, data->start_class, &accum);
777                     if (min1) {
778                         cl_and(data->start_class, &and_with);
779                         flags &= ~SCF_DO_STCLASS;
780                     }
781                 }
782                 else if (flags & SCF_DO_STCLASS_AND) {
783                     if (min1) {
784                         cl_and(data->start_class, &accum);
785                         flags &= ~SCF_DO_STCLASS;
786                     }
787                     else {
788                         /* Switch to OR mode: cache the old value of
789                          * data->start_class */
790                         StructCopy(data->start_class, &and_with,
791                                    struct regnode_charclass_class);
792                         flags &= ~SCF_DO_STCLASS_AND;
793                         StructCopy(&accum, data->start_class,
794                                    struct regnode_charclass_class);
795                         flags |= SCF_DO_STCLASS_OR;
796                         data->start_class->flags |= ANYOF_EOS;
797                     }
798                 }
799             }
800             else if (code == BRANCHJ)   /* single branch is optimized. */
801                 scan = NEXTOPER(NEXTOPER(scan));
802             else                        /* single branch is optimized. */
803                 scan = NEXTOPER(scan);
804             continue;
805         }
806         else if (OP(scan) == EXACT) {
807             I32 l = STR_LEN(scan);
808             UV uc = *((U8*)STRING(scan));
809             if (UTF) {
810                 U8 *s = (U8*)STRING(scan);
811                 l = utf8_length(s, s + l);
812                 uc = utf8_to_uv_simple(s, NULL);
813             }
814             min += l;
815             if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
816                 /* The code below prefers earlier match for fixed
817                    offset, later match for variable offset.  */
818                 if (data->last_end == -1) { /* Update the start info. */
819                     data->last_start_min = data->pos_min;
820                     data->last_start_max = is_inf
821                         ? I32_MAX : data->pos_min + data->pos_delta;
822                 }
823                 sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));
824                 data->last_end = data->pos_min + l;
825                 data->pos_min += l; /* As in the first entry. */
826                 data->flags &= ~SF_BEFORE_EOL;
827             }
828             if (flags & SCF_DO_STCLASS_AND) {
829                 /* Check whether it is compatible with what we know already! */
830                 int compat = 1;
831
832                 if (uc >= 0x100 ||
833                     !(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
834                     && !ANYOF_BITMAP_TEST(data->start_class, uc)
835                     && (!(data->start_class->flags & ANYOF_FOLD)
836                         || !ANYOF_BITMAP_TEST(data->start_class, PL_fold[uc])))
837                     compat = 0;
838                 ANYOF_CLASS_ZERO(data->start_class);
839                 ANYOF_BITMAP_ZERO(data->start_class);
840                 if (compat)
841                     ANYOF_BITMAP_SET(data->start_class, uc);
842                 data->start_class->flags &= ~ANYOF_EOS;
843                 if (uc < 0x100)
844                   data->start_class->flags &= ~ANYOF_UNICODE_ALL;
845             }
846             else if (flags & SCF_DO_STCLASS_OR) {
847                 /* false positive possible if the class is case-folded */
848                 if (uc < 0x100)
849                     ANYOF_BITMAP_SET(data->start_class, uc);
850                 else
851                     data->start_class->flags |= ANYOF_UNICODE_ALL;
852                 data->start_class->flags &= ~ANYOF_EOS;
853                 cl_and(data->start_class, &and_with);
854             }
855             flags &= ~SCF_DO_STCLASS;
856         }
857         else if (PL_regkind[(U8)OP(scan)] == EXACT) { /* But OP != EXACT! */
858             I32 l = STR_LEN(scan);
859             UV uc = *((U8*)STRING(scan));
860
861             /* Search for fixed substrings supports EXACT only. */
862             if (flags & SCF_DO_SUBSTR)
863                 scan_commit(pRExC_state, data);
864             if (UTF) {
865                 U8 *s = (U8 *)STRING(scan);
866                 l = utf8_length(s, s + l);
867                 uc = utf8_to_uv_simple(s, NULL);
868             }
869             min += l;
870             if (data && (flags & SCF_DO_SUBSTR))
871                 data->pos_min += l;
872             if (flags & SCF_DO_STCLASS_AND) {
873                 /* Check whether it is compatible with what we know already! */
874                 int compat = 1;
875
876                 if (uc >= 0x100 ||
877                     !(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE))
878                     && !ANYOF_BITMAP_TEST(data->start_class, uc)
879                     && !ANYOF_BITMAP_TEST(data->start_class, PL_fold[uc]))
880                     compat = 0;
881                 ANYOF_CLASS_ZERO(data->start_class);
882                 ANYOF_BITMAP_ZERO(data->start_class);
883                 if (compat) {
884                     ANYOF_BITMAP_SET(data->start_class, uc);
885                     data->start_class->flags &= ~ANYOF_EOS;
886                     data->start_class->flags |= ANYOF_FOLD;
887                     if (OP(scan) == EXACTFL)
888                         data->start_class->flags |= ANYOF_LOCALE;
889                 }
890             }
891             else if (flags & SCF_DO_STCLASS_OR) {
892                 if (data->start_class->flags & ANYOF_FOLD) {
893                     /* false positive possible if the class is case-folded.
894                        Assume that the locale settings are the same... */
895                     if (uc < 0x100)
896                         ANYOF_BITMAP_SET(data->start_class, uc);
897                     data->start_class->flags &= ~ANYOF_EOS;
898                 }
899                 cl_and(data->start_class, &and_with);
900             }
901             flags &= ~SCF_DO_STCLASS;
902         }
903         else if (strchr((char*)PL_varies,OP(scan))) {
904             I32 mincount, maxcount, minnext, deltanext, fl;
905             I32 f = flags, pos_before = 0;
906             regnode *oscan = scan;
907             struct regnode_charclass_class this_class;
908             struct regnode_charclass_class *oclass = NULL;
909
910             switch (PL_regkind[(U8)OP(scan)]) {
911             case WHILEM:                /* End of (?:...)* . */
912                 scan = NEXTOPER(scan);
913                 goto finish;
914             case PLUS:
915                 if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
916                     next = NEXTOPER(scan);
917                     if (OP(next) == EXACT || (flags & SCF_DO_STCLASS)) {
918                         mincount = 1;
919                         maxcount = REG_INFTY;
920                         next = regnext(scan);
921                         scan = NEXTOPER(scan);
922                         goto do_curly;
923                     }
924                 }
925                 if (flags & SCF_DO_SUBSTR)
926                     data->pos_min++;
927                 min++;
928                 /* Fall through. */
929             case STAR:
930                 if (flags & SCF_DO_STCLASS) {
931                     mincount = 0;
932                     maxcount = REG_INFTY;
933                     next = regnext(scan);
934                     scan = NEXTOPER(scan);
935                     goto do_curly;
936                 }
937                 is_inf = is_inf_internal = 1;
938                 scan = regnext(scan);
939                 if (flags & SCF_DO_SUBSTR) {
940                     scan_commit(pRExC_state, data); /* Cannot extend fixed substrings */
941                     data->longest = &(data->longest_float);
942                 }
943                 goto optimize_curly_tail;
944             case CURLY:
945                 mincount = ARG1(scan);
946                 maxcount = ARG2(scan);
947                 next = regnext(scan);
948                 if (OP(scan) == CURLYX) {
949                     I32 lp = (data ? *(data->last_closep) : 0);
950
951                     scan->flags = ((lp <= U8_MAX) ? lp : U8_MAX);
952                 }
953                 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
954               do_curly:
955                 if (flags & SCF_DO_SUBSTR) {
956                     if (mincount == 0) scan_commit(pRExC_state,data); /* Cannot extend fixed substrings */
957                     pos_before = data->pos_min;
958                 }
959                 if (data) {
960                     fl = data->flags;
961                     data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
962                     if (is_inf)
963                         data->flags |= SF_IS_INF;
964                 }
965                 if (flags & SCF_DO_STCLASS) {
966                     cl_init(pRExC_state, &this_class);
967                     oclass = data->start_class;
968                     data->start_class = &this_class;
969                     f |= SCF_DO_STCLASS_AND;
970                     f &= ~SCF_DO_STCLASS_OR;
971                 }
972                 /* These are the cases when once a subexpression
973                    fails at a particular position, it cannot succeed
974                    even after backtracking at the enclosing scope.
975                 
976                    XXXX what if minimal match and we are at the
977                         initial run of {n,m}? */
978                 if ((mincount != maxcount - 1) && (maxcount != REG_INFTY))
979                     f &= ~SCF_WHILEM_VISITED_POS;
980
981                 /* This will finish on WHILEM, setting scan, or on NULL: */
982                 minnext = study_chunk(pRExC_state, &scan, &deltanext, last, data,
983                                       mincount == 0
984                                         ? (f & ~SCF_DO_SUBSTR) : f);
985
986                 if (flags & SCF_DO_STCLASS)
987                     data->start_class = oclass;
988                 if (mincount == 0 || minnext == 0) {
989                     if (flags & SCF_DO_STCLASS_OR) {
990                         cl_or(pRExC_state, data->start_class, &this_class);
991                     }
992                     else if (flags & SCF_DO_STCLASS_AND) {
993                         /* Switch to OR mode: cache the old value of
994                          * data->start_class */
995                         StructCopy(data->start_class, &and_with,
996                                    struct regnode_charclass_class);
997                         flags &= ~SCF_DO_STCLASS_AND;
998                         StructCopy(&this_class, data->start_class,
999                                    struct regnode_charclass_class);
1000                         flags |= SCF_DO_STCLASS_OR;
1001                         data->start_class->flags |= ANYOF_EOS;
1002                     }
1003                 } else {                /* Non-zero len */
1004                     if (flags & SCF_DO_STCLASS_OR) {
1005                         cl_or(pRExC_state, data->start_class, &this_class);
1006                         cl_and(data->start_class, &and_with);
1007                     }
1008                     else if (flags & SCF_DO_STCLASS_AND)
1009                         cl_and(data->start_class, &this_class);
1010                     flags &= ~SCF_DO_STCLASS;
1011                 }
1012                 if (!scan)              /* It was not CURLYX, but CURLY. */
1013                     scan = next;
1014                 if (ckWARN(WARN_REGEXP) && (minnext + deltanext == 0)
1015                     && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
1016                     && maxcount <= REG_INFTY/3) /* Complement check for big count */
1017                 {
1018                     vWARN(RExC_parse,
1019                           "Quantifier unexpected on zero-length expression");
1020                 }
1021
1022                 min += minnext * mincount;
1023                 is_inf_internal |= ((maxcount == REG_INFTY
1024                                      && (minnext + deltanext) > 0)
1025                                     || deltanext == I32_MAX);
1026                 is_inf |= is_inf_internal;
1027                 delta += (minnext + deltanext) * maxcount - minnext * mincount;
1028
1029                 /* Try powerful optimization CURLYX => CURLYN. */
1030                 if (  OP(oscan) == CURLYX && data
1031                       && data->flags & SF_IN_PAR
1032                       && !(data->flags & SF_HAS_EVAL)
1033                       && !deltanext && minnext == 1 ) {
1034                     /* Try to optimize to CURLYN.  */
1035                     regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
1036                     regnode *nxt1 = nxt, *nxt2;
1037
1038                     /* Skip open. */
1039                     nxt = regnext(nxt);
1040                     if (!strchr((char*)PL_simple,OP(nxt))
1041                         && !(PL_regkind[(U8)OP(nxt)] == EXACT
1042                              && STR_LEN(nxt) == 1))
1043                         goto nogo;
1044                     nxt2 = nxt;
1045                     nxt = regnext(nxt);
1046                     if (OP(nxt) != CLOSE)
1047                         goto nogo;
1048                     /* Now we know that nxt2 is the only contents: */
1049                     oscan->flags = ARG(nxt);
1050                     OP(oscan) = CURLYN;
1051                     OP(nxt1) = NOTHING; /* was OPEN. */
1052 #ifdef DEBUGGING
1053                     OP(nxt1 + 1) = OPTIMIZED; /* was count. */
1054                     NEXT_OFF(nxt1+ 1) = 0; /* just for consistancy. */
1055                     NEXT_OFF(nxt2) = 0; /* just for consistancy with CURLY. */
1056                     OP(nxt) = OPTIMIZED;        /* was CLOSE. */
1057                     OP(nxt + 1) = OPTIMIZED; /* was count. */
1058                     NEXT_OFF(nxt+ 1) = 0; /* just for consistancy. */
1059 #endif
1060                 }
1061               nogo:
1062
1063                 /* Try optimization CURLYX => CURLYM. */
1064                 if (  OP(oscan) == CURLYX && data
1065                       && !(data->flags & SF_HAS_PAR)
1066                       && !(data->flags & SF_HAS_EVAL)
1067                       && !deltanext  ) {
1068                     /* XXXX How to optimize if data == 0? */
1069                     /* Optimize to a simpler form.  */
1070                     regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
1071                     regnode *nxt2;
1072
1073                     OP(oscan) = CURLYM;
1074                     while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
1075                             && (OP(nxt2) != WHILEM))
1076                         nxt = nxt2;
1077                     OP(nxt2)  = SUCCEED; /* Whas WHILEM */
1078                     /* Need to optimize away parenths. */
1079                     if (data->flags & SF_IN_PAR) {
1080                         /* Set the parenth number.  */
1081                         regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
1082
1083                         if (OP(nxt) != CLOSE)
1084                             FAIL("Panic opt close");
1085                         oscan->flags = ARG(nxt);
1086                         OP(nxt1) = OPTIMIZED;   /* was OPEN. */
1087                         OP(nxt) = OPTIMIZED;    /* was CLOSE. */
1088 #ifdef DEBUGGING
1089                         OP(nxt1 + 1) = OPTIMIZED; /* was count. */
1090                         OP(nxt + 1) = OPTIMIZED; /* was count. */
1091                         NEXT_OFF(nxt1 + 1) = 0; /* just for consistancy. */
1092                         NEXT_OFF(nxt + 1) = 0; /* just for consistancy. */
1093 #endif
1094 #if 0
1095                         while ( nxt1 && (OP(nxt1) != WHILEM)) {
1096                             regnode *nnxt = regnext(nxt1);
1097                         
1098                             if (nnxt == nxt) {
1099                                 if (reg_off_by_arg[OP(nxt1)])
1100                                     ARG_SET(nxt1, nxt2 - nxt1);
1101                                 else if (nxt2 - nxt1 < U16_MAX)
1102                                     NEXT_OFF(nxt1) = nxt2 - nxt1;
1103                                 else
1104                                     OP(nxt) = NOTHING;  /* Cannot beautify */
1105                             }
1106                             nxt1 = nnxt;
1107                         }
1108 #endif
1109                         /* Optimize again: */
1110                         study_chunk(pRExC_state, &nxt1, &deltanext, nxt,
1111                                     NULL, 0);
1112                     }
1113                     else
1114                         oscan->flags = 0;
1115                 }
1116                 else if ((OP(oscan) == CURLYX)
1117                          && (flags & SCF_WHILEM_VISITED_POS)
1118                          /* See the comment on a similar expression above.
1119                             However, this time it not a subexpression
1120                             we care about, but the expression itself. */
1121                          && (maxcount == REG_INFTY)
1122                          && data && ++data->whilem_c < 16) {
1123                     /* This stays as CURLYX, we can put the count/of pair. */
1124                     /* Find WHILEM (as in regexec.c) */
1125                     regnode *nxt = oscan + NEXT_OFF(oscan);
1126
1127                     if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
1128                         nxt += ARG(nxt);
1129                     PREVOPER(nxt)->flags = data->whilem_c
1130                         | (RExC_whilem_seen << 4); /* On WHILEM */
1131                 }
1132                 if (data && fl & (SF_HAS_PAR|SF_IN_PAR))
1133                     pars++;
1134                 if (flags & SCF_DO_SUBSTR) {
1135                     SV *last_str = Nullsv;
1136                     int counted = mincount != 0;
1137
1138                     if (data->last_end > 0 && mincount != 0) { /* Ends with a string. */
1139                         I32 b = pos_before >= data->last_start_min
1140                             ? pos_before : data->last_start_min;
1141                         STRLEN l;
1142                         char *s = SvPV(data->last_found, l);
1143                         I32 old = b - data->last_start_min;
1144
1145                         if (UTF)
1146                             old = utf8_hop((U8*)s, old) - (U8*)s;
1147                         
1148                         l -= old;
1149                         /* Get the added string: */
1150                         last_str = newSVpvn(s  + old, l);
1151                         if (deltanext == 0 && pos_before == b) {
1152                             /* What was added is a constant string */
1153                             if (mincount > 1) {
1154                                 SvGROW(last_str, (mincount * l) + 1);
1155                                 repeatcpy(SvPVX(last_str) + l,
1156                                           SvPVX(last_str), l, mincount - 1);
1157                                 SvCUR(last_str) *= mincount;
1158                                 /* Add additional parts. */
1159                                 SvCUR_set(data->last_found,
1160                                           SvCUR(data->last_found) - l);
1161                                 sv_catsv(data->last_found, last_str);
1162                                 data->last_end += l * (mincount - 1);
1163                             }
1164                         } else {
1165                             /* start offset must point into the last copy */
1166                             data->last_start_min += minnext * (mincount - 1);
1167                             data->last_start_max += is_inf ? 0 : (maxcount - 1)
1168                                 * (minnext + data->pos_delta);
1169                         }
1170                     }
1171                     /* It is counted once already... */
1172                     data->pos_min += minnext * (mincount - counted);
1173                     data->pos_delta += - counted * deltanext +
1174                         (minnext + deltanext) * maxcount - minnext * mincount;
1175                     if (mincount != maxcount) {
1176                          /* Cannot extend fixed substrings found inside
1177                             the group.  */
1178                         scan_commit(pRExC_state,data);
1179                         if (mincount && last_str) {
1180                             sv_setsv(data->last_found, last_str);
1181                             data->last_end = data->pos_min;
1182                             data->last_start_min =
1183                                 data->pos_min - CHR_SVLEN(last_str);
1184                             data->last_start_max = is_inf
1185                                 ? I32_MAX
1186                                 : data->pos_min + data->pos_delta
1187                                 - CHR_SVLEN(last_str);
1188                         }
1189                         data->longest = &(data->longest_float);
1190                     }
1191                     SvREFCNT_dec(last_str);
1192                 }
1193                 if (data && (fl & SF_HAS_EVAL))
1194                     data->flags |= SF_HAS_EVAL;
1195               optimize_curly_tail:
1196                 if (OP(oscan) != CURLYX) {
1197                     while (PL_regkind[(U8)OP(next = regnext(oscan))] == NOTHING
1198                            && NEXT_OFF(next))
1199                         NEXT_OFF(oscan) += NEXT_OFF(next);
1200                 }
1201                 continue;
1202             default:                    /* REF and CLUMP only? */
1203                 if (flags & SCF_DO_SUBSTR) {
1204                     scan_commit(pRExC_state,data);      /* Cannot expect anything... */
1205                     data->longest = &(data->longest_float);
1206                 }
1207                 is_inf = is_inf_internal = 1;
1208                 if (flags & SCF_DO_STCLASS_OR)
1209                     cl_anything(pRExC_state, data->start_class);
1210                 flags &= ~SCF_DO_STCLASS;
1211                 break;
1212             }
1213         }
1214         else if (strchr((char*)PL_simple,OP(scan))) {
1215             int value;
1216
1217             if (flags & SCF_DO_SUBSTR) {
1218                 scan_commit(pRExC_state,data);
1219                 data->pos_min++;
1220             }
1221             min++;
1222             if (flags & SCF_DO_STCLASS) {
1223                 data->start_class->flags &= ~ANYOF_EOS; /* No match on empty */
1224
1225                 /* Some of the logic below assumes that switching
1226                    locale on will only add false positives. */
1227                 switch (PL_regkind[(U8)OP(scan)]) {
1228                 case SANY:
1229                 default:
1230                   do_default:
1231                     /* Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d", OP(scan)); */
1232                     if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
1233                         cl_anything(pRExC_state, data->start_class);
1234                     break;
1235                 case REG_ANY:
1236                     if (OP(scan) == SANY)
1237                         goto do_default;
1238                     if (flags & SCF_DO_STCLASS_OR) { /* Everything but \n */
1239                         value = (ANYOF_BITMAP_TEST(data->start_class,'\n')
1240                                  || (data->start_class->flags & ANYOF_CLASS));
1241                         cl_anything(pRExC_state, data->start_class);
1242                     }
1243                     if (flags & SCF_DO_STCLASS_AND || !value)
1244                         ANYOF_BITMAP_CLEAR(data->start_class,'\n');
1245                     break;
1246                 case ANYOF:
1247                     if (flags & SCF_DO_STCLASS_AND)
1248                         cl_and(data->start_class,
1249                                (struct regnode_charclass_class*)scan);
1250                     else
1251                         cl_or(pRExC_state, data->start_class,
1252                               (struct regnode_charclass_class*)scan);
1253                     break;
1254                 case ALNUM:
1255                     if (flags & SCF_DO_STCLASS_AND) {
1256                         if (!(data->start_class->flags & ANYOF_LOCALE)) {
1257                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
1258                             for (value = 0; value < 256; value++)
1259                                 if (!isALNUM(value))
1260                                     ANYOF_BITMAP_CLEAR(data->start_class, value);
1261                         }
1262                     }
1263                     else {
1264                         if (data->start_class->flags & ANYOF_LOCALE)
1265                             ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
1266                         else {
1267                             for (value = 0; value < 256; value++)
1268                                 if (isALNUM(value))
1269                                     ANYOF_BITMAP_SET(data->start_class, value);                 
1270                         }
1271                     }
1272                     break;
1273                 case ALNUML:
1274                     if (flags & SCF_DO_STCLASS_AND) {
1275                         if (data->start_class->flags & ANYOF_LOCALE)
1276                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
1277                     }
1278                     else {
1279                         ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
1280                         data->start_class->flags |= ANYOF_LOCALE;
1281                     }
1282                     break;
1283                 case NALNUM:
1284                     if (flags & SCF_DO_STCLASS_AND) {
1285                         if (!(data->start_class->flags & ANYOF_LOCALE)) {
1286                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
1287                             for (value = 0; value < 256; value++)
1288                                 if (isALNUM(value))
1289                                     ANYOF_BITMAP_CLEAR(data->start_class, value);
1290                         }
1291                     }
1292                     else {
1293                         if (data->start_class->flags & ANYOF_LOCALE)
1294                             ANYOF_CLASS_SET(data->start_class,ANYOF_NALNUM);
1295                         else {
1296                             for (value = 0; value < 256; value++)
1297                                 if (!isALNUM(value))
1298                                     ANYOF_BITMAP_SET(data->start_class, value);                 
1299                         }
1300                     }
1301                     break;
1302                 case NALNUML:
1303                     if (flags & SCF_DO_STCLASS_AND) {
1304                         if (data->start_class->flags & ANYOF_LOCALE)
1305                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
1306                     }
1307                     else {
1308                         data->start_class->flags |= ANYOF_LOCALE;
1309                         ANYOF_CLASS_SET(data->start_class,ANYOF_NALNUM);
1310                     }
1311                     break;
1312                 case SPACE:
1313                     if (flags & SCF_DO_STCLASS_AND) {
1314                         if (!(data->start_class->flags & ANYOF_LOCALE)) {
1315                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NSPACE);
1316                             for (value = 0; value < 256; value++)
1317                                 if (!isSPACE(value))
1318                                     ANYOF_BITMAP_CLEAR(data->start_class, value);
1319                         }
1320                     }
1321                     else {
1322                         if (data->start_class->flags & ANYOF_LOCALE)
1323                             ANYOF_CLASS_SET(data->start_class,ANYOF_SPACE);
1324                         else {
1325                             for (value = 0; value < 256; value++)
1326                                 if (isSPACE(value))
1327                                     ANYOF_BITMAP_SET(data->start_class, value);                 
1328                         }
1329                     }
1330                     break;
1331                 case SPACEL:
1332                     if (flags & SCF_DO_STCLASS_AND) {
1333                         if (data->start_class->flags & ANYOF_LOCALE)
1334                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NSPACE);
1335                     }
1336                     else {
1337                         data->start_class->flags |= ANYOF_LOCALE;
1338                         ANYOF_CLASS_SET(data->start_class,ANYOF_SPACE);
1339                     }
1340                     break;
1341                 case NSPACE:
1342                     if (flags & SCF_DO_STCLASS_AND) {
1343                         if (!(data->start_class->flags & ANYOF_LOCALE)) {
1344                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_SPACE);
1345                             for (value = 0; value < 256; value++)
1346                                 if (isSPACE(value))
1347                                     ANYOF_BITMAP_CLEAR(data->start_class, value);
1348                         }
1349                     }
1350                     else {
1351                         if (data->start_class->flags & ANYOF_LOCALE)
1352                             ANYOF_CLASS_SET(data->start_class,ANYOF_NSPACE);
1353                         else {
1354                             for (value = 0; value < 256; value++)
1355                                 if (!isSPACE(value))
1356                                     ANYOF_BITMAP_SET(data->start_class, value);                 
1357                         }
1358                     }
1359                     break;
1360                 case NSPACEL:
1361                     if (flags & SCF_DO_STCLASS_AND) {
1362                         if (data->start_class->flags & ANYOF_LOCALE) {
1363                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_SPACE);
1364                             for (value = 0; value < 256; value++)
1365                                 if (!isSPACE(value))
1366                                     ANYOF_BITMAP_CLEAR(data->start_class, value);
1367                         }
1368                     }
1369                     else {
1370                         data->start_class->flags |= ANYOF_LOCALE;
1371                         ANYOF_CLASS_SET(data->start_class,ANYOF_NSPACE);
1372                     }
1373                     break;
1374                 case DIGIT:
1375                     if (flags & SCF_DO_STCLASS_AND) {
1376                         ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NDIGIT);
1377                         for (value = 0; value < 256; value++)
1378                             if (!isDIGIT(value))
1379                                 ANYOF_BITMAP_CLEAR(data->start_class, value);
1380                     }
1381                     else {
1382                         if (data->start_class->flags & ANYOF_LOCALE)
1383                             ANYOF_CLASS_SET(data->start_class,ANYOF_DIGIT);
1384                         else {
1385                             for (value = 0; value < 256; value++)
1386                                 if (isDIGIT(value))
1387                                     ANYOF_BITMAP_SET(data->start_class, value);                 
1388                         }
1389                     }
1390                     break;
1391                 case NDIGIT:
1392                     if (flags & SCF_DO_STCLASS_AND) {
1393                         ANYOF_CLASS_CLEAR(data->start_class,ANYOF_DIGIT);
1394                         for (value = 0; value < 256; value++)
1395                             if (isDIGIT(value))
1396                                 ANYOF_BITMAP_CLEAR(data->start_class, value);
1397                     }
1398                     else {
1399                         if (data->start_class->flags & ANYOF_LOCALE)
1400                             ANYOF_CLASS_SET(data->start_class,ANYOF_NDIGIT);
1401                         else {
1402                             for (value = 0; value < 256; value++)
1403                                 if (!isDIGIT(value))
1404                                     ANYOF_BITMAP_SET(data->start_class, value);                 
1405                         }
1406                     }
1407                     break;
1408                 }
1409                 if (flags & SCF_DO_STCLASS_OR)
1410                     cl_and(data->start_class, &and_with);
1411                 flags &= ~SCF_DO_STCLASS;
1412             }
1413         }
1414         else if (PL_regkind[(U8)OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
1415             data->flags |= (OP(scan) == MEOL
1416                             ? SF_BEFORE_MEOL
1417                             : SF_BEFORE_SEOL);
1418         }
1419         else if (  PL_regkind[(U8)OP(scan)] == BRANCHJ
1420                  /* Lookbehind, or need to calculate parens/evals/stclass: */
1421                    && (scan->flags || data || (flags & SCF_DO_STCLASS))
1422                    && (OP(scan) == IFMATCH || OP(scan) == UNLESSM)) {
1423             /* Lookahead/lookbehind */
1424             I32 deltanext, minnext, fake = 0;
1425             regnode *nscan;
1426             struct regnode_charclass_class intrnl;
1427             int f = 0;
1428
1429             data_fake.flags = 0;
1430             if (data) {         
1431                 data_fake.whilem_c = data->whilem_c;
1432                 data_fake.last_closep = data->last_closep;
1433             }
1434             else
1435                 data_fake.last_closep = &fake;
1436             if ( flags & SCF_DO_STCLASS && !scan->flags
1437                  && OP(scan) == IFMATCH ) { /* Lookahead */
1438                 cl_init(pRExC_state, &intrnl);
1439                 data_fake.start_class = &intrnl;
1440                 f |= SCF_DO_STCLASS_AND;
1441             }
1442             if (flags & SCF_WHILEM_VISITED_POS)
1443                 f |= SCF_WHILEM_VISITED_POS;
1444             next = regnext(scan);
1445             nscan = NEXTOPER(NEXTOPER(scan));
1446             minnext = study_chunk(pRExC_state, &nscan, &deltanext, last, &data_fake, f);
1447             if (scan->flags) {
1448                 if (deltanext) {
1449                     vFAIL("Variable length lookbehind not implemented");
1450                 }
1451                 else if (minnext > U8_MAX) {
1452                     vFAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
1453                 }
1454                 scan->flags = minnext;
1455             }
1456             if (data && data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
1457                 pars++;
1458             if (data && (data_fake.flags & SF_HAS_EVAL))
1459                 data->flags |= SF_HAS_EVAL;
1460             if (data)
1461                 data->whilem_c = data_fake.whilem_c;
1462             if (f & SCF_DO_STCLASS_AND) {
1463                 int was = (data->start_class->flags & ANYOF_EOS);
1464
1465                 cl_and(data->start_class, &intrnl);
1466                 if (was)
1467                     data->start_class->flags |= ANYOF_EOS;
1468             }
1469         }
1470         else if (OP(scan) == OPEN) {
1471             pars++;
1472         }
1473         else if (OP(scan) == CLOSE) {
1474             if (ARG(scan) == is_par) {
1475                 next = regnext(scan);
1476
1477                 if ( next && (OP(next) != WHILEM) && next < last)
1478                     is_par = 0;         /* Disable optimization */
1479             }
1480             if (data)
1481                 *(data->last_closep) = ARG(scan);
1482         }
1483         else if (OP(scan) == EVAL) {
1484                 if (data)
1485                     data->flags |= SF_HAS_EVAL;
1486         }
1487         else if (OP(scan) == LOGICAL && scan->flags == 2) { /* Embedded follows */
1488                 if (flags & SCF_DO_SUBSTR) {
1489                     scan_commit(pRExC_state,data);
1490                     data->longest = &(data->longest_float);
1491                 }
1492                 is_inf = is_inf_internal = 1;
1493                 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
1494                     cl_anything(pRExC_state, data->start_class);
1495                 flags &= ~SCF_DO_STCLASS;
1496         }
1497         /* Else: zero-length, ignore. */
1498         scan = regnext(scan);
1499     }
1500
1501   finish:
1502     *scanp = scan;
1503     *deltap = is_inf_internal ? I32_MAX : delta;
1504     if (flags & SCF_DO_SUBSTR && is_inf)
1505         data->pos_delta = I32_MAX - data->pos_min;
1506     if (is_par > U8_MAX)
1507         is_par = 0;
1508     if (is_par && pars==1 && data) {
1509         data->flags |= SF_IN_PAR;
1510         data->flags &= ~SF_HAS_PAR;
1511     }
1512     else if (pars && data) {
1513         data->flags |= SF_HAS_PAR;
1514         data->flags &= ~SF_IN_PAR;
1515     }
1516     if (flags & SCF_DO_STCLASS_OR)
1517         cl_and(data->start_class, &and_with);
1518     return min;
1519 }
1520
1521 STATIC I32
1522 S_add_data(pTHX_ RExC_state_t *pRExC_state, I32 n, char *s)
1523 {
1524     if (RExC_rx->data) {
1525         Renewc(RExC_rx->data,
1526                sizeof(*RExC_rx->data) + sizeof(void*) * (RExC_rx->data->count + n - 1),
1527                char, struct reg_data);
1528         Renew(RExC_rx->data->what, RExC_rx->data->count + n, U8);
1529         RExC_rx->data->count += n;
1530     }
1531     else {
1532         Newc(1207, RExC_rx->data, sizeof(*RExC_rx->data) + sizeof(void*) * (n - 1),
1533              char, struct reg_data);
1534         New(1208, RExC_rx->data->what, n, U8);
1535         RExC_rx->data->count = n;
1536     }
1537     Copy(s, RExC_rx->data->what + RExC_rx->data->count - n, n, U8);
1538     return RExC_rx->data->count - n;
1539 }
1540
1541 void
1542 Perl_reginitcolors(pTHX)
1543 {
1544     int i = 0;
1545     char *s = PerlEnv_getenv("PERL_RE_COLORS");
1546         
1547     if (s) {
1548         PL_colors[0] = s = savepv(s);
1549         while (++i < 6) {
1550             s = strchr(s, '\t');
1551             if (s) {
1552                 *s = '\0';
1553                 PL_colors[i] = ++s;
1554             }
1555             else
1556                 PL_colors[i] = s = "";
1557         }
1558     } else {
1559         while (i < 6)
1560             PL_colors[i++] = "";
1561     }
1562     PL_colorset = 1;
1563 }
1564
1565
1566 /*
1567  - pregcomp - compile a regular expression into internal code
1568  *
1569  * We can't allocate space until we know how big the compiled form will be,
1570  * but we can't compile it (and thus know how big it is) until we've got a
1571  * place to put the code.  So we cheat:  we compile it twice, once with code
1572  * generation turned off and size counting turned on, and once "for real".
1573  * This also means that we don't allocate space until we are sure that the
1574  * thing really will compile successfully, and we never have to move the
1575  * code and thus invalidate pointers into it.  (Note that it has to be in
1576  * one piece because free() must be able to free it all.) [NB: not true in perl]
1577  *
1578  * Beware that the optimization-preparation code in here knows about some
1579  * of the structure of the compiled regexp.  [I'll say.]
1580  */
1581 regexp *
1582 Perl_pregcomp(pTHX_ char *exp, char *xend, PMOP *pm)
1583 {
1584     register regexp *r;
1585     regnode *scan;
1586     regnode *first;
1587     I32 flags;
1588     I32 minlen = 0;
1589     I32 sawplus = 0;
1590     I32 sawopen = 0;
1591     scan_data_t data;
1592     RExC_state_t RExC_state;
1593     RExC_state_t *pRExC_state = &RExC_state;
1594
1595     if (exp == NULL)
1596         FAIL("NULL regexp argument");
1597
1598     /* XXXX This looks very suspicious... */
1599     if (pm->op_pmdynflags & PMdf_CMP_UTF8)
1600         RExC_utf8 = 1;
1601     else
1602         RExC_utf8 = 0;
1603
1604     RExC_precomp = savepvn(exp, xend - exp);
1605     DEBUG_r(if (!PL_colorset) reginitcolors());
1606     DEBUG_r(PerlIO_printf(Perl_debug_log, "%sCompiling REx%s `%s%*s%s'\n",
1607                       PL_colors[4],PL_colors[5],PL_colors[0],
1608                       (int)(xend - exp), RExC_precomp, PL_colors[1]));
1609     RExC_flags16 = pm->op_pmflags;
1610     RExC_sawback = 0;
1611
1612     RExC_seen = 0;
1613     RExC_seen_zerolen = *exp == '^' ? -1 : 0;
1614     RExC_seen_evals = 0;
1615     RExC_extralen = 0;
1616
1617     /* First pass: determine size, legality. */
1618     RExC_parse = exp;
1619     RExC_end = xend;
1620     RExC_naughty = 0;
1621     RExC_npar = 1;
1622     RExC_size = 0L;
1623     RExC_emit = &PL_regdummy;
1624     RExC_whilem_seen = 0;
1625 #if 0 /* REGC() is (currently) a NOP at the first pass.
1626        * Clever compilers notice this and complain. --jhi */
1627     REGC((U8)REG_MAGIC, (char*)RExC_emit);
1628 #endif
1629     if (reg(pRExC_state, 0, &flags) == NULL) {
1630         Safefree(RExC_precomp);
1631         RExC_precomp = Nullch;
1632         return(NULL);
1633     }
1634     DEBUG_r(PerlIO_printf(Perl_debug_log, "size %"IVdf" ", (IV)RExC_size));
1635
1636     /* Small enough for pointer-storage convention?
1637        If extralen==0, this means that we will not need long jumps. */
1638     if (RExC_size >= 0x10000L && RExC_extralen)
1639         RExC_size += RExC_extralen;
1640     else
1641         RExC_extralen = 0;
1642     if (RExC_whilem_seen > 15)
1643         RExC_whilem_seen = 15;
1644
1645     /* Allocate space and initialize. */
1646     Newc(1001, r, sizeof(regexp) + (unsigned)RExC_size * sizeof(regnode),
1647          char, regexp);
1648     if (r == NULL)
1649         FAIL("Regexp out of space");
1650
1651 #ifdef DEBUGGING
1652     /* avoid reading uninitialized memory in DEBUGGING code in study_chunk() */
1653     Zero(r, sizeof(regexp) + (unsigned)RExC_size * sizeof(regnode), char);
1654 #endif
1655     r->refcnt = 1;
1656     r->prelen = xend - exp;
1657     r->precomp = RExC_precomp;
1658     r->subbeg = NULL;
1659     r->reganch = pm->op_pmflags & PMf_COMPILETIME;
1660     r->nparens = RExC_npar - 1; /* set early to validate backrefs */
1661
1662     r->substrs = 0;                     /* Useful during FAIL. */
1663     r->startp = 0;                      /* Useful during FAIL. */
1664     r->endp = 0;                        /* Useful during FAIL. */
1665
1666     RExC_rx = r;
1667
1668     /* Second pass: emit code. */
1669     RExC_parse = exp;
1670     RExC_end = xend;
1671     RExC_naughty = 0;
1672     RExC_npar = 1;
1673     RExC_emit = r->program;
1674     /* Store the count of eval-groups for security checks: */
1675     RExC_emit->next_off = ((RExC_seen_evals > U16_MAX) ? U16_MAX : RExC_seen_evals);
1676     REGC((U8)REG_MAGIC, (char*) RExC_emit++);
1677     r->data = 0;
1678     if (reg(pRExC_state, 0, &flags) == NULL)
1679         return(NULL);
1680
1681     /* Dig out information for optimizations. */
1682     r->reganch = pm->op_pmflags & PMf_COMPILETIME; /* Again? */
1683     pm->op_pmflags = RExC_flags16;
1684     if (UTF)
1685         r->reganch |= ROPT_UTF8;
1686     r->regstclass = NULL;
1687     if (RExC_naughty >= 10)     /* Probably an expensive pattern. */
1688         r->reganch |= ROPT_NAUGHTY;
1689     scan = r->program + 1;              /* First BRANCH. */
1690
1691     /* XXXX To minimize changes to RE engine we always allocate
1692        3-units-long substrs field. */
1693     Newz(1004, r->substrs, 1, struct reg_substr_data);
1694
1695     StructCopy(&zero_scan_data, &data, scan_data_t);
1696     /* XXXX Should not we check for something else?  Usually it is OPEN1... */
1697     if (OP(scan) != BRANCH) {   /* Only one top-level choice. */
1698         I32 fake;
1699         STRLEN longest_float_length, longest_fixed_length;
1700         struct regnode_charclass_class ch_class;
1701         int stclass_flag;
1702         I32 last_close = 0;
1703
1704         first = scan;
1705         /* Skip introductions and multiplicators >= 1. */
1706         while ((OP(first) == OPEN && (sawopen = 1)) ||
1707                /* An OR of *one* alternative - should not happen now. */
1708             (OP(first) == BRANCH && OP(regnext(first)) != BRANCH) ||
1709             (OP(first) == PLUS) ||
1710             (OP(first) == MINMOD) ||
1711                /* An {n,m} with n>0 */
1712             (PL_regkind[(U8)OP(first)] == CURLY && ARG1(first) > 0) ) {
1713                 if (OP(first) == PLUS)
1714                     sawplus = 1;
1715                 else
1716                     first += regarglen[(U8)OP(first)];
1717                 first = NEXTOPER(first);
1718         }
1719
1720         /* Starting-point info. */
1721       again:
1722         if (PL_regkind[(U8)OP(first)] == EXACT) {
1723             if (OP(first) == EXACT)
1724                 ;       /* Empty, get anchored substr later. */
1725             else if ((OP(first) == EXACTF || OP(first) == EXACTFL))
1726                 r->regstclass = first;
1727         }
1728         else if (strchr((char*)PL_simple,OP(first)))
1729             r->regstclass = first;
1730         else if (PL_regkind[(U8)OP(first)] == BOUND ||
1731                  PL_regkind[(U8)OP(first)] == NBOUND)
1732             r->regstclass = first;
1733         else if (PL_regkind[(U8)OP(first)] == BOL) {
1734             r->reganch |= (OP(first) == MBOL
1735                            ? ROPT_ANCH_MBOL
1736                            : (OP(first) == SBOL
1737                               ? ROPT_ANCH_SBOL
1738                               : ROPT_ANCH_BOL));
1739             first = NEXTOPER(first);
1740             goto again;
1741         }
1742         else if (OP(first) == GPOS) {
1743             r->reganch |= ROPT_ANCH_GPOS;
1744             first = NEXTOPER(first);
1745             goto again;
1746         }
1747         else if ((OP(first) == STAR &&
1748             PL_regkind[(U8)OP(NEXTOPER(first))] == REG_ANY) &&
1749             !(r->reganch & ROPT_ANCH) )
1750         {
1751             /* turn .* into ^.* with an implied $*=1 */
1752             int type = OP(NEXTOPER(first));
1753
1754             if (type == REG_ANY)
1755                 type = ROPT_ANCH_MBOL;
1756             else
1757                 type = ROPT_ANCH_SBOL;
1758
1759             r->reganch |= type | ROPT_IMPLICIT;
1760             first = NEXTOPER(first);
1761             goto again;
1762         }
1763         if (sawplus && (!sawopen || !RExC_sawback)
1764             && !(RExC_seen & REG_SEEN_EVAL)) /* May examine pos and $& */
1765             /* x+ must match at the 1st pos of run of x's */
1766             r->reganch |= ROPT_SKIP;
1767
1768         /* Scan is after the zeroth branch, first is atomic matcher. */
1769         DEBUG_r(PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n",
1770                               (IV)(first - scan + 1)));
1771         /*
1772         * If there's something expensive in the r.e., find the
1773         * longest literal string that must appear and make it the
1774         * regmust.  Resolve ties in favor of later strings, since
1775         * the regstart check works with the beginning of the r.e.
1776         * and avoiding duplication strengthens checking.  Not a
1777         * strong reason, but sufficient in the absence of others.
1778         * [Now we resolve ties in favor of the earlier string if
1779         * it happens that c_offset_min has been invalidated, since the
1780         * earlier string may buy us something the later one won't.]
1781         */
1782         minlen = 0;
1783
1784         data.longest_fixed = newSVpvn("",0);
1785         data.longest_float = newSVpvn("",0);
1786         data.last_found = newSVpvn("",0);
1787         data.longest = &(data.longest_fixed);
1788         first = scan;
1789         if (!r->regstclass) {
1790             cl_init(pRExC_state, &ch_class);
1791             data.start_class = &ch_class;
1792             stclass_flag = SCF_DO_STCLASS_AND;
1793         } else                          /* XXXX Check for BOUND? */
1794             stclass_flag = 0;
1795         data.last_closep = &last_close;
1796
1797         minlen = study_chunk(pRExC_state, &first, &fake, scan + RExC_size, /* Up to end */
1798                              &data, SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag);
1799         if ( RExC_npar == 1 && data.longest == &(data.longest_fixed)
1800              && data.last_start_min == 0 && data.last_end > 0
1801              && !RExC_seen_zerolen
1802              && (!(RExC_seen & REG_SEEN_GPOS) || (r->reganch & ROPT_ANCH_GPOS)))
1803             r->reganch |= ROPT_CHECK_ALL;
1804         scan_commit(pRExC_state, &data);
1805         SvREFCNT_dec(data.last_found);
1806
1807         longest_float_length = CHR_SVLEN(data.longest_float);
1808         if (longest_float_length
1809             || (data.flags & SF_FL_BEFORE_EOL
1810                 && (!(data.flags & SF_FL_BEFORE_MEOL)
1811                     || (RExC_flags16 & PMf_MULTILINE)))) {
1812             int t;
1813
1814             if (SvCUR(data.longest_fixed)                       /* ok to leave SvCUR */
1815                 && data.offset_fixed == data.offset_float_min
1816                 && SvCUR(data.longest_fixed) == SvCUR(data.longest_float))
1817                     goto remove_float;          /* As in (a)+. */
1818
1819             r->float_substr = data.longest_float;
1820             r->float_min_offset = data.offset_float_min;
1821             r->float_max_offset = data.offset_float_max;
1822             t = (data.flags & SF_FL_BEFORE_EOL /* Can't have SEOL and MULTI */
1823                        && (!(data.flags & SF_FL_BEFORE_MEOL)
1824                            || (RExC_flags16 & PMf_MULTILINE)));
1825             fbm_compile(r->float_substr, t ? FBMcf_TAIL : 0);
1826         }
1827         else {
1828           remove_float:
1829             r->float_substr = Nullsv;
1830             SvREFCNT_dec(data.longest_float);
1831             longest_float_length = 0;
1832         }
1833
1834         longest_fixed_length = CHR_SVLEN(data.longest_fixed);
1835         if (longest_fixed_length
1836             || (data.flags & SF_FIX_BEFORE_EOL /* Cannot have SEOL and MULTI */
1837                 && (!(data.flags & SF_FIX_BEFORE_MEOL)
1838                     || (RExC_flags16 & PMf_MULTILINE)))) {
1839             int t;
1840
1841             r->anchored_substr = data.longest_fixed;
1842             r->anchored_offset = data.offset_fixed;
1843             t = (data.flags & SF_FIX_BEFORE_EOL /* Can't have SEOL and MULTI */
1844                  && (!(data.flags & SF_FIX_BEFORE_MEOL)
1845                      || (RExC_flags16 & PMf_MULTILINE)));
1846             fbm_compile(r->anchored_substr, t ? FBMcf_TAIL : 0);
1847         }
1848         else {
1849             r->anchored_substr = Nullsv;
1850             SvREFCNT_dec(data.longest_fixed);
1851             longest_fixed_length = 0;
1852         }
1853         if (r->regstclass
1854             && (OP(r->regstclass) == REG_ANY || OP(r->regstclass) == SANY))
1855             r->regstclass = NULL;
1856         if ((!r->anchored_substr || r->anchored_offset) && stclass_flag
1857             && !(data.start_class->flags & ANYOF_EOS)
1858             && !cl_is_anything(data.start_class)) {
1859             SV *sv;
1860             I32 n = add_data(pRExC_state, 1, "f");
1861
1862             New(1006, RExC_rx->data->data[n], 1,
1863                 struct regnode_charclass_class);
1864             StructCopy(data.start_class,
1865                        (struct regnode_charclass_class*)RExC_rx->data->data[n],
1866                        struct regnode_charclass_class);
1867             r->regstclass = (regnode*)RExC_rx->data->data[n];
1868             r->reganch &= ~ROPT_SKIP;   /* Used in find_byclass(). */
1869             PL_regdata = r->data; /* for regprop() */
1870             DEBUG_r((sv = sv_newmortal(),
1871                      regprop(sv, (regnode*)data.start_class),
1872                      PerlIO_printf(Perl_debug_log, "synthetic stclass `%s'.\n",
1873                                    SvPVX(sv))));
1874         }
1875
1876         /* A temporary algorithm prefers floated substr to fixed one to dig more info. */
1877         if (longest_fixed_length > longest_float_length) {
1878             r->check_substr = r->anchored_substr;
1879             r->check_offset_min = r->check_offset_max = r->anchored_offset;
1880             if (r->reganch & ROPT_ANCH_SINGLE)
1881                 r->reganch |= ROPT_NOSCAN;
1882         }
1883         else {
1884             r->check_substr = r->float_substr;
1885             r->check_offset_min = data.offset_float_min;
1886             r->check_offset_max = data.offset_float_max;
1887         }
1888         /* XXXX Currently intuiting is not compatible with ANCH_GPOS.
1889            This should be changed ASAP!  */
1890         if (r->check_substr && !(r->reganch & ROPT_ANCH_GPOS)) {
1891             r->reganch |= RE_USE_INTUIT;
1892             if (SvTAIL(r->check_substr))
1893                 r->reganch |= RE_INTUIT_TAIL;
1894         }
1895     }
1896     else {
1897         /* Several toplevels. Best we can is to set minlen. */
1898         I32 fake;
1899         struct regnode_charclass_class ch_class;
1900         I32 last_close = 0;
1901         
1902         DEBUG_r(PerlIO_printf(Perl_debug_log, "\n"));
1903         scan = r->program + 1;
1904         cl_init(pRExC_state, &ch_class);
1905         data.start_class = &ch_class;
1906         data.last_closep = &last_close;
1907         minlen = study_chunk(pRExC_state, &scan, &fake, scan + RExC_size, &data, SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS);
1908         r->check_substr = r->anchored_substr = r->float_substr = Nullsv;
1909         if (!(data.start_class->flags & ANYOF_EOS)
1910             && !cl_is_anything(data.start_class)) {
1911             SV *sv;
1912             I32 n = add_data(pRExC_state, 1, "f");
1913
1914             New(1006, RExC_rx->data->data[n], 1,
1915                 struct regnode_charclass_class);
1916             StructCopy(data.start_class,
1917                        (struct regnode_charclass_class*)RExC_rx->data->data[n],
1918                        struct regnode_charclass_class);
1919             r->regstclass = (regnode*)RExC_rx->data->data[n];
1920             r->reganch &= ~ROPT_SKIP;   /* Used in find_byclass(). */
1921             DEBUG_r((sv = sv_newmortal(),
1922                      regprop(sv, (regnode*)data.start_class),
1923                      PerlIO_printf(Perl_debug_log, "synthetic stclass `%s'.\n",
1924                                    SvPVX(sv))));
1925         }
1926     }
1927
1928     r->minlen = minlen;
1929     if (RExC_seen & REG_SEEN_GPOS)
1930         r->reganch |= ROPT_GPOS_SEEN;
1931     if (RExC_seen & REG_SEEN_LOOKBEHIND)
1932         r->reganch |= ROPT_LOOKBEHIND_SEEN;
1933     if (RExC_seen & REG_SEEN_EVAL)
1934         r->reganch |= ROPT_EVAL_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             *flagp |= HASWIDTH|SIMPLE;
2644             nextchar(pRExC_state);
2645             break;
2646         case 'X':
2647             ret = reg_node(pRExC_state, CLUMP);
2648             *flagp |= HASWIDTH;
2649             nextchar(pRExC_state);
2650             if (UTF && !PL_utf8_mark)
2651                 is_utf8_mark((U8*)"~");         /* preload table */
2652             break;
2653         case 'w':
2654             ret = reg_node(pRExC_state, LOC ? ALNUML     : ALNUM);
2655             *flagp |= HASWIDTH|SIMPLE;
2656             nextchar(pRExC_state);
2657             if (UTF && !PL_utf8_alnum)
2658                 is_utf8_alnum((U8*)"a");        /* preload table */
2659             break;
2660         case 'W':
2661             ret = reg_node(pRExC_state, LOC ? NALNUML     : NALNUM);
2662             *flagp |= HASWIDTH|SIMPLE;
2663             nextchar(pRExC_state);
2664             if (UTF && !PL_utf8_alnum)
2665                 is_utf8_alnum((U8*)"a");        /* preload table */
2666             break;
2667         case 'b':
2668             RExC_seen_zerolen++;
2669             RExC_seen |= REG_SEEN_LOOKBEHIND;
2670             ret = reg_node(pRExC_state, LOC ? BOUNDL     : BOUND);
2671             *flagp |= SIMPLE;
2672             nextchar(pRExC_state);
2673             if (UTF && !PL_utf8_alnum)
2674                 is_utf8_alnum((U8*)"a");        /* preload table */
2675             break;
2676         case 'B':
2677             RExC_seen_zerolen++;
2678             RExC_seen |= REG_SEEN_LOOKBEHIND;
2679             ret = reg_node(pRExC_state, LOC ? NBOUNDL     : NBOUND);
2680             *flagp |= SIMPLE;
2681             nextchar(pRExC_state);
2682             if (UTF && !PL_utf8_alnum)
2683                 is_utf8_alnum((U8*)"a");        /* preload table */
2684             break;
2685         case 's':
2686             ret = reg_node(pRExC_state, LOC ? SPACEL     : SPACE);
2687             *flagp |= HASWIDTH|SIMPLE;
2688             nextchar(pRExC_state);
2689             if (UTF && !PL_utf8_space)
2690                 is_utf8_space((U8*)" ");        /* preload table */
2691             break;
2692         case 'S':
2693             ret = reg_node(pRExC_state, LOC ? NSPACEL     : NSPACE);
2694             *flagp |= HASWIDTH|SIMPLE;
2695             nextchar(pRExC_state);
2696             if (UTF && !PL_utf8_space)
2697                 is_utf8_space((U8*)" ");        /* preload table */
2698             break;
2699         case 'd':
2700             ret = reg_node(pRExC_state, DIGIT);
2701             *flagp |= HASWIDTH|SIMPLE;
2702             nextchar(pRExC_state);
2703             if (UTF && !PL_utf8_digit)
2704                 is_utf8_digit((U8*)"1");        /* preload table */
2705             break;
2706         case 'D':
2707             ret = reg_node(pRExC_state, NDIGIT);
2708             *flagp |= HASWIDTH|SIMPLE;
2709             nextchar(pRExC_state);
2710             if (UTF && !PL_utf8_digit)
2711                 is_utf8_digit((U8*)"1");        /* preload table */
2712             break;
2713         case 'p':
2714         case 'P':
2715             {   /* a lovely hack--pretend we saw [\pX] instead */
2716                 char* oldregxend = RExC_end;
2717
2718                 if (RExC_parse[1] == '{') {
2719                     RExC_end = strchr(RExC_parse, '}');
2720                     if (!RExC_end) {
2721                         RExC_parse += 2;
2722                         RExC_end = oldregxend;
2723                         vFAIL("Missing right brace on \\p{}");
2724                     }
2725                     RExC_end++;
2726                 }
2727                 else
2728                     RExC_end = RExC_parse + 2;
2729                 RExC_parse--;
2730
2731                 ret = regclass(pRExC_state);
2732
2733                 RExC_end = oldregxend;
2734                 RExC_parse--;
2735                 nextchar(pRExC_state);
2736                 *flagp |= HASWIDTH|SIMPLE;
2737             }
2738             break;
2739         case 'n':
2740         case 'r':
2741         case 't':
2742         case 'f':
2743         case 'e':
2744         case 'a':
2745         case 'x':
2746         case 'c':
2747         case '0':
2748             goto defchar;
2749         case '1': case '2': case '3': case '4':
2750         case '5': case '6': case '7': case '8': case '9':
2751             {
2752                 I32 num = atoi(RExC_parse);
2753
2754                 if (num > 9 && num >= RExC_npar)
2755                     goto defchar;
2756                 else {
2757                     while (isDIGIT(*RExC_parse))
2758                         RExC_parse++;
2759
2760                     if (!SIZE_ONLY && num > RExC_rx->nparens)
2761                         vFAIL("Reference to nonexistent group");
2762                     RExC_sawback = 1;
2763                     ret = reganode(pRExC_state, FOLD
2764                                    ? (LOC ? REFFL : REFF)
2765                                    : REF, num);
2766                     *flagp |= HASWIDTH;
2767                     RExC_parse--;
2768                     nextchar(pRExC_state);
2769                 }
2770             }
2771             break;
2772         case '\0':
2773             if (RExC_parse >= RExC_end)
2774                 FAIL("Trailing \\");
2775             /* FALL THROUGH */
2776         default:
2777             /* Do not generate `unrecognized' warnings here, we fall
2778                back into the quick-grab loop below */
2779             goto defchar;
2780         }
2781         break;
2782
2783     case '#':
2784         if (RExC_flags16 & PMf_EXTENDED) {
2785             while (RExC_parse < RExC_end && *RExC_parse != '\n') RExC_parse++;
2786             if (RExC_parse < RExC_end)
2787                 goto tryagain;
2788         }
2789         /* FALL THROUGH */
2790
2791     default: {
2792             register STRLEN len;
2793             register UV ender;
2794             register char *p;
2795             char *oldp, *s;
2796             STRLEN numlen;
2797
2798             RExC_parse++;
2799
2800         defchar:
2801             ret = reg_node(pRExC_state, FOLD
2802                           ? (LOC ? EXACTFL : EXACTF)
2803                           : EXACT);
2804             s = STRING(ret);
2805             for (len = 0, p = RExC_parse - 1;
2806               len < 127 && p < RExC_end;
2807               len++)
2808             {
2809                 oldp = p;
2810
2811                 if (RExC_flags16 & PMf_EXTENDED)
2812                     p = regwhite(p, RExC_end);
2813                 switch (*p) {
2814                 case '^':
2815                 case '$':
2816                 case '.':
2817                 case '[':
2818                 case '(':
2819                 case ')':
2820                 case '|':
2821                     goto loopdone;
2822                 case '\\':
2823                     switch (*++p) {
2824                     case 'A':
2825                     case 'G':
2826                     case 'Z':
2827                     case 'z':
2828                     case 'w':
2829                     case 'W':
2830                     case 'b':
2831                     case 'B':
2832                     case 's':
2833                     case 'S':
2834                     case 'd':
2835                     case 'D':
2836                     case 'p':
2837                     case 'P':
2838                         --p;
2839                         goto loopdone;
2840                     case 'n':
2841                         ender = '\n';
2842                         p++;
2843                         break;
2844                     case 'r':
2845                         ender = '\r';
2846                         p++;
2847                         break;
2848                     case 't':
2849                         ender = '\t';
2850                         p++;
2851                         break;
2852                     case 'f':
2853                         ender = '\f';
2854                         p++;
2855                         break;
2856                     case 'e':
2857 #ifdef ASCIIish
2858                           ender = '\033';
2859 #else
2860                           ender = '\047';
2861 #endif
2862                         p++;
2863                         break;
2864                     case 'a':
2865 #ifdef ASCIIish
2866                           ender = '\007';
2867 #else
2868                           ender = '\057';
2869 #endif
2870                         p++;
2871                         break;
2872                     case 'x':
2873                         if (*++p == '{') {
2874                             char* e = strchr(p, '}');
2875         
2876                             if (!e) {
2877                                 RExC_parse = p + 1;
2878                                 vFAIL("Missing right brace on \\x{}");
2879                             }
2880                             else {
2881                                 numlen = 1;     /* allow underscores */
2882                                 ender = (UV)scan_hex(p + 1, e - p - 1, &numlen);
2883                                 /* numlen is generous */
2884                                 if (numlen + len >= 127) {
2885                                     p--;
2886                                     goto loopdone;
2887                                 }
2888                                 p = e + 1;
2889                             }
2890                         }
2891                         else {
2892                             numlen = 0;         /* disallow underscores */
2893                             ender = (UV)scan_hex(p, 2, &numlen);
2894                             p += numlen;
2895                         }
2896                         break;
2897                     case 'c':
2898                         p++;
2899                         ender = UCHARAT(p++);
2900                         ender = toCTRL(ender);
2901                         break;
2902                     case '0': case '1': case '2': case '3':case '4':
2903                     case '5': case '6': case '7': case '8':case '9':
2904                         if (*p == '0' ||
2905                           (isDIGIT(p[1]) && atoi(p) >= RExC_npar) ) {
2906                             numlen = 0;         /* disallow underscores */
2907                             ender = (UV)scan_oct(p, 3, &numlen);
2908                             p += numlen;
2909                         }
2910                         else {
2911                             --p;
2912                             goto loopdone;
2913                         }
2914                         break;
2915                     case '\0':
2916                         if (p >= RExC_end)
2917                             FAIL("Trailing \\");
2918                         /* FALL THROUGH */
2919                     default:
2920                         if (!SIZE_ONLY && ckWARN(WARN_REGEXP) && isALPHA(*p))
2921                             vWARN2(p +1, "Unrecognized escape \\%c passed through", *p);
2922                         goto normal_default;
2923                     }
2924                     break;
2925                 default:
2926                   normal_default:
2927                     if (UTF8_IS_START(*p) && UTF) {
2928                         ender = utf8_to_uv((U8*)p, RExC_end - p,
2929                                                &numlen, 0);
2930                         p += numlen;
2931                     }
2932                     else
2933                         ender = *p++;
2934                     break;
2935                 }
2936                 if (RExC_flags16 & PMf_EXTENDED)
2937                     p = regwhite(p, RExC_end);
2938                 if (UTF && FOLD) {
2939                     if (LOC)
2940                         ender = toLOWER_LC_uni(ender);
2941                     else
2942                         ender = toLOWER_uni(ender);
2943                 }
2944                 if (ISMULT2(p)) { /* Back off on ?+*. */
2945                     if (len)
2946                         p = oldp;
2947                     /* ender is a Unicode value so it can be > 0xff --
2948                      * in other words, do not use UTF8_IS_CONTINUED(). */
2949                     else if (ender >= 0x80 && UTF) {
2950                         reguni(pRExC_state, ender, s, &numlen);
2951                         s += numlen;
2952                         len += numlen;
2953                     }
2954                     else {
2955                         len++;
2956                         REGC(ender, s++);
2957                     }
2958                     break;
2959                 }
2960                 /* ender is a Unicode value so it can be > 0xff --
2961                  * in other words, do not use UTF8_IS_CONTINUED(). */
2962                 if (ender >= 0x80 && UTF) {
2963                     reguni(pRExC_state, ender, s, &numlen);
2964                     s += numlen;
2965                     len += numlen - 1;
2966                 }
2967                 else
2968                     REGC(ender, s++);
2969             }
2970         loopdone:
2971             RExC_parse = p - 1;
2972             nextchar(pRExC_state);
2973             {
2974                 /* len is STRLEN which is unsigned, need to copy to signed */
2975                 IV iv = len;
2976                 if (iv < 0)
2977                     vFAIL("Internal disaster");
2978             }
2979             if (len > 0)
2980                 *flagp |= HASWIDTH;
2981             if (len == 1)
2982                 *flagp |= SIMPLE;
2983             if (!SIZE_ONLY)
2984                 STR_LEN(ret) = len;
2985             if (SIZE_ONLY)
2986                 RExC_size += STR_SZ(len);
2987             else
2988                 RExC_emit += STR_SZ(len);
2989         }
2990         break;
2991     }
2992
2993     return(ret);
2994 }
2995
2996 STATIC char *
2997 S_regwhite(pTHX_ char *p, char *e)
2998 {
2999     while (p < e) {
3000         if (isSPACE(*p))
3001             ++p;
3002         else if (*p == '#') {
3003             do {
3004                 p++;
3005             } while (p < e && *p != '\n');
3006         }
3007         else
3008             break;
3009     }
3010     return p;
3011 }
3012
3013 /* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
3014    Character classes ([:foo:]) can also be negated ([:^foo:]).
3015    Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
3016    Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
3017    but trigger warnings because they are currently unimplemented. */
3018 STATIC I32
3019 S_regpposixcc(pTHX_ RExC_state_t *pRExC_state, I32 value)
3020 {
3021     char *posixcc = 0;
3022     I32 namedclass = OOB_NAMEDCLASS;
3023
3024     if (value == '[' && RExC_parse + 1 < RExC_end &&
3025         /* I smell either [: or [= or [. -- POSIX has been here, right? */
3026         (*RExC_parse == ':' ||
3027          *RExC_parse == '=' ||
3028          *RExC_parse == '.')) {
3029         char  c = *RExC_parse;
3030         char* s = RExC_parse++;
3031         
3032         while (RExC_parse < RExC_end && *RExC_parse != c)
3033             RExC_parse++;
3034         if (RExC_parse == RExC_end)
3035             /* Grandfather lone [:, [=, [. */
3036             RExC_parse = s;
3037         else {
3038             char* t = RExC_parse++; /* skip over the c */
3039
3040             if (*RExC_parse == ']') {
3041                 RExC_parse++; /* skip over the ending ] */
3042                 posixcc = s + 1;
3043                 if (*s == ':') {
3044                     I32 complement = *posixcc == '^' ? *posixcc++ : 0;
3045                     I32 skip = 5; /* the most common skip */
3046
3047                     switch (*posixcc) {
3048                     case 'a':
3049                         if (strnEQ(posixcc, "alnum", 5))
3050                             namedclass =
3051                                 complement ? ANYOF_NALNUMC : ANYOF_ALNUMC;
3052                         else if (strnEQ(posixcc, "alpha", 5))
3053                             namedclass =
3054                                 complement ? ANYOF_NALPHA : ANYOF_ALPHA;
3055                         else if (strnEQ(posixcc, "ascii", 5))
3056                             namedclass =
3057                                 complement ? ANYOF_NASCII : ANYOF_ASCII;
3058                         break;
3059                     case 'b':
3060                         if (strnEQ(posixcc, "blank", 5))
3061                             namedclass =
3062                                 complement ? ANYOF_NBLANK : ANYOF_BLANK;
3063                         break;
3064                     case 'c':
3065                         if (strnEQ(posixcc, "cntrl", 5))
3066                             namedclass =
3067                                 complement ? ANYOF_NCNTRL : ANYOF_CNTRL;
3068                         break;
3069                     case 'd':
3070                         if (strnEQ(posixcc, "digit", 5))
3071                             namedclass =
3072                                 complement ? ANYOF_NDIGIT : ANYOF_DIGIT;
3073                         break;
3074                     case 'g':
3075                         if (strnEQ(posixcc, "graph", 5))
3076                             namedclass =
3077                                 complement ? ANYOF_NGRAPH : ANYOF_GRAPH;
3078                         break;
3079                     case 'l':
3080                         if (strnEQ(posixcc, "lower", 5))
3081                             namedclass =
3082                                 complement ? ANYOF_NLOWER : ANYOF_LOWER;
3083                         break;
3084                     case 'p':
3085                         if (strnEQ(posixcc, "print", 5))
3086                             namedclass =
3087                                 complement ? ANYOF_NPRINT : ANYOF_PRINT;
3088                         else if (strnEQ(posixcc, "punct", 5))
3089                             namedclass =
3090                                 complement ? ANYOF_NPUNCT : ANYOF_PUNCT;
3091                         break;
3092                     case 's':
3093                         if (strnEQ(posixcc, "space", 5))
3094                             namedclass =
3095                                 complement ? ANYOF_NPSXSPC : ANYOF_PSXSPC;
3096                         break;
3097                     case 'u':
3098                         if (strnEQ(posixcc, "upper", 5))
3099                             namedclass =
3100                                 complement ? ANYOF_NUPPER : ANYOF_UPPER;
3101                         break;
3102                     case 'w': /* this is not POSIX, this is the Perl \w */
3103                         if (strnEQ(posixcc, "word", 4)) {
3104                             namedclass =
3105                                 complement ? ANYOF_NALNUM : ANYOF_ALNUM;
3106                             skip = 4;
3107                         }
3108                         break;
3109                     case 'x':
3110                         if (strnEQ(posixcc, "xdigit", 6)) {
3111                             namedclass =
3112                                 complement ? ANYOF_NXDIGIT : ANYOF_XDIGIT;
3113                             skip = 6;
3114                         }
3115                         break;
3116                     }
3117                     if (namedclass == OOB_NAMEDCLASS ||
3118                         posixcc[skip] != ':' ||
3119                         posixcc[skip+1] != ']')
3120                     {
3121                         Simple_vFAIL3("POSIX class [:%.*s:] unknown",
3122                                       t - s - 1, s + 1);
3123                     }
3124                 } else if (!SIZE_ONLY) {
3125                     /* [[=foo=]] and [[.foo.]] are still future. */
3126
3127                     /* adjust RExC_parse so the warning shows after
3128                        the class closes */
3129                     while (*RExC_parse && *RExC_parse != ']')
3130                         RExC_parse++;
3131                     Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
3132                 }
3133             } else {
3134                 /* Maternal grandfather:
3135                  * "[:" ending in ":" but not in ":]" */
3136                 RExC_parse = s;
3137             }
3138         }
3139     }
3140
3141     return namedclass;
3142 }
3143
3144 STATIC void
3145 S_checkposixcc(pTHX_ RExC_state_t *pRExC_state)
3146 {
3147     if (!SIZE_ONLY && ckWARN(WARN_REGEXP) &&
3148         (*RExC_parse == ':' ||
3149          *RExC_parse == '=' ||
3150          *RExC_parse == '.')) {
3151         char *s = RExC_parse;
3152         char  c = *s++;
3153
3154         while(*s && isALNUM(*s))
3155             s++;
3156         if (*s && c == *s && s[1] == ']') {
3157             vWARN3(s+2, "POSIX syntax [%c %c] belongs inside character classes", c, c);
3158
3159             /* [[=foo=]] and [[.foo.]] are still future. */
3160             if (c == '=' || c == '.')
3161             {
3162                 /* adjust RExC_parse so the error shows after
3163                    the class closes */
3164                 while (*RExC_parse && *RExC_parse++ != ']')
3165                     ;
3166                 Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
3167             }
3168         }
3169     }
3170 }
3171
3172 STATIC regnode *
3173 S_regclass(pTHX_ RExC_state_t *pRExC_state)
3174 {
3175     register UV value;
3176     register IV lastvalue = OOB_UNICODE;
3177     register IV range = 0;
3178     register regnode *ret;
3179     STRLEN numlen;
3180     IV namedclass;
3181     char *rangebegin;
3182     bool need_class = 0;
3183     SV *listsv;
3184     register char *e;
3185     UV n;
3186     bool dont_optimize_invert = FALSE;
3187
3188     ret = reganode(pRExC_state, ANYOF, 0);
3189
3190     if (!SIZE_ONLY)
3191         ANYOF_FLAGS(ret) = 0;
3192
3193     if (*RExC_parse == '^') {   /* Complement of range. */
3194         RExC_naughty++;
3195         RExC_parse++;
3196         if (!SIZE_ONLY)
3197             ANYOF_FLAGS(ret) |= ANYOF_INVERT;
3198     }
3199
3200     if (SIZE_ONLY)
3201         RExC_size += ANYOF_SKIP;
3202     else {
3203         RExC_emit += ANYOF_SKIP;
3204         if (FOLD)
3205             ANYOF_FLAGS(ret) |= ANYOF_FOLD;
3206         if (LOC)
3207             ANYOF_FLAGS(ret) |= ANYOF_LOCALE;
3208         ANYOF_BITMAP_ZERO(ret);
3209         listsv = newSVpvn("# comment\n", 10);
3210     }
3211
3212     if (!SIZE_ONLY && ckWARN(WARN_REGEXP))
3213         checkposixcc(pRExC_state);
3214
3215     if (*RExC_parse == ']' || *RExC_parse == '-')
3216         goto charclassloop;             /* allow 1st char to be ] or - */
3217
3218     while (RExC_parse < RExC_end && *RExC_parse != ']') {
3219
3220     charclassloop:
3221
3222         namedclass = OOB_NAMEDCLASS; /* initialize as illegal */
3223
3224         if (!range)
3225             rangebegin = RExC_parse;
3226         if (UTF) {
3227             value = utf8_to_uv((U8*)RExC_parse,
3228                                RExC_end - RExC_parse,
3229                                &numlen, 0);
3230             RExC_parse += numlen;
3231         }
3232         else
3233             value = UCHARAT(RExC_parse++);
3234         if (value == '[')
3235             namedclass = regpposixcc(pRExC_state, value);
3236         else if (value == '\\') {
3237             if (UTF) {
3238                 value = utf8_to_uv((U8*)RExC_parse,
3239                                    RExC_end - RExC_parse,
3240                                    &numlen, 0);
3241                 RExC_parse += numlen;
3242             }
3243             else
3244                 value = UCHARAT(RExC_parse++);
3245             /* Some compilers cannot handle switching on 64-bit integer
3246              * values, therefore value cannot be an UV.  Yes, this will
3247              * be a problem later if we want switch on Unicode.
3248              * A similar issue a little bit later when switching on
3249              * namedclass. --jhi */
3250             switch ((I32)value) {
3251             case 'w':   namedclass = ANYOF_ALNUM;       break;
3252             case 'W':   namedclass = ANYOF_NALNUM;      break;
3253             case 's':   namedclass = ANYOF_SPACE;       break;
3254             case 'S':   namedclass = ANYOF_NSPACE;      break;
3255             case 'd':   namedclass = ANYOF_DIGIT;       break;
3256             case 'D':   namedclass = ANYOF_NDIGIT;      break;
3257             case 'p':
3258             case 'P':
3259                 if (*RExC_parse == '{') {
3260                     e = strchr(RExC_parse++, '}');
3261                     if (!e)
3262                         vFAIL("Missing right brace on \\p{}");
3263                     n = e - RExC_parse;
3264                 }
3265                 else {
3266                     e = RExC_parse;
3267                     n = 1;
3268                 }
3269                 if (!SIZE_ONLY) {
3270                     if (value == 'p')
3271                         Perl_sv_catpvf(aTHX_ listsv,
3272                                        "+utf8::%.*s\n", (int)n, RExC_parse);
3273                     else
3274                         Perl_sv_catpvf(aTHX_ listsv,
3275                                        "!utf8::%.*s\n", (int)n, RExC_parse);
3276                 }
3277                 RExC_parse = e + 1;
3278                 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
3279                 continue;
3280             case 'n':   value = '\n';                   break;
3281             case 'r':   value = '\r';                   break;
3282             case 't':   value = '\t';                   break;
3283             case 'f':   value = '\f';                   break;
3284             case 'b':   value = '\b';                   break;
3285 #ifdef ASCIIish
3286             case 'e':   value = '\033';                 break;
3287             case 'a':   value = '\007';                 break;
3288 #else
3289             case 'e':   value = '\047';                 break;
3290             case 'a':   value = '\057';                 break;
3291 #endif
3292             case 'x':
3293                 if (*RExC_parse == '{') {
3294                     e = strchr(RExC_parse++, '}');
3295                     if (!e)
3296                         vFAIL("Missing right brace on \\x{}");
3297                     numlen = 1;         /* allow underscores */
3298                     value = (UV)scan_hex(RExC_parse,
3299                                          e - RExC_parse,
3300                                          &numlen);
3301                     RExC_parse = e + 1;
3302                 }
3303                 else {
3304                     numlen = 0;         /* disallow underscores */
3305                     value = (UV)scan_hex(RExC_parse, 2, &numlen);
3306                     RExC_parse += numlen;
3307                 }
3308                 break;
3309             case 'c':
3310                 value = UCHARAT(RExC_parse++);
3311                 value = toCTRL(value);
3312                 break;
3313             case '0': case '1': case '2': case '3': case '4':
3314             case '5': case '6': case '7': case '8': case '9':
3315                 numlen = 0;             /* disallow underscores */
3316                 value = (UV)scan_oct(--RExC_parse, 3, &numlen);
3317                 RExC_parse += numlen;
3318                 break;
3319             default:
3320                 if (!SIZE_ONLY && ckWARN(WARN_REGEXP) && isALPHA(value))
3321                     vWARN2(RExC_parse,
3322                            "Unrecognized escape \\%c in character class passed through",
3323                            (int)value);
3324                 break;
3325             }
3326         } /* end of \blah */
3327
3328         if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */
3329
3330             if (!SIZE_ONLY && !need_class)
3331                 ANYOF_CLASS_ZERO(ret);
3332
3333             need_class = 1;
3334
3335             /* a bad range like a-\d, a-[:digit:] ? */
3336             if (range) {
3337                 if (!SIZE_ONLY) {
3338                     if (ckWARN(WARN_REGEXP))
3339                         vWARN4(RExC_parse,
3340                                "False [] range \"%*.*s\"",
3341                                RExC_parse - rangebegin,
3342                                RExC_parse - rangebegin,
3343                                rangebegin);
3344                     if (lastvalue < 256) {
3345                         ANYOF_BITMAP_SET(ret, lastvalue);
3346                         ANYOF_BITMAP_SET(ret, '-');
3347                     }
3348                     else {
3349                         ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
3350                         Perl_sv_catpvf(aTHX_ listsv,
3351                                        /* 0x002D is Unicode for '-' */
3352                                        "%04"UVxf"\n002D\n", (UV)lastvalue);
3353                     }
3354                 }
3355
3356                 range = 0; /* this was not a true range */
3357             }
3358
3359             if (!SIZE_ONLY) {
3360                 /* Possible truncation here but in some 64-bit environments
3361                  * the compiler gets heartburn about switch on 64-bit values.
3362                  * A similar issue a little earlier when switching on value.
3363                  * --jhi */
3364                 switch ((I32)namedclass) {
3365                 case ANYOF_ALNUM:
3366                     if (LOC)
3367                         ANYOF_CLASS_SET(ret, ANYOF_ALNUM);
3368                     else {
3369                         for (value = 0; value < 256; value++)
3370                             if (isALNUM(value))
3371                                 ANYOF_BITMAP_SET(ret, value);
3372                     }
3373                     dont_optimize_invert = TRUE;
3374                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsWord\n");    
3375                     break;
3376                 case ANYOF_NALNUM:
3377                     if (LOC)
3378                         ANYOF_CLASS_SET(ret, ANYOF_NALNUM);
3379                     else {
3380                         for (value = 0; value < 256; value++)
3381                             if (!isALNUM(value))
3382                                 ANYOF_BITMAP_SET(ret, value);
3383                     }
3384                     dont_optimize_invert = TRUE;
3385                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsWord\n");
3386                     break;
3387                 case ANYOF_ALNUMC:
3388                     if (LOC)
3389                         ANYOF_CLASS_SET(ret, ANYOF_ALNUMC);
3390                     else {
3391                         for (value = 0; value < 256; value++)
3392                             if (isALNUMC(value))
3393                                 ANYOF_BITMAP_SET(ret, value);
3394                     }
3395                     dont_optimize_invert = TRUE;
3396                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsAlnum\n");
3397                     break;
3398                 case ANYOF_NALNUMC:
3399                     if (LOC)
3400                         ANYOF_CLASS_SET(ret, ANYOF_NALNUMC);
3401                     else {
3402                         for (value = 0; value < 256; value++)
3403                             if (!isALNUMC(value))
3404                                 ANYOF_BITMAP_SET(ret, value);
3405                     }
3406                     dont_optimize_invert = TRUE;
3407                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsAlnum\n");
3408                     break;
3409                 case ANYOF_ALPHA:
3410                     if (LOC)
3411                         ANYOF_CLASS_SET(ret, ANYOF_ALPHA);
3412                     else {
3413                         for (value = 0; value < 256; value++)
3414                             if (isALPHA(value))
3415                                 ANYOF_BITMAP_SET(ret, value);
3416                     }
3417                     dont_optimize_invert = TRUE;
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                     dont_optimize_invert = TRUE;
3429                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsAlpha\n");
3430                     break;
3431                 case ANYOF_ASCII:
3432                     if (LOC)
3433                         ANYOF_CLASS_SET(ret, ANYOF_ASCII);
3434                     else {
3435 #ifdef ASCIIish
3436                         for (value = 0; value < 128; value++)
3437                             ANYOF_BITMAP_SET(ret, value);
3438 #else  /* EBCDIC */
3439                         for (value = 0; value < 256; value++)
3440                             if (isASCII(value))
3441                                 ANYOF_BITMAP_SET(ret, value);
3442 #endif /* EBCDIC */
3443                     }
3444                     dont_optimize_invert = TRUE;
3445                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsASCII\n");
3446                     break;
3447                 case ANYOF_NASCII:
3448                     if (LOC)
3449                         ANYOF_CLASS_SET(ret, ANYOF_NASCII);
3450                     else {
3451 #ifdef ASCIIish
3452                         for (value = 128; value < 256; value++)
3453                             ANYOF_BITMAP_SET(ret, value);
3454 #else  /* EBCDIC */
3455                         for (value = 0; value < 256; value++)
3456                             if (!isASCII(value))
3457                                 ANYOF_BITMAP_SET(ret, value);
3458 #endif /* EBCDIC */
3459                     }
3460                     dont_optimize_invert = TRUE;
3461                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsASCII\n");
3462                     break;
3463                 case ANYOF_BLANK:
3464                     if (LOC)
3465                         ANYOF_CLASS_SET(ret, ANYOF_BLANK);
3466                     else {
3467                         for (value = 0; value < 256; value++)
3468                             if (isBLANK(value))
3469                                 ANYOF_BITMAP_SET(ret, value);
3470                     }
3471                     dont_optimize_invert = TRUE;
3472                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsBlank\n");
3473                     break;
3474                 case ANYOF_NBLANK:
3475                     if (LOC)
3476                         ANYOF_CLASS_SET(ret, ANYOF_NBLANK);
3477                     else {
3478                         for (value = 0; value < 256; value++)
3479                             if (!isBLANK(value))
3480                                 ANYOF_BITMAP_SET(ret, value);
3481                     }
3482                     dont_optimize_invert = TRUE;
3483                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsBlank\n");
3484                     break;
3485                 case ANYOF_CNTRL:
3486                     if (LOC)
3487                         ANYOF_CLASS_SET(ret, ANYOF_CNTRL);
3488                     else {
3489                         for (value = 0; value < 256; value++)
3490                             if (isCNTRL(value))
3491                                 ANYOF_BITMAP_SET(ret, value);
3492                     }
3493                     dont_optimize_invert = TRUE;
3494                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsCntrl\n");
3495                     break;
3496                 case ANYOF_NCNTRL:
3497                     if (LOC)
3498                         ANYOF_CLASS_SET(ret, ANYOF_NCNTRL);
3499                     else {
3500                         for (value = 0; value < 256; value++)
3501                             if (!isCNTRL(value))
3502                                 ANYOF_BITMAP_SET(ret, value);
3503                     }
3504                     dont_optimize_invert = TRUE;
3505                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsCntrl\n");
3506                     break;
3507                 case ANYOF_DIGIT:
3508                     if (LOC)
3509                         ANYOF_CLASS_SET(ret, ANYOF_DIGIT);
3510                     else {
3511                         /* consecutive digits assumed */
3512                         for (value = '0'; value <= '9'; value++)
3513                             ANYOF_BITMAP_SET(ret, value);
3514                     }
3515                     dont_optimize_invert = TRUE;
3516                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsDigit\n");
3517                     break;
3518                 case ANYOF_NDIGIT:
3519                     if (LOC)
3520                         ANYOF_CLASS_SET(ret, ANYOF_NDIGIT);
3521                     else {
3522                         /* consecutive digits assumed */
3523                         for (value = 0; value < '0'; value++)
3524                             ANYOF_BITMAP_SET(ret, value);
3525                         for (value = '9' + 1; value < 256; value++)
3526                             ANYOF_BITMAP_SET(ret, value);
3527                     }
3528                     dont_optimize_invert = TRUE;
3529                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsDigit\n");
3530                     break;
3531                 case ANYOF_GRAPH:
3532                     if (LOC)
3533                         ANYOF_CLASS_SET(ret, ANYOF_GRAPH);
3534                     else {
3535                         for (value = 0; value < 256; value++)
3536                             if (isGRAPH(value))
3537                                 ANYOF_BITMAP_SET(ret, value);
3538                     }
3539                     dont_optimize_invert = TRUE;
3540                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsGraph\n");
3541                     break;
3542                 case ANYOF_NGRAPH:
3543                     if (LOC)
3544                         ANYOF_CLASS_SET(ret, ANYOF_NGRAPH);
3545                     else {
3546                         for (value = 0; value < 256; value++)
3547                             if (!isGRAPH(value))
3548                                 ANYOF_BITMAP_SET(ret, value);
3549                     }
3550                     dont_optimize_invert = TRUE;
3551                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsGraph\n");
3552                     break;
3553                 case ANYOF_LOWER:
3554                     if (LOC)
3555                         ANYOF_CLASS_SET(ret, ANYOF_LOWER);
3556                     else {
3557                         for (value = 0; value < 256; value++)
3558                             if (isLOWER(value))
3559                                 ANYOF_BITMAP_SET(ret, value);
3560                     }
3561                     dont_optimize_invert = TRUE;
3562                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsLower\n");
3563                     break;
3564                 case ANYOF_NLOWER:
3565                     if (LOC)
3566                         ANYOF_CLASS_SET(ret, ANYOF_NLOWER);
3567                     else {
3568                         for (value = 0; value < 256; value++)
3569                             if (!isLOWER(value))
3570                                 ANYOF_BITMAP_SET(ret, value);
3571                     }
3572                     dont_optimize_invert = TRUE;
3573                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsLower\n");
3574                     break;
3575                 case ANYOF_PRINT:
3576                     if (LOC)
3577                         ANYOF_CLASS_SET(ret, ANYOF_PRINT);
3578                     else {
3579                         for (value = 0; value < 256; value++)
3580                             if (isPRINT(value))
3581                                 ANYOF_BITMAP_SET(ret, value);
3582                     }
3583                     dont_optimize_invert = TRUE;
3584                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsPrint\n");
3585                     break;
3586                 case ANYOF_NPRINT:
3587                     if (LOC)
3588                         ANYOF_CLASS_SET(ret, ANYOF_NPRINT);
3589                     else {
3590                         for (value = 0; value < 256; value++)
3591                             if (!isPRINT(value))
3592                                 ANYOF_BITMAP_SET(ret, value);
3593                     }
3594                     dont_optimize_invert = TRUE;
3595                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsPrint\n");
3596                     break;
3597                 case ANYOF_PSXSPC:
3598                     if (LOC)
3599                         ANYOF_CLASS_SET(ret, ANYOF_PSXSPC);
3600                     else {
3601                         for (value = 0; value < 256; value++)
3602                             if (isPSXSPC(value))
3603                                 ANYOF_BITMAP_SET(ret, value);
3604                     }
3605                     dont_optimize_invert = TRUE;
3606                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsSpace\n");
3607                     break;
3608                 case ANYOF_NPSXSPC:
3609                     if (LOC)
3610                         ANYOF_CLASS_SET(ret, ANYOF_NPSXSPC);
3611                     else {
3612                         for (value = 0; value < 256; value++)
3613                             if (!isPSXSPC(value))
3614                                 ANYOF_BITMAP_SET(ret, value);
3615                     }
3616                     dont_optimize_invert = TRUE;
3617                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsSpace\n");
3618                     break;
3619                 case ANYOF_PUNCT:
3620                     if (LOC)
3621                         ANYOF_CLASS_SET(ret, ANYOF_PUNCT);
3622                     else {
3623                         for (value = 0; value < 256; value++)
3624                             if (isPUNCT(value))
3625                                 ANYOF_BITMAP_SET(ret, value);
3626                     }
3627                     dont_optimize_invert = TRUE;
3628                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsPunct\n");
3629                     break;
3630                 case ANYOF_NPUNCT:
3631                     if (LOC)
3632                         ANYOF_CLASS_SET(ret, ANYOF_NPUNCT);
3633                     else {
3634                         for (value = 0; value < 256; value++)
3635                             if (!isPUNCT(value))
3636                                 ANYOF_BITMAP_SET(ret, value);
3637                     }
3638                     dont_optimize_invert = TRUE;
3639                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsPunct\n");
3640                     break;
3641                 case ANYOF_SPACE:
3642                     if (LOC)
3643                         ANYOF_CLASS_SET(ret, ANYOF_SPACE);
3644                     else {
3645                         for (value = 0; value < 256; value++)
3646                             if (isSPACE(value))
3647                                 ANYOF_BITMAP_SET(ret, value);
3648                     }
3649                     dont_optimize_invert = TRUE;
3650                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsSpacePerl\n");
3651                     break;
3652                 case ANYOF_NSPACE:
3653                     if (LOC)
3654                         ANYOF_CLASS_SET(ret, ANYOF_NSPACE);
3655                     else {
3656                         for (value = 0; value < 256; value++)
3657                             if (!isSPACE(value))
3658                                 ANYOF_BITMAP_SET(ret, value);
3659                     }
3660                     dont_optimize_invert = TRUE;
3661                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsSpacePerl\n");
3662                     break;
3663                 case ANYOF_UPPER:
3664                     if (LOC)
3665                         ANYOF_CLASS_SET(ret, ANYOF_UPPER);
3666                     else {
3667                         for (value = 0; value < 256; value++)
3668                             if (isUPPER(value))
3669                                 ANYOF_BITMAP_SET(ret, value);
3670                     }
3671                     dont_optimize_invert = TRUE;
3672                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsUpper\n");
3673                     break;
3674                 case ANYOF_NUPPER:
3675                     if (LOC)
3676                         ANYOF_CLASS_SET(ret, ANYOF_NUPPER);
3677                     else {
3678                         for (value = 0; value < 256; value++)
3679                             if (!isUPPER(value))
3680                                 ANYOF_BITMAP_SET(ret, value);
3681                     }
3682                     dont_optimize_invert = TRUE;
3683                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsUpper\n");
3684                     break;
3685                 case ANYOF_XDIGIT:
3686                     if (LOC)
3687                         ANYOF_CLASS_SET(ret, ANYOF_XDIGIT);
3688                     else {
3689                         for (value = 0; value < 256; value++)
3690                             if (isXDIGIT(value))
3691                                 ANYOF_BITMAP_SET(ret, value);
3692                     }
3693                     dont_optimize_invert = TRUE;
3694                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsXDigit\n");
3695                     break;
3696                 case ANYOF_NXDIGIT:
3697                     if (LOC)
3698                         ANYOF_CLASS_SET(ret, ANYOF_NXDIGIT);
3699                     else {
3700                         for (value = 0; value < 256; value++)
3701                             if (!isXDIGIT(value))
3702                                 ANYOF_BITMAP_SET(ret, value);
3703                     }
3704                     dont_optimize_invert = TRUE;
3705                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsXDigit\n");
3706                     break;
3707                 default:
3708                     vFAIL("Invalid [::] class");
3709                     break;
3710                 }
3711                 if (LOC)
3712                     ANYOF_FLAGS(ret) |= ANYOF_CLASS;
3713                 continue;
3714             }
3715         } /* end of namedclass \blah */
3716
3717         if (range) {
3718             if (lastvalue > value) /* b-a */ {
3719                 Simple_vFAIL4("Invalid [] range \"%*.*s\"",
3720                               RExC_parse - rangebegin,
3721                               RExC_parse - rangebegin,
3722                               rangebegin);
3723             }
3724             range = 0; /* not a true range */
3725         }
3726         else {
3727             lastvalue = value; /* save the beginning of the range */
3728             if (*RExC_parse == '-' && RExC_parse+1 < RExC_end &&
3729                 RExC_parse[1] != ']') {
3730                 RExC_parse++;
3731
3732                 /* a bad range like \w-, [:word:]- ? */
3733                 if (namedclass > OOB_NAMEDCLASS) {
3734                     if (ckWARN(WARN_REGEXP))
3735                         vWARN4(RExC_parse,
3736                                "False [] range \"%*.*s\"",
3737                                RExC_parse - rangebegin,
3738                                RExC_parse - rangebegin,
3739                                rangebegin);
3740                     if (!SIZE_ONLY)
3741                         ANYOF_BITMAP_SET(ret, '-');
3742                 } else
3743                     range = 1;  /* yeah, it's a range! */
3744                 continue;       /* but do it the next time */
3745             }
3746         }
3747
3748         /* now is the next time */
3749         if (!SIZE_ONLY) {
3750             if (lastvalue < 256 && value < 256) {
3751 #ifndef ASCIIish /* EBCDIC, for example. */
3752                 if ((isLOWER(lastvalue) && isLOWER(value)) ||
3753                     (isUPPER(lastvalue) && isUPPER(value)))
3754                 {
3755                     IV i;
3756                     if (isLOWER(lastvalue)) {
3757                         for (i = lastvalue; i <= value; i++)
3758                             if (isLOWER(i))
3759                                 ANYOF_BITMAP_SET(ret, i);
3760                     } else {
3761                         for (i = lastvalue; i <= value; i++)
3762                             if (isUPPER(i))
3763                                 ANYOF_BITMAP_SET(ret, i);
3764                     }
3765                 }
3766                 else
3767 #endif
3768                     for ( ; lastvalue <= value; lastvalue++)
3769                         ANYOF_BITMAP_SET(ret, lastvalue);
3770             } else {
3771                 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
3772                 if (lastvalue < value)
3773                     Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\t%04"UVxf"\n",
3774                                    (UV)lastvalue, (UV)value);
3775                 else
3776                     Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
3777                                    (UV)value);
3778             }
3779         }
3780
3781         range = 0; /* this range (if it was one) is done now */
3782     }
3783
3784     if (need_class) {
3785         if (SIZE_ONLY)
3786             RExC_size += ANYOF_CLASS_ADD_SKIP;
3787         else
3788             RExC_emit += ANYOF_CLASS_ADD_SKIP;
3789     }
3790
3791     /* optimize case-insensitive simple patterns (e.g. /[a-z]/i) */
3792     if (!SIZE_ONLY &&
3793         (ANYOF_FLAGS(ret) &
3794          /* If the only flag is folding (plus possibly inversion). */
3795          (ANYOF_FLAGS_ALL ^ ANYOF_INVERT) == ANYOF_FOLD)) {
3796         for (value = 0; value < 256; ++value) {
3797             if (ANYOF_BITMAP_TEST(ret, value)) {
3798                 IV fold = PL_fold[value];
3799
3800                 if (fold != value)
3801                     ANYOF_BITMAP_SET(ret, fold);
3802             }
3803         }
3804         ANYOF_FLAGS(ret) &= ~ANYOF_FOLD;
3805     }
3806
3807     /* optimize inverted simple patterns (e.g. [^a-z]) */
3808     if (!SIZE_ONLY && !dont_optimize_invert &&
3809         /* If the only flag is inversion. */
3810         (ANYOF_FLAGS(ret) & ANYOF_FLAGS_ALL) == ANYOF_INVERT) {
3811         for (value = 0; value < ANYOF_BITMAP_SIZE; ++value)
3812             ANYOF_BITMAP(ret)[value] ^= ANYOF_FLAGS_ALL;
3813         ANYOF_FLAGS(ret) = ANYOF_UNICODE_ALL;
3814     }
3815
3816     if (!SIZE_ONLY) {
3817         AV *av = newAV();
3818         SV *rv;
3819
3820         av_store(av, 0, listsv);
3821         av_store(av, 1, NULL);
3822         rv = newRV_noinc((SV*)av);
3823         n = add_data(pRExC_state, 1, "s");
3824         RExC_rx->data->data[n] = (void*)rv;
3825         ARG_SET(ret, n);
3826     }
3827
3828     return ret;
3829 }
3830
3831 STATIC char*
3832 S_nextchar(pTHX_ RExC_state_t *pRExC_state)
3833 {
3834     char* retval = RExC_parse++;
3835
3836     for (;;) {
3837         if (*RExC_parse == '(' && RExC_parse[1] == '?' &&
3838                 RExC_parse[2] == '#') {
3839             while (*RExC_parse && *RExC_parse != ')')
3840                 RExC_parse++;
3841             RExC_parse++;
3842             continue;
3843         }
3844         if (RExC_flags16 & PMf_EXTENDED) {
3845             if (isSPACE(*RExC_parse)) {
3846                 RExC_parse++;
3847                 continue;
3848             }
3849             else if (*RExC_parse == '#') {
3850                 while (*RExC_parse && *RExC_parse != '\n')
3851                     RExC_parse++;
3852                 RExC_parse++;
3853                 continue;
3854             }
3855         }
3856         return retval;
3857     }
3858 }
3859
3860 /*
3861 - reg_node - emit a node
3862 */
3863 STATIC regnode *                        /* Location. */
3864 S_reg_node(pTHX_ RExC_state_t *pRExC_state, U8 op)
3865 {
3866     register regnode *ret;
3867     register regnode *ptr;
3868
3869     ret = RExC_emit;
3870     if (SIZE_ONLY) {
3871         SIZE_ALIGN(RExC_size);
3872         RExC_size += 1;
3873         return(ret);
3874     }
3875
3876     NODE_ALIGN_FILL(ret);
3877     ptr = ret;
3878     FILL_ADVANCE_NODE(ptr, op);
3879     RExC_emit = ptr;
3880
3881     return(ret);
3882 }
3883
3884 /*
3885 - reganode - emit a node with an argument
3886 */
3887 STATIC regnode *                        /* Location. */
3888 S_reganode(pTHX_ RExC_state_t *pRExC_state, U8 op, U32 arg)
3889 {
3890     register regnode *ret;
3891     register regnode *ptr;
3892
3893     ret = RExC_emit;
3894     if (SIZE_ONLY) {
3895         SIZE_ALIGN(RExC_size);
3896         RExC_size += 2;
3897         return(ret);
3898     }
3899
3900     NODE_ALIGN_FILL(ret);
3901     ptr = ret;
3902     FILL_ADVANCE_NODE_ARG(ptr, op, arg);
3903     RExC_emit = ptr;
3904
3905     return(ret);
3906 }
3907
3908 /*
3909 - reguni - emit (if appropriate) a Unicode character
3910 */
3911 STATIC void
3912 S_reguni(pTHX_ RExC_state_t *pRExC_state, UV uv, char* s, STRLEN* lenp)
3913 {
3914     *lenp = SIZE_ONLY ? UNISKIP(uv) : (uv_to_utf8((U8*)s, uv) - (U8*)s);
3915 }
3916
3917 /*
3918 - reginsert - insert an operator in front of already-emitted operand
3919 *
3920 * Means relocating the operand.
3921 */
3922 STATIC void
3923 S_reginsert(pTHX_ RExC_state_t *pRExC_state, U8 op, regnode *opnd)
3924 {
3925     register regnode *src;
3926     register regnode *dst;
3927     register regnode *place;
3928     register int offset = regarglen[(U8)op];
3929
3930 /* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
3931
3932     if (SIZE_ONLY) {
3933         RExC_size += NODE_STEP_REGNODE + offset;
3934         return;
3935     }
3936
3937     src = RExC_emit;
3938     RExC_emit += NODE_STEP_REGNODE + offset;
3939     dst = RExC_emit;
3940     while (src > opnd)
3941         StructCopy(--src, --dst, regnode);
3942
3943     place = opnd;               /* Op node, where operand used to be. */
3944     src = NEXTOPER(place);
3945     FILL_ADVANCE_NODE(place, op);
3946     Zero(src, offset, regnode);
3947 }
3948
3949 /*
3950 - regtail - set the next-pointer at the end of a node chain of p to val.
3951 */
3952 STATIC void
3953 S_regtail(pTHX_ RExC_state_t *pRExC_state, regnode *p, regnode *val)
3954 {
3955     register regnode *scan;
3956     register regnode *temp;
3957
3958     if (SIZE_ONLY)
3959         return;
3960
3961     /* Find last node. */
3962     scan = p;
3963     for (;;) {
3964         temp = regnext(scan);
3965         if (temp == NULL)
3966             break;
3967         scan = temp;
3968     }
3969
3970     if (reg_off_by_arg[OP(scan)]) {
3971         ARG_SET(scan, val - scan);
3972     }
3973     else {
3974         NEXT_OFF(scan) = val - scan;
3975     }
3976 }
3977
3978 /*
3979 - regoptail - regtail on operand of first argument; nop if operandless
3980 */
3981 STATIC void
3982 S_regoptail(pTHX_ RExC_state_t *pRExC_state, regnode *p, regnode *val)
3983 {
3984     /* "Operandless" and "op != BRANCH" are synonymous in practice. */
3985     if (p == NULL || SIZE_ONLY)
3986         return;
3987     if (PL_regkind[(U8)OP(p)] == BRANCH) {
3988         regtail(pRExC_state, NEXTOPER(p), val);
3989     }
3990     else if ( PL_regkind[(U8)OP(p)] == BRANCHJ) {
3991         regtail(pRExC_state, NEXTOPER(NEXTOPER(p)), val);
3992     }
3993     else
3994         return;
3995 }
3996
3997 /*
3998  - regcurly - a little FSA that accepts {\d+,?\d*}
3999  */
4000 STATIC I32
4001 S_regcurly(pTHX_ register char *s)
4002 {
4003     if (*s++ != '{')
4004         return FALSE;
4005     if (!isDIGIT(*s))
4006         return FALSE;
4007     while (isDIGIT(*s))
4008         s++;
4009     if (*s == ',')
4010         s++;
4011     while (isDIGIT(*s))
4012         s++;
4013     if (*s != '}')
4014         return FALSE;
4015     return TRUE;
4016 }
4017
4018
4019 STATIC regnode *
4020 S_dumpuntil(pTHX_ regnode *start, regnode *node, regnode *last, SV* sv, I32 l)
4021 {
4022 #ifdef DEBUGGING
4023     register U8 op = EXACT;     /* Arbitrary non-END op. */
4024     register regnode *next;
4025
4026     while (op != END && (!last || node < last)) {
4027         /* While that wasn't END last time... */
4028
4029         NODE_ALIGN(node);
4030         op = OP(node);
4031         if (op == CLOSE)
4032             l--;        
4033         next = regnext(node);
4034         /* Where, what. */
4035         if (OP(node) == OPTIMIZED)
4036             goto after_print;
4037         regprop(sv, node);
4038         PerlIO_printf(Perl_debug_log, "%4"IVdf":%*s%s", (IV)(node - start),
4039                       (int)(2*l + 1), "", SvPVX(sv));
4040         if (next == NULL)               /* Next ptr. */
4041             PerlIO_printf(Perl_debug_log, "(0)");
4042         else
4043             PerlIO_printf(Perl_debug_log, "(%"IVdf")", (IV)(next - start));
4044         (void)PerlIO_putc(Perl_debug_log, '\n');
4045       after_print:
4046         if (PL_regkind[(U8)op] == BRANCHJ) {
4047             register regnode *nnode = (OP(next) == LONGJMP
4048                                        ? regnext(next)
4049                                        : next);
4050             if (last && nnode > last)
4051                 nnode = last;
4052             node = dumpuntil(start, NEXTOPER(NEXTOPER(node)), nnode, sv, l + 1);
4053         }
4054         else if (PL_regkind[(U8)op] == BRANCH) {
4055             node = dumpuntil(start, NEXTOPER(node), next, sv, l + 1);
4056         }
4057         else if ( op == CURLY) {   /* `next' might be very big: optimizer */
4058             node = dumpuntil(start, NEXTOPER(node) + EXTRA_STEP_2ARGS,
4059                              NEXTOPER(node) + EXTRA_STEP_2ARGS + 1, sv, l + 1);
4060         }
4061         else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
4062             node = dumpuntil(start, NEXTOPER(node) + EXTRA_STEP_2ARGS,
4063                              next, sv, l + 1);
4064         }
4065         else if ( op == PLUS || op == STAR) {
4066             node = dumpuntil(start, NEXTOPER(node), NEXTOPER(node) + 1, sv, l + 1);
4067         }
4068         else if (op == ANYOF) {
4069             node = NEXTOPER(node);
4070             node += ANYOF_SKIP;
4071         }
4072         else if (PL_regkind[(U8)op] == EXACT) {
4073             /* Literal string, where present. */
4074             node += NODE_SZ_STR(node) - 1;
4075             node = NEXTOPER(node);
4076         }
4077         else {
4078             node = NEXTOPER(node);
4079             node += regarglen[(U8)op];
4080         }
4081         if (op == CURLYX || op == OPEN)
4082             l++;
4083         else if (op == WHILEM)
4084             l--;
4085     }
4086 #endif  /* DEBUGGING */
4087     return node;
4088 }
4089
4090 /*
4091  - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
4092  */
4093 void
4094 Perl_regdump(pTHX_ regexp *r)
4095 {
4096 #ifdef DEBUGGING
4097     SV *sv = sv_newmortal();
4098
4099     (void)dumpuntil(r->program, r->program + 1, NULL, sv, 0);
4100
4101     /* Header fields of interest. */
4102     if (r->anchored_substr)
4103         PerlIO_printf(Perl_debug_log,
4104                       "anchored `%s%.*s%s'%s at %"IVdf" ",
4105                       PL_colors[0],
4106                       (int)(SvCUR(r->anchored_substr) - (SvTAIL(r->anchored_substr)!=0)),
4107                       SvPVX(r->anchored_substr),
4108                       PL_colors[1],
4109                       SvTAIL(r->anchored_substr) ? "$" : "",
4110                       (IV)r->anchored_offset);
4111     if (r->float_substr)
4112         PerlIO_printf(Perl_debug_log,
4113                       "floating `%s%.*s%s'%s at %"IVdf"..%"UVuf" ",
4114                       PL_colors[0],
4115                       (int)(SvCUR(r->float_substr) - (SvTAIL(r->float_substr)!=0)),
4116                       SvPVX(r->float_substr),
4117                       PL_colors[1],
4118                       SvTAIL(r->float_substr) ? "$" : "",
4119                       (IV)r->float_min_offset, (UV)r->float_max_offset);
4120     if (r->check_substr)
4121         PerlIO_printf(Perl_debug_log,
4122                       r->check_substr == r->float_substr
4123                       ? "(checking floating" : "(checking anchored");
4124     if (r->reganch & ROPT_NOSCAN)
4125         PerlIO_printf(Perl_debug_log, " noscan");
4126     if (r->reganch & ROPT_CHECK_ALL)
4127         PerlIO_printf(Perl_debug_log, " isall");
4128     if (r->check_substr)
4129         PerlIO_printf(Perl_debug_log, ") ");
4130
4131     if (r->regstclass) {
4132         regprop(sv, r->regstclass);
4133         PerlIO_printf(Perl_debug_log, "stclass `%s' ", SvPVX(sv));
4134     }
4135     if (r->reganch & ROPT_ANCH) {
4136         PerlIO_printf(Perl_debug_log, "anchored");
4137         if (r->reganch & ROPT_ANCH_BOL)
4138             PerlIO_printf(Perl_debug_log, "(BOL)");
4139         if (r->reganch & ROPT_ANCH_MBOL)
4140             PerlIO_printf(Perl_debug_log, "(MBOL)");
4141         if (r->reganch & ROPT_ANCH_SBOL)
4142             PerlIO_printf(Perl_debug_log, "(SBOL)");
4143         if (r->reganch & ROPT_ANCH_GPOS)
4144             PerlIO_printf(Perl_debug_log, "(GPOS)");
4145         PerlIO_putc(Perl_debug_log, ' ');
4146     }
4147     if (r->reganch & ROPT_GPOS_SEEN)
4148         PerlIO_printf(Perl_debug_log, "GPOS ");
4149     if (r->reganch & ROPT_SKIP)
4150         PerlIO_printf(Perl_debug_log, "plus ");
4151     if (r->reganch & ROPT_IMPLICIT)
4152         PerlIO_printf(Perl_debug_log, "implicit ");
4153     PerlIO_printf(Perl_debug_log, "minlen %ld ", (long) r->minlen);
4154     if (r->reganch & ROPT_EVAL_SEEN)
4155         PerlIO_printf(Perl_debug_log, "with eval ");
4156     PerlIO_printf(Perl_debug_log, "\n");
4157 #endif  /* DEBUGGING */
4158 }
4159
4160 STATIC void
4161 S_put_byte(pTHX_ SV *sv, int c)
4162 {
4163     if (isCNTRL(c) || c == 127 || c == 255 || !isPRINT(c))
4164         Perl_sv_catpvf(aTHX_ sv, "\\%o", c);
4165     else if (c == '-' || c == ']' || c == '\\' || c == '^')
4166         Perl_sv_catpvf(aTHX_ sv, "\\%c", c);
4167     else
4168         Perl_sv_catpvf(aTHX_ sv, "%c", c);
4169 }
4170
4171 /*
4172 - regprop - printable representation of opcode
4173 */
4174 void
4175 Perl_regprop(pTHX_ SV *sv, regnode *o)
4176 {
4177 #ifdef DEBUGGING
4178     register int k;
4179
4180     sv_setpvn(sv, "", 0);
4181     if (OP(o) >= reg_num)               /* regnode.type is unsigned */
4182         /* It would be nice to FAIL() here, but this may be called from
4183            regexec.c, and it would be hard to supply pRExC_state. */
4184         Perl_croak(aTHX_ "Corrupted regexp opcode");
4185     sv_catpv(sv, (char*)reg_name[OP(o)]); /* Take off const! */
4186
4187     k = PL_regkind[(U8)OP(o)];
4188
4189     if (k == EXACT)
4190         Perl_sv_catpvf(aTHX_ sv, " <%s%.*s%s>", PL_colors[0],
4191                        STR_LEN(o), STRING(o), PL_colors[1]);
4192     else if (k == CURLY) {
4193         if (OP(o) == CURLYM || OP(o) == CURLYN || OP(o) == CURLYX)
4194             Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
4195         Perl_sv_catpvf(aTHX_ sv, " {%d,%d}", ARG1(o), ARG2(o));
4196     }
4197     else if (k == WHILEM && o->flags)                   /* Ordinal/of */
4198         Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
4199     else if (k == REF || k == OPEN || k == CLOSE || k == GROUPP )
4200         Perl_sv_catpvf(aTHX_ sv, "%d", (int)ARG(o));    /* Parenth number */
4201     else if (k == LOGICAL)
4202         Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags);     /* 2: embedded, otherwise 1 */
4203     else if (k == ANYOF) {
4204         int i, rangestart = -1;
4205         U8 flags = ANYOF_FLAGS(o);
4206         const char * const anyofs[] = { /* Should be syncronized with
4207                                          * ANYOF_ #xdefines in regcomp.h */
4208             "\\w",
4209             "\\W",
4210             "\\s",
4211             "\\S",
4212             "\\d",
4213             "\\D",
4214             "[:alnum:]",
4215             "[:^alnum:]",
4216             "[:alpha:]",
4217             "[:^alpha:]",
4218             "[:ascii:]",
4219             "[:^ascii:]",
4220             "[:ctrl:]",
4221             "[:^ctrl:]",
4222             "[:graph:]",
4223             "[:^graph:]",
4224             "[:lower:]",
4225             "[:^lower:]",
4226             "[:print:]",
4227             "[:^print:]",
4228             "[:punct:]",
4229             "[:^punct:]",
4230             "[:upper:]",
4231             "[:^upper:]",
4232             "[:xdigit:]",
4233             "[:^xdigit:]",
4234             "[:space:]",
4235             "[:^space:]",
4236             "[:blank:]",
4237             "[:^blank:]"
4238         };
4239
4240         if (flags & ANYOF_LOCALE)
4241             sv_catpv(sv, "{loc}");
4242         if (flags & ANYOF_FOLD)
4243             sv_catpv(sv, "{i}");
4244         Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
4245         if (flags & ANYOF_INVERT)
4246             sv_catpv(sv, "^");
4247         for (i = 0; i <= 256; i++) {
4248             if (i < 256 && ANYOF_BITMAP_TEST(o,i)) {
4249                 if (rangestart == -1)
4250                     rangestart = i;
4251             } else if (rangestart != -1) {
4252                 if (i <= rangestart + 3)
4253                     for (; rangestart < i; rangestart++)
4254                         put_byte(sv, rangestart);
4255                 else {
4256                     put_byte(sv, rangestart);
4257                     sv_catpv(sv, "-");
4258                     put_byte(sv, i - 1);
4259                 }
4260                 rangestart = -1;
4261             }
4262         }
4263
4264         if (o->flags & ANYOF_CLASS)
4265             for (i = 0; i < sizeof(anyofs)/sizeof(char*); i++)
4266                 if (ANYOF_CLASS_TEST(o,i))
4267                     sv_catpv(sv, anyofs[i]);
4268
4269         if (flags & ANYOF_UNICODE)
4270             sv_catpv(sv, "{unicode}");
4271         else if (flags & ANYOF_UNICODE_ALL)
4272             sv_catpv(sv, "{all-unicode}");
4273
4274         {
4275             SV *lv;
4276             SV *sw = regclass_swash(o, FALSE, &lv);
4277         
4278             if (lv) {
4279                 if (sw) {
4280                     UV i;
4281                     U8 s[UTF8_MAXLEN+1];
4282                 
4283                     for (i = 0; i <= 256; i++) { /* just the first 256 */
4284                         U8 *e = uv_to_utf8(s, i);
4285                         
4286                         if (i < 256 && swash_fetch(sw, s)) {
4287                             if (rangestart == -1)
4288                                 rangestart = i;
4289                         } else if (rangestart != -1) {
4290                             U8 *p;
4291                         
4292                             if (i <= rangestart + 3)
4293                                 for (; rangestart < i; rangestart++) {
4294                                     for(e = uv_to_utf8(s, rangestart), p = s; p < e; p++)
4295                                         put_byte(sv, *p);
4296                                 }
4297                             else {
4298                                 for (e = uv_to_utf8(s, rangestart), p = s; p < e; p++)
4299                                     put_byte(sv, *p);
4300                                 sv_catpv(sv, "-");
4301                                     for (e = uv_to_utf8(s, i - 1), p = s; p < e; p++)
4302                                         put_byte(sv, *p);
4303                                 }
4304                                 rangestart = -1;
4305                             }
4306                         }
4307                         
4308                     sv_catpv(sv, "..."); /* et cetera */
4309                 }
4310
4311                 {
4312                     char *s = savepv(SvPVX(lv));
4313                     char *origs = s;
4314                 
4315                     while(*s && *s != '\n') s++;
4316                 
4317                     if (*s == '\n') {
4318                         char *t = ++s;
4319                         
4320                         while (*s) {
4321                             if (*s == '\n')
4322                                 *s = ' ';
4323                             s++;
4324                         }
4325                         if (s[-1] == ' ')
4326                             s[-1] = 0;
4327                         
4328                         sv_catpv(sv, t);
4329                     }
4330                 
4331                     Safefree(origs);
4332                 }
4333             }
4334         }
4335
4336         Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
4337     }
4338     else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH))
4339         Perl_sv_catpvf(aTHX_ sv, "[-%d]", o->flags);
4340 #endif  /* DEBUGGING */
4341 }
4342
4343 SV *
4344 Perl_re_intuit_string(pTHX_ regexp *prog)
4345 {                               /* Assume that RE_INTUIT is set */
4346     DEBUG_r(
4347         {   STRLEN n_a;
4348             char *s = SvPV(prog->check_substr,n_a);
4349
4350             if (!PL_colorset) reginitcolors();
4351             PerlIO_printf(Perl_debug_log,
4352                       "%sUsing REx substr:%s `%s%.60s%s%s'\n",
4353                       PL_colors[4],PL_colors[5],PL_colors[0],
4354                       s,
4355                       PL_colors[1],
4356                       (strlen(s) > 60 ? "..." : ""));
4357         } );
4358
4359     return prog->check_substr;
4360 }
4361
4362 void
4363 Perl_pregfree(pTHX_ struct regexp *r)
4364 {
4365     DEBUG_r(if (!PL_colorset) reginitcolors());
4366
4367     if (!r || (--r->refcnt > 0))
4368         return;
4369     DEBUG_r(PerlIO_printf(Perl_debug_log,
4370                       "%sFreeing REx:%s `%s%.60s%s%s'\n",
4371                       PL_colors[4],PL_colors[5],PL_colors[0],
4372                       r->precomp,
4373                       PL_colors[1],
4374                       (strlen(r->precomp) > 60 ? "..." : "")));
4375
4376     if (r->precomp)
4377         Safefree(r->precomp);
4378     if (RX_MATCH_COPIED(r))
4379         Safefree(r->subbeg);
4380     if (r->substrs) {
4381         if (r->anchored_substr)
4382             SvREFCNT_dec(r->anchored_substr);
4383         if (r->float_substr)
4384             SvREFCNT_dec(r->float_substr);
4385         Safefree(r->substrs);
4386     }
4387     if (r->data) {
4388         int n = r->data->count;
4389         AV* new_comppad = NULL;
4390         AV* old_comppad;
4391         SV** old_curpad;
4392
4393         while (--n >= 0) {
4394             switch (r->data->what[n]) {
4395             case 's':
4396                 SvREFCNT_dec((SV*)r->data->data[n]);
4397                 break;
4398             case 'f':
4399                 Safefree(r->data->data[n]);
4400                 break;
4401             case 'p':
4402                 new_comppad = (AV*)r->data->data[n];
4403                 break;
4404             case 'o':
4405                 if (new_comppad == NULL)
4406                     Perl_croak(aTHX_ "panic: pregfree comppad");
4407                 old_comppad = PL_comppad;
4408                 old_curpad = PL_curpad;
4409                 /* Watch out for global destruction's random ordering. */
4410                 if (SvTYPE(new_comppad) == SVt_PVAV) {
4411                     PL_comppad = new_comppad;
4412                     PL_curpad = AvARRAY(new_comppad);
4413                 }
4414                 else
4415                     PL_curpad = NULL;
4416                 op_free((OP_4tree*)r->data->data[n]);
4417                 PL_comppad = old_comppad;
4418                 PL_curpad = old_curpad;
4419                 SvREFCNT_dec((SV*)new_comppad);
4420                 new_comppad = NULL;
4421                 break;
4422             case 'n':
4423                 break;
4424             default:
4425                 Perl_croak(aTHX_ "panic: regfree data code '%c'", r->data->what[n]);
4426             }
4427         }
4428         Safefree(r->data->what);
4429         Safefree(r->data);
4430     }
4431     Safefree(r->startp);
4432     Safefree(r->endp);
4433     Safefree(r);
4434 }
4435
4436 /*
4437  - regnext - dig the "next" pointer out of a node
4438  *
4439  * [Note, when REGALIGN is defined there are two places in regmatch()
4440  * that bypass this code for speed.]
4441  */
4442 regnode *
4443 Perl_regnext(pTHX_ register regnode *p)
4444 {
4445     register I32 offset;
4446
4447     if (p == &PL_regdummy)
4448         return(NULL);
4449
4450     offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
4451     if (offset == 0)
4452         return(NULL);
4453
4454     return(p+offset);
4455 }
4456
4457 STATIC void     
4458 S_re_croak2(pTHX_ const char* pat1,const char* pat2,...)
4459 {
4460     va_list args;
4461     STRLEN l1 = strlen(pat1);
4462     STRLEN l2 = strlen(pat2);
4463     char buf[512];
4464     SV *msv;
4465     char *message;
4466
4467     if (l1 > 510)
4468         l1 = 510;
4469     if (l1 + l2 > 510)
4470         l2 = 510 - l1;
4471     Copy(pat1, buf, l1 , char);
4472     Copy(pat2, buf + l1, l2 , char);
4473     buf[l1 + l2] = '\n';
4474     buf[l1 + l2 + 1] = '\0';
4475 #ifdef I_STDARG
4476     /* ANSI variant takes additional second argument */
4477     va_start(args, pat2);
4478 #else
4479     va_start(args);
4480 #endif
4481     msv = vmess(buf, &args);
4482     va_end(args);
4483     message = SvPV(msv,l1);
4484     if (l1 > 512)
4485         l1 = 512;
4486     Copy(message, buf, l1 , char);
4487     buf[l1] = '\0';                     /* Overwrite \n */
4488     Perl_croak(aTHX_ "%s", buf);
4489 }
4490
4491 /* XXX Here's a total kludge.  But we need to re-enter for swash routines. */
4492
4493 void
4494 Perl_save_re_context(pTHX)
4495 {
4496 #if 0
4497     SAVEPPTR(RExC_precomp);             /* uncompiled string. */
4498     SAVEI32(RExC_npar);         /* () count. */
4499     SAVEI32(RExC_size);         /* Code size. */
4500     SAVEI16(RExC_flags16);              /* are we folding, multilining? */
4501     SAVEVPTR(RExC_rx);          /* from regcomp.c */
4502     SAVEI32(RExC_seen);         /* from regcomp.c */
4503     SAVEI32(RExC_sawback);              /* Did we see \1, ...? */
4504     SAVEI32(RExC_naughty);              /* How bad is this pattern? */
4505     SAVEVPTR(RExC_emit);                /* Code-emit pointer; &regdummy = don't */
4506     SAVEPPTR(RExC_end);         /* End of input for compile */
4507     SAVEPPTR(RExC_parse);               /* Input-scan pointer. */
4508 #endif
4509
4510     SAVEI32(PL_reg_flags);              /* from regexec.c */
4511     SAVEPPTR(PL_bostr);
4512     SAVEPPTR(PL_reginput);              /* String-input pointer. */
4513     SAVEPPTR(PL_regbol);                /* Beginning of input, for ^ check. */
4514     SAVEPPTR(PL_regeol);                /* End of input, for $ check. */
4515     SAVEVPTR(PL_regstartp);             /* Pointer to startp array. */
4516     SAVEVPTR(PL_regendp);               /* Ditto for endp. */
4517     SAVEVPTR(PL_reglastparen);          /* Similarly for lastparen. */
4518     SAVEPPTR(PL_regtill);               /* How far we are required to go. */
4519     SAVEI8(PL_regprev);                 /* char before regbol, \n if none */
4520     SAVEGENERICPV(PL_reg_start_tmp);            /* from regexec.c */
4521     PL_reg_start_tmp = 0;
4522     SAVEI32(PL_reg_start_tmpl);         /* from regexec.c */
4523     PL_reg_start_tmpl = 0;
4524     SAVEVPTR(PL_regdata);
4525     SAVEI32(PL_reg_eval_set);           /* from regexec.c */
4526     SAVEI32(PL_regnarrate);             /* from regexec.c */
4527     SAVEVPTR(PL_regprogram);            /* from regexec.c */
4528     SAVEINT(PL_regindent);              /* from regexec.c */
4529     SAVEVPTR(PL_regcc);                 /* from regexec.c */
4530     SAVEVPTR(PL_curcop);
4531     SAVEVPTR(PL_reg_call_cc);           /* from regexec.c */
4532     SAVEVPTR(PL_reg_re);                /* from regexec.c */
4533     SAVEPPTR(PL_reg_ganch);             /* from regexec.c */
4534     SAVESPTR(PL_reg_sv);                /* from regexec.c */
4535     SAVEVPTR(PL_reg_magic);             /* from regexec.c */
4536     SAVEI32(PL_reg_oldpos);                     /* from regexec.c */
4537     SAVEVPTR(PL_reg_oldcurpm);          /* from regexec.c */
4538     SAVEVPTR(PL_reg_curpm);             /* from regexec.c */
4539     SAVEI32(PL_regnpar);                /* () count. */
4540 #ifdef DEBUGGING
4541     SAVEPPTR(PL_reg_starttry);          /* from regexec.c */
4542 #endif
4543 }
4544
4545 #ifdef PERL_OBJECT
4546 #include "XSUB.h"
4547 #undef this
4548 #define this pPerl
4549 #endif
4550
4551 static void
4552 clear_re(pTHXo_ void *r)
4553 {
4554     ReREFCNT_dec((regexp *)r);
4555 }