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