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