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