More printf miscasts flushed out.
[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 I32 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                         for (value = 0; value < 128; value++)
2495                             ANYOF_BITMAP_SET(ret, value);
2496                     }
2497                     break;
2498                 case ANYOF_NASCII:
2499                     if (LOC)
2500                         ANYOF_CLASS_SET(ret, ANYOF_NASCII);
2501                     else {
2502                         for (value = 128; value < 256; value++)
2503                             ANYOF_BITMAP_SET(ret, value);
2504                     }
2505                     break;
2506                 case ANYOF_CNTRL:
2507                     if (LOC)
2508                         ANYOF_CLASS_SET(ret, ANYOF_CNTRL);
2509                     else {
2510                         for (value = 0; value < 256; value++)
2511                             if (isCNTRL(value))
2512                                 ANYOF_BITMAP_SET(ret, value);
2513                     }
2514                     lastvalue = OOB_CHAR8;
2515                     break;
2516                 case ANYOF_NCNTRL:
2517                     if (LOC)
2518                         ANYOF_CLASS_SET(ret, ANYOF_NCNTRL);
2519                     else {
2520                         for (value = 0; value < 256; value++)
2521                             if (!isCNTRL(value))
2522                                 ANYOF_BITMAP_SET(ret, value);
2523                     }
2524                     break;
2525                 case ANYOF_GRAPH:
2526                     if (LOC)
2527                         ANYOF_CLASS_SET(ret, ANYOF_GRAPH);
2528                     else {
2529                         for (value = 0; value < 256; value++)
2530                             if (isGRAPH(value))
2531                                 ANYOF_BITMAP_SET(ret, value);
2532                     }
2533                     break;
2534                 case ANYOF_NGRAPH:
2535                     if (LOC)
2536                         ANYOF_CLASS_SET(ret, ANYOF_NGRAPH);
2537                     else {
2538                         for (value = 0; value < 256; value++)
2539                             if (!isGRAPH(value))
2540                                 ANYOF_BITMAP_SET(ret, value);
2541                     }
2542                     break;
2543                 case ANYOF_LOWER:
2544                     if (LOC)
2545                         ANYOF_CLASS_SET(ret, ANYOF_LOWER);
2546                     else {
2547                         for (value = 0; value < 256; value++)
2548                             if (isLOWER(value))
2549                                 ANYOF_BITMAP_SET(ret, value);
2550                     }
2551                     break;
2552                 case ANYOF_NLOWER:
2553                     if (LOC)
2554                         ANYOF_CLASS_SET(ret, ANYOF_NLOWER);
2555                     else {
2556                         for (value = 0; value < 256; value++)
2557                             if (!isLOWER(value))
2558                                 ANYOF_BITMAP_SET(ret, value);
2559                     }
2560                     break;
2561                 case ANYOF_PRINT:
2562                     if (LOC)
2563                         ANYOF_CLASS_SET(ret, ANYOF_PRINT);
2564                     else {
2565                         for (value = 0; value < 256; value++)
2566                             if (isPRINT(value))
2567                                 ANYOF_BITMAP_SET(ret, value);
2568                     }
2569                     break;
2570                 case ANYOF_NPRINT:
2571                     if (LOC)
2572                         ANYOF_CLASS_SET(ret, ANYOF_NPRINT);
2573                     else {
2574                         for (value = 0; value < 256; value++)
2575                             if (!isPRINT(value))
2576                                 ANYOF_BITMAP_SET(ret, value);
2577                     }
2578                     break;
2579                 case ANYOF_PUNCT:
2580                     if (LOC)
2581                         ANYOF_CLASS_SET(ret, ANYOF_PUNCT);
2582                     else {
2583                         for (value = 0; value < 256; value++)
2584                             if (isPUNCT(value))
2585                                 ANYOF_BITMAP_SET(ret, value);
2586                     }
2587                     break;
2588                 case ANYOF_NPUNCT:
2589                     if (LOC)
2590                         ANYOF_CLASS_SET(ret, ANYOF_NPUNCT);
2591                     else {
2592                         for (value = 0; value < 256; value++)
2593                             if (!isPUNCT(value))
2594                                 ANYOF_BITMAP_SET(ret, value);
2595                     }
2596                     break;
2597                 case ANYOF_UPPER:
2598                     if (LOC)
2599                         ANYOF_CLASS_SET(ret, ANYOF_UPPER);
2600                     else {
2601                         for (value = 0; value < 256; value++)
2602                             if (isUPPER(value))
2603                                 ANYOF_BITMAP_SET(ret, value);
2604                     }
2605                     break;
2606                 case ANYOF_NUPPER:
2607                     if (LOC)
2608                         ANYOF_CLASS_SET(ret, ANYOF_NUPPER);
2609                     else {
2610                         for (value = 0; value < 256; value++)
2611                             if (!isUPPER(value))
2612                                 ANYOF_BITMAP_SET(ret, value);
2613                     }
2614                     break;
2615                 case ANYOF_XDIGIT:
2616                     if (LOC)
2617                         ANYOF_CLASS_SET(ret, ANYOF_XDIGIT);
2618                     else {
2619                         for (value = 0; value < 256; value++)
2620                             if (isXDIGIT(value))
2621                                 ANYOF_BITMAP_SET(ret, value);
2622                     }
2623                     break;
2624                 case ANYOF_NXDIGIT:
2625                     if (LOC)
2626                         ANYOF_CLASS_SET(ret, ANYOF_NXDIGIT);
2627                     else {
2628                         for (value = 0; value < 256; value++)
2629                             if (!isXDIGIT(value))
2630                                 ANYOF_BITMAP_SET(ret, value);
2631                     }
2632                     break;
2633                 default:
2634                     FAIL("invalid [::] class in regexp");
2635                     break;
2636                 }
2637                 if (LOC)
2638                     ANYOF_FLAGS(ret) |= ANYOF_CLASS;
2639                 continue;
2640             }
2641         }
2642         if (range) {
2643             if (lastvalue > value) /* b-a */ {
2644                 Perl_croak(aTHX_
2645                            "/%.127s/: invalid [] range \"%*.*s\" in regexp",
2646                            PL_regprecomp,
2647                            PL_regcomp_parse - rangebegin,
2648                            PL_regcomp_parse - rangebegin,
2649                            rangebegin);
2650             }
2651             range = 0;
2652         }
2653         else {
2654             lastvalue = value;
2655             if (*PL_regcomp_parse == '-' && PL_regcomp_parse+1 < PL_regxend &&
2656                 PL_regcomp_parse[1] != ']') {
2657                 PL_regcomp_parse++;
2658                 if (namedclass > OOB_NAMEDCLASS) { /* \w-, [:word:]- */
2659                     if (ckWARN(WARN_UNSAFE))
2660                         Perl_warner(aTHX_ WARN_UNSAFE,
2661                                     "/%.127s/: false [] range \"%*.*s\" in regexp",
2662                                     PL_regprecomp,
2663                                     PL_regcomp_parse - rangebegin,
2664                                     PL_regcomp_parse - rangebegin,
2665                                     rangebegin);
2666                     if (!SIZE_ONLY)
2667                         ANYOF_BITMAP_SET(ret, '-');
2668                 } else
2669                     range = 1;
2670                 continue;       /* do it next time */
2671             }
2672         }
2673         /* now is the next time */
2674         if (!SIZE_ONLY) {
2675 #ifndef ASCIIish /* EBCDIC, for example. */
2676             if ((isLOWER(lastvalue) && isLOWER(value)) ||
2677                 (isUPPER(lastvalue) && isUPPER(value)))
2678             {
2679                 I32 i;
2680                 if (isLOWER(lastvalue)) {
2681                     for (i = lastvalue; i <= value; i++)
2682                         if (isLOWER(i))
2683                             ANYOF_BITMAP_SET(ret, i);
2684                 } else {
2685                     for (i = lastvalue; i <= value; i++)
2686                         if (isUPPER(i))
2687                             ANYOF_BITMAP_SET(ret, i);
2688                 }
2689             }
2690             else
2691 #endif
2692                 for ( ; lastvalue <= value; lastvalue++)
2693                     ANYOF_BITMAP_SET(ret, lastvalue);
2694         }
2695         range = 0;
2696     }
2697     if (need_class) {
2698         if (SIZE_ONLY)
2699             PL_regsize += ANYOF_CLASS_ADD_SKIP;
2700         else
2701             PL_regcode += ANYOF_CLASS_ADD_SKIP;
2702     }
2703     /* optimize case-insensitive simple patterns (e.g. /[a-z]/i) */
2704     if (!SIZE_ONLY &&
2705         (ANYOF_FLAGS(ret) & (ANYOF_FLAGS_ALL ^ ANYOF_INVERT)) == ANYOF_FOLD) {
2706         for (value = 0; value < 256; ++value) {
2707             if (ANYOF_BITMAP_TEST(ret, value)) {
2708                 I32 cf = PL_fold[value];
2709                 ANYOF_BITMAP_SET(ret, cf);
2710             }
2711         }
2712         ANYOF_FLAGS(ret) &= ~ANYOF_FOLD;
2713     }
2714     /* optimize inverted simple patterns (e.g. [^a-z]) */
2715     if (!SIZE_ONLY && (ANYOF_FLAGS(ret) & ANYOF_FLAGS_ALL) == ANYOF_INVERT) {
2716         for (value = 0; value < ANYOF_BITMAP_SIZE; ++value)
2717             ANYOF_BITMAP(ret)[value] ^= ANYOF_FLAGS_ALL;
2718         ANYOF_FLAGS(ret) = 0;
2719     }
2720     return ret;
2721 }
2722
2723 STATIC regnode *
2724 S_regclassutf8(pTHX)
2725 {
2726     dTHR;
2727     register char *e;
2728     register U32 value;
2729     register U32 lastvalue = OOB_UTF8;
2730     register I32 range = 0;
2731     register regnode *ret;
2732     I32 numlen;
2733     I32 n;
2734     SV *listsv;
2735     U8 flags = 0;
2736     I32 namedclass;
2737     char *rangebegin;
2738
2739     if (*PL_regcomp_parse == '^') {     /* Complement of range. */
2740         PL_regnaughty++;
2741         PL_regcomp_parse++;
2742         if (!SIZE_ONLY)
2743             flags |= ANYOF_INVERT;
2744     }
2745     if (!SIZE_ONLY) {
2746         if (FOLD)
2747             flags |= ANYOF_FOLD;
2748         if (LOC)
2749             flags |= ANYOF_LOCALE;
2750         listsv = newSVpvn("# comment\n",10);
2751     }
2752
2753     if (!SIZE_ONLY && ckWARN(WARN_UNSAFE))
2754         checkposixcc();
2755
2756     if (*PL_regcomp_parse == ']' || *PL_regcomp_parse == '-')
2757         goto skipcond;          /* allow 1st char to be ] or - */
2758
2759     while (PL_regcomp_parse < PL_regxend && *PL_regcomp_parse != ']') {
2760        skipcond:
2761         namedclass = OOB_NAMEDCLASS;
2762         if (!range)
2763             rangebegin = PL_regcomp_parse;
2764         value = utf8_to_uv((U8*)PL_regcomp_parse, &numlen);
2765         PL_regcomp_parse += numlen;
2766         if (value == '[')
2767             namedclass = regpposixcc(value);
2768         else if (value == '\\') {
2769             value = utf8_to_uv((U8*)PL_regcomp_parse, &numlen);
2770             PL_regcomp_parse += numlen;
2771             switch (value) {
2772             case 'w':           namedclass = ANYOF_ALNUM;               break;
2773             case 'W':           namedclass = ANYOF_NALNUM;              break;
2774             case 's':           namedclass = ANYOF_SPACE;               break;
2775             case 'S':           namedclass = ANYOF_NSPACE;              break;
2776             case 'd':           namedclass = ANYOF_DIGIT;               break;
2777             case 'D':           namedclass = ANYOF_NDIGIT;              break;
2778             case 'p':
2779             case 'P':
2780                 if (*PL_regcomp_parse == '{') {
2781                     e = strchr(PL_regcomp_parse++, '}');
2782                     if (!e)
2783                         FAIL("Missing right brace on \\p{}");
2784                     n = e - PL_regcomp_parse;
2785                 }
2786                 else {
2787                     e = PL_regcomp_parse;
2788                     n = 1;
2789                 }
2790                 if (!SIZE_ONLY) {
2791                     if (value == 'p')
2792                         Perl_sv_catpvf(aTHX_ listsv,
2793                                        "+utf8::%.*s\n", n, PL_regcomp_parse);
2794                     else
2795                         Perl_sv_catpvf(aTHX_ listsv,
2796                                        "!utf8::%.*s\n", n, PL_regcomp_parse);
2797                 }
2798                 PL_regcomp_parse = e + 1;
2799                 lastvalue = OOB_UTF8;
2800                 continue;
2801             case 'n':           value = '\n';           break;
2802             case 'r':           value = '\r';           break;
2803             case 't':           value = '\t';           break;
2804             case 'f':           value = '\f';           break;
2805             case 'b':           value = '\b';           break;
2806             case 'e':           value = '\033';         break;
2807             case 'a':           value = '\007';         break;
2808             case 'x':
2809                 if (*PL_regcomp_parse == '{') {
2810                     e = strchr(PL_regcomp_parse++, '}');
2811                     if (!e)
2812                         FAIL("Missing right brace on \\x{}");
2813                     value = (UV)scan_hex(PL_regcomp_parse,
2814                                      e - PL_regcomp_parse,
2815                                      &numlen);
2816                     PL_regcomp_parse = e + 1;
2817                 }
2818                 else {
2819                     value = (UV)scan_hex(PL_regcomp_parse, 2, &numlen);
2820                     PL_regcomp_parse += numlen;
2821                 }
2822                 break;
2823             case 'c':
2824                 value = UCHARAT(PL_regcomp_parse++);
2825                 value = toCTRL(value);
2826                 break;
2827             case '0': case '1': case '2': case '3': case '4':
2828             case '5': case '6': case '7': case '8': case '9':
2829                 value = (UV)scan_oct(--PL_regcomp_parse, 3, &numlen);
2830                 PL_regcomp_parse += numlen;
2831                 break;
2832             default:
2833                 if (!SIZE_ONLY && ckWARN(WARN_UNSAFE) && isALPHA(value))
2834                     Perl_warner(aTHX_ WARN_UNSAFE, 
2835                                 "/%.127s/: Unrecognized escape \\%c in character class passed through",
2836                                 PL_regprecomp,
2837                                 value);
2838                 break;
2839             }
2840         }
2841         if (namedclass > OOB_NAMEDCLASS) {
2842             if (range) { /* a-\d, a-[:digit:] */
2843                 if (!SIZE_ONLY) {
2844                     if (ckWARN(WARN_UNSAFE))
2845                         Perl_warner(aTHX_ WARN_UNSAFE,
2846                                     "/%.127s/: false [] range \"%*.*s\" in regexp",
2847                                     PL_regprecomp,
2848                                     PL_regcomp_parse - rangebegin,
2849                                     PL_regcomp_parse - rangebegin,
2850                                     rangebegin);
2851                     Perl_sv_catpvf(aTHX_ listsv,
2852                                    /* 0x002D is Unicode for '-' */
2853                                    "%04"UVxf"\n002D\n", (UV)lastvalue);
2854                 }
2855                 range = 0;
2856             }
2857             if (!SIZE_ONLY) {
2858                 switch (namedclass) {
2859                 case ANYOF_ALNUM:
2860                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsWord\n");    break;
2861                 case ANYOF_NALNUM:
2862                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsWord\n");    break;
2863                 case ANYOF_ALNUMC:
2864                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsAlnum\n");   break;
2865                 case ANYOF_NALNUMC:
2866                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsAlnum\n");   break;
2867                 case ANYOF_ALPHA:
2868                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsAlpha\n");   break;
2869                 case ANYOF_NALPHA:
2870                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsAlpha\n");   break;
2871                 case ANYOF_ASCII:
2872                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsASCII\n");   break;
2873                 case ANYOF_NASCII:
2874                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsASCII\n");   break;
2875                 case ANYOF_CNTRL:
2876                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsCntrl\n");   break;
2877                 case ANYOF_NCNTRL:
2878                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsCntrl\n");   break;
2879                 case ANYOF_GRAPH:
2880                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsGraph\n");   break;
2881                 case ANYOF_NGRAPH:
2882                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsGraph\n");   break;
2883                 case ANYOF_DIGIT:
2884                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsDigit\n");   break;
2885                 case ANYOF_NDIGIT:
2886                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsDigit\n");   break;
2887                 case ANYOF_LOWER:
2888                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsLower\n");   break;
2889                 case ANYOF_NLOWER:
2890                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsLower\n");   break;
2891                 case ANYOF_PRINT:
2892                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsPrint\n");   break;
2893                 case ANYOF_NPRINT:
2894                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsPrint\n");   break;
2895                 case ANYOF_PUNCT:
2896                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsPunct\n");   break;
2897                 case ANYOF_NPUNCT:
2898                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsPunct\n");   break;
2899                 case ANYOF_SPACE:
2900                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsSpace\n");   break;
2901                 case ANYOF_NSPACE:
2902                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsSpace\n");   break;
2903                 case ANYOF_UPPER:
2904                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsUpper\n");   break;
2905                 case ANYOF_NUPPER:
2906                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsUpper\n");   break;
2907                 case ANYOF_XDIGIT:
2908                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsXDigit\n");  break;
2909                 case ANYOF_NXDIGIT:
2910                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsXDigit\n");  break;
2911                 }
2912                 continue;
2913             }
2914         }
2915         if (range) {
2916             if (lastvalue > value) { /* b-a */
2917                 Perl_croak(aTHX_
2918                            "/%.127s/: invalid [] range \"%*.*s\" in regexp",
2919                            PL_regprecomp,
2920                            PL_regcomp_parse - rangebegin,
2921                            PL_regcomp_parse - rangebegin,
2922                            rangebegin);
2923             }
2924             range = 0;
2925         }
2926         else {
2927             lastvalue = value;
2928             if (*PL_regcomp_parse == '-' && PL_regcomp_parse+1 < PL_regxend &&
2929                 PL_regcomp_parse[1] != ']') {
2930                 PL_regcomp_parse++;
2931                 if (namedclass > OOB_NAMEDCLASS) { /* \w-, [:word:]- */
2932                     if (ckWARN(WARN_UNSAFE))
2933                         Perl_warner(aTHX_ WARN_UNSAFE,
2934                                     "/%.127s/: false [] range \"%*.*s\" in regexp",
2935                                     PL_regprecomp,
2936                                     PL_regcomp_parse - rangebegin,
2937                                     PL_regcomp_parse - rangebegin,
2938                                     rangebegin);
2939                     if (!SIZE_ONLY)
2940                         Perl_sv_catpvf(aTHX_ listsv,
2941                                        /* 0x002D is Unicode for '-' */
2942                                        "002D\n");
2943                 } else
2944                     range = 1;
2945                 continue;       /* do it next time */
2946             }
2947         }
2948         /* now is the next time */
2949         if (!SIZE_ONLY)
2950             Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\t%04"UVxf"\n",
2951                            (UV)lastvalue, (UV)value);
2952         range = 0;
2953     }
2954
2955     ret = reganode(ANYOFUTF8, 0);
2956
2957     if (!SIZE_ONLY) {
2958         SV *rv = swash_init("utf8", "", listsv, 1, 0);
2959         SvREFCNT_dec(listsv);
2960         n = add_data(1,"s");
2961         PL_regcomp_rx->data->data[n] = (void*)rv;
2962         ARG1_SET(ret, flags);
2963         ARG2_SET(ret, n);
2964     }
2965
2966     return ret;
2967 }
2968
2969 STATIC char*
2970 S_nextchar(pTHX)
2971 {
2972     dTHR;
2973     char* retval = PL_regcomp_parse++;
2974
2975     for (;;) {
2976         if (*PL_regcomp_parse == '(' && PL_regcomp_parse[1] == '?' &&
2977                 PL_regcomp_parse[2] == '#') {
2978             while (*PL_regcomp_parse && *PL_regcomp_parse != ')')
2979                 PL_regcomp_parse++;
2980             PL_regcomp_parse++;
2981             continue;
2982         }
2983         if (PL_regflags & PMf_EXTENDED) {
2984             if (isSPACE(*PL_regcomp_parse)) {
2985                 PL_regcomp_parse++;
2986                 continue;
2987             }
2988             else if (*PL_regcomp_parse == '#') {
2989                 while (*PL_regcomp_parse && *PL_regcomp_parse != '\n')
2990                     PL_regcomp_parse++;
2991                 PL_regcomp_parse++;
2992                 continue;
2993             }
2994         }
2995         return retval;
2996     }
2997 }
2998
2999 /*
3000 - reg_node - emit a node
3001 */
3002 STATIC regnode *                        /* Location. */
3003 S_reg_node(pTHX_ U8 op)
3004 {
3005     dTHR;
3006     register regnode *ret;
3007     register regnode *ptr;
3008
3009     ret = PL_regcode;
3010     if (SIZE_ONLY) {
3011         SIZE_ALIGN(PL_regsize);
3012         PL_regsize += 1;
3013         return(ret);
3014     }
3015
3016     NODE_ALIGN_FILL(ret);
3017     ptr = ret;
3018     FILL_ADVANCE_NODE(ptr, op);
3019     PL_regcode = ptr;
3020
3021     return(ret);
3022 }
3023
3024 /*
3025 - reganode - emit a node with an argument
3026 */
3027 STATIC regnode *                        /* Location. */
3028 S_reganode(pTHX_ U8 op, U32 arg)
3029 {
3030     dTHR;
3031     register regnode *ret;
3032     register regnode *ptr;
3033
3034     ret = PL_regcode;
3035     if (SIZE_ONLY) {
3036         SIZE_ALIGN(PL_regsize);
3037         PL_regsize += 2;
3038         return(ret);
3039     }
3040
3041     NODE_ALIGN_FILL(ret);
3042     ptr = ret;
3043     FILL_ADVANCE_NODE_ARG(ptr, op, arg);
3044     PL_regcode = ptr;
3045
3046     return(ret);
3047 }
3048
3049 /*
3050 - reguni - emit (if appropriate) a Unicode character
3051 */
3052 STATIC void
3053 S_reguni(pTHX_ UV uv, char* s, I32* lenp)
3054 {
3055     dTHR;
3056     if (SIZE_ONLY) {
3057         U8 tmpbuf[10];
3058         *lenp = uv_to_utf8(tmpbuf, uv) - tmpbuf;
3059     }
3060     else
3061         *lenp = uv_to_utf8((U8*)s, uv) - (U8*)s;
3062
3063 }
3064
3065 /*
3066 - reginsert - insert an operator in front of already-emitted operand
3067 *
3068 * Means relocating the operand.
3069 */
3070 STATIC void
3071 S_reginsert(pTHX_ U8 op, regnode *opnd)
3072 {
3073     dTHR;
3074     register regnode *src;
3075     register regnode *dst;
3076     register regnode *place;
3077     register int offset = regarglen[(U8)op];
3078     
3079 /* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
3080
3081     if (SIZE_ONLY) {
3082         PL_regsize += NODE_STEP_REGNODE + offset;
3083         return;
3084     }
3085
3086     src = PL_regcode;
3087     PL_regcode += NODE_STEP_REGNODE + offset;
3088     dst = PL_regcode;
3089     while (src > opnd)
3090         StructCopy(--src, --dst, regnode);
3091
3092     place = opnd;               /* Op node, where operand used to be. */
3093     src = NEXTOPER(place);
3094     FILL_ADVANCE_NODE(place, op);
3095     Zero(src, offset, regnode);
3096 }
3097
3098 /*
3099 - regtail - set the next-pointer at the end of a node chain of p to val.
3100 */
3101 STATIC void
3102 S_regtail(pTHX_ regnode *p, regnode *val)
3103 {
3104     dTHR;
3105     register regnode *scan;
3106     register regnode *temp;
3107     register I32 offset;
3108
3109     if (SIZE_ONLY)
3110         return;
3111
3112     /* Find last node. */
3113     scan = p;
3114     for (;;) {
3115         temp = regnext(scan);
3116         if (temp == NULL)
3117             break;
3118         scan = temp;
3119     }
3120
3121     if (reg_off_by_arg[OP(scan)]) {
3122         ARG_SET(scan, val - scan);
3123     }
3124     else {
3125         NEXT_OFF(scan) = val - scan;
3126     }
3127 }
3128
3129 /*
3130 - regoptail - regtail on operand of first argument; nop if operandless
3131 */
3132 STATIC void
3133 S_regoptail(pTHX_ regnode *p, regnode *val)
3134 {
3135     dTHR;
3136     /* "Operandless" and "op != BRANCH" are synonymous in practice. */
3137     if (p == NULL || SIZE_ONLY)
3138         return;
3139     if (PL_regkind[(U8)OP(p)] == BRANCH) {
3140         regtail(NEXTOPER(p), val);
3141     }
3142     else if ( PL_regkind[(U8)OP(p)] == BRANCHJ) {
3143         regtail(NEXTOPER(NEXTOPER(p)), val);
3144     }
3145     else
3146         return;
3147 }
3148
3149 /*
3150  - regcurly - a little FSA that accepts {\d+,?\d*}
3151  */
3152 STATIC I32
3153 S_regcurly(pTHX_ register char *s)
3154 {
3155     if (*s++ != '{')
3156         return FALSE;
3157     if (!isDIGIT(*s))
3158         return FALSE;
3159     while (isDIGIT(*s))
3160         s++;
3161     if (*s == ',')
3162         s++;
3163     while (isDIGIT(*s))
3164         s++;
3165     if (*s != '}')
3166         return FALSE;
3167     return TRUE;
3168 }
3169
3170
3171 STATIC regnode *
3172 S_dumpuntil(pTHX_ regnode *start, regnode *node, regnode *last, SV* sv, I32 l)
3173 {
3174 #ifdef DEBUGGING
3175     register U8 op = EXACT;     /* Arbitrary non-END op. */
3176     register regnode *next, *onode;
3177
3178     while (op != END && (!last || node < last)) {
3179         /* While that wasn't END last time... */
3180
3181         NODE_ALIGN(node);
3182         op = OP(node);
3183         if (op == CLOSE)
3184             l--;        
3185         next = regnext(node);
3186         /* Where, what. */
3187         if (OP(node) == OPTIMIZED)
3188             goto after_print;
3189         regprop(sv, node);
3190         PerlIO_printf(Perl_debug_log, "%4"IVdf":%*s%s", (IV)(node - start),
3191                       2*l + 1, "", SvPVX(sv));
3192         if (next == NULL)               /* Next ptr. */
3193             PerlIO_printf(Perl_debug_log, "(0)");
3194         else 
3195             PerlIO_printf(Perl_debug_log, "(%"IVdf")", (IV)(next - start));
3196         (void)PerlIO_putc(Perl_debug_log, '\n');
3197       after_print:
3198         if (PL_regkind[(U8)op] == BRANCHJ) {
3199             register regnode *nnode = (OP(next) == LONGJMP 
3200                                        ? regnext(next) 
3201                                        : next);
3202             if (last && nnode > last)
3203                 nnode = last;
3204             node = dumpuntil(start, NEXTOPER(NEXTOPER(node)), nnode, sv, l + 1);
3205         }
3206         else if (PL_regkind[(U8)op] == BRANCH) {
3207             node = dumpuntil(start, NEXTOPER(node), next, sv, l + 1);
3208         }
3209         else if ( op == CURLY) {   /* `next' might be very big: optimizer */
3210             node = dumpuntil(start, NEXTOPER(node) + EXTRA_STEP_2ARGS,
3211                              NEXTOPER(node) + EXTRA_STEP_2ARGS + 1, sv, l + 1);
3212         }
3213         else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
3214             node = dumpuntil(start, NEXTOPER(node) + EXTRA_STEP_2ARGS,
3215                              next, sv, l + 1);
3216         }
3217         else if ( op == PLUS || op == STAR) {
3218             node = dumpuntil(start, NEXTOPER(node), NEXTOPER(node) + 1, sv, l + 1);
3219         }
3220         else if (op == ANYOF) {
3221             node = NEXTOPER(node);
3222             node += ANYOF_SKIP;
3223         }
3224         else if (PL_regkind[(U8)op] == EXACT) {
3225             /* Literal string, where present. */
3226             node += NODE_SZ_STR(node) - 1;
3227             node = NEXTOPER(node);
3228         }
3229         else {
3230             node = NEXTOPER(node);
3231             node += regarglen[(U8)op];
3232         }
3233         if (op == CURLYX || op == OPEN)
3234             l++;
3235         else if (op == WHILEM)
3236             l--;
3237     }
3238 #endif  /* DEBUGGING */
3239     return node;
3240 }
3241
3242 /*
3243  - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
3244  */
3245 void
3246 Perl_regdump(pTHX_ regexp *r)
3247 {
3248 #ifdef DEBUGGING
3249     dTHR;
3250     SV *sv = sv_newmortal();
3251
3252     (void)dumpuntil(r->program, r->program + 1, NULL, sv, 0);
3253
3254     /* Header fields of interest. */
3255     if (r->anchored_substr)
3256         PerlIO_printf(Perl_debug_log,
3257                       "anchored `%s%.*s%s'%s at %"IVdf" ", 
3258                       PL_colors[0],
3259                       (int)(SvCUR(r->anchored_substr) - (SvTAIL(r->anchored_substr)!=0)),
3260                       SvPVX(r->anchored_substr), 
3261                       PL_colors[1],
3262                       SvTAIL(r->anchored_substr) ? "$" : "",
3263                       (IV)r->anchored_offset);
3264     if (r->float_substr)
3265         PerlIO_printf(Perl_debug_log,
3266                       "floating `%s%.*s%s'%s at %"IVdf"..%"UVuf" ", 
3267                       PL_colors[0],
3268                       (int)(SvCUR(r->float_substr) - (SvTAIL(r->float_substr)!=0)), 
3269                       SvPVX(r->float_substr),
3270                       PL_colors[1],
3271                       SvTAIL(r->float_substr) ? "$" : "",
3272                       (IV)r->float_min_offset, (UV)r->float_max_offset);
3273     if (r->check_substr)
3274         PerlIO_printf(Perl_debug_log, 
3275                       r->check_substr == r->float_substr 
3276                       ? "(checking floating" : "(checking anchored");
3277     if (r->reganch & ROPT_NOSCAN)
3278         PerlIO_printf(Perl_debug_log, " noscan");
3279     if (r->reganch & ROPT_CHECK_ALL)
3280         PerlIO_printf(Perl_debug_log, " isall");
3281     if (r->check_substr)
3282         PerlIO_printf(Perl_debug_log, ") ");
3283
3284     if (r->regstclass) {
3285         regprop(sv, r->regstclass);
3286         PerlIO_printf(Perl_debug_log, "stclass `%s' ", SvPVX(sv));
3287     }
3288     if (r->reganch & ROPT_ANCH) {
3289         PerlIO_printf(Perl_debug_log, "anchored");
3290         if (r->reganch & ROPT_ANCH_BOL)
3291             PerlIO_printf(Perl_debug_log, "(BOL)");
3292         if (r->reganch & ROPT_ANCH_MBOL)
3293             PerlIO_printf(Perl_debug_log, "(MBOL)");
3294         if (r->reganch & ROPT_ANCH_SBOL)
3295             PerlIO_printf(Perl_debug_log, "(SBOL)");
3296         if (r->reganch & ROPT_ANCH_GPOS)
3297             PerlIO_printf(Perl_debug_log, "(GPOS)");
3298         PerlIO_putc(Perl_debug_log, ' ');
3299     }
3300     if (r->reganch & ROPT_GPOS_SEEN)
3301         PerlIO_printf(Perl_debug_log, "GPOS ");
3302     if (r->reganch & ROPT_SKIP)
3303         PerlIO_printf(Perl_debug_log, "plus ");
3304     if (r->reganch & ROPT_IMPLICIT)
3305         PerlIO_printf(Perl_debug_log, "implicit ");
3306     PerlIO_printf(Perl_debug_log, "minlen %ld ", (long) r->minlen);
3307     if (r->reganch & ROPT_EVAL_SEEN)
3308         PerlIO_printf(Perl_debug_log, "with eval ");
3309     PerlIO_printf(Perl_debug_log, "\n");
3310 #endif  /* DEBUGGING */
3311 }
3312
3313 /*
3314 - regprop - printable representation of opcode
3315 */
3316 void
3317 Perl_regprop(pTHX_ SV *sv, regnode *o)
3318 {
3319 #ifdef DEBUGGING
3320     dTHR;
3321     register int k;
3322
3323     sv_setpvn(sv, "", 0);
3324     if (OP(o) >= reg_num)               /* regnode.type is unsigned */
3325         FAIL("corrupted regexp opcode");
3326     sv_catpv(sv, (char*)reg_name[OP(o)]); /* Take off const! */
3327
3328     k = PL_regkind[(U8)OP(o)];
3329
3330     if (k == EXACT)
3331         Perl_sv_catpvf(aTHX_ sv, " <%s%.*s%s>", PL_colors[0],
3332                        STR_LEN(o), STRING(o), PL_colors[1]);
3333     else if (k == CURLY) {
3334         if (OP(o) == CURLYM || OP(o) == CURLYN)
3335             Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
3336         Perl_sv_catpvf(aTHX_ sv, " {%d,%d}", ARG1(o), ARG2(o));
3337     }
3338     else if (k == WHILEM && o->flags)                   /* Ordinal/of */
3339         Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
3340     else if (k == REF || k == OPEN || k == CLOSE || k == GROUPP )
3341         Perl_sv_catpvf(aTHX_ sv, "%d", ARG(o)); /* Parenth number */
3342     else if (k == LOGICAL)
3343         Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags);     /* 2: embedded, otherwise 1 */
3344     else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH))
3345         Perl_sv_catpvf(aTHX_ sv, "[-%d]", o->flags);
3346 #endif  /* DEBUGGING */
3347 }
3348
3349 SV *
3350 Perl_re_intuit_string(pTHX_ regexp *prog)
3351 {                               /* Assume that RE_INTUIT is set */
3352     DEBUG_r(
3353         {   STRLEN n_a;
3354             char *s = SvPV(prog->check_substr,n_a);
3355
3356             if (!PL_colorset) reginitcolors();
3357             PerlIO_printf(Perl_debug_log,
3358                       "%sUsing REx substr:%s `%s%.60s%s%s'\n",
3359                       PL_colors[4],PL_colors[5],PL_colors[0],
3360                       s,
3361                       PL_colors[1],
3362                       (strlen(s) > 60 ? "..." : ""));
3363         } );
3364
3365     return prog->check_substr;
3366 }
3367
3368 void
3369 Perl_pregfree(pTHX_ struct regexp *r)
3370 {
3371     dTHR;
3372     DEBUG_r(if (!PL_colorset) reginitcolors());
3373
3374     if (!r || (--r->refcnt > 0))
3375         return;
3376     DEBUG_r(PerlIO_printf(Perl_debug_log,
3377                       "%sFreeing REx:%s `%s%.60s%s%s'\n",
3378                       PL_colors[4],PL_colors[5],PL_colors[0],
3379                       r->precomp,
3380                       PL_colors[1],
3381                       (strlen(r->precomp) > 60 ? "..." : "")));
3382
3383     if (r->precomp)
3384         Safefree(r->precomp);
3385     if (RX_MATCH_COPIED(r))
3386         Safefree(r->subbeg);
3387     if (r->substrs) {
3388         if (r->anchored_substr)
3389             SvREFCNT_dec(r->anchored_substr);
3390         if (r->float_substr)
3391             SvREFCNT_dec(r->float_substr);
3392         Safefree(r->substrs);
3393     }
3394     if (r->data) {
3395         int n = r->data->count;
3396         AV* new_comppad = NULL;
3397         AV* old_comppad;
3398         SV** old_curpad;
3399
3400         while (--n >= 0) {
3401             switch (r->data->what[n]) {
3402             case 's':
3403                 SvREFCNT_dec((SV*)r->data->data[n]);
3404                 break;
3405             case 'p':
3406                 new_comppad = (AV*)r->data->data[n];
3407                 break;
3408             case 'o':
3409                 if (new_comppad == NULL)
3410                     Perl_croak(aTHX_ "panic: pregfree comppad");
3411                 old_comppad = PL_comppad;
3412                 old_curpad = PL_curpad;
3413                 PL_comppad = new_comppad;
3414                 PL_curpad = AvARRAY(new_comppad);
3415                 op_free((OP_4tree*)r->data->data[n]);
3416                 PL_comppad = old_comppad;
3417                 PL_curpad = old_curpad;
3418                 SvREFCNT_dec((SV*)new_comppad);
3419                 new_comppad = NULL;
3420                 break;
3421             case 'n':
3422                 break;
3423             default:
3424                 FAIL2("panic: regfree data code '%c'", r->data->what[n]);
3425             }
3426         }
3427         Safefree(r->data->what);
3428         Safefree(r->data);
3429     }
3430     Safefree(r->startp);
3431     Safefree(r->endp);
3432     Safefree(r);
3433 }
3434
3435 /*
3436  - regnext - dig the "next" pointer out of a node
3437  *
3438  * [Note, when REGALIGN is defined there are two places in regmatch()
3439  * that bypass this code for speed.]
3440  */
3441 regnode *
3442 Perl_regnext(pTHX_ register regnode *p)
3443 {
3444     dTHR;
3445     register I32 offset;
3446
3447     if (p == &PL_regdummy)
3448         return(NULL);
3449
3450     offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
3451     if (offset == 0)
3452         return(NULL);
3453
3454     return(p+offset);
3455 }
3456
3457 STATIC void     
3458 S_re_croak2(pTHX_ const char* pat1,const char* pat2,...)
3459 {
3460     va_list args;
3461     STRLEN l1 = strlen(pat1);
3462     STRLEN l2 = strlen(pat2);
3463     char buf[512];
3464     SV *msv;
3465     char *message;
3466
3467     if (l1 > 510)
3468         l1 = 510;
3469     if (l1 + l2 > 510)
3470         l2 = 510 - l1;
3471     Copy(pat1, buf, l1 , char);
3472     Copy(pat2, buf + l1, l2 , char);
3473     buf[l1 + l2] = '\n';
3474     buf[l1 + l2 + 1] = '\0';
3475 #ifdef I_STDARG
3476     /* ANSI variant takes additional second argument */
3477     va_start(args, pat2);
3478 #else
3479     va_start(args);
3480 #endif
3481     msv = vmess(buf, &args);
3482     va_end(args);
3483     message = SvPV(msv,l1);
3484     if (l1 > 512)
3485         l1 = 512;
3486     Copy(message, buf, l1 , char);
3487     buf[l1] = '\0';                     /* Overwrite \n */
3488     Perl_croak(aTHX_ "%s", buf);
3489 }
3490
3491 /* XXX Here's a total kludge.  But we need to re-enter for swash routines. */
3492
3493 void
3494 Perl_save_re_context(pTHX)
3495 {                   
3496     dTHR;
3497     SAVEPPTR(PL_bostr);
3498     SAVEPPTR(PL_regprecomp);            /* uncompiled string. */
3499     SAVEI32(PL_regnpar);                /* () count. */
3500     SAVEI32(PL_regsize);                /* Code size. */
3501     SAVEI16(PL_regflags);               /* are we folding, multilining? */
3502     SAVEPPTR(PL_reginput);              /* String-input pointer. */
3503     SAVEPPTR(PL_regbol);                /* Beginning of input, for ^ check. */
3504     SAVEPPTR(PL_regeol);                /* End of input, for $ check. */
3505     SAVESPTR(PL_regstartp);             /* Pointer to startp array. */
3506     SAVESPTR(PL_regendp);               /* Ditto for endp. */
3507     SAVESPTR(PL_reglastparen);          /* Similarly for lastparen. */
3508     SAVEPPTR(PL_regtill);               /* How far we are required to go. */
3509     SAVEI32(PL_regprev);                /* char before regbol, \n if none */
3510     SAVESPTR(PL_reg_start_tmp);         /* from regexec.c */
3511     PL_reg_start_tmp = 0;
3512     SAVEFREEPV(PL_reg_start_tmp);
3513     SAVEI32(PL_reg_start_tmpl);         /* from regexec.c */
3514     PL_reg_start_tmpl = 0;
3515     SAVESPTR(PL_regdata);
3516     SAVEI32(PL_reg_flags);              /* from regexec.c */
3517     SAVEI32(PL_reg_eval_set);           /* from regexec.c */
3518     SAVEI32(PL_regnarrate);             /* from regexec.c */
3519     SAVESPTR(PL_regprogram);            /* from regexec.c */
3520     SAVEINT(PL_regindent);              /* from regexec.c */
3521     SAVESPTR(PL_regcc);                 /* from regexec.c */
3522     SAVESPTR(PL_curcop);
3523     SAVESPTR(PL_regcomp_rx);            /* from regcomp.c */
3524     SAVEI32(PL_regseen);                /* from regcomp.c */
3525     SAVEI32(PL_regsawback);             /* Did we see \1, ...? */
3526     SAVEI32(PL_regnaughty);             /* How bad is this pattern? */
3527     SAVESPTR(PL_regcode);               /* Code-emit pointer; &regdummy = don't */
3528     SAVEPPTR(PL_regxend);               /* End of input for compile */
3529     SAVEPPTR(PL_regcomp_parse);         /* Input-scan pointer. */
3530     SAVESPTR(PL_reg_call_cc);           /* from regexec.c */
3531     SAVESPTR(PL_reg_re);                /* from regexec.c */
3532     SAVEPPTR(PL_reg_ganch);             /* from regexec.c */
3533     SAVESPTR(PL_reg_sv);                /* from regexec.c */
3534     SAVESPTR(PL_reg_magic);             /* from regexec.c */
3535     SAVEI32(PL_reg_oldpos);                     /* from regexec.c */
3536     SAVESPTR(PL_reg_oldcurpm);          /* from regexec.c */
3537     SAVESPTR(PL_reg_curpm);             /* from regexec.c */
3538 #ifdef DEBUGGING
3539     SAVEPPTR(PL_reg_starttry);          /* from regexec.c */    
3540 #endif
3541 }
3542
3543 #ifdef PERL_OBJECT
3544 #include "XSUB.h"
3545 #undef this
3546 #define this pPerl
3547 #endif
3548
3549 static void
3550 clear_re(pTHXo_ void *r)
3551 {
3552     ReREFCNT_dec((regexp *)r);
3553 }
3554