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