$VERSION "a5" doesn't quite work.
[p5sagit/p5-mst-13.2.git] / regcomp.c
1 /*    regcomp.c
2  */
3
4 /*
5  * "A fair jaw-cracker dwarf-language must be."  --Samwise Gamgee
6  */
7
8 /* NOTE: this is derived from Henry Spencer's regexp code, and should not
9  * confused with the original package (see point 3 below).  Thanks, Henry!
10  */
11
12 /* Additional note: this code is very heavily munged from Henry's version
13  * in places.  In some spots I've traded clarity for efficiency, so don't
14  * blame Henry for some of the lack of readability.
15  */
16
17 /* The names of the functions have been changed from regcomp and
18  * regexec to  pregcomp and pregexec in order to avoid conflicts
19  * with the POSIX routines of the same names.
20 */
21
22 #ifdef PERL_EXT_RE_BUILD
23 /* need to replace pregcomp et al, so enable that */
24 #  ifndef PERL_IN_XSUB_RE
25 #    define PERL_IN_XSUB_RE
26 #  endif
27 /* need access to debugger hooks */
28 #  if defined(PERL_EXT_RE_DEBUG) && !defined(DEBUGGING)
29 #    define DEBUGGING
30 #  endif
31 #endif
32
33 #ifdef PERL_IN_XSUB_RE
34 /* We *really* need to overwrite these symbols: */
35 #  define Perl_pregcomp my_regcomp
36 #  define Perl_regdump my_regdump
37 #  define Perl_regprop my_regprop
38 #  define Perl_pregfree my_regfree
39 #  define Perl_re_intuit_string my_re_intuit_string
40 /* *These* symbols are masked to allow static link. */
41 #  define Perl_regnext my_regnext
42 #  define Perl_save_re_context my_save_re_context
43 #  define Perl_reginitcolors my_reginitcolors
44
45 #  define PERL_NO_GET_CONTEXT
46 #endif
47
48 /*SUPPRESS 112*/
49 /*
50  * pregcomp and pregexec -- regsub and regerror are not used in perl
51  *
52  *      Copyright (c) 1986 by University of Toronto.
53  *      Written by Henry Spencer.  Not derived from licensed software.
54  *
55  *      Permission is granted to anyone to use this software for any
56  *      purpose on any computer system, and to redistribute it freely,
57  *      subject to the following restrictions:
58  *
59  *      1. The author is not responsible for the consequences of use of
60  *              this software, no matter how awful, even if they arise
61  *              from defects in it.
62  *
63  *      2. The origin of this software must not be misrepresented, either
64  *              by explicit claim or by omission.
65  *
66  *      3. Altered versions must be plainly marked as such, and must not
67  *              be misrepresented as being the original software.
68  *
69  *
70  ****    Alterations to Henry's code are...
71  ****
72  ****    Copyright (c) 1991-2001, Larry Wall
73  ****
74  ****    You may distribute under the terms of either the GNU General Public
75  ****    License or the Artistic License, as specified in the README file.
76
77  *
78  * Beware that some of this code is subtly aware of the way operator
79  * precedence is structured in regular expressions.  Serious changes in
80  * regular-expression syntax might require a total rethink.
81  */
82 #include "EXTERN.h"
83 #define PERL_IN_REGCOMP_C
84 #include "perl.h"
85
86 #ifndef PERL_IN_XSUB_RE
87 #  include "INTERN.h"
88 #endif
89
90 #define REG_COMP_C
91 #include "regcomp.h"
92
93 #ifdef op
94 #undef op
95 #endif /* op */
96
97 #ifdef MSDOS
98 # if defined(BUGGY_MSC6)
99  /* MSC 6.00A breaks on op/regexp.t test 85 unless we turn this off */
100  # pragma optimize("a",off)
101  /* But MSC 6.00A is happy with 'w', for aliases only across function calls*/
102  # pragma optimize("w",on )
103 # endif /* BUGGY_MSC6 */
104 #endif /* MSDOS */
105
106 #ifndef STATIC
107 #define STATIC  static
108 #endif
109
110 typedef struct RExC_state_t {
111     U16         flags16;                /* are we folding, multilining? */
112     char        *precomp;               /* uncompiled string. */
113     regexp      *rx;
114     char        *start;                 /* Start of input for compile */
115     char        *end;                   /* End of input for compile */
116     char        *parse;                 /* Input-scan pointer. */
117     I32         whilem_seen;            /* number of WHILEM in this expr */
118     regnode     *emit_start;            /* Start of emitted-code area */
119     regnode     *emit;                  /* Code-emit pointer; &regdummy = don't = compiling */
120     I32         naughty;                /* How bad is this pattern? */
121     I32         sawback;                /* Did we see \1, ...? */
122     U32         seen;
123     I32         size;                   /* Code size. */
124     I32         npar;                   /* () count. */
125     I32         extralen;
126     I32         seen_zerolen;
127     I32         seen_evals;
128     I32         utf8;
129 #if ADD_TO_REGEXEC
130     char        *starttry;              /* -Dr: where regtry was called. */
131 #define RExC_starttry   (pRExC_state->starttry)
132 #endif
133 } RExC_state_t;
134
135 #define RExC_flags16    (pRExC_state->flags16)
136 #define RExC_precomp    (pRExC_state->precomp)
137 #define RExC_rx         (pRExC_state->rx)
138 #define RExC_start      (pRExC_state->start)
139 #define RExC_end        (pRExC_state->end)
140 #define RExC_parse      (pRExC_state->parse)
141 #define RExC_whilem_seen        (pRExC_state->whilem_seen)
142 #define RExC_offsets    (pRExC_state->rx->offsets) /* I am not like the others */
143 #define RExC_emit       (pRExC_state->emit)
144 #define RExC_emit_start (pRExC_state->emit_start)
145 #define RExC_naughty    (pRExC_state->naughty)
146 #define RExC_sawback    (pRExC_state->sawback)
147 #define RExC_seen       (pRExC_state->seen)
148 #define RExC_size       (pRExC_state->size)
149 #define RExC_npar       (pRExC_state->npar)
150 #define RExC_extralen   (pRExC_state->extralen)
151 #define RExC_seen_zerolen       (pRExC_state->seen_zerolen)
152 #define RExC_seen_evals (pRExC_state->seen_evals)
153 #define RExC_utf8       (pRExC_state->utf8)
154
155 #define ISMULT1(c)      ((c) == '*' || (c) == '+' || (c) == '?')
156 #define ISMULT2(s)      ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
157         ((*s) == '{' && regcurly(s)))
158
159 #ifdef SPSTART
160 #undef SPSTART          /* dratted cpp namespace... */
161 #endif
162 /*
163  * Flags to be passed up and down.
164  */
165 #define WORST           0       /* Worst case. */
166 #define HASWIDTH        0x1     /* Known to match non-null strings. */
167 #define SIMPLE          0x2     /* Simple enough to be STAR/PLUS operand. */
168 #define SPSTART         0x4     /* Starts with * or +. */
169 #define TRYAGAIN        0x8     /* Weeded out a declaration. */
170
171 /* Length of a variant. */
172
173 typedef struct scan_data_t {
174     I32 len_min;
175     I32 len_delta;
176     I32 pos_min;
177     I32 pos_delta;
178     SV *last_found;
179     I32 last_end;                       /* min value, <0 unless valid. */
180     I32 last_start_min;
181     I32 last_start_max;
182     SV **longest;                       /* Either &l_fixed, or &l_float. */
183     SV *longest_fixed;
184     I32 offset_fixed;
185     SV *longest_float;
186     I32 offset_float_min;
187     I32 offset_float_max;
188     I32 flags;
189     I32 whilem_c;
190     I32 *last_closep;
191     struct regnode_charclass_class *start_class;
192 } scan_data_t;
193
194 /*
195  * Forward declarations for pregcomp()'s friends.
196  */
197
198 static scan_data_t zero_scan_data = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
199                                       0, 0, 0, 0, 0, 0};
200
201 #define SF_BEFORE_EOL           (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
202 #define SF_BEFORE_SEOL          0x1
203 #define SF_BEFORE_MEOL          0x2
204 #define SF_FIX_BEFORE_EOL       (SF_FIX_BEFORE_SEOL|SF_FIX_BEFORE_MEOL)
205 #define SF_FL_BEFORE_EOL        (SF_FL_BEFORE_SEOL|SF_FL_BEFORE_MEOL)
206
207 #ifdef NO_UNARY_PLUS
208 #  define SF_FIX_SHIFT_EOL      (0+2)
209 #  define SF_FL_SHIFT_EOL               (0+4)
210 #else
211 #  define SF_FIX_SHIFT_EOL      (+2)
212 #  define SF_FL_SHIFT_EOL               (+4)
213 #endif
214
215 #define SF_FIX_BEFORE_SEOL      (SF_BEFORE_SEOL << SF_FIX_SHIFT_EOL)
216 #define SF_FIX_BEFORE_MEOL      (SF_BEFORE_MEOL << SF_FIX_SHIFT_EOL)
217
218 #define SF_FL_BEFORE_SEOL       (SF_BEFORE_SEOL << SF_FL_SHIFT_EOL)
219 #define SF_FL_BEFORE_MEOL       (SF_BEFORE_MEOL << SF_FL_SHIFT_EOL) /* 0x20 */
220 #define SF_IS_INF               0x40
221 #define SF_HAS_PAR              0x80
222 #define SF_IN_PAR               0x100
223 #define SF_HAS_EVAL             0x200
224 #define SCF_DO_SUBSTR           0x400
225 #define SCF_DO_STCLASS_AND      0x0800
226 #define SCF_DO_STCLASS_OR       0x1000
227 #define SCF_DO_STCLASS          (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
228 #define SCF_WHILEM_VISITED_POS  0x2000
229
230 #define UTF RExC_utf8
231 #define LOC (RExC_flags16 & PMf_LOCALE)
232 #define FOLD (RExC_flags16 & PMf_FOLD)
233
234 #define OOB_UNICODE             12345678
235 #define OOB_NAMEDCLASS          -1
236
237 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
238 #define CHR_DIST(a,b) (UTF ? utf8_distance(a,b) : a - b)
239
240
241 /* length of regex to show in messages that don't mark a position within */
242 #define RegexLengthToShowInErrorMessages 127
243
244 /*
245  * If MARKER[12] are adjusted, be sure to adjust the constants at the top
246  * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
247  * op/pragma/warn/regcomp.
248  */
249 #define MARKER1 "<-- HERE"    /* marker as it appears in the description */
250 #define MARKER2 " <-- HERE "  /* marker as it appears within the regex */
251
252 #define REPORT_LOCATION " in regex; marked by " MARKER1 " in m/%.*s" MARKER2 "%s/"
253
254 /*
255  * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
256  * arg. Show regex, up to a maximum length. If it's too long, chop and add
257  * "...".
258  */
259 #define FAIL(msg)                                                             \
260     STMT_START {                                                             \
261         char *ellipses = "";                                                 \
262         IV len = RExC_end - RExC_precomp;                                \
263                                                                              \
264         if (!SIZE_ONLY)                                                      \
265             SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx);                 \
266                                                                              \
267         if (len > RegexLengthToShowInErrorMessages) {                        \
268             /* chop 10 shorter than the max, to ensure meaning of "..." */   \
269             len = RegexLengthToShowInErrorMessages - 10;                     \
270             ellipses = "...";                                                \
271         }                                                                    \
272         Perl_croak(aTHX_ "%s in regex m/%.*s%s/",                            \
273                    msg, (int)len, RExC_precomp, ellipses);                  \
274     } STMT_END
275
276 /*
277  * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
278  * args. Show regex, up to a maximum length. If it's too long, chop and add
279  * "...".
280  */
281 #define FAIL2(pat,msg)                                                        \
282     STMT_START {                                                             \
283         char *ellipses = "";                                                 \
284         IV len = RExC_end - RExC_precomp;                                \
285                                                                              \
286         if (!SIZE_ONLY)                                                      \
287             SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx);                 \
288                                                                              \
289         if (len > RegexLengthToShowInErrorMessages) {                        \
290             /* chop 10 shorter than the max, to ensure meaning of "..." */   \
291             len = RegexLengthToShowInErrorMessages - 10;                     \
292             ellipses = "...";                                                \
293         }                                                                    \
294         S_re_croak2(aTHX_ pat, " in regex m/%.*s%s/",                        \
295                     msg, (int)len, RExC_precomp, ellipses);                \
296     } STMT_END
297
298
299 /*
300  * Simple_vFAIL -- like FAIL, but marks the current location in the scan
301  */
302 #define Simple_vFAIL(m)                                                      \
303     STMT_START {                                                             \
304       IV offset = RExC_parse - RExC_precomp; \
305                                                                              \
306       Perl_croak(aTHX_ "%s" REPORT_LOCATION,               \
307                  m, (int)offset, RExC_precomp, RExC_precomp + offset);     \
308     } STMT_END
309
310 /*
311  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
312  */
313 #define vFAIL(m)                                                             \
314     STMT_START {                                                             \
315       if (!SIZE_ONLY)                                                        \
316             SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx);                 \
317       Simple_vFAIL(m);                                                       \
318     } STMT_END
319
320 /*
321  * Like Simple_vFAIL(), but accepts two arguments.
322  */
323 #define Simple_vFAIL2(m,a1)                                                  \
324     STMT_START {                                                             \
325       IV offset = RExC_parse - RExC_precomp; \
326                                                                              \
327       S_re_croak2(aTHX_ m, REPORT_LOCATION, a1,       \
328                   (int)offset, RExC_precomp, RExC_precomp + offset);       \
329     } STMT_END
330
331 /*
332  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
333  */
334 #define vFAIL2(m,a1)                                                         \
335     STMT_START {                                                             \
336       if (!SIZE_ONLY)                                                        \
337             SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx);                 \
338       Simple_vFAIL2(m, a1);                                                  \
339     } STMT_END
340
341
342 /*
343  * Like Simple_vFAIL(), but accepts three arguments.
344  */
345 #define Simple_vFAIL3(m, a1, a2)                                             \
346     STMT_START {                                                             \
347       IV offset = RExC_parse - RExC_precomp; \
348                                                                              \
349       S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2,   \
350                   (int)offset, RExC_precomp, RExC_precomp + offset);       \
351     } STMT_END
352
353 /*
354  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
355  */
356 #define vFAIL3(m,a1,a2)                                                      \
357     STMT_START {                                                             \
358       if (!SIZE_ONLY)                                                        \
359             SAVEDESTRUCTOR_X(clear_re,(void*)RExC_rx);                 \
360       Simple_vFAIL3(m, a1, a2);                                              \
361     } STMT_END
362
363 /*
364  * Like Simple_vFAIL(), but accepts four arguments.
365  */
366 #define Simple_vFAIL4(m, a1, a2, a3)                                         \
367     STMT_START {                                                             \
368       IV offset = RExC_parse - RExC_precomp; \
369                                                                              \
370       S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, a3,\
371                   (int)offset, RExC_precomp, RExC_precomp + offset);       \
372     } STMT_END
373
374 /*
375  * Like Simple_vFAIL(), but accepts five arguments.
376  */
377 #define Simple_vFAIL5(m, a1, a2, a3, a4)                                     \
378     STMT_START {                                                             \
379       IV offset = RExC_parse - RExC_precomp; \
380       S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, a3, a4,\
381                   (int)offset, RExC_precomp, RExC_precomp + offset);       \
382     } STMT_END
383
384
385 #define vWARN(loc,m)                                                         \
386     STMT_START {                                                             \
387         IV offset = loc - RExC_precomp;          \
388         Perl_warner(aTHX_ WARN_REGEXP, "%s" REPORT_LOCATION,\
389                  m, (int)offset, RExC_precomp, RExC_precomp + offset);          \
390     } STMT_END                                                               \
391
392 #define vWARNdep(loc,m)                                                         \
393     STMT_START {                                                             \
394         IV offset = loc - RExC_precomp;          \
395         int warn_cat = ckWARN(WARN_REGEXP) ? WARN_REGEXP : WARN_DEPRECATED;  \
396         Perl_warner(aTHX_ warn_cat, "%s" REPORT_LOCATION,\
397                  m, (int)offset, RExC_precomp, RExC_precomp + offset);          \
398     } STMT_END                                                               \
399
400
401 #define vWARN2(loc, m, a1)                                                   \
402     STMT_START {                                                             \
403         IV offset = loc - RExC_precomp;          \
404         Perl_warner(aTHX_ WARN_REGEXP, m REPORT_LOCATION,\
405                  a1,                                                         \
406                  (int)offset, RExC_precomp, RExC_precomp + offset);        \
407     } STMT_END
408
409 #define vWARN3(loc, m, a1, a2)                                               \
410     STMT_START {                                                             \
411       IV offset = loc - RExC_precomp;        \
412         Perl_warner(aTHX_ WARN_REGEXP, m REPORT_LOCATION,                    \
413                  a1, a2,                                                     \
414                  (int)offset, RExC_precomp, RExC_precomp + offset);        \
415     } STMT_END
416
417 #define vWARN4(loc, m, a1, a2, a3)                                           \
418     STMT_START {                                                             \
419       IV offset = loc - RExC_precomp;            \
420         Perl_warner(aTHX_ WARN_REGEXP, m REPORT_LOCATION,\
421                  a1, a2, a3,                                                 \
422                  (int)offset, RExC_precomp, RExC_precomp + offset);        \
423     } STMT_END
424
425 /* used for the parse_flags section for (?c) -- japhy */
426 #define vWARN5(loc, m, a1, a2, a3, a4)                                       \
427   STMT_START {                                                   \
428       IV offset = loc - RExC_precomp;   \
429         Perl_warner(aTHX_ WARN_REGEXP, m REPORT_LOCATION,      \
430                  a1, a2, a3, a4,                                 \
431                  (int)offset, RExC_precomp, RExC_precomp + offset);  \
432     } STMT_END
433
434
435 /* Allow for side effects in s */
436 #define REGC(c,s) STMT_START { if (!SIZE_ONLY) *(s) = (c); else (void)(s);} STMT_END
437
438 /* Macros for recording node offsets.   20001227 mjd@plover.com 
439  * Nodes are numbered 1, 2, 3, 4.  Node #n's position is recorded in
440  * element 2*n-1 of the array.  Element #2n holds the byte length node #n.
441  * Element 0 holds the number n.
442  */
443
444 #define MJD_OFFSET_DEBUG(x)
445 /* #define MJD_OFFSET_DEBUG(x) fprintf x */
446
447
448 #  define Set_Node_Offset_To_R(node,byte)                           \
449    STMT_START {                                        \
450      if (! SIZE_ONLY) {                                  \
451        if((node) < 0) {                   \
452          Perl_croak(aTHX_ "value of node is %d in Offset macro", node); \
453        } else {                                                        \
454          RExC_offsets[2*(node)-1] = (byte);                               \
455        }                                                               \
456      }                                                                 \
457    } STMT_END
458
459 #  define Set_Node_Offset(node,byte) Set_Node_Offset_To_R((node)-RExC_emit_start, (byte)-RExC_start)
460 #  define Set_Cur_Node_Offset Set_Node_Offset(RExC_emit, RExC_parse)
461
462 #  define Set_Node_Length_To_R(node,len)                            \
463    STMT_START {                                        \
464      if (! SIZE_ONLY) {                                  \
465        MJD_OFFSET_DEBUG((stderr, "** (%d) size of node %d is %d.\n", __LINE__, (node), (len))); \
466        if((node) < 0) {                   \
467          Perl_croak(aTHX_ "value of node is %d in Length macro", node); \
468        } else {                                                        \
469          RExC_offsets[2*(node)] = (len);                               \
470        }                                                               \
471      }                                                                 \
472    } STMT_END
473
474 #  define Set_Node_Length(node,len) Set_Node_Length_To_R((node)-RExC_emit_start, len)
475 #  define Set_Cur_Node_Length(len)  Set_Node_Length(RExC_emit, len)
476 #  define Set_Node_Cur_Length(node)   Set_Node_Length(node, RExC_parse - parse_start)
477
478 /* Get offsets and lengths */
479 #define Node_Offset(n) (RExC_offsets[2*((n)-RExC_emit_start)-1])
480 #define Node_Length(n) (RExC_offsets[2*((n)-RExC_emit_start)])
481
482 static void clear_re(pTHX_ void *r);
483
484 /* Mark that we cannot extend a found fixed substring at this point.
485    Updata the longest found anchored substring and the longest found
486    floating substrings if needed. */
487
488 STATIC void
489 S_scan_commit(pTHX_ RExC_state_t *pRExC_state, scan_data_t *data)
490 {
491     STRLEN l = CHR_SVLEN(data->last_found);
492     STRLEN old_l = CHR_SVLEN(*data->longest);
493
494     if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
495         sv_setsv(*data->longest, data->last_found);
496         if (*data->longest == data->longest_fixed) {
497             data->offset_fixed = l ? data->last_start_min : data->pos_min;
498             if (data->flags & SF_BEFORE_EOL)
499                 data->flags
500                     |= ((data->flags & SF_BEFORE_EOL) << SF_FIX_SHIFT_EOL);
501             else
502                 data->flags &= ~SF_FIX_BEFORE_EOL;
503         }
504         else {
505             data->offset_float_min = l ? data->last_start_min : data->pos_min;
506             data->offset_float_max = (l
507                                       ? data->last_start_max
508                                       : data->pos_min + data->pos_delta);
509             if (data->flags & SF_BEFORE_EOL)
510                 data->flags
511                     |= ((data->flags & SF_BEFORE_EOL) << SF_FL_SHIFT_EOL);
512             else
513                 data->flags &= ~SF_FL_BEFORE_EOL;
514         }
515     }
516     SvCUR_set(data->last_found, 0);
517     data->last_end = -1;
518     data->flags &= ~SF_BEFORE_EOL;
519 }
520
521 /* Can match anything (initialization) */
522 STATIC void
523 S_cl_anything(pTHX_ RExC_state_t *pRExC_state, struct regnode_charclass_class *cl)
524 {
525     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;        /* Unicode in it? */
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                         U8 c = (U8)*RExC_parse;
2883                         RExC_parse += 2;
2884                         RExC_end = oldregxend;
2885                         vFAIL2("Missing right brace on \\%c{}", c);
2886                     }
2887                     RExC_end++;
2888                 }
2889                 else
2890                     RExC_end = RExC_parse + 2;
2891                 RExC_parse--;
2892
2893                 ret = regclass(pRExC_state);
2894
2895                 RExC_end = oldregxend;
2896                 RExC_parse--;
2897                 Set_Node_Cur_Length(ret); /* MJD */
2898                 nextchar(pRExC_state);
2899                 *flagp |= HASWIDTH|SIMPLE;
2900             }
2901             break;
2902         case 'n':
2903         case 'r':
2904         case 't':
2905         case 'f':
2906         case 'e':
2907         case 'a':
2908         case 'x':
2909         case 'c':
2910         case '0':
2911             goto defchar;
2912         case '1': case '2': case '3': case '4':
2913         case '5': case '6': case '7': case '8': case '9':
2914             {
2915                 I32 num = atoi(RExC_parse);
2916
2917                 if (num > 9 && num >= RExC_npar)
2918                     goto defchar;
2919                 else {
2920                     char * parse_start = RExC_parse - 1; /* MJD */
2921                     while (isDIGIT(*RExC_parse))
2922                         RExC_parse++;
2923
2924                     if (!SIZE_ONLY && num > RExC_rx->nparens)
2925                         vFAIL("Reference to nonexistent group");
2926                     RExC_sawback = 1;
2927                     ret = reganode(pRExC_state, FOLD
2928                                    ? (LOC ? REFFL : REFF)
2929                                    : REF, num);
2930                     *flagp |= HASWIDTH;
2931                     
2932                     /* override incorrect value set in reganode MJD */
2933                     Set_Node_Offset(ret, parse_start+1); 
2934                     Set_Node_Cur_Length(ret); /* MJD */
2935                     RExC_parse--;
2936                     nextchar(pRExC_state);
2937                 }
2938             }
2939             break;
2940         case '\0':
2941             if (RExC_parse >= RExC_end)
2942                 FAIL("Trailing \\");
2943             /* FALL THROUGH */
2944         default:
2945             /* Do not generate `unrecognized' warnings here, we fall
2946                back into the quick-grab loop below */
2947             goto defchar;
2948         }
2949         break;
2950
2951     case '#':
2952         if (RExC_flags16 & PMf_EXTENDED) {
2953             while (RExC_parse < RExC_end && *RExC_parse != '\n') RExC_parse++;
2954             if (RExC_parse < RExC_end)
2955                 goto tryagain;
2956         }
2957         /* FALL THROUGH */
2958
2959     default: {
2960             register STRLEN len;
2961             register UV ender;
2962             register char *p;
2963             char *oldp, *s;
2964             STRLEN numlen;
2965             STRLEN ulen;
2966             U8 tmpbuf[UTF8_MAXLEN*2+1];
2967
2968             parse_start = RExC_parse - 1;
2969
2970             RExC_parse++;
2971
2972         defchar:
2973             ret = reg_node(pRExC_state, FOLD
2974                           ? (LOC ? EXACTFL : EXACTF)
2975                           : EXACT);
2976             s = STRING(ret);
2977             for (len = 0, p = RExC_parse - 1;
2978               len < 127 && p < RExC_end;
2979               len++)
2980             {
2981                 oldp = p;
2982
2983                 if (RExC_flags16 & PMf_EXTENDED)
2984                     p = regwhite(p, RExC_end);
2985                 switch (*p) {
2986                 case '^':
2987                 case '$':
2988                 case '.':
2989                 case '[':
2990                 case '(':
2991                 case ')':
2992                 case '|':
2993                     goto loopdone;
2994                 case '\\':
2995                     switch (*++p) {
2996                     case 'A':
2997                     case 'G':
2998                     case 'Z':
2999                     case 'z':
3000                     case 'w':
3001                     case 'W':
3002                     case 'b':
3003                     case 'B':
3004                     case 's':
3005                     case 'S':
3006                     case 'd':
3007                     case 'D':
3008                     case 'p':
3009                     case 'P':
3010                         --p;
3011                         goto loopdone;
3012                     case 'n':
3013                         ender = '\n';
3014                         p++;
3015                         break;
3016                     case 'r':
3017                         ender = '\r';
3018                         p++;
3019                         break;
3020                     case 't':
3021                         ender = '\t';
3022                         p++;
3023                         break;
3024                     case 'f':
3025                         ender = '\f';
3026                         p++;
3027                         break;
3028                     case 'e':
3029                           ender = ASCII_TO_NATIVE('\033');
3030                         p++;
3031                         break;
3032                     case 'a':
3033                           ender = ASCII_TO_NATIVE('\007');
3034                         p++;
3035                         break;
3036                     case 'x':
3037                         if (*++p == '{') {
3038                             char* e = strchr(p, '}');
3039         
3040                             if (!e) {
3041                                 RExC_parse = p + 1;
3042                                 vFAIL("Missing right brace on \\x{}");
3043                             }
3044                             else {
3045                                 I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
3046                                     | PERL_SCAN_DISALLOW_PREFIX;
3047                                 numlen = e - p - 1;
3048                                 ender = grok_hex(p + 1, &numlen, &flags, NULL);
3049                                 if (ender > 0xff)
3050                                     RExC_utf8 = 1;
3051                                 /* numlen is generous */
3052                                 if (numlen + len >= 127) {
3053                                     p--;
3054                                     goto loopdone;
3055                                 }
3056                                 p = e + 1;
3057                             }
3058                         }
3059                         else {
3060                             I32 flags = PERL_SCAN_DISALLOW_PREFIX;
3061                             numlen = 2;
3062                             ender = grok_hex(p, &numlen, &flags, NULL);
3063                             p += numlen;
3064                         }
3065                         break;
3066                     case 'c':
3067                         p++;
3068                         ender = UCHARAT(p++);
3069                         ender = toCTRL(ender);
3070                         break;
3071                     case '0': case '1': case '2': case '3':case '4':
3072                     case '5': case '6': case '7': case '8':case '9':
3073                         if (*p == '0' ||
3074                           (isDIGIT(p[1]) && atoi(p) >= RExC_npar) ) {
3075                             I32 flags = 0;
3076                             numlen = 3;
3077                             ender = grok_oct(p, &numlen, &flags, NULL);
3078                             p += numlen;
3079                         }
3080                         else {
3081                             --p;
3082                             goto loopdone;
3083                         }
3084                         break;
3085                     case '\0':
3086                         if (p >= RExC_end)
3087                             FAIL("Trailing \\");
3088                         /* FALL THROUGH */
3089                     default:
3090                         if (!SIZE_ONLY && ckWARN(WARN_REGEXP) && isALPHA(*p))
3091                             vWARN2(p + 1, "Unrecognized escape \\%c passed through", UCHARAT(p));
3092                         goto normal_default;
3093                     }
3094                     break;
3095                 default:
3096                   normal_default:
3097                     if (UTF8_IS_START(*p) && UTF) {
3098                         ender = utf8n_to_uvchr((U8*)p, RExC_end - p,
3099                                                &numlen, 0);
3100                         p += numlen;
3101                     }
3102                     else
3103                         ender = *p++;
3104                     break;
3105                 }
3106                 if (RExC_flags16 & PMf_EXTENDED)
3107                     p = regwhite(p, RExC_end);
3108                 if (UTF && FOLD) {
3109                     toLOWER_uni(ender, tmpbuf, &ulen);
3110                     ender = utf8_to_uvchr(tmpbuf, 0);
3111                 }
3112                 if (ISMULT2(p)) { /* Back off on ?+*. */
3113                     if (len)
3114                         p = oldp;
3115                     else if (!UNI_IS_INVARIANT(NATIVE_TO_UNI(ender)) && UTF) {
3116                         reguni(pRExC_state, ender, s, &numlen);
3117                         s += numlen;
3118                         len += numlen;
3119                     }
3120                     else {
3121                         len++;
3122                         REGC(ender, s++);
3123                     }
3124                     break;
3125                 }
3126                 if (!UNI_IS_INVARIANT(NATIVE_TO_UNI(ender)) && UTF) {
3127                     reguni(pRExC_state, ender, s, &numlen);
3128                     s += numlen;
3129                     len += numlen - 1;
3130                 }
3131                 else
3132                     REGC(ender, s++);
3133             }
3134         loopdone:
3135             RExC_parse = p - 1;
3136             Set_Node_Cur_Length(ret); /* MJD */
3137             nextchar(pRExC_state);
3138             {
3139                 /* len is STRLEN which is unsigned, need to copy to signed */
3140                 IV iv = len;
3141                 if (iv < 0)
3142                     vFAIL("Internal disaster");
3143             }
3144             if (len > 0)
3145                 *flagp |= HASWIDTH;
3146             if (len == 1)
3147                 *flagp |= SIMPLE;
3148             if (!SIZE_ONLY)
3149                 STR_LEN(ret) = len;
3150             if (SIZE_ONLY)
3151                 RExC_size += STR_SZ(len);
3152             else
3153                 RExC_emit += STR_SZ(len);
3154         }
3155         break;
3156     }
3157
3158     if (PL_encoding && PL_regkind[(U8)OP(ret)] == EXACT && !RExC_utf8) {
3159          STRLEN oldlen = STR_LEN(ret);
3160          SV *sv        = sv_2mortal(newSVpvn(STRING(ret), oldlen));
3161          char *s       = Perl_sv_recode_to_utf8(aTHX_ sv, PL_encoding);
3162          STRLEN newlen = SvCUR(sv);
3163          if (!SIZE_ONLY) {
3164               DEBUG_r(PerlIO_printf(Perl_debug_log, "recode %*s to %*s\n",
3165                                     oldlen, STRING(ret), newlen, s));
3166               Copy(s, STRING(ret), newlen, char);
3167               STR_LEN(ret) += newlen - oldlen;
3168               RExC_emit += STR_SZ(newlen) - STR_SZ(oldlen);
3169          } else
3170               RExC_size += STR_SZ(newlen) - STR_SZ(oldlen);
3171          RExC_utf8 = 1;
3172     }
3173
3174     return(ret);
3175 }
3176
3177 STATIC char *
3178 S_regwhite(pTHX_ char *p, char *e)
3179 {
3180     while (p < e) {
3181         if (isSPACE(*p))
3182             ++p;
3183         else if (*p == '#') {
3184             do {
3185                 p++;
3186             } while (p < e && *p != '\n');
3187         }
3188         else
3189             break;
3190     }
3191     return p;
3192 }
3193
3194 /* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
3195    Character classes ([:foo:]) can also be negated ([:^foo:]).
3196    Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
3197    Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
3198    but trigger failures because they are currently unimplemented. */
3199
3200 #define POSIXCC_DONE(c)   ((c) == ':')
3201 #define POSIXCC_NOTYET(c) ((c) == '=' || (c) == '.')
3202 #define POSIXCC(c) (POSIXCC_DONE(c) || POSIXCC_NOTYET(c))
3203
3204 STATIC I32
3205 S_regpposixcc(pTHX_ RExC_state_t *pRExC_state, I32 value)
3206 {
3207     char *posixcc = 0;
3208     I32 namedclass = OOB_NAMEDCLASS;
3209
3210     if (value == '[' && RExC_parse + 1 < RExC_end &&
3211         /* I smell either [: or [= or [. -- POSIX has been here, right? */
3212         POSIXCC(UCHARAT(RExC_parse))) {
3213         char  c = UCHARAT(RExC_parse);
3214         char* s = RExC_parse++;
3215         
3216         while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != c)
3217             RExC_parse++;
3218         if (RExC_parse == RExC_end)
3219             /* Grandfather lone [:, [=, [. */
3220             RExC_parse = s;
3221         else {
3222             char* t = RExC_parse++; /* skip over the c */
3223
3224             if (UCHARAT(RExC_parse) == ']') {
3225                 RExC_parse++; /* skip over the ending ] */
3226                 posixcc = s + 1;
3227                 if (*s == ':') {
3228                     I32 complement = *posixcc == '^' ? *posixcc++ : 0;
3229                     I32 skip = 5; /* the most common skip */
3230
3231                     switch (*posixcc) {
3232                     case 'a':
3233                         if (strnEQ(posixcc, "alnum", 5))
3234                             namedclass =
3235                                 complement ? ANYOF_NALNUMC : ANYOF_ALNUMC;
3236                         else if (strnEQ(posixcc, "alpha", 5))
3237                             namedclass =
3238                                 complement ? ANYOF_NALPHA : ANYOF_ALPHA;
3239                         else if (strnEQ(posixcc, "ascii", 5))
3240                             namedclass =
3241                                 complement ? ANYOF_NASCII : ANYOF_ASCII;
3242                         break;
3243                     case 'b':
3244                         if (strnEQ(posixcc, "blank", 5))
3245                             namedclass =
3246                                 complement ? ANYOF_NBLANK : ANYOF_BLANK;
3247                         break;
3248                     case 'c':
3249                         if (strnEQ(posixcc, "cntrl", 5))
3250                             namedclass =
3251                                 complement ? ANYOF_NCNTRL : ANYOF_CNTRL;
3252                         break;
3253                     case 'd':
3254                         if (strnEQ(posixcc, "digit", 5))
3255                             namedclass =
3256                                 complement ? ANYOF_NDIGIT : ANYOF_DIGIT;
3257                         break;
3258                     case 'g':
3259                         if (strnEQ(posixcc, "graph", 5))
3260                             namedclass =
3261                                 complement ? ANYOF_NGRAPH : ANYOF_GRAPH;
3262                         break;
3263                     case 'l':
3264                         if (strnEQ(posixcc, "lower", 5))
3265                             namedclass =
3266                                 complement ? ANYOF_NLOWER : ANYOF_LOWER;
3267                         break;
3268                     case 'p':
3269                         if (strnEQ(posixcc, "print", 5))
3270                             namedclass =
3271                                 complement ? ANYOF_NPRINT : ANYOF_PRINT;
3272                         else if (strnEQ(posixcc, "punct", 5))
3273                             namedclass =
3274                                 complement ? ANYOF_NPUNCT : ANYOF_PUNCT;
3275                         break;
3276                     case 's':
3277                         if (strnEQ(posixcc, "space", 5))
3278                             namedclass =
3279                                 complement ? ANYOF_NPSXSPC : ANYOF_PSXSPC;
3280                         break;
3281                     case 'u':
3282                         if (strnEQ(posixcc, "upper", 5))
3283                             namedclass =
3284                                 complement ? ANYOF_NUPPER : ANYOF_UPPER;
3285                         break;
3286                     case 'w': /* this is not POSIX, this is the Perl \w */
3287                         if (strnEQ(posixcc, "word", 4)) {
3288                             namedclass =
3289                                 complement ? ANYOF_NALNUM : ANYOF_ALNUM;
3290                             skip = 4;
3291                         }
3292                         break;
3293                     case 'x':
3294                         if (strnEQ(posixcc, "xdigit", 6)) {
3295                             namedclass =
3296                                 complement ? ANYOF_NXDIGIT : ANYOF_XDIGIT;
3297                             skip = 6;
3298                         }
3299                         break;
3300                     }
3301                     if (namedclass == OOB_NAMEDCLASS ||
3302                         posixcc[skip] != ':' ||
3303                         posixcc[skip+1] != ']')
3304                     {
3305                         Simple_vFAIL3("POSIX class [:%.*s:] unknown",
3306                                       t - s - 1, s + 1);
3307                     }
3308                 } else if (!SIZE_ONLY) {
3309                     /* [[=foo=]] and [[.foo.]] are still future. */
3310
3311                     /* adjust RExC_parse so the warning shows after
3312                        the class closes */
3313                     while (UCHARAT(RExC_parse) && UCHARAT(RExC_parse) != ']')
3314                         RExC_parse++;
3315                     Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
3316                 }
3317             } else {
3318                 /* Maternal grandfather:
3319                  * "[:" ending in ":" but not in ":]" */
3320                 RExC_parse = s;
3321             }
3322         }
3323     }
3324
3325     return namedclass;
3326 }
3327
3328 STATIC void
3329 S_checkposixcc(pTHX_ RExC_state_t *pRExC_state)
3330 {
3331     if (!SIZE_ONLY && ckWARN(WARN_REGEXP) &&
3332         POSIXCC(UCHARAT(RExC_parse))) {
3333         char *s = RExC_parse;
3334         char  c = *s++;
3335
3336         while(*s && isALNUM(*s))
3337             s++;
3338         if (*s && c == *s && s[1] == ']') {
3339             vWARN3(s+2, "POSIX syntax [%c %c] belongs inside character classes", c, c);
3340
3341             /* [[=foo=]] and [[.foo.]] are still future. */
3342             if (POSIXCC_NOTYET(c)) {
3343                 /* adjust RExC_parse so the error shows after
3344                    the class closes */
3345                 while (UCHARAT(RExC_parse) && UCHARAT(RExC_parse++) != ']')
3346                     ;
3347                 Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
3348             }
3349         }
3350     }
3351 }
3352
3353 STATIC regnode *
3354 S_regclass(pTHX_ RExC_state_t *pRExC_state)
3355 {
3356     register UV value;
3357     register UV nextvalue;
3358     register IV prevvalue = OOB_UNICODE;
3359     register IV range = 0;
3360     register regnode *ret;
3361     STRLEN numlen;
3362     IV namedclass;
3363     char *rangebegin = 0;
3364     bool need_class = 0;
3365     SV *listsv = Nullsv;
3366     register char *e;
3367     UV n;
3368     bool optimize_invert = TRUE;
3369
3370     ret = reganode(pRExC_state, ANYOF, 0);
3371
3372     if (!SIZE_ONLY)
3373         ANYOF_FLAGS(ret) = 0;
3374
3375     if (UCHARAT(RExC_parse) == '^') {   /* Complement of range. */
3376         RExC_naughty++;
3377         RExC_parse++;
3378         if (!SIZE_ONLY)
3379             ANYOF_FLAGS(ret) |= ANYOF_INVERT;
3380     }
3381
3382     if (SIZE_ONLY)
3383         RExC_size += ANYOF_SKIP;
3384     else {
3385         RExC_emit += ANYOF_SKIP;
3386         if (FOLD)
3387             ANYOF_FLAGS(ret) |= ANYOF_FOLD;
3388         if (LOC)
3389             ANYOF_FLAGS(ret) |= ANYOF_LOCALE;
3390         ANYOF_BITMAP_ZERO(ret);
3391         listsv = newSVpvn("# comment\n", 10);
3392     }
3393
3394     nextvalue = RExC_parse < RExC_end ? UCHARAT(RExC_parse) : 0;
3395
3396     if (!SIZE_ONLY && ckWARN(WARN_REGEXP) && POSIXCC(nextvalue))
3397         checkposixcc(pRExC_state);
3398
3399     if (UCHARAT(RExC_parse) == ']' || UCHARAT(RExC_parse) == '-')
3400         goto charclassloop;             /* allow 1st char to be ] or - */
3401
3402     while (RExC_parse < RExC_end && UCHARAT(RExC_parse) != ']') {
3403
3404     charclassloop:
3405
3406         namedclass = OOB_NAMEDCLASS; /* initialize as illegal */
3407
3408         if (!range)
3409             rangebegin = RExC_parse;
3410         if (UTF) {
3411             value = utf8n_to_uvchr((U8*)RExC_parse,
3412                                    RExC_end - RExC_parse,
3413                                    &numlen, 0);
3414             RExC_parse += numlen;
3415         }
3416         else
3417             value = UCHARAT(RExC_parse++);
3418         nextvalue = RExC_parse < RExC_end ? UCHARAT(RExC_parse) : 0;
3419         if (value == '[' && POSIXCC(nextvalue))
3420             namedclass = regpposixcc(pRExC_state, value);
3421         else if (value == '\\') {
3422             if (UTF) {
3423                 value = utf8n_to_uvchr((U8*)RExC_parse,
3424                                    RExC_end - RExC_parse,
3425                                    &numlen, 0);
3426                 RExC_parse += numlen;
3427             }
3428             else
3429                 value = UCHARAT(RExC_parse++);
3430             /* Some compilers cannot handle switching on 64-bit integer
3431              * values, therefore value cannot be an UV.  Yes, this will
3432              * be a problem later if we want switch on Unicode.
3433              * A similar issue a little bit later when switching on
3434              * namedclass. --jhi */
3435             switch ((I32)value) {
3436             case 'w':   namedclass = ANYOF_ALNUM;       break;
3437             case 'W':   namedclass = ANYOF_NALNUM;      break;
3438             case 's':   namedclass = ANYOF_SPACE;       break;
3439             case 'S':   namedclass = ANYOF_NSPACE;      break;
3440             case 'd':   namedclass = ANYOF_DIGIT;       break;
3441             case 'D':   namedclass = ANYOF_NDIGIT;      break;
3442             case 'p':
3443             case 'P':
3444                 if (*RExC_parse == '{') {
3445                     U8 c = (U8)value;
3446                     e = strchr(RExC_parse++, '}');
3447                     if (!e)
3448                         vFAIL2("Missing right brace on \\%c{}", c);
3449                     while (isSPACE(UCHARAT(RExC_parse)))
3450                         RExC_parse++;
3451                     if (e == RExC_parse)
3452                         vFAIL2("Empty \\%c{}", c);
3453                     n = e - RExC_parse;
3454                     while (isSPACE(UCHARAT(RExC_parse + n - 1)))
3455                         n--;
3456                 }
3457                 else {
3458                     e = RExC_parse;
3459                     n = 1;
3460                 }
3461                 if (!SIZE_ONLY) {
3462                     if (UCHARAT(RExC_parse) == '^') {
3463                          RExC_parse++;
3464                          n--;
3465                          value = value == 'p' ? 'P' : 'p'; /* toggle */
3466                          while (isSPACE(UCHARAT(RExC_parse))) {
3467                               RExC_parse++;
3468                               n--;
3469                          }
3470                     }
3471                     if (value == 'p')
3472                          Perl_sv_catpvf(aTHX_ listsv,
3473                                         "+utf8::%.*s\n", (int)n, RExC_parse);
3474                     else
3475                          Perl_sv_catpvf(aTHX_ listsv,
3476                                         "!utf8::%.*s\n", (int)n, RExC_parse);
3477                 }
3478                 RExC_parse = e + 1;
3479                 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
3480                 continue;
3481             case 'n':   value = '\n';                   break;
3482             case 'r':   value = '\r';                   break;
3483             case 't':   value = '\t';                   break;
3484             case 'f':   value = '\f';                   break;
3485             case 'b':   value = '\b';                   break;
3486             case 'e':   value = ASCII_TO_NATIVE('\033');break;
3487             case 'a':   value = ASCII_TO_NATIVE('\007');break;
3488             case 'x':
3489                 if (*RExC_parse == '{') {
3490                     I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
3491                         | PERL_SCAN_DISALLOW_PREFIX;
3492                     e = strchr(RExC_parse++, '}');
3493                     if (!e)
3494                         vFAIL("Missing right brace on \\x{}");
3495
3496                     numlen = e - RExC_parse;
3497                     value = grok_hex(RExC_parse, &numlen, &flags, NULL);
3498                     RExC_parse = e + 1;
3499                 }
3500                 else {
3501                     I32 flags = PERL_SCAN_DISALLOW_PREFIX;
3502                     numlen = 2;
3503                     value = grok_hex(RExC_parse, &numlen, &flags, NULL);
3504                     RExC_parse += numlen;
3505                 }
3506                 break;
3507             case 'c':
3508                 value = UCHARAT(RExC_parse++);
3509                 value = toCTRL(value);
3510                 break;
3511             case '0': case '1': case '2': case '3': case '4':
3512             case '5': case '6': case '7': case '8': case '9':
3513             {
3514                 I32 flags = 0;
3515                 numlen = 3;
3516                 value = grok_oct(--RExC_parse, &numlen, &flags, NULL);
3517                 RExC_parse += numlen;
3518                 break;
3519             }
3520             default:
3521                 if (!SIZE_ONLY && ckWARN(WARN_REGEXP) && isALPHA(value))
3522                     vWARN2(RExC_parse,
3523                            "Unrecognized escape \\%c in character class passed through",
3524                            (int)value);
3525                 break;
3526             }
3527         } /* end of \blah */
3528
3529         if (namedclass > OOB_NAMEDCLASS) { /* this is a named class \blah */
3530
3531             if (!SIZE_ONLY && !need_class)
3532                 ANYOF_CLASS_ZERO(ret);
3533
3534             need_class = 1;
3535
3536             /* a bad range like a-\d, a-[:digit:] ? */
3537             if (range) {
3538                 if (!SIZE_ONLY) {
3539                     if (ckWARN(WARN_REGEXP))
3540                         vWARN4(RExC_parse,
3541                                "False [] range \"%*.*s\"",
3542                                RExC_parse - rangebegin,
3543                                RExC_parse - rangebegin,
3544                                rangebegin);
3545                     if (prevvalue < 256) {
3546                         ANYOF_BITMAP_SET(ret, prevvalue);
3547                         ANYOF_BITMAP_SET(ret, '-');
3548                     }
3549                     else {
3550                         ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
3551                         Perl_sv_catpvf(aTHX_ listsv,
3552                                        "%04"UVxf"\n%04"UVxf"\n", (UV)prevvalue, (UV) '-');
3553                     }
3554                 }
3555
3556                 range = 0; /* this was not a true range */
3557             }
3558
3559             if (!SIZE_ONLY) {
3560                 if (namedclass > OOB_NAMEDCLASS)
3561                     optimize_invert = FALSE;
3562                 /* Possible truncation here but in some 64-bit environments
3563                  * the compiler gets heartburn about switch on 64-bit values.
3564                  * A similar issue a little earlier when switching on value.
3565                  * --jhi */
3566                 switch ((I32)namedclass) {
3567                 case ANYOF_ALNUM:
3568                     if (LOC)
3569                         ANYOF_CLASS_SET(ret, ANYOF_ALNUM);
3570                     else {
3571                         for (value = 0; value < 256; value++)
3572                             if (isALNUM(value))
3573                                 ANYOF_BITMAP_SET(ret, value);
3574                     }
3575                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsWord\n");    
3576                     break;
3577                 case ANYOF_NALNUM:
3578                     if (LOC)
3579                         ANYOF_CLASS_SET(ret, ANYOF_NALNUM);
3580                     else {
3581                         for (value = 0; value < 256; value++)
3582                             if (!isALNUM(value))
3583                                 ANYOF_BITMAP_SET(ret, value);
3584                     }
3585                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsWord\n");
3586                     break;
3587                 case ANYOF_ALNUMC:
3588                     if (LOC)
3589                         ANYOF_CLASS_SET(ret, ANYOF_ALNUMC);
3590                     else {
3591                         for (value = 0; value < 256; value++)
3592                             if (isALNUMC(value))
3593                                 ANYOF_BITMAP_SET(ret, value);
3594                     }
3595                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsAlnum\n");
3596                     break;
3597                 case ANYOF_NALNUMC:
3598                     if (LOC)
3599                         ANYOF_CLASS_SET(ret, ANYOF_NALNUMC);
3600                     else {
3601                         for (value = 0; value < 256; value++)
3602                             if (!isALNUMC(value))
3603                                 ANYOF_BITMAP_SET(ret, value);
3604                     }
3605                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsAlnum\n");
3606                     break;
3607                 case ANYOF_ALPHA:
3608                     if (LOC)
3609                         ANYOF_CLASS_SET(ret, ANYOF_ALPHA);
3610                     else {
3611                         for (value = 0; value < 256; value++)
3612                             if (isALPHA(value))
3613                                 ANYOF_BITMAP_SET(ret, value);
3614                     }
3615                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsAlpha\n");
3616                     break;
3617                 case ANYOF_NALPHA:
3618                     if (LOC)
3619                         ANYOF_CLASS_SET(ret, ANYOF_NALPHA);
3620                     else {
3621                         for (value = 0; value < 256; value++)
3622                             if (!isALPHA(value))
3623                                 ANYOF_BITMAP_SET(ret, value);
3624                     }
3625                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsAlpha\n");
3626                     break;
3627                 case ANYOF_ASCII:
3628                     if (LOC)
3629                         ANYOF_CLASS_SET(ret, ANYOF_ASCII);
3630                     else {
3631 #ifndef EBCDIC
3632                         for (value = 0; value < 128; value++)
3633                             ANYOF_BITMAP_SET(ret, value);
3634 #else  /* EBCDIC */
3635                         for (value = 0; value < 256; value++) {
3636                             if (isASCII(value))
3637                                 ANYOF_BITMAP_SET(ret, value);
3638                         }
3639 #endif /* EBCDIC */
3640                     }
3641                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsASCII\n");
3642                     break;
3643                 case ANYOF_NASCII:
3644                     if (LOC)
3645                         ANYOF_CLASS_SET(ret, ANYOF_NASCII);
3646                     else {
3647 #ifndef EBCDIC
3648                         for (value = 128; value < 256; value++)
3649                             ANYOF_BITMAP_SET(ret, value);
3650 #else  /* EBCDIC */
3651                         for (value = 0; value < 256; value++) {
3652                             if (!isASCII(value))
3653                                 ANYOF_BITMAP_SET(ret, value);
3654                         }
3655 #endif /* EBCDIC */
3656                     }
3657                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsASCII\n");
3658                     break;
3659                 case ANYOF_BLANK:
3660                     if (LOC)
3661                         ANYOF_CLASS_SET(ret, ANYOF_BLANK);
3662                     else {
3663                         for (value = 0; value < 256; value++)
3664                             if (isBLANK(value))
3665                                 ANYOF_BITMAP_SET(ret, value);
3666                     }
3667                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsBlank\n");
3668                     break;
3669                 case ANYOF_NBLANK:
3670                     if (LOC)
3671                         ANYOF_CLASS_SET(ret, ANYOF_NBLANK);
3672                     else {
3673                         for (value = 0; value < 256; value++)
3674                             if (!isBLANK(value))
3675                                 ANYOF_BITMAP_SET(ret, value);
3676                     }
3677                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsBlank\n");
3678                     break;
3679                 case ANYOF_CNTRL:
3680                     if (LOC)
3681                         ANYOF_CLASS_SET(ret, ANYOF_CNTRL);
3682                     else {
3683                         for (value = 0; value < 256; value++)
3684                             if (isCNTRL(value))
3685                                 ANYOF_BITMAP_SET(ret, value);
3686                     }
3687                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsCntrl\n");
3688                     break;
3689                 case ANYOF_NCNTRL:
3690                     if (LOC)
3691                         ANYOF_CLASS_SET(ret, ANYOF_NCNTRL);
3692                     else {
3693                         for (value = 0; value < 256; value++)
3694                             if (!isCNTRL(value))
3695                                 ANYOF_BITMAP_SET(ret, value);
3696                     }
3697                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsCntrl\n");
3698                     break;
3699                 case ANYOF_DIGIT:
3700                     if (LOC)
3701                         ANYOF_CLASS_SET(ret, ANYOF_DIGIT);
3702                     else {
3703                         /* consecutive digits assumed */
3704                         for (value = '0'; value <= '9'; value++)
3705                             ANYOF_BITMAP_SET(ret, value);
3706                     }
3707                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsDigit\n");
3708                     break;
3709                 case ANYOF_NDIGIT:
3710                     if (LOC)
3711                         ANYOF_CLASS_SET(ret, ANYOF_NDIGIT);
3712                     else {
3713                         /* consecutive digits assumed */
3714                         for (value = 0; value < '0'; value++)
3715                             ANYOF_BITMAP_SET(ret, value);
3716                         for (value = '9' + 1; value < 256; value++)
3717                             ANYOF_BITMAP_SET(ret, value);
3718                     }
3719                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsDigit\n");
3720                     break;
3721                 case ANYOF_GRAPH:
3722                     if (LOC)
3723                         ANYOF_CLASS_SET(ret, ANYOF_GRAPH);
3724                     else {
3725                         for (value = 0; value < 256; value++)
3726                             if (isGRAPH(value))
3727                                 ANYOF_BITMAP_SET(ret, value);
3728                     }
3729                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsGraph\n");
3730                     break;
3731                 case ANYOF_NGRAPH:
3732                     if (LOC)
3733                         ANYOF_CLASS_SET(ret, ANYOF_NGRAPH);
3734                     else {
3735                         for (value = 0; value < 256; value++)
3736                             if (!isGRAPH(value))
3737                                 ANYOF_BITMAP_SET(ret, value);
3738                     }
3739                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsGraph\n");
3740                     break;
3741                 case ANYOF_LOWER:
3742                     if (LOC)
3743                         ANYOF_CLASS_SET(ret, ANYOF_LOWER);
3744                     else {
3745                         for (value = 0; value < 256; value++)
3746                             if (isLOWER(value))
3747                                 ANYOF_BITMAP_SET(ret, value);
3748                     }
3749                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsLower\n");
3750                     break;
3751                 case ANYOF_NLOWER:
3752                     if (LOC)
3753                         ANYOF_CLASS_SET(ret, ANYOF_NLOWER);
3754                     else {
3755                         for (value = 0; value < 256; value++)
3756                             if (!isLOWER(value))
3757                                 ANYOF_BITMAP_SET(ret, value);
3758                     }
3759                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsLower\n");
3760                     break;
3761                 case ANYOF_PRINT:
3762                     if (LOC)
3763                         ANYOF_CLASS_SET(ret, ANYOF_PRINT);
3764                     else {
3765                         for (value = 0; value < 256; value++)
3766                             if (isPRINT(value))
3767                                 ANYOF_BITMAP_SET(ret, value);
3768                     }
3769                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsPrint\n");
3770                     break;
3771                 case ANYOF_NPRINT:
3772                     if (LOC)
3773                         ANYOF_CLASS_SET(ret, ANYOF_NPRINT);
3774                     else {
3775                         for (value = 0; value < 256; value++)
3776                             if (!isPRINT(value))
3777                                 ANYOF_BITMAP_SET(ret, value);
3778                     }
3779                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsPrint\n");
3780                     break;
3781                 case ANYOF_PSXSPC:
3782                     if (LOC)
3783                         ANYOF_CLASS_SET(ret, ANYOF_PSXSPC);
3784                     else {
3785                         for (value = 0; value < 256; value++)
3786                             if (isPSXSPC(value))
3787                                 ANYOF_BITMAP_SET(ret, value);
3788                     }
3789                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsSpace\n");
3790                     break;
3791                 case ANYOF_NPSXSPC:
3792                     if (LOC)
3793                         ANYOF_CLASS_SET(ret, ANYOF_NPSXSPC);
3794                     else {
3795                         for (value = 0; value < 256; value++)
3796                             if (!isPSXSPC(value))
3797                                 ANYOF_BITMAP_SET(ret, value);
3798                     }
3799                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsSpace\n");
3800                     break;
3801                 case ANYOF_PUNCT:
3802                     if (LOC)
3803                         ANYOF_CLASS_SET(ret, ANYOF_PUNCT);
3804                     else {
3805                         for (value = 0; value < 256; value++)
3806                             if (isPUNCT(value))
3807                                 ANYOF_BITMAP_SET(ret, value);
3808                     }
3809                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsPunct\n");
3810                     break;
3811                 case ANYOF_NPUNCT:
3812                     if (LOC)
3813                         ANYOF_CLASS_SET(ret, ANYOF_NPUNCT);
3814                     else {
3815                         for (value = 0; value < 256; value++)
3816                             if (!isPUNCT(value))
3817                                 ANYOF_BITMAP_SET(ret, value);
3818                     }
3819                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsPunct\n");
3820                     break;
3821                 case ANYOF_SPACE:
3822                     if (LOC)
3823                         ANYOF_CLASS_SET(ret, ANYOF_SPACE);
3824                     else {
3825                         for (value = 0; value < 256; value++)
3826                             if (isSPACE(value))
3827                                 ANYOF_BITMAP_SET(ret, value);
3828                     }
3829                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsSpacePerl\n");
3830                     break;
3831                 case ANYOF_NSPACE:
3832                     if (LOC)
3833                         ANYOF_CLASS_SET(ret, ANYOF_NSPACE);
3834                     else {
3835                         for (value = 0; value < 256; value++)
3836                             if (!isSPACE(value))
3837                                 ANYOF_BITMAP_SET(ret, value);
3838                     }
3839                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsSpacePerl\n");
3840                     break;
3841                 case ANYOF_UPPER:
3842                     if (LOC)
3843                         ANYOF_CLASS_SET(ret, ANYOF_UPPER);
3844                     else {
3845                         for (value = 0; value < 256; value++)
3846                             if (isUPPER(value))
3847                                 ANYOF_BITMAP_SET(ret, value);
3848                     }
3849                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsUpper\n");
3850                     break;
3851                 case ANYOF_NUPPER:
3852                     if (LOC)
3853                         ANYOF_CLASS_SET(ret, ANYOF_NUPPER);
3854                     else {
3855                         for (value = 0; value < 256; value++)
3856                             if (!isUPPER(value))
3857                                 ANYOF_BITMAP_SET(ret, value);
3858                     }
3859                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsUpper\n");
3860                     break;
3861                 case ANYOF_XDIGIT:
3862                     if (LOC)
3863                         ANYOF_CLASS_SET(ret, ANYOF_XDIGIT);
3864                     else {
3865                         for (value = 0; value < 256; value++)
3866                             if (isXDIGIT(value))
3867                                 ANYOF_BITMAP_SET(ret, value);
3868                     }
3869                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsXDigit\n");
3870                     break;
3871                 case ANYOF_NXDIGIT:
3872                     if (LOC)
3873                         ANYOF_CLASS_SET(ret, ANYOF_NXDIGIT);
3874                     else {
3875                         for (value = 0; value < 256; value++)
3876                             if (!isXDIGIT(value))
3877                                 ANYOF_BITMAP_SET(ret, value);
3878                     }
3879                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsXDigit\n");
3880                     break;
3881                 default:
3882                     vFAIL("Invalid [::] class");
3883                     break;
3884                 }
3885                 if (LOC)
3886                     ANYOF_FLAGS(ret) |= ANYOF_CLASS;
3887                 continue;
3888             }
3889         } /* end of namedclass \blah */
3890
3891         if (range) {
3892             if (prevvalue > value) /* b-a */ {
3893                 Simple_vFAIL4("Invalid [] range \"%*.*s\"",
3894                               RExC_parse - rangebegin,
3895                               RExC_parse - rangebegin,
3896                               rangebegin);
3897                 range = 0; /* not a valid range */
3898             }
3899         }
3900         else {
3901             prevvalue = value; /* save the beginning of the range */
3902             if (*RExC_parse == '-' && RExC_parse+1 < RExC_end &&
3903                 RExC_parse[1] != ']') {
3904                 RExC_parse++;
3905
3906                 /* a bad range like \w-, [:word:]- ? */
3907                 if (namedclass > OOB_NAMEDCLASS) {
3908                     if (ckWARN(WARN_REGEXP))
3909                         vWARN4(RExC_parse,
3910                                "False [] range \"%*.*s\"",
3911                                RExC_parse - rangebegin,
3912                                RExC_parse - rangebegin,
3913                                rangebegin);
3914                     if (!SIZE_ONLY)
3915                         ANYOF_BITMAP_SET(ret, '-');
3916                 } else
3917                     range = 1;  /* yeah, it's a range! */
3918                 continue;       /* but do it the next time */
3919             }
3920         }
3921
3922         /* now is the next time */
3923         if (!SIZE_ONLY) {
3924             IV i;
3925
3926             if (prevvalue < 256) {
3927                 IV ceilvalue = value < 256 ? value : 255;
3928
3929 #ifdef EBCDIC
3930                 if ((isLOWER(prevvalue) && isLOWER(ceilvalue)) ||
3931                     (isUPPER(prevvalue) && isUPPER(ceilvalue)))
3932                 {
3933                     if (isLOWER(prevvalue)) {
3934                         for (i = prevvalue; i <= ceilvalue; i++)
3935                             if (isLOWER(i))
3936                                 ANYOF_BITMAP_SET(ret, i);
3937                     } else {
3938                         for (i = prevvalue; i <= ceilvalue; i++)
3939                             if (isUPPER(i))
3940                                 ANYOF_BITMAP_SET(ret, i);
3941                     }
3942                 }
3943                 else
3944 #endif
3945                     for (i = prevvalue; i <= ceilvalue; i++)
3946                         ANYOF_BITMAP_SET(ret, i);
3947           }
3948           if (value > 255) {
3949                 ANYOF_FLAGS(ret) |= ANYOF_UNICODE;
3950                 if (prevvalue < value)
3951                     Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\t%04"UVxf"\n",
3952                                    (UV)prevvalue, (UV)value);
3953                 else if (prevvalue == value)
3954                     Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n",
3955                                    (UV)value);
3956             }
3957         }
3958
3959         range = 0; /* this range (if it was one) is done now */
3960     }
3961
3962     if (need_class) {
3963         ANYOF_FLAGS(ret) |= ANYOF_LARGE;
3964         if (SIZE_ONLY)
3965             RExC_size += ANYOF_CLASS_ADD_SKIP;
3966         else
3967             RExC_emit += ANYOF_CLASS_ADD_SKIP;
3968     }
3969
3970     /* optimize case-insensitive simple patterns (e.g. /[a-z]/i) */
3971     if (!SIZE_ONLY &&
3972          /* If the only flag is folding (plus possibly inversion). */
3973         ((ANYOF_FLAGS(ret) & (ANYOF_FLAGS_ALL ^ ANYOF_INVERT)) == ANYOF_FOLD)
3974        ) {
3975         for (value = 0; value < 256; ++value) {
3976             if (ANYOF_BITMAP_TEST(ret, value)) {
3977                 IV fold = PL_fold[value];
3978
3979                 if (fold != value)
3980                     ANYOF_BITMAP_SET(ret, fold);
3981             }
3982         }
3983         ANYOF_FLAGS(ret) &= ~ANYOF_FOLD;
3984     }
3985
3986     /* optimize inverted simple patterns (e.g. [^a-z]) */
3987     if (!SIZE_ONLY && optimize_invert &&
3988         /* If the only flag is inversion. */
3989         (ANYOF_FLAGS(ret) & ANYOF_FLAGS_ALL) == ANYOF_INVERT) {
3990         for (value = 0; value < ANYOF_BITMAP_SIZE; ++value)
3991             ANYOF_BITMAP(ret)[value] ^= ANYOF_FLAGS_ALL;
3992         ANYOF_FLAGS(ret) = ANYOF_UNICODE_ALL;
3993     }
3994
3995     if (!SIZE_ONLY) {
3996         AV *av = newAV();
3997         SV *rv;
3998
3999         av_store(av, 0, listsv);
4000         av_store(av, 1, NULL);
4001         rv = newRV_noinc((SV*)av);
4002         n = add_data(pRExC_state, 1, "s");
4003         RExC_rx->data->data[n] = (void*)rv;
4004         ARG_SET(ret, n);
4005     }
4006
4007     return ret;
4008 }
4009
4010 STATIC char*
4011 S_nextchar(pTHX_ RExC_state_t *pRExC_state)
4012 {
4013     char* retval = RExC_parse++;
4014
4015     for (;;) {
4016         if (*RExC_parse == '(' && RExC_parse[1] == '?' &&
4017                 RExC_parse[2] == '#') {
4018             while (*RExC_parse && *RExC_parse != ')')
4019                 RExC_parse++;
4020             RExC_parse++;
4021             continue;
4022         }
4023         if (RExC_flags16 & PMf_EXTENDED) {
4024             if (isSPACE(*RExC_parse)) {
4025                 RExC_parse++;
4026                 continue;
4027             }
4028             else if (*RExC_parse == '#') {
4029                 while (*RExC_parse && *RExC_parse != '\n')
4030                     RExC_parse++;
4031                 RExC_parse++;
4032                 continue;
4033             }
4034         }
4035         return retval;
4036     }
4037 }
4038
4039 /*
4040 - reg_node - emit a node
4041 */
4042 STATIC regnode *                        /* Location. */
4043 S_reg_node(pTHX_ RExC_state_t *pRExC_state, U8 op)
4044 {
4045     register regnode *ret;
4046     register regnode *ptr;
4047
4048     ret = RExC_emit;
4049     if (SIZE_ONLY) {
4050         SIZE_ALIGN(RExC_size);
4051         RExC_size += 1;
4052         return(ret);
4053     }
4054
4055     NODE_ALIGN_FILL(ret);
4056     ptr = ret;
4057     FILL_ADVANCE_NODE(ptr, op);
4058     if (RExC_offsets) {         /* MJD */
4059       MJD_OFFSET_DEBUG((stderr, "%s:%u: (op %s) %s %u <- %u (len %u) (max %u).\n", 
4060               "reg_node", __LINE__, 
4061               reg_name[op],
4062               RExC_emit - RExC_emit_start > RExC_offsets[0] 
4063               ? "Overwriting end of array!\n" : "OK",
4064               RExC_emit - RExC_emit_start,
4065               RExC_parse - RExC_start,
4066               RExC_offsets[0])); 
4067       Set_Node_Offset(RExC_emit, RExC_parse + (op == END));
4068     }
4069             
4070     RExC_emit = ptr;
4071
4072     return(ret);
4073 }
4074
4075 /*
4076 - reganode - emit a node with an argument
4077 */
4078 STATIC regnode *                        /* Location. */
4079 S_reganode(pTHX_ RExC_state_t *pRExC_state, U8 op, U32 arg)
4080 {
4081     register regnode *ret;
4082     register regnode *ptr;
4083
4084     ret = RExC_emit;
4085     if (SIZE_ONLY) {
4086         SIZE_ALIGN(RExC_size);
4087         RExC_size += 2;
4088         return(ret);
4089     }
4090
4091     NODE_ALIGN_FILL(ret);
4092     ptr = ret;
4093     FILL_ADVANCE_NODE_ARG(ptr, op, arg);
4094     if (RExC_offsets) {         /* MJD */
4095       MJD_OFFSET_DEBUG((stderr, "%s: %s %u <- %u (max %u).\n", 
4096               "reganode",
4097               RExC_emit - RExC_emit_start > RExC_offsets[0] ? 
4098               "Overwriting end of array!\n" : "OK",
4099               RExC_emit - RExC_emit_start,
4100               RExC_parse - RExC_start,
4101               RExC_offsets[0])); 
4102       Set_Cur_Node_Offset;
4103     }
4104             
4105     RExC_emit = ptr;
4106
4107     return(ret);
4108 }
4109
4110 /*
4111 - reguni - emit (if appropriate) a Unicode character
4112 */
4113 STATIC void
4114 S_reguni(pTHX_ RExC_state_t *pRExC_state, UV uv, char* s, STRLEN* lenp)
4115 {
4116     *lenp = SIZE_ONLY ? UNISKIP(uv) : (uvchr_to_utf8((U8*)s, uv) - (U8*)s);
4117 }
4118
4119 /*
4120 - reginsert - insert an operator in front of already-emitted operand
4121 *
4122 * Means relocating the operand.
4123 */
4124 STATIC void
4125 S_reginsert(pTHX_ RExC_state_t *pRExC_state, U8 op, regnode *opnd)
4126 {
4127     register regnode *src;
4128     register regnode *dst;
4129     register regnode *place;
4130     register int offset = regarglen[(U8)op];
4131
4132 /* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
4133
4134     if (SIZE_ONLY) {
4135         RExC_size += NODE_STEP_REGNODE + offset;
4136         return;
4137     }
4138
4139     src = RExC_emit;
4140     RExC_emit += NODE_STEP_REGNODE + offset;
4141     dst = RExC_emit;
4142     while (src > opnd) {
4143         StructCopy(--src, --dst, regnode);
4144         if (RExC_offsets) {     /* MJD 20010112 */
4145           MJD_OFFSET_DEBUG((stderr, "%s: %s copy %u -> %u (max %u).\n", 
4146                   "reg_insert",
4147                   dst - RExC_emit_start > RExC_offsets[0] 
4148                   ? "Overwriting end of array!\n" : "OK",
4149                   src - RExC_emit_start,
4150                   dst - RExC_emit_start,
4151                   RExC_offsets[0])); 
4152           Set_Node_Offset_To_R(dst-RExC_emit_start, Node_Offset(src));
4153           Set_Node_Length_To_R(dst-RExC_emit_start, Node_Length(src));
4154         }
4155     }
4156     
4157
4158     place = opnd;               /* Op node, where operand used to be. */
4159     if (RExC_offsets) {         /* MJD */
4160       MJD_OFFSET_DEBUG((stderr, "%s: %s %u <- %u (max %u).\n", 
4161               "reginsert",
4162               place - RExC_emit_start > RExC_offsets[0] 
4163               ? "Overwriting end of array!\n" : "OK",
4164               place - RExC_emit_start,
4165               RExC_parse - RExC_start,
4166               RExC_offsets[0])); 
4167       Set_Node_Offset(place, RExC_parse);
4168     }
4169     src = NEXTOPER(place);
4170     FILL_ADVANCE_NODE(place, op);
4171     Zero(src, offset, regnode);
4172 }
4173
4174 /*
4175 - regtail - set the next-pointer at the end of a node chain of p to val.
4176 */
4177 STATIC void
4178 S_regtail(pTHX_ RExC_state_t *pRExC_state, regnode *p, regnode *val)
4179 {
4180     register regnode *scan;
4181     register regnode *temp;
4182
4183     if (SIZE_ONLY)
4184         return;
4185
4186     /* Find last node. */
4187     scan = p;
4188     for (;;) {
4189         temp = regnext(scan);
4190         if (temp == NULL)
4191             break;
4192         scan = temp;
4193     }
4194
4195     if (reg_off_by_arg[OP(scan)]) {
4196         ARG_SET(scan, val - scan);
4197     }
4198     else {
4199         NEXT_OFF(scan) = val - scan;
4200     }
4201 }
4202
4203 /*
4204 - regoptail - regtail on operand of first argument; nop if operandless
4205 */
4206 STATIC void
4207 S_regoptail(pTHX_ RExC_state_t *pRExC_state, regnode *p, regnode *val)
4208 {
4209     /* "Operandless" and "op != BRANCH" are synonymous in practice. */
4210     if (p == NULL || SIZE_ONLY)
4211         return;
4212     if (PL_regkind[(U8)OP(p)] == BRANCH) {
4213         regtail(pRExC_state, NEXTOPER(p), val);
4214     }
4215     else if ( PL_regkind[(U8)OP(p)] == BRANCHJ) {
4216         regtail(pRExC_state, NEXTOPER(NEXTOPER(p)), val);
4217     }
4218     else
4219         return;
4220 }
4221
4222 /*
4223  - regcurly - a little FSA that accepts {\d+,?\d*}
4224  */
4225 STATIC I32
4226 S_regcurly(pTHX_ register char *s)
4227 {
4228     if (*s++ != '{')
4229         return FALSE;
4230     if (!isDIGIT(*s))
4231         return FALSE;
4232     while (isDIGIT(*s))
4233         s++;
4234     if (*s == ',')
4235         s++;
4236     while (isDIGIT(*s))
4237         s++;
4238     if (*s != '}')
4239         return FALSE;
4240     return TRUE;
4241 }
4242
4243
4244 #ifdef DEBUGGING
4245
4246 STATIC regnode *
4247 S_dumpuntil(pTHX_ regnode *start, regnode *node, regnode *last, SV* sv, I32 l)
4248 {
4249     register U8 op = EXACT;     /* Arbitrary non-END op. */
4250     register regnode *next;
4251
4252     while (op != END && (!last || node < last)) {
4253         /* While that wasn't END last time... */
4254
4255         NODE_ALIGN(node);
4256         op = OP(node);
4257         if (op == CLOSE)
4258             l--;        
4259         next = regnext(node);
4260         /* Where, what. */
4261         if (OP(node) == OPTIMIZED)
4262             goto after_print;
4263         regprop(sv, node);
4264         PerlIO_printf(Perl_debug_log, "%4"IVdf":%*s%s", (IV)(node - start),
4265                       (int)(2*l + 1), "", SvPVX(sv));
4266         if (next == NULL)               /* Next ptr. */
4267             PerlIO_printf(Perl_debug_log, "(0)");
4268         else
4269             PerlIO_printf(Perl_debug_log, "(%"IVdf")", (IV)(next - start));
4270         (void)PerlIO_putc(Perl_debug_log, '\n');
4271       after_print:
4272         if (PL_regkind[(U8)op] == BRANCHJ) {
4273             register regnode *nnode = (OP(next) == LONGJMP
4274                                        ? regnext(next)
4275                                        : next);
4276             if (last && nnode > last)
4277                 nnode = last;
4278             node = dumpuntil(start, NEXTOPER(NEXTOPER(node)), nnode, sv, l + 1);
4279         }
4280         else if (PL_regkind[(U8)op] == BRANCH) {
4281             node = dumpuntil(start, NEXTOPER(node), next, sv, l + 1);
4282         }
4283         else if ( op == CURLY) {   /* `next' might be very big: optimizer */
4284             node = dumpuntil(start, NEXTOPER(node) + EXTRA_STEP_2ARGS,
4285                              NEXTOPER(node) + EXTRA_STEP_2ARGS + 1, sv, l + 1);
4286         }
4287         else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
4288             node = dumpuntil(start, NEXTOPER(node) + EXTRA_STEP_2ARGS,
4289                              next, sv, l + 1);
4290         }
4291         else if ( op == PLUS || op == STAR) {
4292             node = dumpuntil(start, NEXTOPER(node), NEXTOPER(node) + 1, sv, l + 1);
4293         }
4294         else if (op == ANYOF) {
4295             /* arglen 1 + class block */
4296             node += 1 + ((ANYOF_FLAGS(node) & ANYOF_LARGE)
4297                     ? ANYOF_CLASS_SKIP : ANYOF_SKIP);
4298             node = NEXTOPER(node);
4299         }
4300         else if (PL_regkind[(U8)op] == EXACT) {
4301             /* Literal string, where present. */
4302             node += NODE_SZ_STR(node) - 1;
4303             node = NEXTOPER(node);
4304         }
4305         else {
4306             node = NEXTOPER(node);
4307             node += regarglen[(U8)op];
4308         }
4309         if (op == CURLYX || op == OPEN)
4310             l++;
4311         else if (op == WHILEM)
4312             l--;
4313     }
4314     return node;
4315 }
4316
4317 #endif  /* DEBUGGING */
4318
4319 /*
4320  - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
4321  */
4322 void
4323 Perl_regdump(pTHX_ regexp *r)
4324 {
4325 #ifdef DEBUGGING
4326     SV *sv = sv_newmortal();
4327
4328     (void)dumpuntil(r->program, r->program + 1, NULL, sv, 0);
4329
4330     /* Header fields of interest. */
4331     if (r->anchored_substr)
4332         PerlIO_printf(Perl_debug_log,
4333                       "anchored `%s%.*s%s'%s at %"IVdf" ",
4334                       PL_colors[0],
4335                       (int)(SvCUR(r->anchored_substr) - (SvTAIL(r->anchored_substr)!=0)),
4336                       SvPVX(r->anchored_substr),
4337                       PL_colors[1],
4338                       SvTAIL(r->anchored_substr) ? "$" : "",
4339                       (IV)r->anchored_offset);
4340     if (r->float_substr)
4341         PerlIO_printf(Perl_debug_log,
4342                       "floating `%s%.*s%s'%s at %"IVdf"..%"UVuf" ",
4343                       PL_colors[0],
4344                       (int)(SvCUR(r->float_substr) - (SvTAIL(r->float_substr)!=0)),
4345                       SvPVX(r->float_substr),
4346                       PL_colors[1],
4347                       SvTAIL(r->float_substr) ? "$" : "",
4348                       (IV)r->float_min_offset, (UV)r->float_max_offset);
4349     if (r->check_substr)
4350         PerlIO_printf(Perl_debug_log,
4351                       r->check_substr == r->float_substr
4352                       ? "(checking floating" : "(checking anchored");
4353     if (r->reganch & ROPT_NOSCAN)
4354         PerlIO_printf(Perl_debug_log, " noscan");
4355     if (r->reganch & ROPT_CHECK_ALL)
4356         PerlIO_printf(Perl_debug_log, " isall");
4357     if (r->check_substr)
4358         PerlIO_printf(Perl_debug_log, ") ");
4359
4360     if (r->regstclass) {
4361         regprop(sv, r->regstclass);
4362         PerlIO_printf(Perl_debug_log, "stclass `%s' ", SvPVX(sv));
4363     }
4364     if (r->reganch & ROPT_ANCH) {
4365         PerlIO_printf(Perl_debug_log, "anchored");
4366         if (r->reganch & ROPT_ANCH_BOL)
4367             PerlIO_printf(Perl_debug_log, "(BOL)");
4368         if (r->reganch & ROPT_ANCH_MBOL)
4369             PerlIO_printf(Perl_debug_log, "(MBOL)");
4370         if (r->reganch & ROPT_ANCH_SBOL)
4371             PerlIO_printf(Perl_debug_log, "(SBOL)");
4372         if (r->reganch & ROPT_ANCH_GPOS)
4373             PerlIO_printf(Perl_debug_log, "(GPOS)");
4374         PerlIO_putc(Perl_debug_log, ' ');
4375     }
4376     if (r->reganch & ROPT_GPOS_SEEN)
4377         PerlIO_printf(Perl_debug_log, "GPOS ");
4378     if (r->reganch & ROPT_SKIP)
4379         PerlIO_printf(Perl_debug_log, "plus ");
4380     if (r->reganch & ROPT_IMPLICIT)
4381         PerlIO_printf(Perl_debug_log, "implicit ");
4382     PerlIO_printf(Perl_debug_log, "minlen %ld ", (long) r->minlen);
4383     if (r->reganch & ROPT_EVAL_SEEN)
4384         PerlIO_printf(Perl_debug_log, "with eval ");
4385     PerlIO_printf(Perl_debug_log, "\n");
4386     if (r->offsets) {
4387       U32 i;
4388       U32 len = r->offsets[0];
4389       PerlIO_printf(Perl_debug_log, "Offsets: [%"UVuf"]\n\t", (UV)r->offsets[0]);
4390       for (i = 1; i <= len; i++)
4391         PerlIO_printf(Perl_debug_log, "%"UVuf"[%"UVuf"] ", 
4392                       (UV)r->offsets[i*2-1], 
4393                       (UV)r->offsets[i*2]);
4394       PerlIO_printf(Perl_debug_log, "\n");
4395     }
4396 #endif  /* DEBUGGING */
4397 }
4398
4399 #ifdef DEBUGGING
4400
4401 STATIC void
4402 S_put_byte(pTHX_ SV *sv, int c)
4403 {
4404     if (isCNTRL(c) || c == 255 || !isPRINT(c))
4405         Perl_sv_catpvf(aTHX_ sv, "\\%o", c);
4406     else if (c == '-' || c == ']' || c == '\\' || c == '^')
4407         Perl_sv_catpvf(aTHX_ sv, "\\%c", c);
4408     else
4409         Perl_sv_catpvf(aTHX_ sv, "%c", c);
4410 }
4411
4412 #endif  /* DEBUGGING */
4413
4414 /*
4415 - regprop - printable representation of opcode
4416 */
4417 void
4418 Perl_regprop(pTHX_ SV *sv, regnode *o)
4419 {
4420 #ifdef DEBUGGING
4421     register int k;
4422
4423     sv_setpvn(sv, "", 0);
4424     if (OP(o) >= reg_num)               /* regnode.type is unsigned */
4425         /* It would be nice to FAIL() here, but this may be called from
4426            regexec.c, and it would be hard to supply pRExC_state. */
4427         Perl_croak(aTHX_ "Corrupted regexp opcode");
4428     sv_catpv(sv, (char*)reg_name[OP(o)]); /* Take off const! */
4429
4430     k = PL_regkind[(U8)OP(o)];
4431
4432     if (k == EXACT) {
4433         SV *dsv = sv_2mortal(newSVpvn("", 0));
4434         bool do_utf8 = DO_UTF8(sv);
4435         char *s    = do_utf8 ?
4436           pv_uni_display(dsv, (U8*)STRING(o), STR_LEN(o), 60, 0) :
4437           STRING(o);
4438         int len = do_utf8 ?
4439           strlen(s) :
4440           STR_LEN(o);
4441         Perl_sv_catpvf(aTHX_ sv, " <%s%.*s%s>",
4442                        PL_colors[0],
4443                        len, s,
4444                        PL_colors[1]);
4445     }
4446     else if (k == CURLY) {
4447         if (OP(o) == CURLYM || OP(o) == CURLYN || OP(o) == CURLYX)
4448             Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
4449         Perl_sv_catpvf(aTHX_ sv, " {%d,%d}", ARG1(o), ARG2(o));
4450     }
4451     else if (k == WHILEM && o->flags)                   /* Ordinal/of */
4452         Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
4453     else if (k == REF || k == OPEN || k == CLOSE || k == GROUPP )
4454         Perl_sv_catpvf(aTHX_ sv, "%d", (int)ARG(o));    /* Parenth number */
4455     else if (k == LOGICAL)
4456         Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags);     /* 2: embedded, otherwise 1 */
4457     else if (k == ANYOF) {
4458         int i, rangestart = -1;
4459         U8 flags = ANYOF_FLAGS(o);
4460         const char * const anyofs[] = { /* Should be syncronized with
4461                                          * ANYOF_ #xdefines in regcomp.h */
4462             "\\w",
4463             "\\W",
4464             "\\s",
4465             "\\S",
4466             "\\d",
4467             "\\D",
4468             "[:alnum:]",
4469             "[:^alnum:]",
4470             "[:alpha:]",
4471             "[:^alpha:]",
4472             "[:ascii:]",
4473             "[:^ascii:]",
4474             "[:ctrl:]",
4475             "[:^ctrl:]",
4476             "[:graph:]",
4477             "[:^graph:]",
4478             "[:lower:]",
4479             "[:^lower:]",
4480             "[:print:]",
4481             "[:^print:]",
4482             "[:punct:]",
4483             "[:^punct:]",
4484             "[:upper:]",
4485             "[:^upper:]",
4486             "[:xdigit:]",
4487             "[:^xdigit:]",
4488             "[:space:]",
4489             "[:^space:]",
4490             "[:blank:]",
4491             "[:^blank:]"
4492         };
4493
4494         if (flags & ANYOF_LOCALE)
4495             sv_catpv(sv, "{loc}");
4496         if (flags & ANYOF_FOLD)
4497             sv_catpv(sv, "{i}");
4498         Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
4499         if (flags & ANYOF_INVERT)
4500             sv_catpv(sv, "^");
4501         for (i = 0; i <= 256; i++) {
4502             if (i < 256 && ANYOF_BITMAP_TEST(o,i)) {
4503                 if (rangestart == -1)
4504                     rangestart = i;
4505             } else if (rangestart != -1) {
4506                 if (i <= rangestart + 3)
4507                     for (; rangestart < i; rangestart++)
4508                         put_byte(sv, rangestart);
4509                 else {
4510                     put_byte(sv, rangestart);
4511                     sv_catpv(sv, "-");
4512                     put_byte(sv, i - 1);
4513                 }
4514                 rangestart = -1;
4515             }
4516         }
4517
4518         if (o->flags & ANYOF_CLASS)
4519             for (i = 0; i < sizeof(anyofs)/sizeof(char*); i++)
4520                 if (ANYOF_CLASS_TEST(o,i))
4521                     sv_catpv(sv, anyofs[i]);
4522
4523         if (flags & ANYOF_UNICODE)
4524             sv_catpv(sv, "{unicode}");
4525         else if (flags & ANYOF_UNICODE_ALL)
4526             sv_catpv(sv, "{unicode_all}");
4527
4528         {
4529             SV *lv;
4530             SV *sw = regclass_swash(o, FALSE, &lv);
4531         
4532             if (lv) {
4533                 if (sw) {
4534                     UV i;
4535                     U8 s[UTF8_MAXLEN+1];
4536                 
4537                     for (i = 0; i <= 256; i++) { /* just the first 256 */
4538                         U8 *e = uvchr_to_utf8(s, i);
4539                         
4540                         if (i < 256 && swash_fetch(sw, s, TRUE)) {
4541                             if (rangestart == -1)
4542                                 rangestart = i;
4543                         } else if (rangestart != -1) {
4544                             U8 *p;
4545                         
4546                             if (i <= rangestart + 3)
4547                                 for (; rangestart < i; rangestart++) {
4548                                     for(e = uvchr_to_utf8(s, rangestart), p = s; p < e; p++)
4549                                         put_byte(sv, *p);
4550                                 }
4551                             else {
4552                                 for (e = uvchr_to_utf8(s, rangestart), p = s; p < e; p++)
4553                                     put_byte(sv, *p);
4554                                 sv_catpv(sv, "-");
4555                                     for (e = uvchr_to_utf8(s, i - 1), p = s; p < e; p++)
4556                                         put_byte(sv, *p);
4557                                 }
4558                                 rangestart = -1;
4559                             }
4560                         }
4561                         
4562                     sv_catpv(sv, "..."); /* et cetera */
4563                 }
4564
4565                 {
4566                     char *s = savepv(SvPVX(lv));
4567                     char *origs = s;
4568                 
4569                     while(*s && *s != '\n') s++;
4570                 
4571                     if (*s == '\n') {
4572                         char *t = ++s;
4573                         
4574                         while (*s) {
4575                             if (*s == '\n')
4576                                 *s = ' ';
4577                             s++;
4578                         }
4579                         if (s[-1] == ' ')
4580                             s[-1] = 0;
4581                         
4582                         sv_catpv(sv, t);
4583                     }
4584                 
4585                     Safefree(origs);
4586                 }
4587             }
4588         }
4589
4590         Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
4591     }
4592     else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH))
4593         Perl_sv_catpvf(aTHX_ sv, "[-%d]", o->flags);
4594 #endif  /* DEBUGGING */
4595 }
4596
4597 SV *
4598 Perl_re_intuit_string(pTHX_ regexp *prog)
4599 {                               /* Assume that RE_INTUIT is set */
4600     DEBUG_r(
4601         {   STRLEN n_a;
4602             char *s = SvPV(prog->check_substr,n_a);
4603
4604             if (!PL_colorset) reginitcolors();
4605             PerlIO_printf(Perl_debug_log,
4606                       "%sUsing REx substr:%s `%s%.60s%s%s'\n",
4607                       PL_colors[4],PL_colors[5],PL_colors[0],
4608                       s,
4609                       PL_colors[1],
4610                       (strlen(s) > 60 ? "..." : ""));
4611         } );
4612
4613     return prog->check_substr;
4614 }
4615
4616 void
4617 Perl_pregfree(pTHX_ struct regexp *r)
4618 {
4619     DEBUG_r(if (!PL_colorset) reginitcolors());
4620
4621     if (!r || (--r->refcnt > 0))
4622         return;
4623     DEBUG_r(PerlIO_printf(Perl_debug_log,
4624                       "%sFreeing REx:%s `%s%.60s%s%s'\n",
4625                       PL_colors[4],PL_colors[5],PL_colors[0],
4626                       r->precomp,
4627                       PL_colors[1],
4628                       (strlen(r->precomp) > 60 ? "..." : "")));
4629
4630     if (r->precomp)
4631         Safefree(r->precomp);
4632     if (r->offsets)             /* 20010421 MJD */
4633         Safefree(r->offsets);
4634     if (RX_MATCH_COPIED(r))
4635         Safefree(r->subbeg);
4636     if (r->substrs) {
4637         if (r->anchored_substr)
4638             SvREFCNT_dec(r->anchored_substr);
4639         if (r->float_substr)
4640             SvREFCNT_dec(r->float_substr);
4641         Safefree(r->substrs);
4642     }
4643     if (r->data) {
4644         int n = r->data->count;
4645         AV* new_comppad = NULL;
4646         AV* old_comppad;
4647         SV** old_curpad;
4648
4649         while (--n >= 0) {
4650           /* If you add a ->what type here, update the comment in regcomp.h */
4651             switch (r->data->what[n]) {
4652             case 's':
4653                 SvREFCNT_dec((SV*)r->data->data[n]);
4654                 break;
4655             case 'f':
4656                 Safefree(r->data->data[n]);
4657                 break;
4658             case 'p':
4659                 new_comppad = (AV*)r->data->data[n];
4660                 break;
4661             case 'o':
4662                 if (new_comppad == NULL)
4663                     Perl_croak(aTHX_ "panic: pregfree comppad");
4664                 old_comppad = PL_comppad;
4665                 old_curpad = PL_curpad;
4666                 /* Watch out for global destruction's random ordering. */
4667                 if (SvTYPE(new_comppad) == SVt_PVAV) {
4668                     PL_comppad = new_comppad;
4669                     PL_curpad = AvARRAY(new_comppad);
4670                 }
4671                 else
4672                     PL_curpad = NULL;
4673
4674                 if (!OpREFCNT_dec((OP_4tree*)r->data->data[n])) {
4675                     op_free((OP_4tree*)r->data->data[n]);
4676                 }
4677
4678                 PL_comppad = old_comppad;
4679                 PL_curpad = old_curpad;
4680                 SvREFCNT_dec((SV*)new_comppad);
4681                 new_comppad = NULL;
4682                 break;
4683             case 'n':
4684                 break;
4685             default:
4686                 Perl_croak(aTHX_ "panic: regfree data code '%c'", r->data->what[n]);
4687             }
4688         }
4689         Safefree(r->data->what);
4690         Safefree(r->data);
4691     }
4692     Safefree(r->startp);
4693     Safefree(r->endp);
4694     Safefree(r);
4695 }
4696
4697 /*
4698  - regnext - dig the "next" pointer out of a node
4699  *
4700  * [Note, when REGALIGN is defined there are two places in regmatch()
4701  * that bypass this code for speed.]
4702  */
4703 regnode *
4704 Perl_regnext(pTHX_ register regnode *p)
4705 {
4706     register I32 offset;
4707
4708     if (p == &PL_regdummy)
4709         return(NULL);
4710
4711     offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
4712     if (offset == 0)
4713         return(NULL);
4714
4715     return(p+offset);
4716 }
4717
4718 STATIC void     
4719 S_re_croak2(pTHX_ const char* pat1,const char* pat2,...)
4720 {
4721     va_list args;
4722     STRLEN l1 = strlen(pat1);
4723     STRLEN l2 = strlen(pat2);
4724     char buf[512];
4725     SV *msv;
4726     char *message;
4727
4728     if (l1 > 510)
4729         l1 = 510;
4730     if (l1 + l2 > 510)
4731         l2 = 510 - l1;
4732     Copy(pat1, buf, l1 , char);
4733     Copy(pat2, buf + l1, l2 , char);
4734     buf[l1 + l2] = '\n';
4735     buf[l1 + l2 + 1] = '\0';
4736 #ifdef I_STDARG
4737     /* ANSI variant takes additional second argument */
4738     va_start(args, pat2);
4739 #else
4740     va_start(args);
4741 #endif
4742     msv = vmess(buf, &args);
4743     va_end(args);
4744     message = SvPV(msv,l1);
4745     if (l1 > 512)
4746         l1 = 512;
4747     Copy(message, buf, l1 , char);
4748     buf[l1] = '\0';                     /* Overwrite \n */
4749     Perl_croak(aTHX_ "%s", buf);
4750 }
4751
4752 /* XXX Here's a total kludge.  But we need to re-enter for swash routines. */
4753
4754 void
4755 Perl_save_re_context(pTHX)
4756 {
4757 #if 0
4758     SAVEPPTR(RExC_precomp);             /* uncompiled string. */
4759     SAVEI32(RExC_npar);         /* () count. */
4760     SAVEI32(RExC_size);         /* Code size. */
4761     SAVEI16(RExC_flags16);              /* are we folding, multilining? */
4762     SAVEVPTR(RExC_rx);          /* from regcomp.c */
4763     SAVEI32(RExC_seen);         /* from regcomp.c */
4764     SAVEI32(RExC_sawback);              /* Did we see \1, ...? */
4765     SAVEI32(RExC_naughty);              /* How bad is this pattern? */
4766     SAVEVPTR(RExC_emit);                /* Code-emit pointer; &regdummy = don't */
4767     SAVEPPTR(RExC_end);         /* End of input for compile */
4768     SAVEPPTR(RExC_parse);               /* Input-scan pointer. */
4769 #endif
4770
4771     SAVEI32(PL_reg_flags);              /* from regexec.c */
4772     SAVEPPTR(PL_bostr);
4773     SAVEPPTR(PL_reginput);              /* String-input pointer. */
4774     SAVEPPTR(PL_regbol);                /* Beginning of input, for ^ check. */
4775     SAVEPPTR(PL_regeol);                /* End of input, for $ check. */
4776     SAVEVPTR(PL_regstartp);             /* Pointer to startp array. */
4777     SAVEVPTR(PL_regendp);               /* Ditto for endp. */
4778     SAVEVPTR(PL_reglastparen);          /* Similarly for lastparen. */
4779     SAVEPPTR(PL_regtill);               /* How far we are required to go. */
4780     SAVEGENERICPV(PL_reg_start_tmp);            /* from regexec.c */
4781     PL_reg_start_tmp = 0;
4782     SAVEI32(PL_reg_start_tmpl);         /* from regexec.c */
4783     PL_reg_start_tmpl = 0;
4784     SAVEVPTR(PL_regdata);
4785     SAVEI32(PL_reg_eval_set);           /* from regexec.c */
4786     SAVEI32(PL_regnarrate);             /* from regexec.c */
4787     SAVEVPTR(PL_regprogram);            /* from regexec.c */
4788     SAVEINT(PL_regindent);              /* from regexec.c */
4789     SAVEVPTR(PL_regcc);                 /* from regexec.c */
4790     SAVEVPTR(PL_curcop);
4791     SAVEVPTR(PL_reg_call_cc);           /* from regexec.c */
4792     SAVEVPTR(PL_reg_re);                /* from regexec.c */
4793     SAVEPPTR(PL_reg_ganch);             /* from regexec.c */
4794     SAVESPTR(PL_reg_sv);                /* from regexec.c */
4795     SAVEI8(PL_reg_match_utf8);          /* from regexec.c */
4796     SAVEVPTR(PL_reg_magic);             /* from regexec.c */
4797     SAVEI32(PL_reg_oldpos);                     /* from regexec.c */
4798     SAVEVPTR(PL_reg_oldcurpm);          /* from regexec.c */
4799     SAVEVPTR(PL_reg_curpm);             /* from regexec.c */
4800     SAVEI32(PL_regnpar);                /* () count. */
4801     SAVEI32(PL_regsize);                /* from regexec.c */
4802 #ifdef DEBUGGING
4803     SAVEPPTR(PL_reg_starttry);          /* from regexec.c */
4804 #endif
4805 }
4806
4807 static void
4808 clear_re(pTHX_ void *r)
4809 {
4810     ReREFCNT_dec((regexp *)r);
4811 }
4812