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