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