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