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