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