Untangle the IV_IS_QUAD jungle by introduding
[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-1999, Larry Wall
73  ****
74  ****    You may distribute under the terms of either the GNU General Public
75  ****    License or the Artistic License, as specified in the README file.
76
77  *
78  * Beware that some of this code is subtly aware of the way operator
79  * precedence is structured in regular expressions.  Serious changes in
80  * regular-expression syntax might require a total rethink.
81  */
82 #include "EXTERN.h"
83 #define PERL_IN_REGCOMP_C
84 #include "perl.h"
85
86 #ifdef PERL_IN_XSUB_RE
87 #  if defined(PERL_CAPI) || defined(PERL_OBJECT)
88 #    include "XSUB.h"
89 #  endif
90 #else
91 #  include "INTERN.h"
92 #endif
93
94 #define REG_COMP_C
95 #include "regcomp.h"
96
97 #ifdef op
98 #undef op
99 #endif /* op */
100
101 #ifdef MSDOS
102 # if defined(BUGGY_MSC6)
103  /* MSC 6.00A breaks on op/regexp.t test 85 unless we turn this off */
104  # pragma optimize("a",off)
105  /* But MSC 6.00A is happy with 'w', for aliases only across function calls*/
106  # pragma optimize("w",on )
107 # endif /* BUGGY_MSC6 */
108 #endif /* MSDOS */
109
110 #ifndef STATIC
111 #define STATIC  static
112 #endif
113
114 #define ISMULT1(c)      ((c) == '*' || (c) == '+' || (c) == '?')
115 #define ISMULT2(s)      ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
116         ((*s) == '{' && regcurly(s)))
117 #ifdef atarist
118 #define PERL_META       "^$.[()|?+*\\"
119 #else
120 #define META    "^$.[()|?+*\\"
121 #endif
122
123 #ifdef SPSTART
124 #undef SPSTART          /* dratted cpp namespace... */
125 #endif
126 /*
127  * Flags to be passed up and down.
128  */
129 #define WORST           0       /* Worst case. */
130 #define HASWIDTH        0x1     /* Known to match non-null strings. */
131 #define SIMPLE          0x2     /* Simple enough to be STAR/PLUS operand. */
132 #define SPSTART         0x4     /* Starts with * or +. */
133 #define TRYAGAIN        0x8     /* Weeded out a declaration. */
134
135 /* Length of a variant. */
136
137 typedef struct scan_data_t {
138     I32 len_min;
139     I32 len_delta;
140     I32 pos_min;
141     I32 pos_delta;
142     SV *last_found;
143     I32 last_end;                       /* min value, <0 unless valid. */
144     I32 last_start_min;
145     I32 last_start_max;
146     SV **longest;                       /* Either &l_fixed, or &l_float. */
147     SV *longest_fixed;
148     I32 offset_fixed;
149     SV *longest_float;
150     I32 offset_float_min;
151     I32 offset_float_max;
152     I32 flags;
153     I32 whilem_c;
154 } scan_data_t;
155
156 /*
157  * Forward declarations for pregcomp()'s friends.
158  */
159
160 static scan_data_t zero_scan_data = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
161                                       0, 0, 0, 0 };
162
163 #define SF_BEFORE_EOL           (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
164 #define SF_BEFORE_SEOL          0x1
165 #define SF_BEFORE_MEOL          0x2
166 #define SF_FIX_BEFORE_EOL       (SF_FIX_BEFORE_SEOL|SF_FIX_BEFORE_MEOL)
167 #define SF_FL_BEFORE_EOL        (SF_FL_BEFORE_SEOL|SF_FL_BEFORE_MEOL)
168
169 #ifdef NO_UNARY_PLUS
170 #  define SF_FIX_SHIFT_EOL      (0+2)
171 #  define SF_FL_SHIFT_EOL               (0+4)
172 #else
173 #  define SF_FIX_SHIFT_EOL      (+2)
174 #  define SF_FL_SHIFT_EOL               (+4)
175 #endif
176
177 #define SF_FIX_BEFORE_SEOL      (SF_BEFORE_SEOL << SF_FIX_SHIFT_EOL)
178 #define SF_FIX_BEFORE_MEOL      (SF_BEFORE_MEOL << SF_FIX_SHIFT_EOL)
179
180 #define SF_FL_BEFORE_SEOL       (SF_BEFORE_SEOL << SF_FL_SHIFT_EOL)
181 #define SF_FL_BEFORE_MEOL       (SF_BEFORE_MEOL << SF_FL_SHIFT_EOL) /* 0x20 */
182 #define SF_IS_INF               0x40
183 #define SF_HAS_PAR              0x80
184 #define SF_IN_PAR               0x100
185 #define SF_HAS_EVAL             0x200
186 #define SCF_DO_SUBSTR           0x400
187
188 #define RF_utf8         8
189 #define UTF (PL_reg_flags & RF_utf8)
190 #define LOC (PL_regflags & PMf_LOCALE)
191 #define FOLD (PL_regflags & PMf_FOLD)
192
193 #define OOB_CHAR8               1234
194 #define OOB_UTF8                123456
195 #define OOB_NAMEDCLASS          -1
196
197 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
198 #define CHR_DIST(a,b) (UTF ? utf8_distance(a,b) : a - b)
199
200 /* Allow for side effects in s */
201 #define REGC(c,s) STMT_START { if (!SIZE_ONLY) *(s) = (c); else (s);} STMT_END
202
203 static void clear_re(pTHXo_ void *r);
204
205 STATIC void
206 S_scan_commit(pTHX_ scan_data_t *data)
207 {
208     dTHR;
209     STRLEN l = CHR_SVLEN(data->last_found);
210     STRLEN old_l = CHR_SVLEN(*data->longest);
211     
212     if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
213         sv_setsv(*data->longest, data->last_found);
214         if (*data->longest == data->longest_fixed) {
215             data->offset_fixed = l ? data->last_start_min : data->pos_min;
216             if (data->flags & SF_BEFORE_EOL)
217                 data->flags 
218                     |= ((data->flags & SF_BEFORE_EOL) << SF_FIX_SHIFT_EOL);
219             else
220                 data->flags &= ~SF_FIX_BEFORE_EOL;
221         }
222         else {
223             data->offset_float_min = l ? data->last_start_min : data->pos_min;
224             data->offset_float_max = (l 
225                                       ? data->last_start_max 
226                                       : data->pos_min + data->pos_delta);
227             if (data->flags & SF_BEFORE_EOL)
228                 data->flags 
229                     |= ((data->flags & SF_BEFORE_EOL) << SF_FL_SHIFT_EOL);
230             else
231                 data->flags &= ~SF_FL_BEFORE_EOL;
232         }
233     }
234     SvCUR_set(data->last_found, 0);
235     data->last_end = -1;
236     data->flags &= ~SF_BEFORE_EOL;
237 }
238
239 /* Stops at toplevel WHILEM as well as at `last'. At end *scanp is set
240    to the position after last scanned or to NULL. */
241
242 STATIC I32
243 S_study_chunk(pTHX_ regnode **scanp, I32 *deltap, regnode *last, scan_data_t *data, U32 flags)
244                         /* scanp: Start here (read-write). */
245                         /* deltap: Write maxlen-minlen here. */
246                         /* last: Stop before this one. */
247 {
248     dTHR;
249     I32 min = 0, pars = 0, code;
250     regnode *scan = *scanp, *next;
251     I32 delta = 0;
252     int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
253     int is_inf_internal = 0;            /* The studied chunk is infinite */
254     I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
255     scan_data_t data_fake;
256     
257     while (scan && OP(scan) != END && scan < last) {
258         /* Peephole optimizer: */
259
260         if (PL_regkind[(U8)OP(scan)] == EXACT) {
261             regnode *n = regnext(scan);
262             U32 stringok = 1;
263 #ifdef DEBUGGING
264             regnode *stop = scan;
265 #endif 
266
267             next = scan + NODE_SZ_STR(scan);
268             /* Skip NOTHING, merge EXACT*. */
269             while (n &&
270                    ( PL_regkind[(U8)OP(n)] == NOTHING || 
271                      (stringok && (OP(n) == OP(scan))))
272                    && NEXT_OFF(n)
273                    && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX) {
274                 if (OP(n) == TAIL || n > next)
275                     stringok = 0;
276                 if (PL_regkind[(U8)OP(n)] == NOTHING) {
277                     NEXT_OFF(scan) += NEXT_OFF(n);
278                     next = n + NODE_STEP_REGNODE;
279 #ifdef DEBUGGING
280                     if (stringok)
281                         stop = n;
282 #endif 
283                     n = regnext(n);
284                 }
285                 else {
286                     int oldl = STR_LEN(scan);
287                     regnode *nnext = regnext(n);
288                     
289                     if (oldl + STR_LEN(n) > U8_MAX) 
290                         break;
291                     NEXT_OFF(scan) += NEXT_OFF(n);
292                     STR_LEN(scan) += STR_LEN(n);
293                     next = n + NODE_SZ_STR(n);
294                     /* Now we can overwrite *n : */
295                     Move(STRING(n), STRING(scan) + oldl,
296                          STR_LEN(n), char);
297 #ifdef DEBUGGING
298                     if (stringok)
299                         stop = next - 1;
300 #endif 
301                     n = nnext;
302                 }
303             }
304 #ifdef DEBUGGING
305             /* Allow dumping */
306             n = scan + NODE_SZ_STR(scan);
307             while (n <= stop) {
308                 /* Purify reports a benign UMR here sometimes, because we
309                  * don't initialize the OP() slot of a node when that node
310                  * is occupied by just the trailing null of the string in
311                  * an EXACT node */
312                 if (PL_regkind[(U8)OP(n)] != NOTHING || OP(n) == NOTHING) {
313                     OP(n) = OPTIMIZED;
314                     NEXT_OFF(n) = 0;
315                 }
316                 n++;
317             }
318 #endif 
319
320         }
321         if (OP(scan) != CURLYX) {
322             int max = (reg_off_by_arg[OP(scan)]
323                        ? I32_MAX
324                        /* I32 may be smaller than U16 on CRAYs! */
325                        : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
326             int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
327             int noff;
328             regnode *n = scan;
329             
330             /* Skip NOTHING and LONGJMP. */
331             while ((n = regnext(n))
332                    && ((PL_regkind[(U8)OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
333                        || ((OP(n) == LONGJMP) && (noff = ARG(n))))
334                    && off + noff < max)
335                 off += noff;
336             if (reg_off_by_arg[OP(scan)])
337                 ARG(scan) = off;
338             else 
339                 NEXT_OFF(scan) = off;
340         }
341         if (OP(scan) == BRANCH || OP(scan) == BRANCHJ 
342                    || OP(scan) == IFTHEN || OP(scan) == SUSPEND) {
343             next = regnext(scan);
344             code = OP(scan);
345             
346             if (OP(next) == code || code == IFTHEN || code == SUSPEND) { 
347                 I32 max1 = 0, min1 = I32_MAX, num = 0;
348                 
349                 if (flags & SCF_DO_SUBSTR)
350                     scan_commit(data);
351                 while (OP(scan) == code) {
352                     I32 deltanext, minnext;
353
354                     num++;
355                     data_fake.flags = 0;
356                     if (data)
357                         data_fake.whilem_c = data->whilem_c;
358                     next = regnext(scan);
359                     scan = NEXTOPER(scan);
360                     if (code != BRANCH)
361                         scan = NEXTOPER(scan);
362                     /* We suppose the run is continuous, last=next...*/
363                     minnext = study_chunk(&scan, &deltanext, next,
364                                           &data_fake, 0);
365                     if (min1 > minnext) 
366                         min1 = minnext;
367                     if (max1 < minnext + deltanext)
368                         max1 = minnext + deltanext;
369                     if (deltanext == I32_MAX)
370                         is_inf = is_inf_internal = 1;
371                     scan = next;
372                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
373                         pars++;
374                     if (data && (data_fake.flags & SF_HAS_EVAL))
375                         data->flags |= SF_HAS_EVAL;
376                     if (data)
377                         data->whilem_c = data_fake.whilem_c;
378                     if (code == SUSPEND) 
379                         break;
380                 }
381                 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
382                     min1 = 0;
383                 if (flags & SCF_DO_SUBSTR) {
384                     data->pos_min += min1;
385                     data->pos_delta += max1 - min1;
386                     if (max1 != min1 || is_inf)
387                         data->longest = &(data->longest_float);
388                 }
389                 min += min1;
390                 delta += max1 - min1;
391             }
392             else if (code == BRANCHJ)   /* single branch is optimized. */
393                 scan = NEXTOPER(NEXTOPER(scan));
394             else                        /* single branch is optimized. */
395                 scan = NEXTOPER(scan);
396             continue;
397         }
398         else if (OP(scan) == EXACT) {
399             I32 l = STR_LEN(scan);
400             if (UTF) {
401                 unsigned char *s = (unsigned char *)STRING(scan);
402                 unsigned char *e = s + l;
403                 I32 newl = 0;
404                 while (s < e) {
405                     newl++;
406                     s += UTF8SKIP(s);
407                 }
408                 l = newl;
409             }
410             min += l;
411             if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
412                 /* The code below prefers earlier match for fixed
413                    offset, later match for variable offset.  */
414                 if (data->last_end == -1) { /* Update the start info. */
415                     data->last_start_min = data->pos_min;
416                     data->last_start_max = is_inf
417                         ? I32_MAX : data->pos_min + data->pos_delta; 
418                 }
419                 sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));
420                 data->last_end = data->pos_min + l;
421                 data->pos_min += l; /* As in the first entry. */
422                 data->flags &= ~SF_BEFORE_EOL;
423             }
424         }
425         else if (PL_regkind[(U8)OP(scan)] == EXACT) {
426             I32 l = STR_LEN(scan);
427             if (flags & SCF_DO_SUBSTR) 
428                 scan_commit(data);
429             if (UTF) {
430                 unsigned char *s = (unsigned char *)STRING(scan);
431                 unsigned char *e = s + l;
432                 I32 newl = 0;
433                 while (s < e) {
434                     newl++;
435                     s += UTF8SKIP(s);
436                 }
437                 l = newl;
438             }
439             min += l;
440             if (data && (flags & SCF_DO_SUBSTR))
441                 data->pos_min += l;
442         }
443         else if (strchr((char*)PL_varies,OP(scan))) {
444             I32 mincount, maxcount, minnext, deltanext, pos_before, fl;
445             regnode *oscan = scan;
446             
447             switch (PL_regkind[(U8)OP(scan)]) {
448             case WHILEM:
449                 scan = NEXTOPER(scan);
450                 goto finish;
451             case PLUS:
452                 if (flags & SCF_DO_SUBSTR) {
453                     next = NEXTOPER(scan);
454                     if (OP(next) == EXACT) {
455                         mincount = 1; 
456                         maxcount = REG_INFTY; 
457                         next = regnext(scan);
458                         scan = NEXTOPER(scan);
459                         goto do_curly;
460                     }
461                 }
462                 if (flags & SCF_DO_SUBSTR)
463                     data->pos_min++;
464                 min++;
465                 /* Fall through. */
466             case STAR:
467                 is_inf = is_inf_internal = 1; 
468                 scan = regnext(scan);
469                 if (flags & SCF_DO_SUBSTR) {
470                     scan_commit(data);
471                     data->longest = &(data->longest_float);
472                 }
473                 goto optimize_curly_tail;
474             case CURLY:
475                 mincount = ARG1(scan); 
476                 maxcount = ARG2(scan);
477                 next = regnext(scan);
478                 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
479               do_curly:
480                 if (flags & SCF_DO_SUBSTR) {
481                     if (mincount == 0) scan_commit(data);
482                     pos_before = data->pos_min;
483                 }
484                 if (data) {
485                     fl = data->flags;
486                     data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
487                     if (is_inf)
488                         data->flags |= SF_IS_INF;
489                 }
490                 /* This will finish on WHILEM, setting scan, or on NULL: */
491                 minnext = study_chunk(&scan, &deltanext, last, data, 
492                                       mincount == 0 
493                                         ? (flags & ~SCF_DO_SUBSTR) : flags);
494                 if (!scan)              /* It was not CURLYX, but CURLY. */
495                     scan = next;
496                 if (ckWARN(WARN_UNSAFE) && (minnext + deltanext == 0) 
497                     && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
498                     && maxcount <= REG_INFTY/3) /* Complement check for big count */
499                     Perl_warner(aTHX_ WARN_UNSAFE,
500                                 "Strange *+?{} on zero-length expression");
501                 min += minnext * mincount;
502                 is_inf_internal |= (maxcount == REG_INFTY 
503                                     && (minnext + deltanext) > 0
504                                    || deltanext == I32_MAX);
505                 is_inf |= is_inf_internal;
506                 delta += (minnext + deltanext) * maxcount - minnext * mincount;
507
508                 /* Try powerful optimization CURLYX => CURLYN. */
509                 if (  OP(oscan) == CURLYX && data 
510                       && data->flags & SF_IN_PAR
511                       && !(data->flags & SF_HAS_EVAL)
512                       && !deltanext && minnext == 1 ) {
513                     /* Try to optimize to CURLYN.  */
514                     regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
515                     regnode *nxt1 = nxt, *nxt2;
516
517                     /* Skip open. */
518                     nxt = regnext(nxt);
519                     if (!strchr((char*)PL_simple,OP(nxt))
520                         && !(PL_regkind[(U8)OP(nxt)] == EXACT
521                              && STR_LEN(nxt) == 1)) 
522                         goto nogo;
523                     nxt2 = nxt;
524                     nxt = regnext(nxt);
525                     if (OP(nxt) != CLOSE) 
526                         goto nogo;
527                     /* Now we know that nxt2 is the only contents: */
528                     oscan->flags = ARG(nxt);
529                     OP(oscan) = CURLYN;
530                     OP(nxt1) = NOTHING; /* was OPEN. */
531 #ifdef DEBUGGING
532                     OP(nxt1 + 1) = OPTIMIZED; /* was count. */
533                     NEXT_OFF(nxt1+ 1) = 0; /* just for consistancy. */
534                     NEXT_OFF(nxt2) = 0; /* just for consistancy with CURLY. */
535                     OP(nxt) = OPTIMIZED;        /* was CLOSE. */
536                     OP(nxt + 1) = OPTIMIZED; /* was count. */
537                     NEXT_OFF(nxt+ 1) = 0; /* just for consistancy. */
538 #endif 
539                 }
540               nogo:
541
542                 /* Try optimization CURLYX => CURLYM. */
543                 if (  OP(oscan) == CURLYX && data 
544                       && !(data->flags & SF_HAS_PAR)
545                       && !(data->flags & SF_HAS_EVAL)
546                       && !deltanext  ) {
547                     /* XXXX How to optimize if data == 0? */
548                     /* Optimize to a simpler form.  */
549                     regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
550                     regnode *nxt2;
551
552                     OP(oscan) = CURLYM;
553                     while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
554                             && (OP(nxt2) != WHILEM)) 
555                         nxt = nxt2;
556                     OP(nxt2)  = SUCCEED; /* Whas WHILEM */
557                     /* Need to optimize away parenths. */
558                     if (data->flags & SF_IN_PAR) {
559                         /* Set the parenth number.  */
560                         regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
561
562                         if (OP(nxt) != CLOSE) 
563                             FAIL("panic opt close");
564                         oscan->flags = ARG(nxt);
565                         OP(nxt1) = OPTIMIZED;   /* was OPEN. */
566                         OP(nxt) = OPTIMIZED;    /* was CLOSE. */
567 #ifdef DEBUGGING
568                         OP(nxt1 + 1) = OPTIMIZED; /* was count. */
569                         OP(nxt + 1) = OPTIMIZED; /* was count. */
570                         NEXT_OFF(nxt1 + 1) = 0; /* just for consistancy. */
571                         NEXT_OFF(nxt + 1) = 0; /* just for consistancy. */
572 #endif 
573 #if 0
574                         while ( nxt1 && (OP(nxt1) != WHILEM)) {
575                             regnode *nnxt = regnext(nxt1);
576                             
577                             if (nnxt == nxt) {
578                                 if (reg_off_by_arg[OP(nxt1)])
579                                     ARG_SET(nxt1, nxt2 - nxt1);
580                                 else if (nxt2 - nxt1 < U16_MAX)
581                                     NEXT_OFF(nxt1) = nxt2 - nxt1;
582                                 else
583                                     OP(nxt) = NOTHING;  /* Cannot beautify */
584                             }
585                             nxt1 = nnxt;
586                         }
587 #endif
588                         /* Optimize again: */
589                         study_chunk(&nxt1, &deltanext, nxt, NULL, 0);
590                     }
591                     else
592                         oscan->flags = 0;
593                 }
594                 else if (OP(oscan) == CURLYX && data && ++data->whilem_c < 16) {
595                     /* This stays as CURLYX, and can put the count/of pair. */
596                     /* Find WHILEM (as in regexec.c) */
597                     regnode *nxt = oscan + NEXT_OFF(oscan);
598
599                     if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
600                         nxt += ARG(nxt);
601                     PREVOPER(nxt)->flags = data->whilem_c
602                         | (PL_reg_whilem_seen << 4); /* On WHILEM */
603                 }
604                 if (data && fl & (SF_HAS_PAR|SF_IN_PAR)) 
605                     pars++;
606                 if (flags & SCF_DO_SUBSTR) {
607                     SV *last_str = Nullsv;
608                     int counted = mincount != 0;
609
610                     if (data->last_end > 0 && mincount != 0) { /* Ends with a string. */
611                         I32 b = pos_before >= data->last_start_min 
612                             ? pos_before : data->last_start_min;
613                         STRLEN l;
614                         char *s = SvPV(data->last_found, l);
615                         I32 old = b - data->last_start_min;
616
617                         if (UTF)
618                             old = utf8_hop((U8*)s, old) - (U8*)s;
619                         
620                         l -= old;
621                         /* Get the added string: */
622                         last_str = newSVpvn(s  + old, l);
623                         if (deltanext == 0 && pos_before == b) {
624                             /* What was added is a constant string */
625                             if (mincount > 1) {
626                                 SvGROW(last_str, (mincount * l) + 1);
627                                 repeatcpy(SvPVX(last_str) + l, 
628                                           SvPVX(last_str), l, mincount - 1);
629                                 SvCUR(last_str) *= mincount;
630                                 /* Add additional parts. */
631                                 SvCUR_set(data->last_found, 
632                                           SvCUR(data->last_found) - l);
633                                 sv_catsv(data->last_found, last_str);
634                                 data->last_end += l * (mincount - 1);
635                             }
636                         }
637                     }
638                     /* It is counted once already... */
639                     data->pos_min += minnext * (mincount - counted);
640                     data->pos_delta += - counted * deltanext +
641                         (minnext + deltanext) * maxcount - minnext * mincount;
642                     if (mincount != maxcount) {
643                         scan_commit(data);
644                         if (mincount && last_str) {
645                             sv_setsv(data->last_found, last_str);
646                             data->last_end = data->pos_min;
647                             data->last_start_min = 
648                                 data->pos_min - CHR_SVLEN(last_str);
649                             data->last_start_max = is_inf 
650                                 ? I32_MAX 
651                                 : data->pos_min + data->pos_delta
652                                 - CHR_SVLEN(last_str);
653                         }
654                         data->longest = &(data->longest_float);
655                     }
656                     SvREFCNT_dec(last_str);
657                 }
658                 if (data && (fl & SF_HAS_EVAL))
659                     data->flags |= SF_HAS_EVAL;
660               optimize_curly_tail:
661                 if (OP(oscan) != CURLYX) {
662                     while (PL_regkind[(U8)OP(next = regnext(oscan))] == NOTHING
663                            && NEXT_OFF(next))
664                         NEXT_OFF(oscan) += NEXT_OFF(next);
665                 }
666                 continue;
667             default:                    /* REF only? */
668                 if (flags & SCF_DO_SUBSTR) {
669                     scan_commit(data);
670                     data->longest = &(data->longest_float);
671                 }
672                 is_inf = is_inf_internal = 1;
673                 break;
674             }
675         }
676         else if (strchr((char*)PL_simple,OP(scan)) || PL_regkind[(U8)OP(scan)] == ANYUTF8) {
677             if (flags & SCF_DO_SUBSTR) {
678                 scan_commit(data);
679                 data->pos_min++;
680             }
681             min++;
682         }
683         else if (PL_regkind[(U8)OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
684             data->flags |= (OP(scan) == MEOL
685                             ? SF_BEFORE_MEOL
686                             : SF_BEFORE_SEOL);
687         }
688         else if (PL_regkind[(U8)OP(scan)] == BRANCHJ
689                    && (scan->flags || data)
690                    && (OP(scan) == IFMATCH || OP(scan) == UNLESSM)) {
691             I32 deltanext, minnext;
692             regnode *nscan;
693
694             data_fake.flags = 0;
695             if (data)
696                 data_fake.whilem_c = data->whilem_c;
697             next = regnext(scan);
698             nscan = NEXTOPER(NEXTOPER(scan));
699             minnext = study_chunk(&nscan, &deltanext, last, &data_fake, 0);
700             if (scan->flags) {
701                 if (deltanext) {
702                     FAIL("variable length lookbehind not implemented");
703                 }
704                 else if (minnext > U8_MAX) {
705                     FAIL2("lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
706                 }
707                 scan->flags = minnext;
708             }
709             if (data && data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
710                 pars++;
711             if (data && (data_fake.flags & SF_HAS_EVAL))
712                 data->flags |= SF_HAS_EVAL;
713             if (data)
714                 data->whilem_c = data_fake.whilem_c;
715         }
716         else if (OP(scan) == OPEN) {
717             pars++;
718         }
719         else if (OP(scan) == CLOSE && ARG(scan) == is_par) {
720             next = regnext(scan);
721
722             if ( next && (OP(next) != WHILEM) && next < last)
723                 is_par = 0;             /* Disable optimization */
724         }
725         else if (OP(scan) == EVAL) {
726                 if (data)
727                     data->flags |= SF_HAS_EVAL;
728         }
729         else if (OP(scan) == LOGICAL && scan->flags == 2) { /* Embedded */
730                 if (flags & SCF_DO_SUBSTR) {
731                     scan_commit(data);
732                     data->longest = &(data->longest_float);
733                 }
734                 is_inf = is_inf_internal = 1;
735         }
736         /* Else: zero-length, ignore. */
737         scan = regnext(scan);
738     }
739
740   finish:
741     *scanp = scan;
742     *deltap = is_inf_internal ? I32_MAX : delta;
743     if (flags & SCF_DO_SUBSTR && is_inf) 
744         data->pos_delta = I32_MAX - data->pos_min;
745     if (is_par > U8_MAX)
746         is_par = 0;
747     if (is_par && pars==1 && data) {
748         data->flags |= SF_IN_PAR;
749         data->flags &= ~SF_HAS_PAR;
750     }
751     else if (pars && data) {
752         data->flags |= SF_HAS_PAR;
753         data->flags &= ~SF_IN_PAR;
754     }
755     return min;
756 }
757
758 STATIC I32
759 S_add_data(pTHX_ I32 n, char *s)
760 {
761     dTHR;
762     if (PL_regcomp_rx->data) {
763         Renewc(PL_regcomp_rx->data, 
764                sizeof(*PL_regcomp_rx->data) + sizeof(void*) * (PL_regcomp_rx->data->count + n - 1), 
765                char, struct reg_data);
766         Renew(PL_regcomp_rx->data->what, PL_regcomp_rx->data->count + n, U8);
767         PL_regcomp_rx->data->count += n;
768     }
769     else {
770         Newc(1207, PL_regcomp_rx->data, sizeof(*PL_regcomp_rx->data) + sizeof(void*) * (n - 1),
771              char, struct reg_data);
772         New(1208, PL_regcomp_rx->data->what, n, U8);
773         PL_regcomp_rx->data->count = n;
774     }
775     Copy(s, PL_regcomp_rx->data->what + PL_regcomp_rx->data->count - n, n, U8);
776     return PL_regcomp_rx->data->count - n;
777 }
778
779 void
780 Perl_reginitcolors(pTHX)
781 {
782     dTHR;
783     int i = 0;
784     char *s = PerlEnv_getenv("PERL_RE_COLORS");
785             
786     if (s) {
787         PL_colors[0] = s = savepv(s);
788         while (++i < 6) {
789             s = strchr(s, '\t');
790             if (s) {
791                 *s = '\0';
792                 PL_colors[i] = ++s;
793             }
794             else
795                 PL_colors[i] = s = "";
796         }
797     } else {
798         while (i < 6) 
799             PL_colors[i++] = "";
800     }
801     PL_colorset = 1;
802 }
803
804 /*
805  - pregcomp - compile a regular expression into internal code
806  *
807  * We can't allocate space until we know how big the compiled form will be,
808  * but we can't compile it (and thus know how big it is) until we've got a
809  * place to put the code.  So we cheat:  we compile it twice, once with code
810  * generation turned off and size counting turned on, and once "for real".
811  * This also means that we don't allocate space until we are sure that the
812  * thing really will compile successfully, and we never have to move the
813  * code and thus invalidate pointers into it.  (Note that it has to be in
814  * one piece because free() must be able to free it all.) [NB: not true in perl]
815  *
816  * Beware that the optimization-preparation code in here knows about some
817  * of the structure of the compiled regexp.  [I'll say.]
818  */
819 regexp *
820 Perl_pregcomp(pTHX_ char *exp, char *xend, PMOP *pm)
821 {
822     dTHR;
823     register regexp *r;
824     regnode *scan;
825     SV **longest;
826     SV *longest_fixed;
827     SV *longest_float;
828     regnode *first;
829     I32 flags;
830     I32 minlen = 0;
831     I32 sawplus = 0;
832     I32 sawopen = 0;
833     scan_data_t data;
834
835     if (exp == NULL)
836         FAIL("NULL regexp argument");
837
838     if (PL_curcop == &PL_compiling ? (PL_hints & HINT_UTF8) : IN_UTF8)
839         PL_reg_flags |= RF_utf8;
840     else
841         PL_reg_flags = 0;
842
843     PL_regprecomp = savepvn(exp, xend - exp);
844     DEBUG_r(if (!PL_colorset) reginitcolors());
845     DEBUG_r(PerlIO_printf(Perl_debug_log, "%sCompiling REx%s `%s%*s%s'\n",
846                       PL_colors[4],PL_colors[5],PL_colors[0],
847                       xend - exp, PL_regprecomp, PL_colors[1]));
848     PL_regflags = pm->op_pmflags;
849     PL_regsawback = 0;
850
851     PL_regseen = 0;
852     PL_seen_zerolen = *exp == '^' ? -1 : 0;
853     PL_seen_evals = 0;
854     PL_extralen = 0;
855
856     /* First pass: determine size, legality. */
857     PL_regcomp_parse = exp;
858     PL_regxend = xend;
859     PL_regnaughty = 0;
860     PL_regnpar = 1;
861     PL_regsize = 0L;
862     PL_regcode = &PL_regdummy;
863     PL_reg_whilem_seen = 0;
864     REGC((U8)REG_MAGIC, (char*)PL_regcode);
865     if (reg(0, &flags) == NULL) {
866         Safefree(PL_regprecomp);
867         PL_regprecomp = Nullch;
868         return(NULL);
869     }
870     DEBUG_r(PerlIO_printf(Perl_debug_log, "size %d ", PL_regsize));
871
872     /* Small enough for pointer-storage convention?
873        If extralen==0, this means that we will not need long jumps. */
874     if (PL_regsize >= 0x10000L && PL_extralen)
875         PL_regsize += PL_extralen;
876     else
877         PL_extralen = 0;
878     if (PL_reg_whilem_seen > 15)
879         PL_reg_whilem_seen = 15;
880
881     /* Allocate space and initialize. */
882     Newc(1001, r, sizeof(regexp) + (unsigned)PL_regsize * sizeof(regnode),
883          char, regexp);
884     if (r == NULL)
885         FAIL("regexp out of space");
886     r->refcnt = 1;
887     r->prelen = xend - exp;
888     r->precomp = PL_regprecomp;
889     r->subbeg = NULL;
890     r->reganch = pm->op_pmflags & PMf_COMPILETIME;
891     r->nparens = PL_regnpar - 1;        /* set early to validate backrefs */
892
893     r->substrs = 0;                     /* Useful during FAIL. */
894     r->startp = 0;                      /* Useful during FAIL. */
895     r->endp = 0;                        /* Useful during FAIL. */
896
897     PL_regcomp_rx = r;
898
899     /* Second pass: emit code. */
900     PL_regcomp_parse = exp;
901     PL_regxend = xend;
902     PL_regnaughty = 0;
903     PL_regnpar = 1;
904     PL_regcode = r->program;
905     /* Store the count of eval-groups for security checks: */
906     PL_regcode->next_off = ((PL_seen_evals > U16_MAX) ? U16_MAX : PL_seen_evals);
907     REGC((U8)REG_MAGIC, (char*) PL_regcode++);
908     r->data = 0;
909     if (reg(0, &flags) == NULL)
910         return(NULL);
911
912     /* Dig out information for optimizations. */
913     r->reganch = pm->op_pmflags & PMf_COMPILETIME; /* Again? */
914     pm->op_pmflags = PL_regflags;
915     if (UTF)
916         r->reganch |= ROPT_UTF8;
917     r->regstclass = NULL;
918     if (PL_regnaughty >= 10)    /* Probably an expensive pattern. */
919         r->reganch |= ROPT_NAUGHTY;
920     scan = r->program + 1;              /* First BRANCH. */
921
922     /* XXXX To minimize changes to RE engine we always allocate
923        3-units-long substrs field. */
924     Newz(1004, r->substrs, 1, struct reg_substr_data);
925
926     StructCopy(&zero_scan_data, &data, scan_data_t);
927     if (OP(scan) != BRANCH) {   /* Only one top-level choice. */
928         I32 fake;
929         STRLEN longest_float_length, longest_fixed_length;
930
931         first = scan;
932         /* Skip introductions and multiplicators >= 1. */
933         while ((OP(first) == OPEN && (sawopen = 1)) ||
934             (OP(first) == BRANCH && OP(regnext(first)) != BRANCH) ||
935             (OP(first) == PLUS) ||
936             (OP(first) == MINMOD) ||
937             (PL_regkind[(U8)OP(first)] == CURLY && ARG1(first) > 0) ) {
938                 if (OP(first) == PLUS)
939                     sawplus = 1;
940                 else
941                     first += regarglen[(U8)OP(first)];
942                 first = NEXTOPER(first);
943         }
944
945         /* Starting-point info. */
946       again:
947         if (OP(first) == EXACT);        /* Empty, get anchored substr later. */
948         else if (strchr((char*)PL_simple+4,OP(first)))
949             r->regstclass = first;
950         else if (PL_regkind[(U8)OP(first)] == BOUND ||
951                  PL_regkind[(U8)OP(first)] == NBOUND)
952             r->regstclass = first;
953         else if (PL_regkind[(U8)OP(first)] == BOL) {
954             r->reganch |= (OP(first) == MBOL
955                            ? ROPT_ANCH_MBOL
956                            : (OP(first) == SBOL
957                               ? ROPT_ANCH_SBOL
958                               : ROPT_ANCH_BOL));
959             first = NEXTOPER(first);
960             goto again;
961         }
962         else if (OP(first) == GPOS) {
963             r->reganch |= ROPT_ANCH_GPOS;
964             first = NEXTOPER(first);
965             goto again;
966         }
967         else if ((OP(first) == STAR &&
968             PL_regkind[(U8)OP(NEXTOPER(first))] == REG_ANY) &&
969             !(r->reganch & ROPT_ANCH) )
970         {
971             /* turn .* into ^.* with an implied $*=1 */
972             int type = OP(NEXTOPER(first));
973
974             if (type == REG_ANY || type == ANYUTF8)
975                 type = ROPT_ANCH_MBOL;
976             else
977                 type = ROPT_ANCH_SBOL;
978
979             r->reganch |= type | ROPT_IMPLICIT;
980             first = NEXTOPER(first);
981             goto again;
982         }
983         if (sawplus && (!sawopen || !PL_regsawback) 
984             && !(PL_regseen & REG_SEEN_EVAL)) /* May examine pos and $& */
985             /* x+ must match at the 1st pos of run of x's */
986             r->reganch |= ROPT_SKIP;
987
988         /* Scan is after the zeroth branch, first is atomic matcher. */
989         DEBUG_r(PerlIO_printf(Perl_debug_log, "first at %d\n", 
990                               first - scan + 1));
991         /*
992         * If there's something expensive in the r.e., find the
993         * longest literal string that must appear and make it the
994         * regmust.  Resolve ties in favor of later strings, since
995         * the regstart check works with the beginning of the r.e.
996         * and avoiding duplication strengthens checking.  Not a
997         * strong reason, but sufficient in the absence of others.
998         * [Now we resolve ties in favor of the earlier string if
999         * it happens that c_offset_min has been invalidated, since the
1000         * earlier string may buy us something the later one won't.]
1001         */
1002         minlen = 0;
1003
1004         data.longest_fixed = newSVpvn("",0);
1005         data.longest_float = newSVpvn("",0);
1006         data.last_found = newSVpvn("",0);
1007         data.longest = &(data.longest_fixed);
1008         first = scan;
1009         
1010         minlen = study_chunk(&first, &fake, scan + PL_regsize, /* Up to end */
1011                              &data, SCF_DO_SUBSTR);
1012         if ( PL_regnpar == 1 && data.longest == &(data.longest_fixed)
1013              && data.last_start_min == 0 && data.last_end > 0 
1014              && !PL_seen_zerolen
1015              && (!(PL_regseen & REG_SEEN_GPOS) || (r->reganch & ROPT_ANCH_GPOS)))
1016             r->reganch |= ROPT_CHECK_ALL;
1017         scan_commit(&data);
1018         SvREFCNT_dec(data.last_found);
1019
1020         longest_float_length = CHR_SVLEN(data.longest_float);
1021         if (longest_float_length
1022             || (data.flags & SF_FL_BEFORE_EOL
1023                 && (!(data.flags & SF_FL_BEFORE_MEOL)
1024                     || (PL_regflags & PMf_MULTILINE)))) {
1025             int t;
1026
1027             if (SvCUR(data.longest_fixed)                       /* ok to leave SvCUR */
1028                 && data.offset_fixed == data.offset_float_min
1029                 && SvCUR(data.longest_fixed) == SvCUR(data.longest_float))
1030                     goto remove_float;          /* As in (a)+. */
1031
1032             r->float_substr = data.longest_float;
1033             r->float_min_offset = data.offset_float_min;
1034             r->float_max_offset = data.offset_float_max;
1035             t = (data.flags & SF_FL_BEFORE_EOL /* Can't have SEOL and MULTI */
1036                        && (!(data.flags & SF_FL_BEFORE_MEOL)
1037                            || (PL_regflags & PMf_MULTILINE)));
1038             fbm_compile(r->float_substr, t ? FBMcf_TAIL : 0);
1039         }
1040         else {
1041           remove_float:
1042             r->float_substr = Nullsv;
1043             SvREFCNT_dec(data.longest_float);
1044             longest_float_length = 0;
1045         }
1046
1047         longest_fixed_length = CHR_SVLEN(data.longest_fixed);
1048         if (longest_fixed_length
1049             || (data.flags & SF_FIX_BEFORE_EOL /* Cannot have SEOL and MULTI */
1050                 && (!(data.flags & SF_FIX_BEFORE_MEOL)
1051                     || (PL_regflags & PMf_MULTILINE)))) {
1052             int t;
1053
1054             r->anchored_substr = data.longest_fixed;
1055             r->anchored_offset = data.offset_fixed;
1056             t = (data.flags & SF_FIX_BEFORE_EOL /* Can't have SEOL and MULTI */
1057                  && (!(data.flags & SF_FIX_BEFORE_MEOL)
1058                      || (PL_regflags & PMf_MULTILINE)));
1059             fbm_compile(r->anchored_substr, t ? FBMcf_TAIL : 0);
1060         }
1061         else {
1062             r->anchored_substr = Nullsv;
1063             SvREFCNT_dec(data.longest_fixed);
1064             longest_fixed_length = 0;
1065         }
1066
1067         /* A temporary algorithm prefers floated substr to fixed one to dig more info. */
1068         if (longest_fixed_length > longest_float_length) {
1069             r->check_substr = r->anchored_substr;
1070             r->check_offset_min = r->check_offset_max = r->anchored_offset;
1071             if (r->reganch & ROPT_ANCH_SINGLE)
1072                 r->reganch |= ROPT_NOSCAN;
1073         }
1074         else {
1075             r->check_substr = r->float_substr;
1076             r->check_offset_min = data.offset_float_min;
1077             r->check_offset_max = data.offset_float_max;
1078         }
1079         if (r->check_substr) {
1080             r->reganch |= RE_USE_INTUIT;
1081             if (SvTAIL(r->check_substr))
1082                 r->reganch |= RE_INTUIT_TAIL;
1083         }
1084     }
1085     else {
1086         /* Several toplevels. Best we can is to set minlen. */
1087         I32 fake;
1088         
1089         DEBUG_r(PerlIO_printf(Perl_debug_log, "\n"));
1090         scan = r->program + 1;
1091         minlen = study_chunk(&scan, &fake, scan + PL_regsize, &data, 0);
1092         r->check_substr = r->anchored_substr = r->float_substr = Nullsv;
1093     }
1094
1095     r->minlen = minlen;
1096     if (PL_regseen & REG_SEEN_GPOS) 
1097         r->reganch |= ROPT_GPOS_SEEN;
1098     if (PL_regseen & REG_SEEN_LOOKBEHIND)
1099         r->reganch |= ROPT_LOOKBEHIND_SEEN;
1100     if (PL_regseen & REG_SEEN_EVAL)
1101         r->reganch |= ROPT_EVAL_SEEN;
1102     Newz(1002, r->startp, PL_regnpar, I32);
1103     Newz(1002, r->endp, PL_regnpar, I32);
1104     DEBUG_r(regdump(r));
1105     return(r);
1106 }
1107
1108 /*
1109  - reg - regular expression, i.e. main body or parenthesized thing
1110  *
1111  * Caller must absorb opening parenthesis.
1112  *
1113  * Combining parenthesis handling with the base level of regular expression
1114  * is a trifle forced, but the need to tie the tails of the branches to what
1115  * follows makes it hard to avoid.
1116  */
1117 STATIC regnode *
1118 S_reg(pTHX_ I32 paren, I32 *flagp)
1119     /* paren: Parenthesized? 0=top, 1=(, inside: changed to letter. */
1120 {
1121     dTHR;
1122     register regnode *ret;              /* Will be the head of the group. */
1123     register regnode *br;
1124     register regnode *lastbr;
1125     register regnode *ender = 0;
1126     register I32 parno = 0;
1127     I32 flags, oregflags = PL_regflags, have_branch = 0, open = 0;
1128     char c;
1129
1130     *flagp = 0;                         /* Tentatively. */
1131
1132     /* Make an OPEN node, if parenthesized. */
1133     if (paren) {
1134         if (*PL_regcomp_parse == '?') {
1135             U16 posflags = 0, negflags = 0;
1136             U16 *flagsp = &posflags;
1137             int logical = 0;
1138
1139             PL_regcomp_parse++;
1140             paren = *PL_regcomp_parse++;
1141             ret = NULL;                 /* For look-ahead/behind. */
1142             switch (paren) {
1143             case '<':
1144                 PL_regseen |= REG_SEEN_LOOKBEHIND;
1145                 if (*PL_regcomp_parse == '!') 
1146                     paren = ',';
1147                 if (*PL_regcomp_parse != '=' && *PL_regcomp_parse != '!') 
1148                     goto unknown;
1149                 PL_regcomp_parse++;
1150             case '=':
1151             case '!':
1152                 PL_seen_zerolen++;
1153             case ':':
1154             case '>':
1155                 break;
1156             case '$':
1157             case '@':
1158                 FAIL2("Sequence (?%c...) not implemented", (int)paren);
1159                 break;
1160             case '#':
1161                 while (*PL_regcomp_parse && *PL_regcomp_parse != ')')
1162                     PL_regcomp_parse++;
1163                 if (*PL_regcomp_parse != ')')
1164                     FAIL("Sequence (?#... not terminated");
1165                 nextchar();
1166                 *flagp = TRYAGAIN;
1167                 return NULL;
1168             case 'p':
1169                 logical = 1;
1170                 paren = *PL_regcomp_parse++;
1171                 /* FALL THROUGH */
1172             case '{':
1173             {
1174                 dTHR;
1175                 I32 count = 1, n = 0;
1176                 char c;
1177                 char *s = PL_regcomp_parse;
1178                 SV *sv;
1179                 OP_4tree *sop, *rop;
1180
1181                 PL_seen_zerolen++;
1182                 PL_regseen |= REG_SEEN_EVAL;
1183                 while (count && (c = *PL_regcomp_parse)) {
1184                     if (c == '\\' && PL_regcomp_parse[1])
1185                         PL_regcomp_parse++;
1186                     else if (c == '{') 
1187                         count++;
1188                     else if (c == '}') 
1189                         count--;
1190                     PL_regcomp_parse++;
1191                 }
1192                 if (*PL_regcomp_parse != ')')
1193                     FAIL("Sequence (?{...}) not terminated or not {}-balanced");
1194                 if (!SIZE_ONLY) {
1195                     AV *av;
1196                     
1197                     if (PL_regcomp_parse - 1 - s) 
1198                         sv = newSVpvn(s, PL_regcomp_parse - 1 - s);
1199                     else
1200                         sv = newSVpvn("", 0);
1201
1202                     rop = sv_compile_2op(sv, &sop, "re", &av);
1203
1204                     n = add_data(3, "nop");
1205                     PL_regcomp_rx->data->data[n] = (void*)rop;
1206                     PL_regcomp_rx->data->data[n+1] = (void*)sop;
1207                     PL_regcomp_rx->data->data[n+2] = (void*)av;
1208                     SvREFCNT_dec(sv);
1209                 }
1210                 else {                                          /* First pass */
1211                     if (PL_reginterp_cnt < ++PL_seen_evals
1212                         && PL_curcop != &PL_compiling)
1213                         /* No compiled RE interpolated, has runtime
1214                            components ===> unsafe.  */
1215                         FAIL("Eval-group not allowed at runtime, use re 'eval'");
1216                     if (PL_tainted)
1217                         FAIL("Eval-group in insecure regular expression");
1218                 }
1219                 
1220                 nextchar();
1221                 if (logical) {
1222                     ret = reg_node(LOGICAL);
1223                     if (!SIZE_ONLY)
1224                         ret->flags = 2;
1225                     regtail(ret, reganode(EVAL, n));
1226                     return ret;
1227                 }
1228                 return reganode(EVAL, n);
1229             }
1230             case '(':
1231             {
1232                 if (PL_regcomp_parse[0] == '?') {
1233                     if (PL_regcomp_parse[1] == '=' || PL_regcomp_parse[1] == '!' 
1234                         || PL_regcomp_parse[1] == '<' 
1235                         || PL_regcomp_parse[1] == '{') { /* Lookahead or eval. */
1236                         I32 flag;
1237                         
1238                         ret = reg_node(LOGICAL);
1239                         if (!SIZE_ONLY)
1240                             ret->flags = 1;
1241                         regtail(ret, reg(1, &flag));
1242                         goto insert_if;
1243                     } 
1244                 }
1245                 else if (PL_regcomp_parse[0] >= '1' && PL_regcomp_parse[0] <= '9' ) {
1246                     parno = atoi(PL_regcomp_parse++);
1247
1248                     while (isDIGIT(*PL_regcomp_parse))
1249                         PL_regcomp_parse++;
1250                     ret = reganode(GROUPP, parno);
1251                     if ((c = *nextchar()) != ')')
1252                         FAIL2("Switch (?(number%c not recognized", c);
1253                   insert_if:
1254                     regtail(ret, reganode(IFTHEN, 0));
1255                     br = regbranch(&flags, 1);
1256                     if (br == NULL)
1257                         br = reganode(LONGJMP, 0);
1258                     else
1259                         regtail(br, reganode(LONGJMP, 0));
1260                     c = *nextchar();
1261                     if (flags&HASWIDTH)
1262                         *flagp |= HASWIDTH;
1263                     if (c == '|') {
1264                         lastbr = reganode(IFTHEN, 0); /* Fake one for optimizer. */
1265                         regbranch(&flags, 1);
1266                         regtail(ret, lastbr);
1267                         if (flags&HASWIDTH)
1268                             *flagp |= HASWIDTH;
1269                         c = *nextchar();
1270                     }
1271                     else
1272                         lastbr = NULL;
1273                     if (c != ')')
1274                         FAIL("Switch (?(condition)... contains too many branches");
1275                     ender = reg_node(TAIL);
1276                     regtail(br, ender);
1277                     if (lastbr) {
1278                         regtail(lastbr, ender);
1279                         regtail(NEXTOPER(NEXTOPER(lastbr)), ender);
1280                     }
1281                     else
1282                         regtail(ret, ender);
1283                     return ret;
1284                 }
1285                 else {
1286                     FAIL2("Unknown condition for (?(%.2s", PL_regcomp_parse);
1287                 }
1288             }
1289             case 0:
1290                 FAIL("Sequence (? incomplete");
1291                 break;
1292             default:
1293                 --PL_regcomp_parse;
1294               parse_flags:
1295                 while (*PL_regcomp_parse && strchr("iogcmsx", *PL_regcomp_parse)) {
1296                     if (*PL_regcomp_parse != 'o')
1297                         pmflag(flagsp, *PL_regcomp_parse);
1298                     ++PL_regcomp_parse;
1299                 }
1300                 if (*PL_regcomp_parse == '-') {
1301                     flagsp = &negflags;
1302                     ++PL_regcomp_parse;
1303                     goto parse_flags;
1304                 }
1305                 PL_regflags |= posflags;
1306                 PL_regflags &= ~negflags;
1307                 if (*PL_regcomp_parse == ':') {
1308                     PL_regcomp_parse++;
1309                     paren = ':';
1310                     break;
1311                 }               
1312               unknown:
1313                 if (*PL_regcomp_parse != ')')
1314                     FAIL2("Sequence (?%c...) not recognized", *PL_regcomp_parse);
1315                 nextchar();
1316                 *flagp = TRYAGAIN;
1317                 return NULL;
1318             }
1319         }
1320         else {
1321             parno = PL_regnpar;
1322             PL_regnpar++;
1323             ret = reganode(OPEN, parno);
1324             open = 1;
1325         }
1326     }
1327     else
1328         ret = NULL;
1329
1330     /* Pick up the branches, linking them together. */
1331     br = regbranch(&flags, 1);
1332     if (br == NULL)
1333         return(NULL);
1334     if (*PL_regcomp_parse == '|') {
1335         if (!SIZE_ONLY && PL_extralen) {
1336             reginsert(BRANCHJ, br);
1337         }
1338         else
1339             reginsert(BRANCH, br);
1340         have_branch = 1;
1341         if (SIZE_ONLY)
1342             PL_extralen += 1;           /* For BRANCHJ-BRANCH. */
1343     }
1344     else if (paren == ':') {
1345         *flagp |= flags&SIMPLE;
1346     }
1347     if (open) {                         /* Starts with OPEN. */
1348         regtail(ret, br);               /* OPEN -> first. */
1349     }
1350     else if (paren != '?')              /* Not Conditional */
1351         ret = br;
1352     if (flags&HASWIDTH)
1353         *flagp |= HASWIDTH;
1354     *flagp |= flags&SPSTART;
1355     lastbr = br;
1356     while (*PL_regcomp_parse == '|') {
1357         if (!SIZE_ONLY && PL_extralen) {
1358             ender = reganode(LONGJMP,0);
1359             regtail(NEXTOPER(NEXTOPER(lastbr)), ender); /* Append to the previous. */
1360         }
1361         if (SIZE_ONLY)
1362             PL_extralen += 2;           /* Account for LONGJMP. */
1363         nextchar();
1364         br = regbranch(&flags, 0);
1365         if (br == NULL)
1366             return(NULL);
1367         regtail(lastbr, br);            /* BRANCH -> BRANCH. */
1368         lastbr = br;
1369         if (flags&HASWIDTH)
1370             *flagp |= HASWIDTH;
1371         *flagp |= flags&SPSTART;
1372     }
1373
1374     if (have_branch || paren != ':') {
1375         /* Make a closing node, and hook it on the end. */
1376         switch (paren) {
1377         case ':':
1378             ender = reg_node(TAIL);
1379             break;
1380         case 1:
1381             ender = reganode(CLOSE, parno);
1382             break;
1383         case '<':
1384         case ',':
1385         case '=':
1386         case '!':
1387             *flagp &= ~HASWIDTH;
1388             /* FALL THROUGH */
1389         case '>':
1390             ender = reg_node(SUCCEED);
1391             break;
1392         case 0:
1393             ender = reg_node(END);
1394             break;
1395         }
1396         regtail(lastbr, ender);
1397
1398         if (have_branch) {
1399             /* Hook the tails of the branches to the closing node. */
1400             for (br = ret; br != NULL; br = regnext(br)) {
1401                 regoptail(br, ender);
1402             }
1403         }
1404     }
1405
1406     {
1407         char *p;
1408         static char parens[] = "=!<,>";
1409
1410         if (paren && (p = strchr(parens, paren))) {
1411             int node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
1412             int flag = (p - parens) > 1;
1413
1414             if (paren == '>')
1415                 node = SUSPEND, flag = 0;
1416             reginsert(node,ret);
1417             ret->flags = flag;
1418             regtail(ret, reg_node(TAIL));
1419         }
1420     }
1421
1422     /* Check for proper termination. */
1423     if (paren) {
1424         PL_regflags = oregflags;
1425         if (PL_regcomp_parse >= PL_regxend || *nextchar() != ')') {
1426             FAIL("unmatched () in regexp");
1427         }
1428     }
1429     else if (!paren && PL_regcomp_parse < PL_regxend) {
1430         if (*PL_regcomp_parse == ')') {
1431             FAIL("unmatched () in regexp");
1432         }
1433         else
1434             FAIL("junk on end of regexp");      /* "Can't happen". */
1435         /* NOTREACHED */
1436     }
1437
1438     return(ret);
1439 }
1440
1441 /*
1442  - regbranch - one alternative of an | operator
1443  *
1444  * Implements the concatenation operator.
1445  */
1446 STATIC regnode *
1447 S_regbranch(pTHX_ I32 *flagp, I32 first)
1448 {
1449     dTHR;
1450     register regnode *ret;
1451     register regnode *chain = NULL;
1452     register regnode *latest;
1453     I32 flags = 0, c = 0;
1454
1455     if (first) 
1456         ret = NULL;
1457     else {
1458         if (!SIZE_ONLY && PL_extralen) 
1459             ret = reganode(BRANCHJ,0);
1460         else
1461             ret = reg_node(BRANCH);
1462     }
1463         
1464     if (!first && SIZE_ONLY) 
1465         PL_extralen += 1;                       /* BRANCHJ */
1466     
1467     *flagp = WORST;                     /* Tentatively. */
1468
1469     PL_regcomp_parse--;
1470     nextchar();
1471     while (PL_regcomp_parse < PL_regxend && *PL_regcomp_parse != '|' && *PL_regcomp_parse != ')') {
1472         flags &= ~TRYAGAIN;
1473         latest = regpiece(&flags);
1474         if (latest == NULL) {
1475             if (flags & TRYAGAIN)
1476                 continue;
1477             return(NULL);
1478         }
1479         else if (ret == NULL)
1480             ret = latest;
1481         *flagp |= flags&HASWIDTH;
1482         if (chain == NULL)      /* First piece. */
1483             *flagp |= flags&SPSTART;
1484         else {
1485             PL_regnaughty++;
1486             regtail(chain, latest);
1487         }
1488         chain = latest;
1489         c++;
1490     }
1491     if (chain == NULL) {        /* Loop ran zero times. */
1492         chain = reg_node(NOTHING);
1493         if (ret == NULL)
1494             ret = chain;
1495     }
1496     if (c == 1) {
1497         *flagp |= flags&SIMPLE;
1498     }
1499
1500     return(ret);
1501 }
1502
1503 /*
1504  - regpiece - something followed by possible [*+?]
1505  *
1506  * Note that the branching code sequences used for ? and the general cases
1507  * of * and + are somewhat optimized:  they use the same NOTHING node as
1508  * both the endmarker for their branch list and the body of the last branch.
1509  * It might seem that this node could be dispensed with entirely, but the
1510  * endmarker role is not redundant.
1511  */
1512 STATIC regnode *
1513 S_regpiece(pTHX_ I32 *flagp)
1514 {
1515     dTHR;
1516     register regnode *ret;
1517     register char op;
1518     register char *next;
1519     I32 flags;
1520     char *origparse = PL_regcomp_parse;
1521     char *maxpos;
1522     I32 min;
1523     I32 max = REG_INFTY;
1524
1525     ret = regatom(&flags);
1526     if (ret == NULL) {
1527         if (flags & TRYAGAIN)
1528             *flagp |= TRYAGAIN;
1529         return(NULL);
1530     }
1531
1532     op = *PL_regcomp_parse;
1533
1534     if (op == '{' && regcurly(PL_regcomp_parse)) {
1535         next = PL_regcomp_parse + 1;
1536         maxpos = Nullch;
1537         while (isDIGIT(*next) || *next == ',') {
1538             if (*next == ',') {
1539                 if (maxpos)
1540                     break;
1541                 else
1542                     maxpos = next;
1543             }
1544             next++;
1545         }
1546         if (*next == '}') {             /* got one */
1547             if (!maxpos)
1548                 maxpos = next;
1549             PL_regcomp_parse++;
1550             min = atoi(PL_regcomp_parse);
1551             if (*maxpos == ',')
1552                 maxpos++;
1553             else
1554                 maxpos = PL_regcomp_parse;
1555             max = atoi(maxpos);
1556             if (!max && *maxpos != '0')
1557                 max = REG_INFTY;                /* meaning "infinity" */
1558             else if (max >= REG_INFTY)
1559                 FAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
1560             PL_regcomp_parse = next;
1561             nextchar();
1562
1563         do_curly:
1564             if ((flags&SIMPLE)) {
1565                 PL_regnaughty += 2 + PL_regnaughty / 2;
1566                 reginsert(CURLY, ret);
1567             }
1568             else {
1569                 regnode *w = reg_node(WHILEM);
1570
1571                 w->flags = 0;
1572                 regtail(ret, w);
1573                 if (!SIZE_ONLY && PL_extralen) {
1574                     reginsert(LONGJMP,ret);
1575                     reginsert(NOTHING,ret);
1576                     NEXT_OFF(ret) = 3;  /* Go over LONGJMP. */
1577                 }
1578                 reginsert(CURLYX,ret);
1579                 if (!SIZE_ONLY && PL_extralen)
1580                     NEXT_OFF(ret) = 3;  /* Go over NOTHING to LONGJMP. */
1581                 regtail(ret, reg_node(NOTHING));
1582                 if (SIZE_ONLY)
1583                     PL_reg_whilem_seen++, PL_extralen += 3;
1584                 PL_regnaughty += 4 + PL_regnaughty;     /* compound interest */
1585             }
1586             ret->flags = 0;
1587
1588             if (min > 0)
1589                 *flagp = WORST;
1590             if (max > 0)
1591                 *flagp |= HASWIDTH;
1592             if (max && max < min)
1593                 FAIL("Can't do {n,m} with n > m");
1594             if (!SIZE_ONLY) {
1595                 ARG1_SET(ret, min);
1596                 ARG2_SET(ret, max);
1597             }
1598
1599             goto nest_check;
1600         }
1601     }
1602
1603     if (!ISMULT1(op)) {
1604         *flagp = flags;
1605         return(ret);
1606     }
1607
1608 #if 0                           /* Now runtime fix should be reliable. */
1609     if (!(flags&HASWIDTH) && op != '?')
1610       FAIL("regexp *+ operand could be empty");
1611 #endif 
1612
1613     nextchar();
1614
1615     *flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
1616
1617     if (op == '*' && (flags&SIMPLE)) {
1618         reginsert(STAR, ret);
1619         ret->flags = 0;
1620         PL_regnaughty += 4;
1621     }
1622     else if (op == '*') {
1623         min = 0;
1624         goto do_curly;
1625     }
1626     else if (op == '+' && (flags&SIMPLE)) {
1627         reginsert(PLUS, ret);
1628         ret->flags = 0;
1629         PL_regnaughty += 3;
1630     }
1631     else if (op == '+') {
1632         min = 1;
1633         goto do_curly;
1634     }
1635     else if (op == '?') {
1636         min = 0; max = 1;
1637         goto do_curly;
1638     }
1639   nest_check:
1640     if (ckWARN(WARN_UNSAFE) && !SIZE_ONLY && !(flags&HASWIDTH) && max > REG_INFTY/3) {
1641         Perl_warner(aTHX_ WARN_UNSAFE, "%.*s matches null string many times",
1642             PL_regcomp_parse - origparse, origparse);
1643     }
1644
1645     if (*PL_regcomp_parse == '?') {
1646         nextchar();
1647         reginsert(MINMOD, ret);
1648         regtail(ret, ret + NODE_STEP_REGNODE);
1649     }
1650     if (ISMULT2(PL_regcomp_parse))
1651         FAIL("nested *?+ in regexp");
1652
1653     return(ret);
1654 }
1655
1656 /*
1657  - regatom - the lowest level
1658  *
1659  * Optimization:  gobbles an entire sequence of ordinary characters so that
1660  * it can turn them into a single node, which is smaller to store and
1661  * faster to run.  Backslashed characters are exceptions, each becoming a
1662  * separate node; the code is simpler that way and it's not worth fixing.
1663  *
1664  * [Yes, it is worth fixing, some scripts can run twice the speed.]
1665  */
1666 STATIC regnode *
1667 S_regatom(pTHX_ I32 *flagp)
1668 {
1669     dTHR;
1670     register regnode *ret = 0;
1671     I32 flags;
1672
1673     *flagp = WORST;             /* Tentatively. */
1674
1675 tryagain:
1676     switch (*PL_regcomp_parse) {
1677     case '^':
1678         PL_seen_zerolen++;
1679         nextchar();
1680         if (PL_regflags & PMf_MULTILINE)
1681             ret = reg_node(MBOL);
1682         else if (PL_regflags & PMf_SINGLELINE)
1683             ret = reg_node(SBOL);
1684         else
1685             ret = reg_node(BOL);
1686         break;
1687     case '$':
1688         if (PL_regcomp_parse[1]) 
1689             PL_seen_zerolen++;
1690         nextchar();
1691         if (PL_regflags & PMf_MULTILINE)
1692             ret = reg_node(MEOL);
1693         else if (PL_regflags & PMf_SINGLELINE)
1694             ret = reg_node(SEOL);
1695         else
1696             ret = reg_node(EOL);
1697         break;
1698     case '.':
1699         nextchar();
1700         if (UTF) {
1701             if (PL_regflags & PMf_SINGLELINE)
1702                 ret = reg_node(SANYUTF8);
1703             else
1704                 ret = reg_node(ANYUTF8);
1705             *flagp |= HASWIDTH;
1706         }
1707         else {
1708             if (PL_regflags & PMf_SINGLELINE)
1709                 ret = reg_node(SANY);
1710             else
1711                 ret = reg_node(REG_ANY);
1712             *flagp |= HASWIDTH|SIMPLE;
1713         }
1714         PL_regnaughty++;
1715         break;
1716     case '[':
1717         PL_regcomp_parse++;
1718         ret = (UTF ? regclassutf8() : regclass());
1719         if (*PL_regcomp_parse != ']')
1720             FAIL("unmatched [] in regexp");
1721         nextchar();
1722         *flagp |= HASWIDTH|SIMPLE;
1723         break;
1724     case '(':
1725         nextchar();
1726         ret = reg(1, &flags);
1727         if (ret == NULL) {
1728                 if (flags & TRYAGAIN)
1729                     goto tryagain;
1730                 return(NULL);
1731         }
1732         *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE);
1733         break;
1734     case '|':
1735     case ')':
1736         if (flags & TRYAGAIN) {
1737             *flagp |= TRYAGAIN;
1738             return NULL;
1739         }
1740         FAIL2("internal urp in regexp at /%s/", PL_regcomp_parse);
1741                                 /* Supposed to be caught earlier. */
1742         break;
1743     case '{':
1744         if (!regcurly(PL_regcomp_parse)) {
1745             PL_regcomp_parse++;
1746             goto defchar;
1747         }
1748         /* FALL THROUGH */
1749     case '?':
1750     case '+':
1751     case '*':
1752         FAIL("?+*{} follows nothing in regexp");
1753         break;
1754     case '\\':
1755         switch (*++PL_regcomp_parse) {
1756         case 'A':
1757             PL_seen_zerolen++;
1758             ret = reg_node(SBOL);
1759             *flagp |= SIMPLE;
1760             nextchar();
1761             break;
1762         case 'G':
1763             ret = reg_node(GPOS);
1764             PL_regseen |= REG_SEEN_GPOS;
1765             *flagp |= SIMPLE;
1766             nextchar();
1767             break;
1768         case 'Z':
1769             ret = reg_node(SEOL);
1770             *flagp |= SIMPLE;
1771             nextchar();
1772             break;
1773         case 'z':
1774             ret = reg_node(EOS);
1775             *flagp |= SIMPLE;
1776             PL_seen_zerolen++;          /* Do not optimize RE away */
1777             nextchar();
1778             break;
1779         case 'C':
1780             ret = reg_node(SANY);
1781             *flagp |= HASWIDTH|SIMPLE;
1782             nextchar();
1783             break;
1784         case 'X':
1785             ret = reg_node(CLUMP);
1786             *flagp |= HASWIDTH;
1787             nextchar();
1788             if (UTF && !PL_utf8_mark)
1789                 is_utf8_mark((U8*)"~");         /* preload table */
1790             break;
1791         case 'w':
1792             ret = reg_node(
1793                 UTF
1794                     ? (LOC ? ALNUMLUTF8 : ALNUMUTF8)
1795                     : (LOC ? ALNUML     : ALNUM));
1796             *flagp |= HASWIDTH|SIMPLE;
1797             nextchar();
1798             if (UTF && !PL_utf8_alnum)
1799                 is_utf8_alnum((U8*)"a");        /* preload table */
1800             break;
1801         case 'W':
1802             ret = reg_node(
1803                 UTF
1804                     ? (LOC ? NALNUMLUTF8 : NALNUMUTF8)
1805                     : (LOC ? NALNUML     : NALNUM));
1806             *flagp |= HASWIDTH|SIMPLE;
1807             nextchar();
1808             if (UTF && !PL_utf8_alnum)
1809                 is_utf8_alnum((U8*)"a");        /* preload table */
1810             break;
1811         case 'b':
1812             PL_seen_zerolen++;
1813             PL_regseen |= REG_SEEN_LOOKBEHIND;
1814             ret = reg_node(
1815                 UTF
1816                     ? (LOC ? BOUNDLUTF8 : BOUNDUTF8)
1817                     : (LOC ? BOUNDL     : BOUND));
1818             *flagp |= SIMPLE;
1819             nextchar();
1820             if (UTF && !PL_utf8_alnum)
1821                 is_utf8_alnum((U8*)"a");        /* preload table */
1822             break;
1823         case 'B':
1824             PL_seen_zerolen++;
1825             PL_regseen |= REG_SEEN_LOOKBEHIND;
1826             ret = reg_node(
1827                 UTF
1828                     ? (LOC ? NBOUNDLUTF8 : NBOUNDUTF8)
1829                     : (LOC ? NBOUNDL     : NBOUND));
1830             *flagp |= SIMPLE;
1831             nextchar();
1832             if (UTF && !PL_utf8_alnum)
1833                 is_utf8_alnum((U8*)"a");        /* preload table */
1834             break;
1835         case 's':
1836             ret = reg_node(
1837                 UTF
1838                     ? (LOC ? SPACELUTF8 : SPACEUTF8)
1839                     : (LOC ? SPACEL     : SPACE));
1840             *flagp |= HASWIDTH|SIMPLE;
1841             nextchar();
1842             if (UTF && !PL_utf8_space)
1843                 is_utf8_space((U8*)" ");        /* preload table */
1844             break;
1845         case 'S':
1846             ret = reg_node(
1847                 UTF
1848                     ? (LOC ? NSPACELUTF8 : NSPACEUTF8)
1849                     : (LOC ? NSPACEL     : NSPACE));
1850             *flagp |= HASWIDTH|SIMPLE;
1851             nextchar();
1852             if (UTF && !PL_utf8_space)
1853                 is_utf8_space((U8*)" ");        /* preload table */
1854             break;
1855         case 'd':
1856             ret = reg_node(UTF ? DIGITUTF8 : DIGIT);
1857             *flagp |= HASWIDTH|SIMPLE;
1858             nextchar();
1859             if (UTF && !PL_utf8_digit)
1860                 is_utf8_digit((U8*)"1");        /* preload table */
1861             break;
1862         case 'D':
1863             ret = reg_node(UTF ? NDIGITUTF8 : NDIGIT);
1864             *flagp |= HASWIDTH|SIMPLE;
1865             nextchar();
1866             if (UTF && !PL_utf8_digit)
1867                 is_utf8_digit((U8*)"1");        /* preload table */
1868             break;
1869         case 'p':
1870         case 'P':
1871             {   /* a lovely hack--pretend we saw [\pX] instead */
1872                 char* oldregxend = PL_regxend;
1873
1874                 if (PL_regcomp_parse[1] == '{') {
1875                     PL_regxend = strchr(PL_regcomp_parse, '}');
1876                     if (!PL_regxend)
1877                         FAIL("Missing right brace on \\p{}");
1878                     PL_regxend++;
1879                 }
1880                 else
1881                     PL_regxend = PL_regcomp_parse + 2;
1882                 PL_regcomp_parse--;
1883
1884                 ret = regclassutf8();
1885
1886                 PL_regxend = oldregxend;
1887                 PL_regcomp_parse--;
1888                 nextchar();
1889                 *flagp |= HASWIDTH|SIMPLE;
1890             }
1891             break;
1892         case 'n':
1893         case 'r':
1894         case 't':
1895         case 'f':
1896         case 'e':
1897         case 'a':
1898         case 'x':
1899         case 'c':
1900         case '0':
1901             goto defchar;
1902         case '1': case '2': case '3': case '4':
1903         case '5': case '6': case '7': case '8': case '9':
1904             {
1905                 I32 num = atoi(PL_regcomp_parse);
1906
1907                 if (num > 9 && num >= PL_regnpar)
1908                     goto defchar;
1909                 else {
1910                     if (!SIZE_ONLY && num > PL_regcomp_rx->nparens)
1911                         FAIL("reference to nonexistent group");
1912                     PL_regsawback = 1;
1913                     ret = reganode(FOLD
1914                                    ? (LOC ? REFFL : REFF)
1915                                    : REF, num);
1916                     *flagp |= HASWIDTH;
1917                     while (isDIGIT(*PL_regcomp_parse))
1918                         PL_regcomp_parse++;
1919                     PL_regcomp_parse--;
1920                     nextchar();
1921                 }
1922             }
1923             break;
1924         case '\0':
1925             if (PL_regcomp_parse >= PL_regxend)
1926                 FAIL("trailing \\ in regexp");
1927             /* FALL THROUGH */
1928         default:
1929             /* Do not generate `unrecognized' warnings here, we fall
1930                back into the quick-grab loop below */
1931             goto defchar;
1932         }
1933         break;
1934
1935     case '#':
1936         if (PL_regflags & PMf_EXTENDED) {
1937             while (PL_regcomp_parse < PL_regxend && *PL_regcomp_parse != '\n') PL_regcomp_parse++;
1938             if (PL_regcomp_parse < PL_regxend)
1939                 goto tryagain;
1940         }
1941         /* FALL THROUGH */
1942
1943     default: {
1944             register I32 len;
1945             register UV ender;
1946             register char *p;
1947             char *oldp, *s;
1948             I32 numlen;
1949
1950             PL_regcomp_parse++;
1951
1952         defchar:
1953             ret = reg_node(FOLD
1954                           ? (LOC ? EXACTFL : EXACTF)
1955                           : EXACT);
1956             s = STRING(ret);
1957             for (len = 0, p = PL_regcomp_parse - 1;
1958               len < 127 && p < PL_regxend;
1959               len++)
1960             {
1961                 oldp = p;
1962
1963                 if (PL_regflags & PMf_EXTENDED)
1964                     p = regwhite(p, PL_regxend);
1965                 switch (*p) {
1966                 case '^':
1967                 case '$':
1968                 case '.':
1969                 case '[':
1970                 case '(':
1971                 case ')':
1972                 case '|':
1973                     goto loopdone;
1974                 case '\\':
1975                     switch (*++p) {
1976                     case 'A':
1977                     case 'G':
1978                     case 'Z':
1979                     case 'z':
1980                     case 'w':
1981                     case 'W':
1982                     case 'b':
1983                     case 'B':
1984                     case 's':
1985                     case 'S':
1986                     case 'd':
1987                     case 'D':
1988                     case 'p':
1989                     case 'P':
1990                         --p;
1991                         goto loopdone;
1992                     case 'n':
1993                         ender = '\n';
1994                         p++;
1995                         break;
1996                     case 'r':
1997                         ender = '\r';
1998                         p++;
1999                         break;
2000                     case 't':
2001                         ender = '\t';
2002                         p++;
2003                         break;
2004                     case 'f':
2005                         ender = '\f';
2006                         p++;
2007                         break;
2008                     case 'e':
2009                         ender = '\033';
2010                         p++;
2011                         break;
2012                     case 'a':
2013                         ender = '\007';
2014                         p++;
2015                         break;
2016                     case 'x':
2017                         if (*++p == '{') {
2018                             char* e = strchr(p, '}');
2019          
2020                             if (!e)
2021                                 FAIL("Missing right brace on \\x{}");
2022                             else if (UTF) {
2023                                 ender = scan_hex(p + 1, e - p, &numlen);
2024                                 if (numlen + len >= 127) {      /* numlen is generous */
2025                                     p--;
2026                                     goto loopdone;
2027                                 }
2028                                 p = e + 1;
2029                             }
2030                             else
2031                                 FAIL("Can't use \\x{} without 'use utf8' declaration");
2032                         }
2033                         else {
2034                             ender = scan_hex(p, 2, &numlen);
2035                             p += numlen;
2036                         }
2037                         break;
2038                     case 'c':
2039                         p++;
2040                         ender = UCHARAT(p++);
2041                         ender = toCTRL(ender);
2042                         break;
2043                     case '0': case '1': case '2': case '3':case '4':
2044                     case '5': case '6': case '7': case '8':case '9':
2045                         if (*p == '0' ||
2046                           (isDIGIT(p[1]) && atoi(p) >= PL_regnpar) ) {
2047                             ender = scan_oct(p, 3, &numlen);
2048                             p += numlen;
2049                         }
2050                         else {
2051                             --p;
2052                             goto loopdone;
2053                         }
2054                         break;
2055                     case '\0':
2056                         if (p >= PL_regxend)
2057                             FAIL("trailing \\ in regexp");
2058                         /* FALL THROUGH */
2059                     default:
2060                         if (!SIZE_ONLY && ckWARN(WARN_UNSAFE) && isALPHA(*p))
2061                             Perl_warner(aTHX_ WARN_UNSAFE, 
2062                                    "/%.127s/: Unrecognized escape \\%c passed through",
2063                                    PL_regprecomp,
2064                                    *p);
2065                         goto normal_default;
2066                     }
2067                     break;
2068                 default:
2069                   normal_default:
2070                     if ((*p & 0xc0) == 0xc0 && UTF) {
2071                         ender = utf8_to_uv((U8*)p, &numlen);
2072                         p += numlen;
2073                     }
2074                     else
2075                         ender = *p++;
2076                     break;
2077                 }
2078                 if (PL_regflags & PMf_EXTENDED)
2079                     p = regwhite(p, PL_regxend);
2080                 if (UTF && FOLD) {
2081                     if (LOC)
2082                         ender = toLOWER_LC_uni(ender);
2083                     else
2084                         ender = toLOWER_uni(ender);
2085                 }
2086                 if (ISMULT2(p)) { /* Back off on ?+*. */
2087                     if (len)
2088                         p = oldp;
2089                     else if (ender >= 0x80 && UTF) {
2090                         reguni(ender, s, &numlen);
2091                         s += numlen;
2092                         len += numlen;
2093                     }
2094                     else {
2095                         len++;
2096                         REGC(ender, s++);
2097                     }
2098                     break;
2099                 }
2100                 if (ender >= 0x80 && UTF) {
2101                     reguni(ender, s, &numlen);
2102                     s += numlen;
2103                     len += numlen - 1;
2104                 }
2105                 else
2106                     REGC(ender, s++);
2107             }
2108         loopdone:
2109             PL_regcomp_parse = p - 1;
2110             nextchar();
2111             if (len < 0)
2112                 FAIL("internal disaster in regexp");
2113             if (len > 0)
2114                 *flagp |= HASWIDTH;
2115             if (len == 1)
2116                 *flagp |= SIMPLE;
2117             if (!SIZE_ONLY)
2118                 STR_LEN(ret) = len;
2119             if (SIZE_ONLY)
2120                 PL_regsize += STR_SZ(len);
2121             else
2122                 PL_regcode += STR_SZ(len);
2123         }
2124         break;
2125     }
2126
2127     return(ret);
2128 }
2129
2130 STATIC char *
2131 S_regwhite(pTHX_ char *p, char *e)
2132 {
2133     while (p < e) {
2134         if (isSPACE(*p))
2135             ++p;
2136         else if (*p == '#') {
2137             do {
2138                 p++;
2139             } while (p < e && *p != '\n');
2140         }
2141         else
2142             break;
2143     }
2144     return p;
2145 }
2146
2147 /* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
2148    Character classes ([:foo:]) can also be negated ([:^foo:]).
2149    Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
2150    Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
2151    but trigger warnings because they are currently unimplemented. */
2152 STATIC I32
2153 S_regpposixcc(pTHX_ I32 value)
2154 {
2155     dTHR;
2156     char *posixcc = 0;
2157     I32 namedclass = -1;
2158
2159     if (value == '[' && PL_regcomp_parse + 1 < PL_regxend &&
2160         /* I smell either [: or [= or [. -- POSIX has been here, right? */
2161         (*PL_regcomp_parse == ':' ||
2162          *PL_regcomp_parse == '=' ||
2163          *PL_regcomp_parse == '.')) {
2164         char  c = *PL_regcomp_parse;
2165         char* s = PL_regcomp_parse++;
2166             
2167         while (PL_regcomp_parse < PL_regxend && *PL_regcomp_parse != c)
2168             PL_regcomp_parse++;
2169         if (PL_regcomp_parse == PL_regxend)
2170             /* Grandfather lone [:, [=, [. */
2171             PL_regcomp_parse = s;
2172         else {
2173             char* t = PL_regcomp_parse++; /* skip over the c */
2174
2175             if (*PL_regcomp_parse == ']') {
2176                 PL_regcomp_parse++; /* skip over the ending ] */
2177                 posixcc = s + 1;
2178                 if (*s == ':') {
2179                     I32 complement = *posixcc == '^' ? *posixcc++ : 0;
2180                     I32 skip = 5; /* the most common skip */
2181
2182                     switch (*posixcc) {
2183                     case 'a':
2184                         if (strnEQ(posixcc, "alnum", 5))
2185                             namedclass =
2186                                 complement ? ANYOF_NALNUMC : ANYOF_ALNUMC;
2187                         else if (strnEQ(posixcc, "alpha", 5))
2188                             namedclass =
2189                                 complement ? ANYOF_NALPHA : ANYOF_ALPHA;
2190                         else if (strnEQ(posixcc, "ascii", 5))
2191                             namedclass =
2192                                 complement ? ANYOF_NASCII : ANYOF_ASCII;
2193                         break;
2194                     case 'c':
2195                         if (strnEQ(posixcc, "cntrl", 5))
2196                             namedclass =
2197                                 complement ? ANYOF_NCNTRL : ANYOF_CNTRL;
2198                         break;
2199                     case 'd':
2200                         if (strnEQ(posixcc, "digit", 5))
2201                             namedclass =
2202                                 complement ? ANYOF_NDIGIT : ANYOF_DIGIT;
2203                         break;
2204                     case 'g':
2205                         if (strnEQ(posixcc, "graph", 5))
2206                             namedclass =
2207                                 complement ? ANYOF_NGRAPH : ANYOF_GRAPH;
2208                         break;
2209                     case 'l':
2210                         if (strnEQ(posixcc, "lower", 5))
2211                             namedclass =
2212                                 complement ? ANYOF_NLOWER : ANYOF_LOWER;
2213                         break;
2214                     case 'p':
2215                         if (strnEQ(posixcc, "print", 5))
2216                             namedclass =
2217                                 complement ? ANYOF_NPRINT : ANYOF_PRINT;
2218                         else if (strnEQ(posixcc, "punct", 5))
2219                             namedclass =
2220                                 complement ? ANYOF_NPUNCT : ANYOF_PUNCT;
2221                         break;
2222                     case 's':
2223                         if (strnEQ(posixcc, "space", 5))
2224                             namedclass =
2225                                 complement ? ANYOF_NSPACE : ANYOF_SPACE;
2226                     case 'u':
2227                         if (strnEQ(posixcc, "upper", 5))
2228                             namedclass =
2229                                 complement ? ANYOF_NUPPER : ANYOF_UPPER;
2230                         break;
2231                     case 'w': /* this is not POSIX, this is the Perl \w */
2232                         if (strnEQ(posixcc, "word", 4)) {
2233                             namedclass =
2234                                 complement ? ANYOF_NALNUM : ANYOF_ALNUM;
2235                             skip = 4;
2236                         }
2237                         break;
2238                     case 'x':
2239                         if (strnEQ(posixcc, "xdigit", 6)) {
2240                             namedclass =
2241                                 complement ? ANYOF_NXDIGIT : ANYOF_XDIGIT;
2242                             skip = 6;
2243                         }
2244                         break;
2245                     }
2246                     if ((namedclass == OOB_NAMEDCLASS ||
2247                          !(posixcc + skip + 2 < PL_regxend &&
2248                            (posixcc[skip] == ':' &&
2249                             posixcc[skip + 1] == ']'))))
2250                         Perl_croak(aTHX_ "Character class [:%.*s:] unknown",
2251                                    t - s - 1, s + 1); 
2252                 } else if (ckWARN(WARN_UNSAFE) && !SIZE_ONLY)
2253                     /* [[=foo=]] and [[.foo.]] are still future. */
2254                     Perl_warner(aTHX_ WARN_UNSAFE,
2255                                 "Character class syntax [%c %c] is reserved for future extensions", c, c);
2256             } else {
2257                 /* Maternal grandfather:
2258                  * "[:" ending in ":" but not in ":]" */
2259                 PL_regcomp_parse = s;
2260             }
2261         }
2262     }
2263
2264     return namedclass;
2265 }
2266
2267 STATIC void
2268 S_checkposixcc(pTHX)
2269 {
2270     if (ckWARN(WARN_UNSAFE) && !SIZE_ONLY &&
2271         (*PL_regcomp_parse == ':' ||
2272          *PL_regcomp_parse == '=' ||
2273          *PL_regcomp_parse == '.')) {
2274         char *s = PL_regcomp_parse;
2275         char  c = *s++;
2276
2277         while(*s && isALNUM(*s))
2278             s++;
2279         if (*s && c == *s && s[1] == ']') {
2280             Perl_warner(aTHX_ WARN_UNSAFE,
2281                         "Character class syntax [%c %c] belongs inside character classes", c, c);
2282             if (c == '=' || c == '.')
2283                 Perl_warner(aTHX_ WARN_UNSAFE,
2284                             "Character class syntax [%c %c] is reserved for future extensions", c, c);
2285         }
2286     }
2287 }
2288
2289 STATIC regnode *
2290 S_regclass(pTHX)
2291 {
2292     dTHR;
2293     register char *opnd, *s;
2294     register I32 value;
2295     register I32 lastvalue = OOB_CHAR8;
2296     register I32 range = 0;
2297     register regnode *ret;
2298     register I32 def;
2299     I32 numlen;
2300     I32 namedclass;
2301
2302     s = opnd = MASK(PL_regcode);
2303     ret = reg_node(ANYOF);
2304     for (value = 0; value < ANYOF_SIZE; value++)
2305         REGC(0, s++);
2306     if (*PL_regcomp_parse == '^') {     /* Complement of range. */
2307         PL_regnaughty++;
2308         PL_regcomp_parse++;
2309         if (!SIZE_ONLY)
2310             ANYOF_FLAGS(opnd) |= ANYOF_INVERT;
2311     }
2312     if (!SIZE_ONLY) {
2313         PL_regcode += ANY_SKIP;
2314         if (FOLD)
2315             ANYOF_FLAGS(opnd) |= ANYOF_FOLD;
2316         if (LOC)
2317             ANYOF_FLAGS(opnd) |= ANYOF_LOCALE;
2318     }
2319     else {
2320         PL_regsize += ANY_SKIP;
2321     }
2322
2323     checkposixcc();
2324
2325     if (*PL_regcomp_parse == ']' || *PL_regcomp_parse == '-')
2326         goto skipcond;          /* allow 1st char to be ] or - */
2327     while (PL_regcomp_parse < PL_regxend && *PL_regcomp_parse != ']') {
2328        skipcond:
2329         namedclass = OOB_NAMEDCLASS;
2330         value = UCHARAT(PL_regcomp_parse++);
2331         if (value == '[')
2332             namedclass = regpposixcc(value);
2333         else if (value == '\\') {
2334             value = UCHARAT(PL_regcomp_parse++);
2335             switch (value) {
2336             case 'w':   namedclass = ANYOF_ALNUM;       break;
2337             case 'W':   namedclass = ANYOF_NALNUM;      break;
2338             case 's':   namedclass = ANYOF_SPACE;       break;
2339             case 'S':   namedclass = ANYOF_NSPACE;      break;
2340             case 'd':   namedclass = ANYOF_DIGIT;       break;
2341             case 'D':   namedclass = ANYOF_NDIGIT;      break;
2342             case 'n':   value = '\n';                   break;
2343             case 'r':   value = '\r';                   break;
2344             case 't':   value = '\t';                   break;
2345             case 'f':   value = '\f';                   break;
2346             case 'b':   value = '\b';                   break;
2347             case 'e':   value = '\033';                 break;
2348             case 'a':   value = '\007';                 break;
2349             case 'x':
2350                 value = scan_hex(PL_regcomp_parse, 2, &numlen);
2351                 PL_regcomp_parse += numlen;
2352                 break;
2353             case 'c':
2354                 value = UCHARAT(PL_regcomp_parse++);
2355                 value = toCTRL(value);
2356                 break;
2357             case '0': case '1': case '2': case '3': case '4':
2358             case '5': case '6': case '7': case '8': case '9':
2359                 value = scan_oct(--PL_regcomp_parse, 3, &numlen);
2360                 PL_regcomp_parse += numlen;
2361                 break;
2362             }
2363         }
2364         if (!SIZE_ONLY && namedclass > OOB_NAMEDCLASS) {
2365             if (range)
2366                 FAIL("invalid [] range in regexp"); /* [a-\w], [a-[:word:]] */
2367             switch (namedclass) {
2368             case ANYOF_ALNUM:
2369                 if (LOC)
2370                     ANYOF_CLASS_SET(opnd, ANYOF_ALNUM);
2371                 else {
2372                     for (value = 0; value < 256; value++)
2373                         if (isALNUM(value))
2374                             ANYOF_BITMAP_SET(opnd, value);
2375                 }
2376                 break;
2377             case ANYOF_NALNUM:
2378                 if (LOC)
2379                     ANYOF_CLASS_SET(opnd, ANYOF_NALNUM);
2380                 else {
2381                     for (value = 0; value < 256; value++)
2382                         if (!isALNUM(value))
2383                             ANYOF_BITMAP_SET(opnd, value);
2384                 }
2385                 break;
2386             case ANYOF_SPACE:
2387                 if (LOC)
2388                     ANYOF_CLASS_SET(opnd, ANYOF_SPACE);
2389                 else {
2390                     for (value = 0; value < 256; value++)
2391                         if (isSPACE(value))
2392                             ANYOF_BITMAP_SET(opnd, value);
2393                 }
2394                 break;
2395             case ANYOF_NSPACE:
2396                 if (LOC)
2397                     ANYOF_CLASS_SET(opnd, ANYOF_NSPACE);
2398                 else {
2399                     for (value = 0; value < 256; value++)
2400                         if (!isSPACE(value))
2401                             ANYOF_BITMAP_SET(opnd, value);
2402                 }
2403                 break;
2404             case ANYOF_DIGIT:
2405                 if (LOC)
2406                     ANYOF_CLASS_SET(opnd, ANYOF_DIGIT);
2407                 else {
2408                     for (value = '0'; value <= '9'; value++)
2409                         ANYOF_BITMAP_SET(opnd, value);
2410                 }
2411                 break;
2412             case ANYOF_NDIGIT:
2413                 if (LOC)
2414                     ANYOF_CLASS_SET(opnd, ANYOF_NDIGIT);
2415                 else {
2416                     for (value = 0; value < '0'; value++)
2417                         ANYOF_BITMAP_SET(opnd, value);
2418                     for (value = '9' + 1; value < 256; value++)
2419                         ANYOF_BITMAP_SET(opnd, value);
2420                 }
2421                 break;
2422             case ANYOF_NALNUMC:
2423                 if (LOC)
2424                     ANYOF_CLASS_SET(opnd, ANYOF_NALNUMC);
2425                 else {
2426                     for (value = 0; value < 256; value++)
2427                         if (!isALNUMC(value))
2428                             ANYOF_BITMAP_SET(opnd, value);
2429                 }
2430                 break;
2431             case ANYOF_ALNUMC:
2432                 if (LOC)
2433                     ANYOF_CLASS_SET(opnd, ANYOF_ALNUMC);
2434                 else {
2435                     for (value = 0; value < 256; value++)
2436                         if (isALNUMC(value))
2437                             ANYOF_BITMAP_SET(opnd, value);
2438                 }
2439                 break;
2440             case ANYOF_ALPHA:
2441                 if (LOC)
2442                     ANYOF_CLASS_SET(opnd, ANYOF_ALPHA);
2443                 else {
2444                     for (value = 0; value < 256; value++)
2445                         if (isALPHA(value))
2446                             ANYOF_BITMAP_SET(opnd, value);
2447                 }
2448                 break;
2449             case ANYOF_NALPHA:
2450                 if (LOC)
2451                     ANYOF_CLASS_SET(opnd, ANYOF_NALPHA);
2452                 else {
2453                     for (value = 0; value < 256; value++)
2454                         if (!isALPHA(value))
2455                             ANYOF_BITMAP_SET(opnd, value);
2456                 }
2457                 break;
2458             case ANYOF_ASCII:
2459                 if (LOC)
2460                     ANYOF_CLASS_SET(opnd, ANYOF_ASCII);
2461                 else {
2462                     for (value = 0; value < 128; value++)
2463                         ANYOF_BITMAP_SET(opnd, value);
2464                 }
2465                 break;
2466             case ANYOF_NASCII:
2467                 if (LOC)
2468                     ANYOF_CLASS_SET(opnd, ANYOF_NASCII);
2469                 else {
2470                     for (value = 128; value < 256; value++)
2471                         ANYOF_BITMAP_SET(opnd, value);
2472                 }
2473                 break;
2474             case ANYOF_CNTRL:
2475                 if (LOC)
2476                     ANYOF_CLASS_SET(opnd, ANYOF_CNTRL);
2477                 else {
2478                     for (value = 0; value < 256; value++)
2479                         if (isCNTRL(value))
2480                             ANYOF_BITMAP_SET(opnd, value);
2481                 }
2482                 lastvalue = OOB_CHAR8;
2483                 break;
2484             case ANYOF_NCNTRL:
2485                 if (LOC)
2486                     ANYOF_CLASS_SET(opnd, ANYOF_NCNTRL);
2487                 else {
2488                     for (value = 0; value < 256; value++)
2489                         if (!isCNTRL(value))
2490                             ANYOF_BITMAP_SET(opnd, value);
2491                 }
2492                 break;
2493             case ANYOF_GRAPH:
2494                 if (LOC)
2495                     ANYOF_CLASS_SET(opnd, ANYOF_GRAPH);
2496                 else {
2497                     for (value = 0; value < 256; value++)
2498                         if (isGRAPH(value))
2499                             ANYOF_BITMAP_SET(opnd, value);
2500                 }
2501                 break;
2502             case ANYOF_NGRAPH:
2503                 if (LOC)
2504                     ANYOF_CLASS_SET(opnd, ANYOF_NGRAPH);
2505                 else {
2506                     for (value = 0; value < 256; value++)
2507                         if (!isGRAPH(value))
2508                             ANYOF_BITMAP_SET(opnd, value);
2509                 }
2510                 break;
2511             case ANYOF_LOWER:
2512                 if (LOC)
2513                     ANYOF_CLASS_SET(opnd, ANYOF_LOWER);
2514                 else {
2515                     for (value = 0; value < 256; value++)
2516                         if (isLOWER(value))
2517                             ANYOF_BITMAP_SET(opnd, value);
2518                 }
2519                 break;
2520             case ANYOF_NLOWER:
2521                 if (LOC)
2522                     ANYOF_CLASS_SET(opnd, ANYOF_NLOWER);
2523                 else {
2524                     for (value = 0; value < 256; value++)
2525                         if (!isLOWER(value))
2526                             ANYOF_BITMAP_SET(opnd, value);
2527                 }
2528                 break;
2529             case ANYOF_PRINT:
2530                 if (LOC)
2531                     ANYOF_CLASS_SET(opnd, ANYOF_PRINT);
2532                 else {
2533                     for (value = 0; value < 256; value++)
2534                         if (isPRINT(value))
2535                             ANYOF_BITMAP_SET(opnd, value);
2536                 }
2537                 break;
2538             case ANYOF_NPRINT:
2539                 if (LOC)
2540                     ANYOF_CLASS_SET(opnd, ANYOF_NPRINT);
2541                 else {
2542                     for (value = 0; value < 256; value++)
2543                         if (!isPRINT(value))
2544                             ANYOF_BITMAP_SET(opnd, value);
2545                 }
2546                 break;
2547             case ANYOF_PUNCT:
2548                 if (LOC)
2549                     ANYOF_CLASS_SET(opnd, ANYOF_PUNCT);
2550                 else {
2551                     for (value = 0; value < 256; value++)
2552                         if (isPUNCT(value))
2553                             ANYOF_BITMAP_SET(opnd, value);
2554                 }
2555                 break;
2556             case ANYOF_NPUNCT:
2557                 if (LOC)
2558                     ANYOF_CLASS_SET(opnd, ANYOF_NPUNCT);
2559                 else {
2560                     for (value = 0; value < 256; value++)
2561                         if (!isPUNCT(value))
2562                             ANYOF_BITMAP_SET(opnd, value);
2563                 }
2564                 break;
2565             case ANYOF_UPPER:
2566                 if (LOC)
2567                     ANYOF_CLASS_SET(opnd, ANYOF_UPPER);
2568                 else {
2569                     for (value = 0; value < 256; value++)
2570                         if (isUPPER(value))
2571                             ANYOF_BITMAP_SET(opnd, value);
2572                 }
2573                 break;
2574             case ANYOF_NUPPER:
2575                 if (LOC)
2576                     ANYOF_CLASS_SET(opnd, ANYOF_NUPPER);
2577                 else {
2578                     for (value = 0; value < 256; value++)
2579                         if (!isUPPER(value))
2580                             ANYOF_BITMAP_SET(opnd, value);
2581                 }
2582                 break;
2583             case ANYOF_XDIGIT:
2584                 if (LOC)
2585                     ANYOF_CLASS_SET(opnd, ANYOF_XDIGIT);
2586                 else {
2587                     for (value = 0; value < 256; value++)
2588                         if (isXDIGIT(value))
2589                             ANYOF_BITMAP_SET(opnd, value);
2590                 }
2591                 break;
2592             case ANYOF_NXDIGIT:
2593                 if (LOC)
2594                     ANYOF_CLASS_SET(opnd, ANYOF_NXDIGIT);
2595                 else {
2596                     for (value = 0; value < 256; value++)
2597                         if (!isXDIGIT(value))
2598                             ANYOF_BITMAP_SET(opnd, value);
2599                 }
2600                 break;
2601             default:
2602                 FAIL("invalid [::] class in regexp");
2603                 break;
2604             }
2605             if (LOC)
2606                 ANYOF_FLAGS(opnd) |= ANYOF_CLASS;
2607             continue;
2608         }
2609         if (range) {
2610             if (lastvalue > value)
2611                 FAIL("invalid [] range in regexp"); /* [b-a] */
2612             range = 0;
2613         }
2614         else {
2615             lastvalue = value;
2616             if (*PL_regcomp_parse == '-' && PL_regcomp_parse+1 < PL_regxend &&
2617                 PL_regcomp_parse[1] != ']') {
2618                 if (namedclass > OOB_NAMEDCLASS)
2619                     FAIL("invalid [] range in regexp"); /* [\w-a] */
2620                 PL_regcomp_parse++;
2621                 range = 1;
2622                 continue;       /* do it next time */
2623             }
2624         }
2625         /* now is the next time */
2626         if (!SIZE_ONLY) {
2627 #ifndef ASCIIish /* EBCDIC, for example. */
2628             if ((isLOWER(lastvalue) && isLOWER(value)) ||
2629                 (isUPPER(lastvalue) && isUPPER(value)))
2630             {
2631                 I32 i;
2632                 if (isLOWER(lastvalue)) {
2633                     for (i = lastvalue; i <= value; i++)
2634                         if (isLOWER(i))
2635                             ANYOF_BITMAP_SET(opnd, i);
2636                 } else {
2637                     for (i = lastvalue; i <= value; i++)
2638                         if (isUPPER(i))
2639                             ANYOF_BITMAP_SET(opnd, i);
2640                 }
2641             }
2642             else
2643 #endif
2644                 for ( ; lastvalue <= value; lastvalue++)
2645                     ANYOF_BITMAP_SET(opnd, lastvalue);
2646         }
2647         range = 0;
2648     }
2649     /* optimize case-insensitive simple patterns (e.g. /[a-z]/i) */
2650     if (!SIZE_ONLY &&
2651         (ANYOF_FLAGS(opnd) & (ANYOF_FLAGS_ALL ^ ANYOF_INVERT)) == ANYOF_FOLD) {
2652         for (value = 0; value < 256; ++value) {
2653             if (ANYOF_BITMAP_TEST(opnd, value)) {
2654                 I32 cf = PL_fold[value];
2655                 ANYOF_BITMAP_SET(opnd, cf);
2656             }
2657         }
2658         ANYOF_FLAGS(opnd) &= ~ANYOF_FOLD;
2659     }
2660     /* optimize inverted simple patterns (e.g. [^a-z]) */
2661     if (!SIZE_ONLY && (ANYOF_FLAGS(opnd) & ANYOF_FLAGS_ALL) == ANYOF_INVERT) {
2662         for (value = 0; value < ANYOF_BITMAP_SIZE; ++value)
2663             opnd[ANYOF_BITMAP_OFFSET + value] ^= ANYOF_FLAGS_ALL;
2664         ANYOF_FLAGS(opnd) = 0;
2665     }
2666     return ret;
2667 }
2668
2669 STATIC regnode *
2670 S_regclassutf8(pTHX)
2671 {
2672     dTHR;
2673     register char *opnd, *e;
2674     register U32 value;
2675     register U32 lastvalue = OOB_UTF8;
2676     register I32 range = 0;
2677     register regnode *ret;
2678     I32 numlen;
2679     I32 n;
2680     SV *listsv;
2681     U8 flags = 0;
2682     I32 namedclass;
2683
2684     if (*PL_regcomp_parse == '^') {     /* Complement of range. */
2685         PL_regnaughty++;
2686         PL_regcomp_parse++;
2687         if (!SIZE_ONLY)
2688             flags |= ANYOF_INVERT;
2689     }
2690     if (!SIZE_ONLY) {
2691         if (FOLD)
2692             flags |= ANYOF_FOLD;
2693         if (LOC)
2694             flags |= ANYOF_LOCALE;
2695         listsv = newSVpvn("# comment\n",10);
2696     }
2697
2698     checkposixcc();
2699
2700     if (*PL_regcomp_parse == ']' || *PL_regcomp_parse == '-')
2701         goto skipcond;          /* allow 1st char to be ] or - */
2702
2703     while (PL_regcomp_parse < PL_regxend && *PL_regcomp_parse != ']') {
2704        skipcond:
2705         namedclass = OOB_NAMEDCLASS;
2706         value = utf8_to_uv((U8*)PL_regcomp_parse, &numlen);
2707         PL_regcomp_parse += numlen;
2708
2709         if (value == '[')
2710             namedclass = regpposixcc(value);
2711         else if (value == '\\') {
2712             value = utf8_to_uv((U8*)PL_regcomp_parse, &numlen);
2713             PL_regcomp_parse += numlen;
2714             switch (value) {
2715             case 'w':           namedclass = ANYOF_ALNUM;               break;
2716             case 'W':           namedclass = ANYOF_NALNUM;              break;
2717             case 's':           namedclass = ANYOF_SPACE;               break;
2718             case 'S':           namedclass = ANYOF_NSPACE;              break;
2719             case 'd':           namedclass = ANYOF_DIGIT;               break;
2720             case 'D':           namedclass = ANYOF_NDIGIT;              break;
2721             case 'p':
2722             case 'P':
2723                 if (*PL_regcomp_parse == '{') {
2724                     e = strchr(PL_regcomp_parse++, '}');
2725                     if (!e)
2726                         FAIL("Missing right brace on \\p{}");
2727                     n = e - PL_regcomp_parse;
2728                 }
2729                 else {
2730                     e = PL_regcomp_parse;
2731                     n = 1;
2732                 }
2733                 if (!SIZE_ONLY) {
2734                     if (value == 'p')
2735                         Perl_sv_catpvf(aTHX_ listsv,
2736                                        "+utf8::%.*s\n", n, PL_regcomp_parse);
2737                     else
2738                         Perl_sv_catpvf(aTHX_ listsv,
2739                                        "!utf8::%.*s\n", n, PL_regcomp_parse);
2740                 }
2741                 PL_regcomp_parse = e + 1;
2742                 lastvalue = OOB_UTF8;
2743                 continue;
2744             case 'n':           value = '\n';           break;
2745             case 'r':           value = '\r';           break;
2746             case 't':           value = '\t';           break;
2747             case 'f':           value = '\f';           break;
2748             case 'b':           value = '\b';           break;
2749             case 'e':           value = '\033';         break;
2750             case 'a':           value = '\007';         break;
2751             case 'x':
2752                 if (*PL_regcomp_parse == '{') {
2753                     e = strchr(PL_regcomp_parse++, '}');
2754                     if (!e)
2755                         FAIL("Missing right brace on \\x{}");
2756                     value = scan_hex(PL_regcomp_parse,
2757                                      e - PL_regcomp_parse,
2758                                      &numlen);
2759                     PL_regcomp_parse = e + 1;
2760                 }
2761                 else {
2762                     value = scan_hex(PL_regcomp_parse, 2, &numlen);
2763                     PL_regcomp_parse += numlen;
2764                 }
2765                 break;
2766             case 'c':
2767                 value = UCHARAT(PL_regcomp_parse++);
2768                 value = toCTRL(value);
2769                 break;
2770             case '0': case '1': case '2': case '3': case '4':
2771             case '5': case '6': case '7': case '8': case '9':
2772                 value = scan_oct(--PL_regcomp_parse, 3, &numlen);
2773                 PL_regcomp_parse += numlen;
2774                 break;
2775             }
2776         }
2777         if (!SIZE_ONLY && namedclass > OOB_NAMEDCLASS) {
2778             if (range)
2779                 FAIL("invalid [] range in regexp"); /* [a-\w], [a-[:word:]] */
2780             switch (namedclass) {
2781             case ANYOF_ALNUM:
2782                 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsWord\n");        break;
2783             case ANYOF_NALNUM:
2784                 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsWord\n");        break;
2785             case ANYOF_ALNUMC:
2786                 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsAlnum\n");       break;
2787             case ANYOF_NALNUMC:
2788                 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsAlnum\n");       break;
2789             case ANYOF_ALPHA:
2790                 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsAlpha\n");       break;
2791             case ANYOF_NALPHA:
2792                 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsAlpha\n");       break;
2793             case ANYOF_ASCII:
2794                 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsASCII\n");       break;
2795             case ANYOF_NASCII:
2796                 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsASCII\n");       break;
2797             case ANYOF_CNTRL:
2798                 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsCntrl\n");       break;
2799             case ANYOF_NCNTRL:
2800                 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsCntrl\n");       break;
2801             case ANYOF_GRAPH:
2802                 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsGraph\n");       break;
2803             case ANYOF_NGRAPH:
2804                 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsGraph\n");       break;
2805             case ANYOF_DIGIT:
2806                 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsDigit\n");       break;
2807             case ANYOF_NDIGIT:
2808                 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsDigit\n");       break;
2809             case ANYOF_LOWER:
2810                 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsLower\n");       break;
2811             case ANYOF_NLOWER:
2812                 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsLower\n");       break;
2813             case ANYOF_PRINT:
2814                 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsPrint\n");       break;
2815             case ANYOF_NPRINT:
2816                 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsPrint\n");       break;
2817             case ANYOF_PUNCT:
2818                 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsPunct\n");       break;
2819             case ANYOF_NPUNCT:
2820                 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsPunct\n");       break;
2821             case ANYOF_SPACE:
2822                 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsSpace\n");       break;
2823             case ANYOF_NSPACE:
2824                 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsSpace\n");       break;
2825             case ANYOF_UPPER:
2826                 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsUpper\n");       break;
2827             case ANYOF_NUPPER:
2828                 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsUpper\n");       break;
2829             case ANYOF_XDIGIT:
2830                 Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsXDigit\n");      break;
2831             case ANYOF_NXDIGIT:
2832                 Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsXDigit\n");      break;
2833             }
2834             continue;
2835         }
2836         if (range) {
2837             if (lastvalue > value)
2838                 FAIL("invalid [] range in regexp"); /* [b-a] */
2839             if (!SIZE_ONLY)
2840                 Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\t%04"UVxf"\n", (UV)lastvalue, (UV)value);
2841             range = 0;
2842         }
2843         else {
2844             lastvalue = value;
2845             if (*PL_regcomp_parse == '-' && PL_regcomp_parse+1 < PL_regxend &&
2846                 PL_regcomp_parse[1] != ']') {
2847                 if (namedclass > OOB_NAMEDCLASS)
2848                     FAIL("invalid [] range in regexp"); /* [\w-a] */
2849                 PL_regcomp_parse++;
2850                 range = 1;
2851                 continue;       /* do it next time */
2852             }
2853         }
2854         /* now is the next time */
2855         if (!SIZE_ONLY)
2856             Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\n", (UV)value);
2857         range = 0;
2858     }
2859
2860     ret = reganode(ANYOFUTF8, 0);
2861
2862     if (!SIZE_ONLY) {
2863         SV *rv = swash_init("utf8", "", listsv, 1, 0);
2864         SvREFCNT_dec(listsv);
2865         n = add_data(1,"s");
2866         PL_regcomp_rx->data->data[n] = (void*)rv;
2867         ARG1_SET(ret, flags);
2868         ARG2_SET(ret, n);
2869     }
2870
2871     return ret;
2872 }
2873
2874 STATIC char*
2875 S_nextchar(pTHX)
2876 {
2877     dTHR;
2878     char* retval = PL_regcomp_parse++;
2879
2880     for (;;) {
2881         if (*PL_regcomp_parse == '(' && PL_regcomp_parse[1] == '?' &&
2882                 PL_regcomp_parse[2] == '#') {
2883             while (*PL_regcomp_parse && *PL_regcomp_parse != ')')
2884                 PL_regcomp_parse++;
2885             PL_regcomp_parse++;
2886             continue;
2887         }
2888         if (PL_regflags & PMf_EXTENDED) {
2889             if (isSPACE(*PL_regcomp_parse)) {
2890                 PL_regcomp_parse++;
2891                 continue;
2892             }
2893             else if (*PL_regcomp_parse == '#') {
2894                 while (*PL_regcomp_parse && *PL_regcomp_parse != '\n')
2895                     PL_regcomp_parse++;
2896                 PL_regcomp_parse++;
2897                 continue;
2898             }
2899         }
2900         return retval;
2901     }
2902 }
2903
2904 /*
2905 - reg_node - emit a node
2906 */
2907 STATIC regnode *                        /* Location. */
2908 S_reg_node(pTHX_ U8 op)
2909 {
2910     dTHR;
2911     register regnode *ret;
2912     register regnode *ptr;
2913
2914     ret = PL_regcode;
2915     if (SIZE_ONLY) {
2916         SIZE_ALIGN(PL_regsize);
2917         PL_regsize += 1;
2918         return(ret);
2919     }
2920
2921     NODE_ALIGN_FILL(ret);
2922     ptr = ret;
2923     FILL_ADVANCE_NODE(ptr, op);
2924     PL_regcode = ptr;
2925
2926     return(ret);
2927 }
2928
2929 /*
2930 - reganode - emit a node with an argument
2931 */
2932 STATIC regnode *                        /* Location. */
2933 S_reganode(pTHX_ U8 op, U32 arg)
2934 {
2935     dTHR;
2936     register regnode *ret;
2937     register regnode *ptr;
2938
2939     ret = PL_regcode;
2940     if (SIZE_ONLY) {
2941         SIZE_ALIGN(PL_regsize);
2942         PL_regsize += 2;
2943         return(ret);
2944     }
2945
2946     NODE_ALIGN_FILL(ret);
2947     ptr = ret;
2948     FILL_ADVANCE_NODE_ARG(ptr, op, arg);
2949     PL_regcode = ptr;
2950
2951     return(ret);
2952 }
2953
2954 /*
2955 - reguni - emit (if appropriate) a Unicode character
2956 */
2957 STATIC void
2958 S_reguni(pTHX_ UV uv, char* s, I32* lenp)
2959 {
2960     dTHR;
2961     if (SIZE_ONLY) {
2962         U8 tmpbuf[10];
2963         *lenp = uv_to_utf8(tmpbuf, uv) - tmpbuf;
2964     }
2965     else
2966         *lenp = uv_to_utf8((U8*)s, uv) - (U8*)s;
2967
2968 }
2969
2970 /*
2971 - reginsert - insert an operator in front of already-emitted operand
2972 *
2973 * Means relocating the operand.
2974 */
2975 STATIC void
2976 S_reginsert(pTHX_ U8 op, regnode *opnd)
2977 {
2978     dTHR;
2979     register regnode *src;
2980     register regnode *dst;
2981     register regnode *place;
2982     register int offset = regarglen[(U8)op];
2983     
2984 /* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
2985
2986     if (SIZE_ONLY) {
2987         PL_regsize += NODE_STEP_REGNODE + offset;
2988         return;
2989     }
2990
2991     src = PL_regcode;
2992     PL_regcode += NODE_STEP_REGNODE + offset;
2993     dst = PL_regcode;
2994     while (src > opnd)
2995         StructCopy(--src, --dst, regnode);
2996
2997     place = opnd;               /* Op node, where operand used to be. */
2998     src = NEXTOPER(place);
2999     FILL_ADVANCE_NODE(place, op);
3000     Zero(src, offset, regnode);
3001 }
3002
3003 /*
3004 - regtail - set the next-pointer at the end of a node chain of p to val.
3005 */
3006 STATIC void
3007 S_regtail(pTHX_ regnode *p, regnode *val)
3008 {
3009     dTHR;
3010     register regnode *scan;
3011     register regnode *temp;
3012     register I32 offset;
3013
3014     if (SIZE_ONLY)
3015         return;
3016
3017     /* Find last node. */
3018     scan = p;
3019     for (;;) {
3020         temp = regnext(scan);
3021         if (temp == NULL)
3022             break;
3023         scan = temp;
3024     }
3025
3026     if (reg_off_by_arg[OP(scan)]) {
3027         ARG_SET(scan, val - scan);
3028     }
3029     else {
3030         NEXT_OFF(scan) = val - scan;
3031     }
3032 }
3033
3034 /*
3035 - regoptail - regtail on operand of first argument; nop if operandless
3036 */
3037 STATIC void
3038 S_regoptail(pTHX_ regnode *p, regnode *val)
3039 {
3040     dTHR;
3041     /* "Operandless" and "op != BRANCH" are synonymous in practice. */
3042     if (p == NULL || SIZE_ONLY)
3043         return;
3044     if (PL_regkind[(U8)OP(p)] == BRANCH) {
3045         regtail(NEXTOPER(p), val);
3046     }
3047     else if ( PL_regkind[(U8)OP(p)] == BRANCHJ) {
3048         regtail(NEXTOPER(NEXTOPER(p)), val);
3049     }
3050     else
3051         return;
3052 }
3053
3054 /*
3055  - regcurly - a little FSA that accepts {\d+,?\d*}
3056  */
3057 STATIC I32
3058 S_regcurly(pTHX_ register char *s)
3059 {
3060     if (*s++ != '{')
3061         return FALSE;
3062     if (!isDIGIT(*s))
3063         return FALSE;
3064     while (isDIGIT(*s))
3065         s++;
3066     if (*s == ',')
3067         s++;
3068     while (isDIGIT(*s))
3069         s++;
3070     if (*s != '}')
3071         return FALSE;
3072     return TRUE;
3073 }
3074
3075
3076 STATIC regnode *
3077 S_dumpuntil(pTHX_ regnode *start, regnode *node, regnode *last, SV* sv, I32 l)
3078 {
3079 #ifdef DEBUGGING
3080     register U8 op = EXACT;     /* Arbitrary non-END op. */
3081     register regnode *next, *onode;
3082
3083     while (op != END && (!last || node < last)) {
3084         /* While that wasn't END last time... */
3085
3086         NODE_ALIGN(node);
3087         op = OP(node);
3088         if (op == CLOSE)
3089             l--;        
3090         next = regnext(node);
3091         /* Where, what. */
3092         if (OP(node) == OPTIMIZED)
3093             goto after_print;
3094         regprop(sv, node);
3095         PerlIO_printf(Perl_debug_log, "%4d:%*s%s", node - start, 
3096                       2*l + 1, "", SvPVX(sv));
3097         if (next == NULL)               /* Next ptr. */
3098             PerlIO_printf(Perl_debug_log, "(0)");
3099         else 
3100             PerlIO_printf(Perl_debug_log, "(%d)", next - start);
3101         (void)PerlIO_putc(Perl_debug_log, '\n');
3102       after_print:
3103         if (PL_regkind[(U8)op] == BRANCHJ) {
3104             register regnode *nnode = (OP(next) == LONGJMP 
3105                                        ? regnext(next) 
3106                                        : next);
3107             if (last && nnode > last)
3108                 nnode = last;
3109             node = dumpuntil(start, NEXTOPER(NEXTOPER(node)), nnode, sv, l + 1);
3110         }
3111         else if (PL_regkind[(U8)op] == BRANCH) {
3112             node = dumpuntil(start, NEXTOPER(node), next, sv, l + 1);
3113         }
3114         else if ( op == CURLY) {   /* `next' might be very big: optimizer */
3115             node = dumpuntil(start, NEXTOPER(node) + EXTRA_STEP_2ARGS,
3116                              NEXTOPER(node) + EXTRA_STEP_2ARGS + 1, sv, l + 1);
3117         }
3118         else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
3119             node = dumpuntil(start, NEXTOPER(node) + EXTRA_STEP_2ARGS,
3120                              next, sv, l + 1);
3121         }
3122         else if ( op == PLUS || op == STAR) {
3123             node = dumpuntil(start, NEXTOPER(node), NEXTOPER(node) + 1, sv, l + 1);
3124         }
3125         else if (op == ANYOF) {
3126             node = NEXTOPER(node);
3127             node += ANY_SKIP;
3128         }
3129         else if (PL_regkind[(U8)op] == EXACT) {
3130             /* Literal string, where present. */
3131             node += NODE_SZ_STR(node) - 1;
3132             node = NEXTOPER(node);
3133         }
3134         else {
3135             node = NEXTOPER(node);
3136             node += regarglen[(U8)op];
3137         }
3138         if (op == CURLYX || op == OPEN)
3139             l++;
3140         else if (op == WHILEM)
3141             l--;
3142     }
3143 #endif  /* DEBUGGING */
3144     return node;
3145 }
3146
3147 /*
3148  - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
3149  */
3150 void
3151 Perl_regdump(pTHX_ regexp *r)
3152 {
3153 #ifdef DEBUGGING
3154     dTHR;
3155     SV *sv = sv_newmortal();
3156
3157     (void)dumpuntil(r->program, r->program + 1, NULL, sv, 0);
3158
3159     /* Header fields of interest. */
3160     if (r->anchored_substr)
3161         PerlIO_printf(Perl_debug_log, "anchored `%s%.*s%s'%s at %d ", 
3162                       PL_colors[0],
3163                       SvCUR(r->anchored_substr) - (SvTAIL(r->anchored_substr)!=0),
3164                       SvPVX(r->anchored_substr), 
3165                       PL_colors[1],
3166                       SvTAIL(r->anchored_substr) ? "$" : "",
3167                       r->anchored_offset);
3168     if (r->float_substr)
3169         PerlIO_printf(Perl_debug_log, "floating `%s%.*s%s'%s at %d..%u ", 
3170                       PL_colors[0],
3171                       SvCUR(r->float_substr) - (SvTAIL(r->float_substr)!=0), 
3172                       SvPVX(r->float_substr),
3173                       PL_colors[1],
3174                       SvTAIL(r->float_substr) ? "$" : "",
3175                       r->float_min_offset, r->float_max_offset);
3176     if (r->check_substr)
3177         PerlIO_printf(Perl_debug_log, 
3178                       r->check_substr == r->float_substr 
3179                       ? "(checking floating" : "(checking anchored");
3180     if (r->reganch & ROPT_NOSCAN)
3181         PerlIO_printf(Perl_debug_log, " noscan");
3182     if (r->reganch & ROPT_CHECK_ALL)
3183         PerlIO_printf(Perl_debug_log, " isall");
3184     if (r->check_substr)
3185         PerlIO_printf(Perl_debug_log, ") ");
3186
3187     if (r->regstclass) {
3188         regprop(sv, r->regstclass);
3189         PerlIO_printf(Perl_debug_log, "stclass `%s' ", SvPVX(sv));
3190     }
3191     if (r->reganch & ROPT_ANCH) {
3192         PerlIO_printf(Perl_debug_log, "anchored");
3193         if (r->reganch & ROPT_ANCH_BOL)
3194             PerlIO_printf(Perl_debug_log, "(BOL)");
3195         if (r->reganch & ROPT_ANCH_MBOL)
3196             PerlIO_printf(Perl_debug_log, "(MBOL)");
3197         if (r->reganch & ROPT_ANCH_SBOL)
3198             PerlIO_printf(Perl_debug_log, "(SBOL)");
3199         if (r->reganch & ROPT_ANCH_GPOS)
3200             PerlIO_printf(Perl_debug_log, "(GPOS)");
3201         PerlIO_putc(Perl_debug_log, ' ');
3202     }
3203     if (r->reganch & ROPT_GPOS_SEEN)
3204         PerlIO_printf(Perl_debug_log, "GPOS ");
3205     if (r->reganch & ROPT_SKIP)
3206         PerlIO_printf(Perl_debug_log, "plus ");
3207     if (r->reganch & ROPT_IMPLICIT)
3208         PerlIO_printf(Perl_debug_log, "implicit ");
3209     PerlIO_printf(Perl_debug_log, "minlen %ld ", (long) r->minlen);
3210     if (r->reganch & ROPT_EVAL_SEEN)
3211         PerlIO_printf(Perl_debug_log, "with eval ");
3212     PerlIO_printf(Perl_debug_log, "\n");
3213 #endif  /* DEBUGGING */
3214 }
3215
3216 /*
3217 - regprop - printable representation of opcode
3218 */
3219 void
3220 Perl_regprop(pTHX_ SV *sv, regnode *o)
3221 {
3222 #ifdef DEBUGGING
3223     dTHR;
3224     register int k;
3225
3226     sv_setpvn(sv, "", 0);
3227     if (OP(o) >= reg_num)               /* regnode.type is unsigned */
3228         FAIL("corrupted regexp opcode");
3229     sv_catpv(sv, (char*)reg_name[OP(o)]); /* Take off const! */
3230
3231     k = PL_regkind[(U8)OP(o)];
3232
3233     if (k == EXACT)
3234         Perl_sv_catpvf(aTHX_ sv, " <%s%.*s%s>", PL_colors[0],
3235                        STR_LEN(o), STRING(o), PL_colors[1]);
3236     else if (k == CURLY) {
3237         if (OP(o) == CURLYM || OP(o) == CURLYN)
3238             Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
3239         Perl_sv_catpvf(aTHX_ sv, " {%d,%d}", ARG1(o), ARG2(o));
3240     }
3241     else if (k == WHILEM && o->flags)                   /* Ordinal/of */
3242         Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
3243     else if (k == REF || k == OPEN || k == CLOSE || k == GROUPP )
3244         Perl_sv_catpvf(aTHX_ sv, "%d", ARG(o)); /* Parenth number */
3245     else if (k == LOGICAL)
3246         Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags);     /* 2: embedded, otherwise 1 */
3247     else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH))
3248         Perl_sv_catpvf(aTHX_ sv, "[-%d]", o->flags);
3249 #endif  /* DEBUGGING */
3250 }
3251
3252 SV *
3253 Perl_re_intuit_string(pTHX_ regexp *prog)
3254 {                               /* Assume that RE_INTUIT is set */
3255     DEBUG_r(
3256         {   STRLEN n_a;
3257             char *s = SvPV(prog->check_substr,n_a);
3258
3259             if (!PL_colorset) reginitcolors();
3260             PerlIO_printf(Perl_debug_log,
3261                       "%sUsing REx substr:%s `%s%.60s%s%s'\n",
3262                       PL_colors[4],PL_colors[5],PL_colors[0],
3263                       s,
3264                       PL_colors[1],
3265                       (strlen(s) > 60 ? "..." : ""));
3266         } );
3267
3268     return prog->check_substr;
3269 }
3270
3271 void
3272 Perl_pregfree(pTHX_ struct regexp *r)
3273 {
3274     dTHR;
3275     DEBUG_r(if (!PL_colorset) reginitcolors());
3276
3277     if (!r || (--r->refcnt > 0))
3278         return;
3279     DEBUG_r(PerlIO_printf(Perl_debug_log,
3280                       "%sFreeing REx:%s `%s%.60s%s%s'\n",
3281                       PL_colors[4],PL_colors[5],PL_colors[0],
3282                       r->precomp,
3283                       PL_colors[1],
3284                       (strlen(r->precomp) > 60 ? "..." : "")));
3285
3286     if (r->precomp)
3287         Safefree(r->precomp);
3288     if (RX_MATCH_COPIED(r))
3289         Safefree(r->subbeg);
3290     if (r->substrs) {
3291         if (r->anchored_substr)
3292             SvREFCNT_dec(r->anchored_substr);
3293         if (r->float_substr)
3294             SvREFCNT_dec(r->float_substr);
3295         Safefree(r->substrs);
3296     }
3297     if (r->data) {
3298         int n = r->data->count;
3299         AV* new_comppad = NULL;
3300         AV* old_comppad;
3301         SV** old_curpad;
3302
3303         while (--n >= 0) {
3304             switch (r->data->what[n]) {
3305             case 's':
3306                 SvREFCNT_dec((SV*)r->data->data[n]);
3307                 break;
3308             case 'p':
3309                 new_comppad = (AV*)r->data->data[n];
3310                 break;
3311             case 'o':
3312                 if (new_comppad == NULL)
3313                     Perl_croak(aTHX_ "panic: pregfree comppad");
3314                 old_comppad = PL_comppad;
3315                 old_curpad = PL_curpad;
3316                 PL_comppad = new_comppad;
3317                 PL_curpad = AvARRAY(new_comppad);
3318                 op_free((OP_4tree*)r->data->data[n]);
3319                 PL_comppad = old_comppad;
3320                 PL_curpad = old_curpad;
3321                 SvREFCNT_dec((SV*)new_comppad);
3322                 new_comppad = NULL;
3323                 break;
3324             case 'n':
3325                 break;
3326             default:
3327                 FAIL2("panic: regfree data code '%c'", r->data->what[n]);
3328             }
3329         }
3330         Safefree(r->data->what);
3331         Safefree(r->data);
3332     }
3333     Safefree(r->startp);
3334     Safefree(r->endp);
3335     Safefree(r);
3336 }
3337
3338 /*
3339  - regnext - dig the "next" pointer out of a node
3340  *
3341  * [Note, when REGALIGN is defined there are two places in regmatch()
3342  * that bypass this code for speed.]
3343  */
3344 regnode *
3345 Perl_regnext(pTHX_ register regnode *p)
3346 {
3347     dTHR;
3348     register I32 offset;
3349
3350     if (p == &PL_regdummy)
3351         return(NULL);
3352
3353     offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
3354     if (offset == 0)
3355         return(NULL);
3356
3357     return(p+offset);
3358 }
3359
3360 STATIC void     
3361 S_re_croak2(pTHX_ const char* pat1,const char* pat2,...)
3362 {
3363     va_list args;
3364     STRLEN l1 = strlen(pat1);
3365     STRLEN l2 = strlen(pat2);
3366     char buf[512];
3367     SV *msv;
3368     char *message;
3369
3370     if (l1 > 510)
3371         l1 = 510;
3372     if (l1 + l2 > 510)
3373         l2 = 510 - l1;
3374     Copy(pat1, buf, l1 , char);
3375     Copy(pat2, buf + l1, l2 , char);
3376     buf[l1 + l2] = '\n';
3377     buf[l1 + l2 + 1] = '\0';
3378 #ifdef I_STDARG
3379     /* ANSI variant takes additional second argument */
3380     va_start(args, pat2);
3381 #else
3382     va_start(args);
3383 #endif
3384     msv = vmess(buf, &args);
3385     va_end(args);
3386     message = SvPV(msv,l1);
3387     if (l1 > 512)
3388         l1 = 512;
3389     Copy(message, buf, l1 , char);
3390     buf[l1] = '\0';                     /* Overwrite \n */
3391     Perl_croak(aTHX_ "%s", buf);
3392 }
3393
3394 /* XXX Here's a total kludge.  But we need to re-enter for swash routines. */
3395
3396 void
3397 Perl_save_re_context(pTHX)
3398 {                   
3399     dTHR;
3400     SAVEPPTR(PL_bostr);
3401     SAVEPPTR(PL_regprecomp);            /* uncompiled string. */
3402     SAVEI32(PL_regnpar);                /* () count. */
3403     SAVEI32(PL_regsize);                /* Code size. */
3404     SAVEI16(PL_regflags);               /* are we folding, multilining? */
3405     SAVEPPTR(PL_reginput);              /* String-input pointer. */
3406     SAVEPPTR(PL_regbol);                /* Beginning of input, for ^ check. */
3407     SAVEPPTR(PL_regeol);                /* End of input, for $ check. */
3408     SAVESPTR(PL_regstartp);             /* Pointer to startp array. */
3409     SAVESPTR(PL_regendp);               /* Ditto for endp. */
3410     SAVESPTR(PL_reglastparen);          /* Similarly for lastparen. */
3411     SAVEPPTR(PL_regtill);               /* How far we are required to go. */
3412     SAVEI32(PL_regprev);                /* char before regbol, \n if none */
3413     SAVESPTR(PL_reg_start_tmp);         /* from regexec.c */
3414     PL_reg_start_tmp = 0;
3415     SAVEFREEPV(PL_reg_start_tmp);
3416     SAVEI32(PL_reg_start_tmpl);         /* from regexec.c */
3417     PL_reg_start_tmpl = 0;
3418     SAVESPTR(PL_regdata);
3419     SAVEI32(PL_reg_flags);              /* from regexec.c */
3420     SAVEI32(PL_reg_eval_set);           /* from regexec.c */
3421     SAVEI32(PL_regnarrate);             /* from regexec.c */
3422     SAVESPTR(PL_regprogram);            /* from regexec.c */
3423     SAVEINT(PL_regindent);              /* from regexec.c */
3424     SAVESPTR(PL_regcc);                 /* from regexec.c */
3425     SAVESPTR(PL_curcop);
3426     SAVESPTR(PL_regcomp_rx);            /* from regcomp.c */
3427     SAVEI32(PL_regseen);                /* from regcomp.c */
3428     SAVEI32(PL_regsawback);             /* Did we see \1, ...? */
3429     SAVEI32(PL_regnaughty);             /* How bad is this pattern? */
3430     SAVESPTR(PL_regcode);               /* Code-emit pointer; &regdummy = don't */
3431     SAVEPPTR(PL_regxend);               /* End of input for compile */
3432     SAVEPPTR(PL_regcomp_parse);         /* Input-scan pointer. */
3433     SAVESPTR(PL_reg_call_cc);           /* from regexec.c */
3434     SAVESPTR(PL_reg_re);                /* from regexec.c */
3435     SAVEPPTR(PL_reg_ganch);             /* from regexec.c */
3436     SAVESPTR(PL_reg_sv);                /* from regexec.c */
3437     SAVESPTR(PL_reg_magic);             /* from regexec.c */
3438     SAVEI32(PL_reg_oldpos);                     /* from regexec.c */
3439     SAVESPTR(PL_reg_oldcurpm);          /* from regexec.c */
3440     SAVESPTR(PL_reg_curpm);             /* from regexec.c */
3441 #ifdef DEBUGGING
3442     SAVEPPTR(PL_reg_starttry);          /* from regexec.c */    
3443 #endif
3444 }
3445
3446 #ifdef PERL_OBJECT
3447 #define NO_XSLOCKS
3448 #include "XSUB.h"
3449 #undef this
3450 #define this pPerl
3451 #endif
3452
3453 static void
3454 clear_re(pTHXo_ void *r)
3455 {
3456     ReREFCNT_dec((regexp *)r);
3457 }
3458