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