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