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