07822329edc9db2389d60531192540cc6e8fb792
[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 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(PerlIO_printf(Perl_debug_log, "compiling RE `%*s'\n",
802                           xend - exp, PL_regprecomp));
803     PL_regflags = pm->op_pmflags;
804     PL_regsawback = 0;
805
806     PL_regseen = 0;
807     PL_seen_zerolen = *exp == '^' ? -1 : 0;
808     PL_seen_evals = 0;
809     PL_extralen = 0;
810
811     /* First pass: determine size, legality. */
812     PL_regcomp_parse = exp;
813     PL_regxend = xend;
814     PL_regnaughty = 0;
815     PL_regnpar = 1;
816     PL_regsize = 0L;
817     PL_regcode = &PL_regdummy;
818     regc((U8)MAGIC, (char*)PL_regcode);
819     if (reg(0, &flags) == NULL) {
820         Safefree(PL_regprecomp);
821         PL_regprecomp = Nullch;
822         return(NULL);
823     }
824     DEBUG_r(PerlIO_printf(Perl_debug_log, "size %d ", PL_regsize));
825
826     DEBUG_r(
827         if (!PL_colorset) {
828             int i = 0;
829             char *s = PerlEnv_getenv("TERMCAP_COLORS");
830             
831             PL_colorset = 1;
832             if (s) {
833                 PL_colors[0] = s = savepv(s);
834                 while (++i < 4) {
835                     s = strchr(s, '\t');
836                     if (!s) 
837                         FAIL("Not enough TABs in TERMCAP_COLORS");
838                     *s = '\0';
839                     PL_colors[i] = ++s;
840                 }
841             }
842             else {
843                 while (i < 4) 
844                     PL_colors[i++] = "";
845             }
846             /* Reset colors: */
847             PerlIO_printf(Perl_debug_log, "%s%s%s%s", 
848                           PL_colors[0],PL_colors[1],PL_colors[2],PL_colors[3]);
849         }
850         );
851
852     /* Small enough for pointer-storage convention?
853        If extralen==0, this means that we will not need long jumps. */
854     if (PL_regsize >= 0x10000L && PL_extralen)
855         PL_regsize += PL_extralen;
856     else
857         PL_extralen = 0;
858
859     /* Allocate space and initialize. */
860     Newc(1001, r, sizeof(regexp) + (unsigned)PL_regsize * sizeof(regnode),
861          char, regexp);
862     if (r == NULL)
863         FAIL("regexp out of space");
864     r->refcnt = 1;
865     r->prelen = xend - exp;
866     r->precomp = PL_regprecomp;
867     r->subbeg = r->subbase = NULL;
868     r->nparens = PL_regnpar - 1;                /* set early to validate backrefs */
869     PL_regcomp_rx = r;
870
871     /* Second pass: emit code. */
872     PL_regcomp_parse = exp;
873     PL_regxend = xend;
874     PL_regnaughty = 0;
875     PL_regnpar = 1;
876     PL_regcode = r->program;
877     /* Store the count of eval-groups for security checks: */
878     PL_regcode->next_off = ((PL_seen_evals > U16_MAX) ? U16_MAX : PL_seen_evals);
879     regc((U8)MAGIC, (char*) PL_regcode++);
880     r->data = 0;
881     if (reg(0, &flags) == NULL)
882         return(NULL);
883
884     /* Dig out information for optimizations. */
885     r->reganch = pm->op_pmflags & PMf_COMPILETIME;
886     pm->op_pmflags = PL_regflags;
887     if (UTF)
888         r->reganch |= ROPT_UTF8;
889     r->regstclass = NULL;
890     if (PL_regnaughty >= 10)    /* Probably an expensive pattern. */
891         r->reganch |= ROPT_NAUGHTY;
892     scan = r->program + 1;              /* First BRANCH. */
893
894     /* XXXX To minimize changes to RE engine we always allocate
895        3-units-long substrs field. */
896     Newz(1004, r->substrs, 1, struct reg_substr_data);
897
898     if (OP(scan) != BRANCH) {   /* Only one top-level choice. */
899         scan_data_t data;
900         I32 fake;
901         STRLEN longest_float_length, longest_fixed_length;
902
903         StructCopy(&zero_scan_data, &data, scan_data_t);
904         first = scan;
905         /* Skip introductions and multiplicators >= 1. */
906         while ((OP(first) == OPEN && (sawopen = 1)) ||
907             (OP(first) == BRANCH && OP(regnext(first)) != BRANCH) ||
908             (OP(first) == PLUS) ||
909             (OP(first) == MINMOD) ||
910             (regkind[(U8)OP(first)] == CURLY && ARG1(first) > 0) ) {
911                 if (OP(first) == PLUS)
912                     sawplus = 1;
913                 else
914                     first += regarglen[(U8)OP(first)];
915                 first = NEXTOPER(first);
916         }
917
918         /* Starting-point info. */
919       again:
920         if (OP(first) == EXACT);        /* Empty, get anchored substr later. */
921         else if (strchr(simple+4,OP(first)))
922             r->regstclass = first;
923         else if (regkind[(U8)OP(first)] == BOUND ||
924                  regkind[(U8)OP(first)] == NBOUND)
925             r->regstclass = first;
926         else if (regkind[(U8)OP(first)] == BOL) {
927             r->reganch |= (OP(first) == MBOL ? ROPT_ANCH_MBOL: ROPT_ANCH_BOL);
928             first = NEXTOPER(first);
929             goto again;
930         }
931         else if (OP(first) == GPOS) {
932             r->reganch |= ROPT_ANCH_GPOS;
933             first = NEXTOPER(first);
934             goto again;
935         }
936         else if ((OP(first) == STAR &&
937             regkind[(U8)OP(NEXTOPER(first))] == ANY) &&
938             !(r->reganch & ROPT_ANCH) )
939         {
940             /* turn .* into ^.* with an implied $*=1 */
941             r->reganch |= ROPT_ANCH_BOL | ROPT_IMPLICIT;
942             first = NEXTOPER(first);
943             goto again;
944         }
945         if (sawplus && (!sawopen || !PL_regsawback))
946             r->reganch |= ROPT_SKIP;    /* x+ must match 1st of run */
947
948         /* Scan is after the zeroth branch, first is atomic matcher. */
949         DEBUG_r(PerlIO_printf(Perl_debug_log, "first at %d\n", 
950                               first - scan + 1));
951         /*
952         * If there's something expensive in the r.e., find the
953         * longest literal string that must appear and make it the
954         * regmust.  Resolve ties in favor of later strings, since
955         * the regstart check works with the beginning of the r.e.
956         * and avoiding duplication strengthens checking.  Not a
957         * strong reason, but sufficient in the absence of others.
958         * [Now we resolve ties in favor of the earlier string if
959         * it happens that c_offset_min has been invalidated, since the
960         * earlier string may buy us something the later one won't.]
961         */
962         minlen = 0;
963
964         data.longest_fixed = newSVpv("",0);
965         data.longest_float = newSVpv("",0);
966         data.last_found = newSVpv("",0);
967         data.longest = &(data.longest_fixed);
968         first = scan;
969         
970         minlen = study_chunk(&first, &fake, scan + PL_regsize, /* Up to end */
971                              &data, SCF_DO_SUBSTR);
972         if ( PL_regnpar == 1 && data.longest == &(data.longest_fixed)
973              && data.last_start_min == 0 && data.last_end > 0 
974              && !PL_seen_zerolen
975              && (!(PL_regseen & REG_SEEN_GPOS) || (r->reganch & ROPT_ANCH_GPOS)))
976             r->reganch |= ROPT_CHECK_ALL;
977         scan_commit(&data);
978         SvREFCNT_dec(data.last_found);
979
980         longest_float_length = CHR_SVLEN(data.longest_float);
981         if (longest_float_length
982             || (data.flags & SF_FL_BEFORE_EOL
983                 && (!(data.flags & SF_FL_BEFORE_MEOL)
984                     || (PL_regflags & PMf_MULTILINE)))) {
985             if (SvCUR(data.longest_fixed)                       /* ok to leave SvCUR */
986                 && data.offset_fixed == data.offset_float_min
987                 && SvCUR(data.longest_fixed) == SvCUR(data.longest_float))
988                     goto remove_float;          /* As in (a)+. */
989
990             r->float_substr = data.longest_float;
991             r->float_min_offset = data.offset_float_min;
992             r->float_max_offset = data.offset_float_max;
993             fbm_compile(r->float_substr, 0);
994             BmUSEFUL(r->float_substr) = 100;
995             if (data.flags & SF_FL_BEFORE_EOL /* Cannot have SEOL and MULTI */
996                 && (!(data.flags & SF_FL_BEFORE_MEOL)
997                     || (PL_regflags & PMf_MULTILINE))) 
998                 SvTAIL_on(r->float_substr);
999         }
1000         else {
1001           remove_float:
1002             r->float_substr = Nullsv;
1003             SvREFCNT_dec(data.longest_float);
1004             longest_float_length = 0;
1005         }
1006
1007         longest_fixed_length = CHR_SVLEN(data.longest_fixed);
1008         if (longest_fixed_length
1009             || (data.flags & SF_FIX_BEFORE_EOL /* Cannot have SEOL and MULTI */
1010                 && (!(data.flags & SF_FIX_BEFORE_MEOL)
1011                     || (PL_regflags & PMf_MULTILINE)))) {
1012             r->anchored_substr = data.longest_fixed;
1013             r->anchored_offset = data.offset_fixed;
1014             fbm_compile(r->anchored_substr, 0);
1015             BmUSEFUL(r->anchored_substr) = 100;
1016             if (data.flags & SF_FIX_BEFORE_EOL /* Cannot have SEOL and MULTI */
1017                 && (!(data.flags & SF_FIX_BEFORE_MEOL)
1018                     || (PL_regflags & PMf_MULTILINE)))
1019                 SvTAIL_on(r->anchored_substr);
1020         }
1021         else {
1022             r->anchored_substr = Nullsv;
1023             SvREFCNT_dec(data.longest_fixed);
1024             longest_fixed_length = 0;
1025         }
1026
1027         /* A temporary algorithm prefers floated substr to fixed one to dig more info. */
1028         if (longest_fixed_length > longest_float_length) {
1029             r->check_substr = r->anchored_substr;
1030             r->check_offset_min = r->check_offset_max = r->anchored_offset;
1031             if (r->reganch & ROPT_ANCH_SINGLE)
1032                 r->reganch |= ROPT_NOSCAN;
1033         }
1034         else {
1035             r->check_substr = r->float_substr;
1036             r->check_offset_min = data.offset_float_min;
1037             r->check_offset_max = data.offset_float_max;
1038         }
1039     }
1040     else {
1041         /* Several toplevels. Best we can is to set minlen. */
1042         I32 fake;
1043         
1044         DEBUG_r(PerlIO_printf(Perl_debug_log, "\n"));
1045         scan = r->program + 1;
1046         minlen = study_chunk(&scan, &fake, scan + PL_regsize, NULL, 0);
1047         r->check_substr = r->anchored_substr = r->float_substr = Nullsv;
1048     }
1049
1050     r->minlen = minlen;
1051     if (PL_regseen & REG_SEEN_GPOS) 
1052         r->reganch |= ROPT_GPOS_SEEN;
1053     if (PL_regseen & REG_SEEN_LOOKBEHIND)
1054         r->reganch |= ROPT_LOOKBEHIND_SEEN;
1055     if (PL_regseen & REG_SEEN_EVAL)
1056         r->reganch |= ROPT_EVAL_SEEN;
1057     Newz(1002, r->startp, PL_regnpar, char*);
1058     Newz(1002, r->endp, PL_regnpar, char*);
1059     DEBUG_r(regdump(r));
1060     return(r);
1061 }
1062
1063 /*
1064  - reg - regular expression, i.e. main body or parenthesized thing
1065  *
1066  * Caller must absorb opening parenthesis.
1067  *
1068  * Combining parenthesis handling with the base level of regular expression
1069  * is a trifle forced, but the need to tie the tails of the branches to what
1070  * follows makes it hard to avoid.
1071  */
1072 STATIC regnode *
1073 reg(I32 paren, I32 *flagp)
1074     /* paren: Parenthesized? 0=top, 1=(, inside: changed to letter. */
1075 {
1076     dTHR;
1077     register regnode *ret;              /* Will be the head of the group. */
1078     register regnode *br;
1079     register regnode *lastbr;
1080     register regnode *ender = 0;
1081     register I32 parno = 0;
1082     I32 flags, oregflags = PL_regflags, have_branch = 0, open = 0;
1083     char c;
1084
1085     *flagp = 0;                         /* Tentatively. */
1086
1087     /* Make an OPEN node, if parenthesized. */
1088     if (paren) {
1089         if (*PL_regcomp_parse == '?') {
1090             U16 posflags = 0, negflags = 0;
1091             U16 *flagsp = &posflags;
1092             int logical = 0;
1093
1094             PL_regcomp_parse++;
1095             paren = *PL_regcomp_parse++;
1096             ret = NULL;                 /* For look-ahead/behind. */
1097             switch (paren) {
1098             case '<':
1099                 PL_regseen |= REG_SEEN_LOOKBEHIND;
1100                 if (*PL_regcomp_parse == '!') 
1101                     paren = ',';
1102                 if (*PL_regcomp_parse != '=' && *PL_regcomp_parse != '!') 
1103                     goto unknown;
1104                 PL_regcomp_parse++;
1105             case '=':
1106             case '!':
1107                 PL_seen_zerolen++;
1108             case ':':
1109             case '>':
1110                 break;
1111             case '$':
1112             case '@':
1113                 FAIL2("Sequence (?%c...) not implemented", (int)paren);
1114                 break;
1115             case '#':
1116                 while (*PL_regcomp_parse && *PL_regcomp_parse != ')')
1117                     PL_regcomp_parse++;
1118                 if (*PL_regcomp_parse != ')')
1119                     FAIL("Sequence (?#... not terminated");
1120                 nextchar();
1121                 *flagp = TRYAGAIN;
1122                 return NULL;
1123             case 'p':
1124                 logical = 1;
1125                 paren = *PL_regcomp_parse++;
1126                 /* FALL THROUGH */
1127             case '{':
1128             {
1129                 dTHR;
1130                 I32 count = 1, n = 0;
1131                 char c;
1132                 char *s = PL_regcomp_parse;
1133                 SV *sv;
1134                 OP_4tree *sop, *rop;
1135
1136                 PL_seen_zerolen++;
1137                 PL_regseen |= REG_SEEN_EVAL;
1138                 while (count && (c = *PL_regcomp_parse)) {
1139                     if (c == '\\' && PL_regcomp_parse[1])
1140                         PL_regcomp_parse++;
1141                     else if (c == '{') 
1142                         count++;
1143                     else if (c == '}') 
1144                         count--;
1145                     PL_regcomp_parse++;
1146                 }
1147                 if (*PL_regcomp_parse != ')')
1148                     FAIL("Sequence (?{...}) not terminated or not {}-balanced");
1149                 if (!SIZE_ONLY) {
1150                     AV *av;
1151                     
1152                     if (PL_regcomp_parse - 1 - s) 
1153                         sv = newSVpv(s, PL_regcomp_parse - 1 - s);
1154                     else
1155                         sv = newSVpv("", 0);
1156
1157                     rop = sv_compile_2op(sv, &sop, "re", &av);
1158
1159                     n = add_data(3, "nso");
1160                     PL_regcomp_rx->data->data[n] = (void*)rop;
1161                     PL_regcomp_rx->data->data[n+1] = (void*)av;
1162                     PL_regcomp_rx->data->data[n+2] = (void*)sop;
1163                     SvREFCNT_dec(sv);
1164                 }
1165                 else {          /* First pass */
1166                     if (PL_reginterp_cnt < ++PL_seen_evals && PL_curcop != &compiling)
1167                         /* No compiled RE interpolated, has runtime
1168                            components ===> unsafe.  */
1169                         FAIL("Eval-group not allowed at runtime, use re 'eval'");
1170                     if (PL_tainted)
1171                         FAIL("Eval-group in insecure regular expression");
1172                 }
1173                 
1174                 nextchar();
1175                 if (logical) {
1176                     ret = reg_node(LOGICAL);
1177                     if (!SIZE_ONLY)
1178                         ret->flags = 2;
1179                     regtail(ret, reganode(EVAL, n));
1180                     return ret;
1181                 }
1182                 return reganode(EVAL, n);
1183             }
1184             case '(':
1185             {
1186                 if (PL_regcomp_parse[0] == '?') {
1187                     if (PL_regcomp_parse[1] == '=' || PL_regcomp_parse[1] == '!' 
1188                         || PL_regcomp_parse[1] == '<' 
1189                         || PL_regcomp_parse[1] == '{') { /* Lookahead or eval. */
1190                         I32 flag;
1191                         
1192                         ret = reg_node(LOGICAL);
1193                         if (!SIZE_ONLY)
1194                             ret->flags = 1;
1195                         regtail(ret, reg(1, &flag));
1196                         goto insert_if;
1197                     } 
1198                 }
1199                 else if (PL_regcomp_parse[0] >= '1' && PL_regcomp_parse[0] <= '9' ) {
1200                     parno = atoi(PL_regcomp_parse++);
1201
1202                     while (isDIGIT(*PL_regcomp_parse))
1203                         PL_regcomp_parse++;
1204                     ret = reganode(GROUPP, parno);
1205                     if ((c = *nextchar()) != ')')
1206                         FAIL2("Switch (?(number%c not recognized", c);
1207                   insert_if:
1208                     regtail(ret, reganode(IFTHEN, 0));
1209                     br = regbranch(&flags, 1);
1210                     if (br == NULL)
1211                         br = reganode(LONGJMP, 0);
1212                     else
1213                         regtail(br, reganode(LONGJMP, 0));
1214                     c = *nextchar();
1215                     if (c == '|') {
1216                         lastbr = reganode(IFTHEN, 0); /* Fake one for optimizer. */
1217                         regbranch(&flags, 1);
1218                         regtail(ret, lastbr);
1219                         c = *nextchar();
1220                     }
1221                     else
1222                         lastbr = NULL;
1223                     if (c != ')')
1224                         FAIL("Switch (?(condition)... contains too many branches");
1225                     ender = reg_node(TAIL);
1226                     regtail(br, ender);
1227                     if (lastbr) {
1228                         regtail(lastbr, ender);
1229                         regtail(NEXTOPER(NEXTOPER(lastbr)), ender);
1230                     }
1231                     else
1232                         regtail(ret, ender);
1233                     return ret;
1234                 }
1235                 else {
1236                     FAIL2("Unknown condition for (?(%.2s", PL_regcomp_parse);
1237                 }
1238             }
1239             case 0:
1240                 FAIL("Sequence (? incomplete");
1241                 break;
1242             default:
1243                 --PL_regcomp_parse;
1244               parse_flags:
1245                 while (*PL_regcomp_parse && strchr("iogcmsx", *PL_regcomp_parse)) {
1246                     if (*PL_regcomp_parse != 'o')
1247                         pmflag(flagsp, *PL_regcomp_parse);
1248                     ++PL_regcomp_parse;
1249                 }
1250                 if (*PL_regcomp_parse == '-') {
1251                     flagsp = &negflags;
1252                     ++PL_regcomp_parse;
1253                     goto parse_flags;
1254                 }
1255                 PL_regflags |= posflags;
1256                 PL_regflags &= ~negflags;
1257                 if (*PL_regcomp_parse == ':') {
1258                     PL_regcomp_parse++;
1259                     paren = ':';
1260                     break;
1261                 }               
1262               unknown:
1263                 if (*PL_regcomp_parse != ')')
1264                     FAIL2("Sequence (?%c...) not recognized", *PL_regcomp_parse);
1265                 nextchar();
1266                 *flagp = TRYAGAIN;
1267                 return NULL;
1268             }
1269         }
1270         else {
1271             parno = PL_regnpar;
1272             PL_regnpar++;
1273             ret = reganode(OPEN, parno);
1274             open = 1;
1275         }
1276     }
1277     else
1278         ret = NULL;
1279
1280     /* Pick up the branches, linking them together. */
1281     br = regbranch(&flags, 1);
1282     if (br == NULL)
1283         return(NULL);
1284     if (*PL_regcomp_parse == '|') {
1285         if (!SIZE_ONLY && PL_extralen) {
1286             reginsert(BRANCHJ, br);
1287         }
1288         else
1289             reginsert(BRANCH, br);
1290         have_branch = 1;
1291         if (SIZE_ONLY)
1292             PL_extralen += 1;           /* For BRANCHJ-BRANCH. */
1293     }
1294     else if (paren == ':') {
1295         *flagp |= flags&SIMPLE;
1296     }
1297     if (open) {                         /* Starts with OPEN. */
1298         regtail(ret, br);               /* OPEN -> first. */
1299     }
1300     else if (paren != '?')              /* Not Conditional */
1301         ret = br;
1302     if (flags&HASWIDTH)
1303         *flagp |= HASWIDTH;
1304     *flagp |= flags&SPSTART;
1305     lastbr = br;
1306     while (*PL_regcomp_parse == '|') {
1307         if (!SIZE_ONLY && PL_extralen) {
1308             ender = reganode(LONGJMP,0);
1309             regtail(NEXTOPER(NEXTOPER(lastbr)), ender); /* Append to the previous. */
1310         }
1311         if (SIZE_ONLY)
1312             PL_extralen += 2;           /* Account for LONGJMP. */
1313         nextchar();
1314         br = regbranch(&flags, 0);
1315         if (br == NULL)
1316             return(NULL);
1317         regtail(lastbr, br);            /* BRANCH -> BRANCH. */
1318         lastbr = br;
1319         if (flags&HASWIDTH)
1320             *flagp |= HASWIDTH;
1321         *flagp |= flags&SPSTART;
1322     }
1323
1324     if (have_branch || paren != ':') {
1325         /* Make a closing node, and hook it on the end. */
1326         switch (paren) {
1327         case ':':
1328             ender = reg_node(TAIL);
1329             break;
1330         case 1:
1331             ender = reganode(CLOSE, parno);
1332             break;
1333         case '<':
1334         case ',':
1335         case '=':
1336         case '!':
1337             *flagp &= ~HASWIDTH;
1338             /* FALL THROUGH */
1339         case '>':
1340             ender = reg_node(SUCCEED);
1341             break;
1342         case 0:
1343             ender = reg_node(END);
1344             break;
1345         }
1346         regtail(lastbr, ender);
1347
1348         if (have_branch) {
1349             /* Hook the tails of the branches to the closing node. */
1350             for (br = ret; br != NULL; br = regnext(br)) {
1351                 regoptail(br, ender);
1352             }
1353         }
1354     }
1355
1356     {
1357         char *p;
1358         static char parens[] = "=!<,>";
1359
1360         if (paren && (p = strchr(parens, paren))) {
1361             int node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
1362             int flag = (p - parens) > 1;
1363
1364             if (paren == '>')
1365                 node = SUSPEND, flag = 0;
1366             reginsert(node,ret);
1367             ret->flags = flag;
1368             regtail(ret, reg_node(TAIL));
1369         }
1370     }
1371
1372     /* Check for proper termination. */
1373     if (paren && (PL_regcomp_parse >= PL_regxend || *nextchar() != ')')) {
1374         FAIL("unmatched () in regexp");
1375     }
1376     else if (!paren && PL_regcomp_parse < PL_regxend) {
1377         if (*PL_regcomp_parse == ')') {
1378             FAIL("unmatched () in regexp");
1379         }
1380         else
1381             FAIL("junk on end of regexp");      /* "Can't happen". */
1382         /* NOTREACHED */
1383     }
1384     if (paren != 0) {
1385         PL_regflags = oregflags;
1386     }
1387
1388     return(ret);
1389 }
1390
1391 /*
1392  - regbranch - one alternative of an | operator
1393  *
1394  * Implements the concatenation operator.
1395  */
1396 STATIC regnode *
1397 regbranch(I32 *flagp, I32 first)
1398 {
1399     dTHR;
1400     register regnode *ret;
1401     register regnode *chain = NULL;
1402     register regnode *latest;
1403     I32 flags = 0, c = 0;
1404
1405     if (first) 
1406         ret = NULL;
1407     else {
1408         if (!SIZE_ONLY && PL_extralen) 
1409             ret = reganode(BRANCHJ,0);
1410         else
1411             ret = reg_node(BRANCH);
1412     }
1413         
1414     if (!first && SIZE_ONLY) 
1415         PL_extralen += 1;                       /* BRANCHJ */
1416     
1417     *flagp = WORST;                     /* Tentatively. */
1418
1419     PL_regcomp_parse--;
1420     nextchar();
1421     while (PL_regcomp_parse < PL_regxend && *PL_regcomp_parse != '|' && *PL_regcomp_parse != ')') {
1422         flags &= ~TRYAGAIN;
1423         latest = regpiece(&flags);
1424         if (latest == NULL) {
1425             if (flags & TRYAGAIN)
1426                 continue;
1427             return(NULL);
1428         }
1429         else if (ret == NULL)
1430             ret = latest;
1431         *flagp |= flags&HASWIDTH;
1432         if (chain == NULL)      /* First piece. */
1433             *flagp |= flags&SPSTART;
1434         else {
1435             PL_regnaughty++;
1436             regtail(chain, latest);
1437         }
1438         chain = latest;
1439         c++;
1440     }
1441     if (chain == NULL) {        /* Loop ran zero times. */
1442         chain = reg_node(NOTHING);
1443         if (ret == NULL)
1444             ret = chain;
1445     }
1446     if (c == 1) {
1447         *flagp |= flags&SIMPLE;
1448     }
1449
1450     return(ret);
1451 }
1452
1453 /*
1454  - regpiece - something followed by possible [*+?]
1455  *
1456  * Note that the branching code sequences used for ? and the general cases
1457  * of * and + are somewhat optimized:  they use the same NOTHING node as
1458  * both the endmarker for their branch list and the body of the last branch.
1459  * It might seem that this node could be dispensed with entirely, but the
1460  * endmarker role is not redundant.
1461  */
1462 STATIC regnode *
1463 regpiece(I32 *flagp)
1464 {
1465     dTHR;
1466     register regnode *ret;
1467     register char op;
1468     register char *next;
1469     I32 flags;
1470     char *origparse = PL_regcomp_parse;
1471     char *maxpos;
1472     I32 min;
1473     I32 max = REG_INFTY;
1474
1475     ret = regatom(&flags);
1476     if (ret == NULL) {
1477         if (flags & TRYAGAIN)
1478             *flagp |= TRYAGAIN;
1479         return(NULL);
1480     }
1481
1482     op = *PL_regcomp_parse;
1483
1484     if (op == '{' && regcurly(PL_regcomp_parse)) {
1485         next = PL_regcomp_parse + 1;
1486         maxpos = Nullch;
1487         while (isDIGIT(*next) || *next == ',') {
1488             if (*next == ',') {
1489                 if (maxpos)
1490                     break;
1491                 else
1492                     maxpos = next;
1493             }
1494             next++;
1495         }
1496         if (*next == '}') {             /* got one */
1497             if (!maxpos)
1498                 maxpos = next;
1499             PL_regcomp_parse++;
1500             min = atoi(PL_regcomp_parse);
1501             if (*maxpos == ',')
1502                 maxpos++;
1503             else
1504                 maxpos = PL_regcomp_parse;
1505             max = atoi(maxpos);
1506             if (!max && *maxpos != '0')
1507                 max = REG_INFTY;                /* meaning "infinity" */
1508             else if (max >= REG_INFTY)
1509                 FAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
1510             PL_regcomp_parse = next;
1511             nextchar();
1512
1513         do_curly:
1514             if ((flags&SIMPLE)) {
1515                 PL_regnaughty += 2 + PL_regnaughty / 2;
1516                 reginsert(CURLY, ret);
1517             }
1518             else {
1519                 PL_regnaughty += 4 + PL_regnaughty;     /* compound interest */
1520                 regtail(ret, reg_node(WHILEM));
1521                 if (!SIZE_ONLY && PL_extralen) {
1522                     reginsert(LONGJMP,ret);
1523                     reginsert(NOTHING,ret);
1524                     NEXT_OFF(ret) = 3;  /* Go over LONGJMP. */
1525                 }
1526                 reginsert(CURLYX,ret);
1527                 if (!SIZE_ONLY && PL_extralen)
1528                     NEXT_OFF(ret) = 3;  /* Go over NOTHING to LONGJMP. */
1529                 regtail(ret, reg_node(NOTHING));
1530                 if (SIZE_ONLY)
1531                     PL_extralen += 3;
1532             }
1533             ret->flags = 0;
1534
1535             if (min > 0)
1536                 *flagp = WORST;
1537             if (max > 0)
1538                 *flagp |= HASWIDTH;
1539             if (max && max < min)
1540                 FAIL("Can't do {n,m} with n > m");
1541             if (!SIZE_ONLY) {
1542                 ARG1_SET(ret, min);
1543                 ARG2_SET(ret, max);
1544             }
1545
1546             goto nest_check;
1547         }
1548     }
1549
1550     if (!ISMULT1(op)) {
1551         *flagp = flags;
1552         return(ret);
1553     }
1554
1555 #if 0                           /* Now runtime fix should be reliable. */
1556     if (!(flags&HASWIDTH) && op != '?')
1557       FAIL("regexp *+ operand could be empty");
1558 #endif 
1559
1560     nextchar();
1561
1562     *flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
1563
1564     if (op == '*' && (flags&SIMPLE)) {
1565         reginsert(STAR, ret);
1566         ret->flags = 0;
1567         PL_regnaughty += 4;
1568     }
1569     else if (op == '*') {
1570         min = 0;
1571         goto do_curly;
1572     }
1573     else if (op == '+' && (flags&SIMPLE)) {
1574         reginsert(PLUS, ret);
1575         ret->flags = 0;
1576         PL_regnaughty += 3;
1577     }
1578     else if (op == '+') {
1579         min = 1;
1580         goto do_curly;
1581     }
1582     else if (op == '?') {
1583         min = 0; max = 1;
1584         goto do_curly;
1585     }
1586   nest_check:
1587     if (ckWARN(WARN_UNSAFE) && !SIZE_ONLY && !(flags&HASWIDTH) && max > 10000) {
1588         warner(WARN_UNSAFE, "%.*s matches null string many times",
1589             PL_regcomp_parse - origparse, origparse);
1590     }
1591
1592     if (*PL_regcomp_parse == '?') {
1593         nextchar();
1594         reginsert(MINMOD, ret);
1595         regtail(ret, ret + NODE_STEP_REGNODE);
1596     }
1597     if (ISMULT2(PL_regcomp_parse))
1598         FAIL("nested *?+ in regexp");
1599
1600     return(ret);
1601 }
1602
1603 /*
1604  - regatom - the lowest level
1605  *
1606  * Optimization:  gobbles an entire sequence of ordinary characters so that
1607  * it can turn them into a single node, which is smaller to store and
1608  * faster to run.  Backslashed characters are exceptions, each becoming a
1609  * separate node; the code is simpler that way and it's not worth fixing.
1610  *
1611  * [Yes, it is worth fixing, some scripts can run twice the speed.]
1612  */
1613 STATIC regnode *
1614 regatom(I32 *flagp)
1615 {
1616     dTHR;
1617     register regnode *ret = 0;
1618     I32 flags;
1619
1620     *flagp = WORST;             /* Tentatively. */
1621
1622 tryagain:
1623     switch (*PL_regcomp_parse) {
1624     case '^':
1625         PL_seen_zerolen++;
1626         nextchar();
1627         if (PL_regflags & PMf_MULTILINE)
1628             ret = reg_node(MBOL);
1629         else if (PL_regflags & PMf_SINGLELINE)
1630             ret = reg_node(SBOL);
1631         else
1632             ret = reg_node(BOL);
1633         break;
1634     case '$':
1635         if (PL_regcomp_parse[1]) 
1636             PL_seen_zerolen++;
1637         nextchar();
1638         if (PL_regflags & PMf_MULTILINE)
1639             ret = reg_node(MEOL);
1640         else if (PL_regflags & PMf_SINGLELINE)
1641             ret = reg_node(SEOL);
1642         else
1643             ret = reg_node(EOL);
1644         break;
1645     case '.':
1646         nextchar();
1647         if (UTF) {
1648             if (PL_regflags & PMf_SINGLELINE)
1649                 ret = reg_node(SANYUTF8);
1650             else
1651                 ret = reg_node(ANYUTF8);
1652             *flagp |= HASWIDTH;
1653         }
1654         else {
1655             if (PL_regflags & PMf_SINGLELINE)
1656                 ret = reg_node(SANY);
1657             else
1658                 ret = reg_node(ANY);
1659             *flagp |= HASWIDTH|SIMPLE;
1660         }
1661         PL_regnaughty++;
1662         break;
1663     case '[':
1664         PL_regcomp_parse++;
1665         ret = (UTF ? regclassutf8() : regclass());
1666         if (*PL_regcomp_parse != ']')
1667             FAIL("unmatched [] in regexp");
1668         nextchar();
1669         *flagp |= HASWIDTH|SIMPLE;
1670         break;
1671     case '(':
1672         nextchar();
1673         ret = reg(1, &flags);
1674         if (ret == NULL) {
1675                 if (flags & TRYAGAIN)
1676                     goto tryagain;
1677                 return(NULL);
1678         }
1679         *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE);
1680         break;
1681     case '|':
1682     case ')':
1683         if (flags & TRYAGAIN) {
1684             *flagp |= TRYAGAIN;
1685             return NULL;
1686         }
1687         FAIL2("internal urp in regexp at /%s/", PL_regcomp_parse);
1688                                 /* Supposed to be caught earlier. */
1689         break;
1690     case '{':
1691         if (!regcurly(PL_regcomp_parse)) {
1692             PL_regcomp_parse++;
1693             goto defchar;
1694         }
1695         /* FALL THROUGH */
1696     case '?':
1697     case '+':
1698     case '*':
1699         FAIL("?+*{} follows nothing in regexp");
1700         break;
1701     case '\\':
1702         switch (*++PL_regcomp_parse) {
1703         case 'A':
1704             PL_seen_zerolen++;
1705             ret = reg_node(SBOL);
1706             *flagp |= SIMPLE;
1707             nextchar();
1708             break;
1709         case 'G':
1710             ret = reg_node(GPOS);
1711             PL_regseen |= REG_SEEN_GPOS;
1712             *flagp |= SIMPLE;
1713             nextchar();
1714             break;
1715         case 'Z':
1716             ret = reg_node(SEOL);
1717             *flagp |= SIMPLE;
1718             nextchar();
1719             break;
1720         case 'z':
1721             ret = reg_node(EOS);
1722             *flagp |= SIMPLE;
1723             PL_seen_zerolen++;          /* Do not optimize RE away */
1724             nextchar();
1725             break;
1726         case 'C':
1727             ret = reg_node(SANY);
1728             *flagp |= HASWIDTH|SIMPLE;
1729             nextchar();
1730             break;
1731         case 'X':
1732             ret = reg_node(CLUMP);
1733             *flagp |= HASWIDTH;
1734             nextchar();
1735             if (UTF && !PL_utf8_mark)
1736                 is_utf8_mark((U8*)"~");         /* preload table */
1737             break;
1738         case 'w':
1739             ret = reg_node(
1740                 UTF
1741                     ? (LOC ? ALNUMLUTF8 : ALNUMUTF8)
1742                     : (LOC ? ALNUML     : ALNUM));
1743             *flagp |= HASWIDTH|SIMPLE;
1744             nextchar();
1745             if (UTF && !PL_utf8_alnum)
1746                 is_utf8_alnum((U8*)"a");        /* preload table */
1747             break;
1748         case 'W':
1749             ret = reg_node(
1750                 UTF
1751                     ? (LOC ? NALNUMLUTF8 : NALNUMUTF8)
1752                     : (LOC ? NALNUML     : NALNUM));
1753             *flagp |= HASWIDTH|SIMPLE;
1754             nextchar();
1755             if (UTF && !PL_utf8_alnum)
1756                 is_utf8_alnum((U8*)"a");        /* preload table */
1757             break;
1758         case 'b':
1759             PL_seen_zerolen++;
1760             ret = reg_node(
1761                 UTF
1762                     ? (LOC ? BOUNDLUTF8 : BOUNDUTF8)
1763                     : (LOC ? BOUNDL     : BOUND));
1764             *flagp |= SIMPLE;
1765             nextchar();
1766             if (UTF && !PL_utf8_alnum)
1767                 is_utf8_alnum((U8*)"a");        /* preload table */
1768             break;
1769         case 'B':
1770             PL_seen_zerolen++;
1771             ret = reg_node(
1772                 UTF
1773                     ? (LOC ? NBOUNDLUTF8 : NBOUNDUTF8)
1774                     : (LOC ? NBOUNDL     : NBOUND));
1775             *flagp |= SIMPLE;
1776             nextchar();
1777             if (UTF && !PL_utf8_alnum)
1778                 is_utf8_alnum((U8*)"a");        /* preload table */
1779             break;
1780         case 's':
1781             ret = reg_node(
1782                 UTF
1783                     ? (LOC ? SPACELUTF8 : SPACEUTF8)
1784                     : (LOC ? SPACEL     : SPACE));
1785             *flagp |= HASWIDTH|SIMPLE;
1786             nextchar();
1787             if (UTF && !PL_utf8_space)
1788                 is_utf8_space((U8*)" ");        /* preload table */
1789             break;
1790         case 'S':
1791             ret = reg_node(
1792                 UTF
1793                     ? (LOC ? NSPACELUTF8 : NSPACEUTF8)
1794                     : (LOC ? NSPACEL     : NSPACE));
1795             *flagp |= HASWIDTH|SIMPLE;
1796             nextchar();
1797             if (UTF && !PL_utf8_space)
1798                 is_utf8_space((U8*)" ");        /* preload table */
1799             break;
1800         case 'd':
1801             ret = reg_node(UTF ? DIGITUTF8 : DIGIT);
1802             *flagp |= HASWIDTH|SIMPLE;
1803             nextchar();
1804             if (UTF && !PL_utf8_digit)
1805                 is_utf8_digit((U8*)"1");        /* preload table */
1806             break;
1807         case 'D':
1808             ret = reg_node(UTF ? NDIGITUTF8 : NDIGIT);
1809             *flagp |= HASWIDTH|SIMPLE;
1810             nextchar();
1811             if (UTF && !PL_utf8_digit)
1812                 is_utf8_digit((U8*)"1");        /* preload table */
1813             break;
1814         case 'p':
1815         case 'P':
1816             {   /* a lovely hack--pretend we saw [\pX] instead */
1817                 char* oldregxend = PL_regxend;
1818
1819                 if (PL_regcomp_parse[1] == '{') {
1820                     PL_regxend = strchr(PL_regcomp_parse, '}');
1821                     if (!PL_regxend)
1822                         FAIL("Missing right brace on \\p{}");
1823                     PL_regxend++;
1824                 }
1825                 else
1826                     PL_regxend = PL_regcomp_parse + 2;
1827                 PL_regcomp_parse--;
1828
1829                 ret = regclassutf8();
1830
1831                 PL_regxend = oldregxend;
1832                 PL_regcomp_parse--;
1833                 nextchar();
1834                 *flagp |= HASWIDTH|SIMPLE;
1835             }
1836             break;
1837         case 'n':
1838         case 'r':
1839         case 't':
1840         case 'f':
1841         case 'e':
1842         case 'a':
1843         case 'x':
1844         case 'c':
1845         case '0':
1846             goto defchar;
1847         case '1': case '2': case '3': case '4':
1848         case '5': case '6': case '7': case '8': case '9':
1849             {
1850                 I32 num = atoi(PL_regcomp_parse);
1851
1852                 if (num > 9 && num >= PL_regnpar)
1853                     goto defchar;
1854                 else {
1855                     if (!SIZE_ONLY && num > PL_regcomp_rx->nparens)
1856                         FAIL("reference to nonexistent group");
1857                     PL_regsawback = 1;
1858                     ret = reganode(FOLD
1859                                    ? (LOC ? REFFL : REFF)
1860                                    : REF, num);
1861                     *flagp |= HASWIDTH;
1862                     while (isDIGIT(*PL_regcomp_parse))
1863                         PL_regcomp_parse++;
1864                     PL_regcomp_parse--;
1865                     nextchar();
1866                 }
1867             }
1868             break;
1869         case '\0':
1870             if (PL_regcomp_parse >= PL_regxend)
1871                 FAIL("trailing \\ in regexp");
1872             /* FALL THROUGH */
1873         default:
1874             goto defchar;
1875         }
1876         break;
1877
1878     case '#':
1879         if (PL_regflags & PMf_EXTENDED) {
1880             while (PL_regcomp_parse < PL_regxend && *PL_regcomp_parse != '\n') PL_regcomp_parse++;
1881             if (PL_regcomp_parse < PL_regxend)
1882                 goto tryagain;
1883         }
1884         /* FALL THROUGH */
1885
1886     default: {
1887             register I32 len;
1888             register UV ender;
1889             register char *p;
1890             char *oldp, *s;
1891             I32 numlen;
1892
1893             PL_regcomp_parse++;
1894
1895         defchar:
1896             ret = reg_node(FOLD
1897                           ? (LOC ? EXACTFL : EXACTF)
1898                           : EXACT);
1899             s = (char *) OPERAND(ret);
1900             regc(0, s++);               /* save spot for len */
1901             for (len = 0, p = PL_regcomp_parse - 1;
1902               len < 127 && p < PL_regxend;
1903               len++)
1904             {
1905                 oldp = p;
1906
1907                 if (PL_regflags & PMf_EXTENDED)
1908                     p = regwhite(p, PL_regxend);
1909                 switch (*p) {
1910                 case '^':
1911                 case '$':
1912                 case '.':
1913                 case '[':
1914                 case '(':
1915                 case ')':
1916                 case '|':
1917                     goto loopdone;
1918                 case '\\':
1919                     switch (*++p) {
1920                     case 'A':
1921                     case 'G':
1922                     case 'Z':
1923                     case 'z':
1924                     case 'w':
1925                     case 'W':
1926                     case 'b':
1927                     case 'B':
1928                     case 's':
1929                     case 'S':
1930                     case 'd':
1931                     case 'D':
1932                     case 'p':
1933                     case 'P':
1934                         --p;
1935                         goto loopdone;
1936                     case 'n':
1937                         ender = '\n';
1938                         p++;
1939                         break;
1940                     case 'r':
1941                         ender = '\r';
1942                         p++;
1943                         break;
1944                     case 't':
1945                         ender = '\t';
1946                         p++;
1947                         break;
1948                     case 'f':
1949                         ender = '\f';
1950                         p++;
1951                         break;
1952                     case 'e':
1953                         ender = '\033';
1954                         p++;
1955                         break;
1956                     case 'a':
1957                         ender = '\007';
1958                         p++;
1959                         break;
1960                     case 'x':
1961                         if (*++p == '{') {
1962                             char* e = strchr(p, '}');
1963          
1964                             if (!e)
1965                                 FAIL("Missing right brace on \\x{}");
1966                             else if (UTF) {
1967                                 ender = scan_hex(p + 1, e - p, &numlen);
1968                                 if (numlen + len >= 127) {      /* numlen is generous */
1969                                     p--;
1970                                     goto loopdone;
1971                                 }
1972                                 p = e + 1;
1973                             }
1974                             else
1975                                 FAIL("Can't use \\x{} without 'use utf8' declaration");
1976                         }
1977                         else {
1978                             ender = scan_hex(p, 2, &numlen);
1979                             p += numlen;
1980                         }
1981                         break;
1982                     case 'c':
1983                         p++;
1984                         ender = UCHARAT(p++);
1985                         ender = toCTRL(ender);
1986                         break;
1987                     case '0': case '1': case '2': case '3':case '4':
1988                     case '5': case '6': case '7': case '8':case '9':
1989                         if (*p == '0' ||
1990                           (isDIGIT(p[1]) && atoi(p) >= PL_regnpar) ) {
1991                             ender = scan_oct(p, 3, &numlen);
1992                             p += numlen;
1993                         }
1994                         else {
1995                             --p;
1996                             goto loopdone;
1997                         }
1998                         break;
1999                     case '\0':
2000                         if (p >= PL_regxend)
2001                             FAIL("trailing \\ in regexp");
2002                         /* FALL THROUGH */
2003                     default:
2004                         goto normal_default;
2005                     }
2006                     break;
2007                 default:
2008                   normal_default:
2009                     if ((*p & 0xc0) == 0xc0 && UTF) {
2010                         ender = utf8_to_uv((U8*)p, &numlen);
2011                         p += numlen;
2012                     }
2013                     else
2014                         ender = *p++;
2015                     break;
2016                 }
2017                 if (PL_regflags & PMf_EXTENDED)
2018                     p = regwhite(p, PL_regxend);
2019                 if (UTF && FOLD) {
2020                     if (LOC)
2021                         ender = toLOWER_LC_uni(ender);
2022                     else
2023                         ender = toLOWER_uni(ender);
2024                 }
2025                 if (ISMULT2(p)) { /* Back off on ?+*. */
2026                     if (len)
2027                         p = oldp;
2028                     else if (ender >= 0x80 && UTF) {
2029                         reguni(ender, s, &numlen);
2030                         s += numlen;
2031                         len += numlen;
2032                     }
2033                     else {
2034                         len++;
2035                         regc(ender, s++);
2036                     }
2037                     break;
2038                 }
2039                 if (ender >= 0x80 && UTF) {
2040                     reguni(ender, s, &numlen);
2041                     s += numlen;
2042                     len += numlen - 1;
2043                 }
2044                 else
2045                     regc(ender, s++);
2046             }
2047         loopdone:
2048             PL_regcomp_parse = p - 1;
2049             nextchar();
2050             if (len < 0)
2051                 FAIL("internal disaster in regexp");
2052             if (len > 0)
2053                 *flagp |= HASWIDTH;
2054             if (len == 1)
2055                 *flagp |= SIMPLE;
2056             if (!SIZE_ONLY)
2057                 *OPERAND(ret) = len;
2058             regc('\0', s++);
2059             if (SIZE_ONLY) {
2060                 PL_regsize += (len + 2 + sizeof(regnode) - 1) / sizeof(regnode);
2061             }
2062             else {
2063                 PL_regcode += (len + 2 + sizeof(regnode) - 1) / sizeof(regnode);
2064             }
2065         }
2066         break;
2067     }
2068
2069     return(ret);
2070 }
2071
2072 STATIC char *
2073 regwhite(char *p, char *e)
2074 {
2075     while (p < e) {
2076         if (isSPACE(*p))
2077             ++p;
2078         else if (*p == '#') {
2079             do {
2080                 p++;
2081             } while (p < e && *p != '\n');
2082         }
2083         else
2084             break;
2085     }
2086     return p;
2087 }
2088
2089 STATIC regnode *
2090 regclass(void)
2091 {
2092     dTHR;
2093     register char *opnd, *s;
2094     register I32 value;
2095     register I32 lastvalue = 1234;
2096     register I32 range = 0;
2097     register regnode *ret;
2098     register I32 def;
2099     I32 numlen;
2100
2101     s = opnd = (char *) OPERAND(PL_regcode);
2102     ret = reg_node(ANYOF);
2103     for (value = 0; value < 33; value++)
2104         regc(0, s++);
2105     if (*PL_regcomp_parse == '^') {     /* Complement of range. */
2106         PL_regnaughty++;
2107         PL_regcomp_parse++;
2108         if (!SIZE_ONLY)
2109             *opnd |= ANYOF_INVERT;
2110     }
2111     if (!SIZE_ONLY) {
2112         PL_regcode += ANY_SKIP;
2113         if (FOLD)
2114             *opnd |= ANYOF_FOLD;
2115         if (LOC)
2116             *opnd |= ANYOF_LOCALE;
2117     }
2118     else {
2119         PL_regsize += ANY_SKIP;
2120     }
2121     if (*PL_regcomp_parse == ']' || *PL_regcomp_parse == '-')
2122         goto skipcond;          /* allow 1st char to be ] or - */
2123     while (PL_regcomp_parse < PL_regxend && *PL_regcomp_parse != ']') {
2124        skipcond:
2125         value = UCHARAT(PL_regcomp_parse++);
2126         if (value == '[' && PL_regcomp_parse + 1 < PL_regxend &&
2127             /* I smell either [: or [= or [. -- POSIX has been here, right? */
2128             (*PL_regcomp_parse == ':' || *PL_regcomp_parse == '=' || *PL_regcomp_parse == '.')) {
2129             char  posixccc = *PL_regcomp_parse;
2130             char* posixccs = PL_regcomp_parse++;
2131             
2132             while (PL_regcomp_parse < PL_regxend && *PL_regcomp_parse != posixccc)
2133                 PL_regcomp_parse++;
2134             if (PL_regcomp_parse == PL_regxend)
2135                 /* Grandfather lone [:, [=, [. */
2136                 PL_regcomp_parse = posixccs;
2137             else {
2138                 PL_regcomp_parse++; /* skip over the posixccc */
2139                 if (*PL_regcomp_parse == ']') {
2140                     /* Not Implemented Yet.
2141                      * (POSIX Extended Character Classes, that is)
2142                      * The text between e.g. [: and :] would start
2143                      * at posixccs + 1 and stop at regcomp_parse - 2. */
2144                     if (ckWARN(WARN_UNSAFE) && !SIZE_ONLY)
2145                         warner(WARN_UNSAFE,
2146                             "Character class syntax [%c %c] is reserved for future extensions", posixccc, posixccc);
2147                     PL_regcomp_parse++; /* skip over the ending ] */
2148                 }
2149             }
2150         }
2151         if (value == '\\') {
2152             value = UCHARAT(PL_regcomp_parse++);
2153             switch (value) {
2154             case 'w':
2155                 if (!SIZE_ONLY) {
2156                     if (LOC)
2157                         *opnd |= ANYOF_ALNUML;
2158                     else {
2159                         for (value = 0; value < 256; value++)
2160                             if (isALNUM(value))
2161                                 ANYOF_SET(opnd, value);
2162                     }
2163                 }
2164                 lastvalue = 1234;
2165                 continue;
2166             case 'W':
2167                 if (!SIZE_ONLY) {
2168                     if (LOC)
2169                         *opnd |= ANYOF_NALNUML;
2170                     else {
2171                         for (value = 0; value < 256; value++)
2172                             if (!isALNUM(value))
2173                                 ANYOF_SET(opnd, value);
2174                     }
2175                 }
2176                 lastvalue = 1234;
2177                 continue;
2178             case 's':
2179                 if (!SIZE_ONLY) {
2180                     if (LOC)
2181                         *opnd |= ANYOF_SPACEL;
2182                     else {
2183                         for (value = 0; value < 256; value++)
2184                             if (isSPACE(value))
2185                                 ANYOF_SET(opnd, value);
2186                     }
2187                 }
2188                 lastvalue = 1234;
2189                 continue;
2190             case 'S':
2191                 if (!SIZE_ONLY) {
2192                     if (LOC)
2193                         *opnd |= ANYOF_NSPACEL;
2194                     else {
2195                         for (value = 0; value < 256; value++)
2196                             if (!isSPACE(value))
2197                                 ANYOF_SET(opnd, value);
2198                     }
2199                 }
2200                 lastvalue = 1234;
2201                 continue;
2202             case 'd':
2203                 if (!SIZE_ONLY) {
2204                     for (value = '0'; value <= '9'; value++)
2205                         ANYOF_SET(opnd, value);
2206                 }
2207                 lastvalue = 1234;
2208                 continue;
2209             case 'D':
2210                 if (!SIZE_ONLY) {
2211                     for (value = 0; value < '0'; value++)
2212                         ANYOF_SET(opnd, value);
2213                     for (value = '9' + 1; value < 256; value++)
2214                         ANYOF_SET(opnd, value);
2215                 }
2216                 lastvalue = 1234;
2217                 continue;
2218             case 'n':
2219                 value = '\n';
2220                 break;
2221             case 'r':
2222                 value = '\r';
2223                 break;
2224             case 't':
2225                 value = '\t';
2226                 break;
2227             case 'f':
2228                 value = '\f';
2229                 break;
2230             case 'b':
2231                 value = '\b';
2232                 break;
2233             case 'e':
2234                 value = '\033';
2235                 break;
2236             case 'a':
2237                 value = '\007';
2238                 break;
2239             case 'x':
2240                 value = scan_hex(PL_regcomp_parse, 2, &numlen);
2241                 PL_regcomp_parse += numlen;
2242                 break;
2243             case 'c':
2244                 value = UCHARAT(PL_regcomp_parse++);
2245                 value = toCTRL(value);
2246                 break;
2247             case '0': case '1': case '2': case '3': case '4':
2248             case '5': case '6': case '7': case '8': case '9':
2249                 value = scan_oct(--PL_regcomp_parse, 3, &numlen);
2250                 PL_regcomp_parse += numlen;
2251                 break;
2252             }
2253         }
2254         if (range) {
2255             if (lastvalue > value)
2256                 FAIL("invalid [] range in regexp");
2257             range = 0;
2258         }
2259         else {
2260             lastvalue = value;
2261             if (*PL_regcomp_parse == '-' && PL_regcomp_parse+1 < PL_regxend &&
2262               PL_regcomp_parse[1] != ']') {
2263                 PL_regcomp_parse++;
2264                 range = 1;
2265                 continue;       /* do it next time */
2266             }
2267         }
2268         if (!SIZE_ONLY) {
2269 #ifndef ASCIIish
2270             if ((isLOWER(lastvalue) && isLOWER(value)) ||
2271                 (isUPPER(lastvalue) && isUPPER(value))) {
2272                 if (isLOWER(lastvalue)) {
2273                     for (i = lastvalue; i <= value; i++)
2274                         if (isLOWER(i))
2275                             ANYOF_SET(opnd, i);
2276                 } else {
2277                     for (i = lastvalue; i <= value; i++)
2278                         if (isUPPER(i))
2279                             ANYOF_SET(opnd, i);
2280                 }
2281             }
2282             else
2283 #endif
2284                 for ( ; lastvalue <= value; lastvalue++)
2285                     ANYOF_SET(opnd, lastvalue);
2286         }
2287         lastvalue = value;
2288     }
2289     /* optimize case-insensitive simple patterns (e.g. /[a-z]/i) */
2290     if (!SIZE_ONLY && (*opnd & (0xFF ^ ANYOF_INVERT)) == ANYOF_FOLD) {
2291         for (value = 0; value < 256; ++value) {
2292             if (ANYOF_TEST(opnd, value)) {
2293                 I32 cf = fold[value];
2294                 ANYOF_SET(opnd, cf);
2295             }
2296         }
2297         *opnd &= ~ANYOF_FOLD;
2298     }
2299     /* optimize inverted simple patterns (e.g. [^a-z]) */
2300     if (!SIZE_ONLY && (*opnd & 0xFF) == ANYOF_INVERT) {
2301         for (value = 0; value < 32; ++value)
2302             opnd[1 + value] ^= 0xFF;
2303         *opnd = 0;
2304     }
2305     return ret;
2306 }
2307
2308 STATIC regnode *
2309 regclassutf8(void)
2310 {
2311     register char *opnd, *e;
2312     register U32 value;
2313     register U32 lastvalue = 123456;
2314     register I32 range = 0;
2315     register regnode *ret;
2316     I32 numlen;
2317     I32 n;
2318     SV *listsv;
2319     U8 flags = 0;
2320     dTHR;
2321
2322     if (*PL_regcomp_parse == '^') {     /* Complement of range. */
2323         PL_regnaughty++;
2324         PL_regcomp_parse++;
2325         if (!SIZE_ONLY)
2326             flags |= ANYOF_INVERT;
2327     }
2328     if (!SIZE_ONLY) {
2329         if (FOLD)
2330             flags |= ANYOF_FOLD;
2331         if (LOC)
2332             flags |= ANYOF_LOCALE;
2333         listsv = newSVpv("# comment\n",0);
2334     }
2335
2336     if (*PL_regcomp_parse == ']' || *PL_regcomp_parse == '-')
2337         goto skipcond;          /* allow 1st char to be ] or - */
2338
2339     while (PL_regcomp_parse < PL_regxend && *PL_regcomp_parse != ']') {
2340        skipcond:
2341         value = utf8_to_uv((U8*)PL_regcomp_parse, &numlen);
2342         PL_regcomp_parse += numlen;
2343
2344         if (value == '[' && PL_regcomp_parse + 1 < PL_regxend &&
2345             /* I smell either [: or [= or [. -- POSIX has been here, right? */
2346             (*PL_regcomp_parse == ':' || *PL_regcomp_parse == '=' || *PL_regcomp_parse == '.')) {
2347             char  posixccc = *PL_regcomp_parse;
2348             char* posixccs = PL_regcomp_parse++;
2349             
2350             while (PL_regcomp_parse < PL_regxend && *PL_regcomp_parse != posixccc)
2351                 PL_regcomp_parse++;
2352             if (PL_regcomp_parse == PL_regxend)
2353                 /* Grandfather lone [:, [=, [. */
2354                 PL_regcomp_parse = posixccs;
2355             else {
2356                 PL_regcomp_parse++; /* skip over the posixccc */
2357                 if (*PL_regcomp_parse == ']') {
2358                     /* Not Implemented Yet.
2359                      * (POSIX Extended Character Classes, that is)
2360                      * The text between e.g. [: and :] would start
2361                      * at posixccs + 1 and stop at regcomp_parse - 2. */
2362                     if (ckWARN(WARN_UNSAFE) && !SIZE_ONLY)
2363                         warner(WARN_UNSAFE,
2364                             "Character class syntax [%c %c] is reserved for future extensions", posixccc, posixccc);
2365                     PL_regcomp_parse++; /* skip over the ending ] */
2366                 }
2367             }
2368         }
2369
2370         if (value == '\\') {
2371             value = utf8_to_uv((U8*)PL_regcomp_parse, &numlen);
2372             PL_regcomp_parse += numlen;
2373             switch (value) {
2374             case 'w':
2375                 if (!SIZE_ONLY) {
2376                     if (LOC)
2377                         flags |= ANYOF_ALNUML;
2378
2379                     sv_catpvf(listsv, "+utf8::IsAlnum\n");
2380                 }
2381                 lastvalue = 123456;
2382                 continue;
2383             case 'W':
2384                 if (!SIZE_ONLY) {
2385                     if (LOC)
2386                         flags |= ANYOF_NALNUML;
2387
2388                     sv_catpvf(listsv,
2389                         "-utf8::IsAlpha\n-utf8::IsDigit\n0000\t%04x\n%04x\tffff\n",
2390                         '_' - 1,
2391                         '_' + 1);
2392                 }
2393                 lastvalue = 123456;
2394                 continue;
2395             case 's':
2396                 if (!SIZE_ONLY) {
2397                     if (LOC)
2398                         flags |= ANYOF_SPACEL;
2399                     sv_catpvf(listsv, "+utf8::IsSpace\n");
2400                     if (!PL_utf8_space)
2401                         is_utf8_space((U8*)" ");
2402                 }
2403                 lastvalue = 123456;
2404                 continue;
2405             case 'S':
2406                 if (!SIZE_ONLY) {
2407                     if (LOC)
2408                         flags |= ANYOF_NSPACEL;
2409                     sv_catpvf(listsv,
2410                         "!utf8::IsSpace\n");
2411                     if (!PL_utf8_space)
2412                         is_utf8_space((U8*)" ");
2413                 }
2414                 lastvalue = 123456;
2415                 continue;
2416             case 'd':
2417                 if (!SIZE_ONLY) {
2418                     sv_catpvf(listsv, "+utf8::IsDigit\n");
2419                 }
2420                 lastvalue = 123456;
2421                 continue;
2422             case 'D':
2423                 if (!SIZE_ONLY) {
2424                     sv_catpvf(listsv,
2425                         "!utf8::IsDigit\n");
2426                 }
2427                 lastvalue = 123456;
2428                 continue;
2429             case 'p':
2430             case 'P':
2431                 if (*PL_regcomp_parse == '{') {
2432                     e = strchr(PL_regcomp_parse++, '}');
2433                     if (!e)
2434                         FAIL("Missing right brace on \\p{}");
2435                     n = e - PL_regcomp_parse;
2436                 }
2437                 else {
2438                     e = PL_regcomp_parse;
2439                     n = 1;
2440                 }
2441                 if (!SIZE_ONLY) {
2442                     if (value == 'p')
2443                         sv_catpvf(listsv, "+utf8::%.*s\n", n, PL_regcomp_parse);
2444                     else
2445                         sv_catpvf(listsv,
2446                             "!utf8::%.*s\n", n, PL_regcomp_parse);
2447                 }
2448                 PL_regcomp_parse = e + 1;
2449                 lastvalue = 123456;
2450                 continue;
2451             case 'n':
2452                 value = '\n';
2453                 break;
2454             case 'r':
2455                 value = '\r';
2456                 break;
2457             case 't':
2458                 value = '\t';
2459                 break;
2460             case 'f':
2461                 value = '\f';
2462                 break;
2463             case 'b':
2464                 value = '\b';
2465                 break;
2466             case 'e':
2467                 value = '\033';
2468                 break;
2469             case 'a':
2470                 value = '\007';
2471                 break;
2472             case 'x':
2473                 if (*PL_regcomp_parse == '{') {
2474                     e = strchr(PL_regcomp_parse++, '}');
2475                     if (!e)
2476                         FAIL("Missing right brace on \\x{}");
2477                     value = scan_hex(PL_regcomp_parse + 1, e - PL_regcomp_parse, &numlen);
2478                     PL_regcomp_parse = e + 1;
2479                 }
2480                 else {
2481                     value = scan_hex(PL_regcomp_parse, 2, &numlen);
2482                     PL_regcomp_parse += numlen;
2483                 }
2484                 break;
2485             case 'c':
2486                 value = UCHARAT(PL_regcomp_parse++);
2487                 value = toCTRL(value);
2488                 break;
2489             case '0': case '1': case '2': case '3': case '4':
2490             case '5': case '6': case '7': case '8': case '9':
2491                 value = scan_oct(--PL_regcomp_parse, 3, &numlen);
2492                 PL_regcomp_parse += numlen;
2493                 break;
2494             }
2495         }
2496         if (range) {
2497             if (lastvalue > value)
2498                 FAIL("invalid [] range in regexp");
2499             if (!SIZE_ONLY)
2500                 sv_catpvf(listsv, "%04x\t%04x\n", lastvalue, value);
2501             lastvalue = value;
2502             range = 0;
2503         }
2504         else {
2505             lastvalue = value;
2506             if (*PL_regcomp_parse == '-' && PL_regcomp_parse+1 < PL_regxend &&
2507               PL_regcomp_parse[1] != ']') {
2508                 PL_regcomp_parse++;
2509                 range = 1;
2510                 continue;       /* do it next time */
2511             }
2512             if (!SIZE_ONLY)
2513                 sv_catpvf(listsv, "%04x\n", value);
2514         }
2515     }
2516
2517     ret = reganode(ANYOFUTF8, 0);
2518
2519     if (!SIZE_ONLY) {
2520         SV *rv = swash_init("utf8", "", listsv, 1, 0);
2521         SvREFCNT_dec(listsv);
2522         n = add_data(1,"s");
2523         PL_regcomp_rx->data->data[n] = (void*)rv;
2524         ARG1_SET(ret, flags);
2525         ARG2_SET(ret, n);
2526     }
2527
2528     return ret;
2529 }
2530
2531 STATIC char*
2532 nextchar(void)
2533 {
2534     dTHR;
2535     char* retval = PL_regcomp_parse++;
2536
2537     for (;;) {
2538         if (*PL_regcomp_parse == '(' && PL_regcomp_parse[1] == '?' &&
2539                 PL_regcomp_parse[2] == '#') {
2540             while (*PL_regcomp_parse && *PL_regcomp_parse != ')')
2541                 PL_regcomp_parse++;
2542             PL_regcomp_parse++;
2543             continue;
2544         }
2545         if (PL_regflags & PMf_EXTENDED) {
2546             if (isSPACE(*PL_regcomp_parse)) {
2547                 PL_regcomp_parse++;
2548                 continue;
2549             }
2550             else if (*PL_regcomp_parse == '#') {
2551                 while (*PL_regcomp_parse && *PL_regcomp_parse != '\n')
2552                     PL_regcomp_parse++;
2553                 PL_regcomp_parse++;
2554                 continue;
2555             }
2556         }
2557         return retval;
2558     }
2559 }
2560
2561 /*
2562 - reg_node - emit a node
2563 */
2564 STATIC regnode *                        /* Location. */
2565 reg_node(U8 op)
2566 {
2567     dTHR;
2568     register regnode *ret;
2569     register regnode *ptr;
2570
2571     ret = PL_regcode;
2572     if (SIZE_ONLY) {
2573         SIZE_ALIGN(PL_regsize);
2574         PL_regsize += 1;
2575         return(ret);
2576     }
2577
2578     NODE_ALIGN_FILL(ret);
2579     ptr = ret;
2580     FILL_ADVANCE_NODE(ptr, op);
2581     PL_regcode = ptr;
2582
2583     return(ret);
2584 }
2585
2586 /*
2587 - reganode - emit a node with an argument
2588 */
2589 STATIC regnode *                        /* Location. */
2590 reganode(U8 op, U32 arg)
2591 {
2592     dTHR;
2593     register regnode *ret;
2594     register regnode *ptr;
2595
2596     ret = PL_regcode;
2597     if (SIZE_ONLY) {
2598         SIZE_ALIGN(PL_regsize);
2599         PL_regsize += 2;
2600         return(ret);
2601     }
2602
2603     NODE_ALIGN_FILL(ret);
2604     ptr = ret;
2605     FILL_ADVANCE_NODE_ARG(ptr, op, arg);
2606     PL_regcode = ptr;
2607
2608     return(ret);
2609 }
2610
2611 /*
2612 - regc - emit (if appropriate) a Unicode character
2613 */
2614 STATIC void
2615 reguni(UV uv, char* s, I32* lenp)
2616 {
2617     dTHR;
2618     if (SIZE_ONLY) {
2619         U8 tmpbuf[10];
2620         *lenp = uv_to_utf8(tmpbuf, uv) - tmpbuf;
2621     }
2622     else
2623         *lenp = uv_to_utf8((U8*)s, uv) - (U8*)s;
2624
2625 }
2626
2627 /*
2628 - regc - emit (if appropriate) a byte of code
2629 */
2630 STATIC void
2631 regc(U8 b, char* s)
2632 {
2633     dTHR;
2634     if (!SIZE_ONLY)
2635         *s = b;
2636 }
2637
2638 /*
2639 - reginsert - insert an operator in front of already-emitted operand
2640 *
2641 * Means relocating the operand.
2642 */
2643 STATIC void
2644 reginsert(U8 op, regnode *opnd)
2645 {
2646     dTHR;
2647     register regnode *src;
2648     register regnode *dst;
2649     register regnode *place;
2650     register int offset = regarglen[(U8)op];
2651     
2652 /* (regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
2653
2654     if (SIZE_ONLY) {
2655         PL_regsize += NODE_STEP_REGNODE + offset;
2656         return;
2657     }
2658
2659     src = PL_regcode;
2660     PL_regcode += NODE_STEP_REGNODE + offset;
2661     dst = PL_regcode;
2662     while (src > opnd)
2663         StructCopy(--src, --dst, regnode);
2664
2665     place = opnd;               /* Op node, where operand used to be. */
2666     src = NEXTOPER(place);
2667     FILL_ADVANCE_NODE(place, op);
2668     Zero(src, offset, regnode);
2669 }
2670
2671 /*
2672 - regtail - set the next-pointer at the end of a node chain of p to val.
2673 */
2674 STATIC void
2675 regtail(regnode *p, regnode *val)
2676 {
2677     dTHR;
2678     register regnode *scan;
2679     register regnode *temp;
2680     register I32 offset;
2681
2682     if (SIZE_ONLY)
2683         return;
2684
2685     /* Find last node. */
2686     scan = p;
2687     for (;;) {
2688         temp = regnext(scan);
2689         if (temp == NULL)
2690             break;
2691         scan = temp;
2692     }
2693
2694     if (reg_off_by_arg[OP(scan)]) {
2695         ARG_SET(scan, val - scan);
2696     }
2697     else {
2698         NEXT_OFF(scan) = val - scan;
2699     }
2700 }
2701
2702 /*
2703 - regoptail - regtail on operand of first argument; nop if operandless
2704 */
2705 STATIC void
2706 regoptail(regnode *p, regnode *val)
2707 {
2708     dTHR;
2709     /* "Operandless" and "op != BRANCH" are synonymous in practice. */
2710     if (p == NULL || SIZE_ONLY)
2711         return;
2712     if (regkind[(U8)OP(p)] == BRANCH) {
2713         regtail(NEXTOPER(p), val);
2714     }
2715     else if ( regkind[(U8)OP(p)] == BRANCHJ) {
2716         regtail(NEXTOPER(NEXTOPER(p)), val);
2717     }
2718     else
2719         return;
2720 }
2721
2722 /*
2723  - regcurly - a little FSA that accepts {\d+,?\d*}
2724  */
2725 STATIC I32
2726 regcurly(register char *s)
2727 {
2728     if (*s++ != '{')
2729         return FALSE;
2730     if (!isDIGIT(*s))
2731         return FALSE;
2732     while (isDIGIT(*s))
2733         s++;
2734     if (*s == ',')
2735         s++;
2736     while (isDIGIT(*s))
2737         s++;
2738     if (*s != '}')
2739         return FALSE;
2740     return TRUE;
2741 }
2742
2743
2744 STATIC regnode *
2745 dumpuntil(regnode *start, regnode *node, regnode *last, SV* sv, I32 l)
2746 {
2747 #ifdef DEBUGGING
2748     register char op = EXACT;   /* Arbitrary non-END op. */
2749     register regnode *next, *onode;
2750
2751     while (op != END && (!last || node < last)) {
2752         /* While that wasn't END last time... */
2753
2754         NODE_ALIGN(node);
2755         op = OP(node);
2756         if (op == CLOSE)
2757             l--;        
2758         next = regnext(node);
2759         /* Where, what. */
2760         if (OP(node) == OPTIMIZED)
2761             goto after_print;
2762         regprop(sv, node);
2763         PerlIO_printf(Perl_debug_log, "%4d:%*s%s", node - start, 
2764                       2*l + 1, "", SvPVX(sv));
2765         if (next == NULL)               /* Next ptr. */
2766             PerlIO_printf(Perl_debug_log, "(0)");
2767         else 
2768             PerlIO_printf(Perl_debug_log, "(%d)", next - start);
2769         (void)PerlIO_putc(Perl_debug_log, '\n');
2770       after_print:
2771         if (regkind[(U8)op] == BRANCHJ) {
2772             register regnode *nnode = (OP(next) == LONGJMP 
2773                                        ? regnext(next) 
2774                                        : next);
2775             if (last && nnode > last)
2776                 nnode = last;
2777             node = dumpuntil(start, NEXTOPER(NEXTOPER(node)), nnode, sv, l + 1);
2778         }
2779         else if (regkind[(U8)op] == BRANCH) {
2780             node = dumpuntil(start, NEXTOPER(node), next, sv, l + 1);
2781         }
2782         else if ( op == CURLY) {   /* `next' might be very big: optimizer */
2783             node = dumpuntil(start, NEXTOPER(node) + EXTRA_STEP_2ARGS,
2784                              NEXTOPER(node) + EXTRA_STEP_2ARGS + 1, sv, l + 1);
2785         }
2786         else if (regkind[(U8)op] == CURLY && op != CURLYX) {
2787             node = dumpuntil(start, NEXTOPER(node) + EXTRA_STEP_2ARGS,
2788                              next, sv, l + 1);
2789         }
2790         else if ( op == PLUS || op == STAR) {
2791             node = dumpuntil(start, NEXTOPER(node), NEXTOPER(node) + 1, sv, l + 1);
2792         }
2793         else if (op == ANYOF) {
2794             node = NEXTOPER(node);
2795             node += ANY_SKIP;
2796         }
2797         else if (regkind[(U8)op] == EXACT) {
2798             /* Literal string, where present. */
2799             node += ((*OPERAND(node)) + 2 + sizeof(regnode) - 1) / sizeof(regnode);
2800             node = NEXTOPER(node);
2801         }
2802         else {
2803             node = NEXTOPER(node);
2804             node += regarglen[(U8)op];
2805         }
2806         if (op == CURLYX || op == OPEN)
2807             l++;
2808         else if (op == WHILEM)
2809             l--;
2810     }
2811 #endif  /* DEBUGGING */
2812     return node;
2813 }
2814
2815 /*
2816  - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
2817  */
2818 void
2819 regdump(regexp *r)
2820 {
2821 #ifdef DEBUGGING
2822     dTHR;
2823     SV *sv = sv_newmortal();
2824
2825     (void)dumpuntil(r->program, r->program + 1, NULL, sv, 0);
2826
2827     /* Header fields of interest. */
2828     if (r->anchored_substr)
2829         PerlIO_printf(Perl_debug_log, "anchored `%s%s%s'%s at %d ", 
2830                       PL_colors[0],
2831                       SvPVX(r->anchored_substr), 
2832                       PL_colors[1],
2833                       SvTAIL(r->anchored_substr) ? "$" : "",
2834                       r->anchored_offset);
2835     if (r->float_substr)
2836         PerlIO_printf(Perl_debug_log, "floating `%s%s%s'%s at %d..%u ", 
2837                       PL_colors[0],
2838                       SvPVX(r->float_substr), 
2839                       PL_colors[1],
2840                       SvTAIL(r->float_substr) ? "$" : "",
2841                       r->float_min_offset, r->float_max_offset);
2842     if (r->check_substr)
2843         PerlIO_printf(Perl_debug_log, 
2844                       r->check_substr == r->float_substr 
2845                       ? "(checking floating" : "(checking anchored");
2846     if (r->reganch & ROPT_NOSCAN)
2847         PerlIO_printf(Perl_debug_log, " noscan");
2848     if (r->reganch & ROPT_CHECK_ALL)
2849         PerlIO_printf(Perl_debug_log, " isall");
2850     if (r->check_substr)
2851         PerlIO_printf(Perl_debug_log, ") ");
2852
2853     if (r->regstclass) {
2854         regprop(sv, r->regstclass);
2855         PerlIO_printf(Perl_debug_log, "stclass `%s' ", SvPVX(sv));
2856     }
2857     if (r->reganch & ROPT_ANCH) {
2858         PerlIO_printf(Perl_debug_log, "anchored");
2859         if (r->reganch & ROPT_ANCH_BOL)
2860             PerlIO_printf(Perl_debug_log, "(BOL)");
2861         if (r->reganch & ROPT_ANCH_MBOL)
2862             PerlIO_printf(Perl_debug_log, "(MBOL)");
2863         if (r->reganch & ROPT_ANCH_GPOS)
2864             PerlIO_printf(Perl_debug_log, "(GPOS)");
2865         PerlIO_putc(Perl_debug_log, ' ');
2866     }
2867     if (r->reganch & ROPT_GPOS_SEEN)
2868         PerlIO_printf(Perl_debug_log, "GPOS ");
2869     if (r->reganch & ROPT_SKIP)
2870         PerlIO_printf(Perl_debug_log, "plus ");
2871     if (r->reganch & ROPT_IMPLICIT)
2872         PerlIO_printf(Perl_debug_log, "implicit ");
2873     PerlIO_printf(Perl_debug_log, "minlen %ld ", (long) r->minlen);
2874     if (r->reganch & ROPT_EVAL_SEEN)
2875         PerlIO_printf(Perl_debug_log, "with eval ");
2876     PerlIO_printf(Perl_debug_log, "\n");
2877 #endif  /* DEBUGGING */
2878 }
2879
2880 /*
2881 - regprop - printable representation of opcode
2882 */
2883 void
2884 regprop(SV *sv, regnode *o)
2885 {
2886 #ifdef DEBUGGING
2887     dTHR;
2888     register char *p = 0;
2889
2890     sv_setpvn(sv, "", 0);
2891     switch (OP(o)) {
2892     case BOL:
2893         p = "BOL";
2894         break;
2895     case MBOL:
2896         p = "MBOL";
2897         break;
2898     case SBOL:
2899         p = "SBOL";
2900         break;
2901     case EOL:
2902         p = "EOL";
2903         break;
2904     case EOS:
2905         p = "EOS";
2906         break;
2907     case MEOL:
2908         p = "MEOL";
2909         break;
2910     case SEOL:
2911         p = "SEOL";
2912         break;
2913     case ANY:
2914         p = "ANY";
2915         break;
2916     case SANY:
2917         p = "SANY";
2918         break;
2919     case ANYUTF8:
2920         p = "ANYUTF8";
2921         break;
2922     case SANYUTF8:
2923         p = "SANYUTF8";
2924         break;
2925     case ANYOFUTF8:
2926         p = "ANYOFUTF8";
2927         break;
2928     case ANYOF:
2929         p = "ANYOF";
2930         break;
2931     case BRANCH:
2932         p = "BRANCH";
2933         break;
2934     case EXACT:
2935         sv_catpvf(sv, "EXACT <%s%s%s>", PL_colors[0], OPERAND(o) + 1, PL_colors[1]);
2936         break;
2937     case EXACTF:
2938         sv_catpvf(sv, "EXACTF <%s%s%s>", PL_colors[0], OPERAND(o) + 1, PL_colors[1]);
2939         break;
2940     case EXACTFL:
2941         sv_catpvf(sv, "EXACTFL <%s%s%s>", PL_colors[0], OPERAND(o) + 1, PL_colors[1]);
2942         break;
2943     case NOTHING:
2944         p = "NOTHING";
2945         break;
2946     case TAIL:
2947         p = "TAIL";
2948         break;
2949     case BACK:
2950         p = "BACK";
2951         break;
2952     case END:
2953         p = "END";
2954         break;
2955     case BOUND:
2956         p = "BOUND";
2957         break;
2958     case BOUNDL:
2959         p = "BOUNDL";
2960         break;
2961     case NBOUND:
2962         p = "NBOUND";
2963         break;
2964     case NBOUNDL:
2965         p = "NBOUNDL";
2966         break;
2967     case CURLY:
2968         sv_catpvf(sv, "CURLY {%d,%d}", ARG1(o), ARG2(o));
2969         break;
2970     case CURLYM:
2971         sv_catpvf(sv, "CURLYM[%d] {%d,%d}", o->flags, ARG1(o), ARG2(o));
2972         break;
2973     case CURLYN:
2974         sv_catpvf(sv, "CURLYN[%d] {%d,%d}", o->flags, ARG1(o), ARG2(o));
2975         break;
2976     case CURLYX:
2977         sv_catpvf(sv, "CURLYX {%d,%d}", ARG1(o), ARG2(o));
2978         break;
2979     case REF:
2980         sv_catpvf(sv, "REF%d", ARG(o));
2981         break;
2982     case REFF:
2983         sv_catpvf(sv, "REFF%d", ARG(o));
2984         break;
2985     case REFFL:
2986         sv_catpvf(sv, "REFFL%d", ARG(o));
2987         break;
2988     case OPEN:
2989         sv_catpvf(sv, "OPEN%d", ARG(o));
2990         break;
2991     case CLOSE:
2992         sv_catpvf(sv, "CLOSE%d", ARG(o));
2993         p = NULL;
2994         break;
2995     case STAR:
2996         p = "STAR";
2997         break;
2998     case PLUS:
2999         p = "PLUS";
3000         break;
3001     case MINMOD:
3002         p = "MINMOD";
3003         break;
3004     case GPOS:
3005         p = "GPOS";
3006         break;
3007     case UNLESSM:
3008         sv_catpvf(sv, "UNLESSM[-%d]", o->flags);
3009         break;
3010     case IFMATCH:
3011         sv_catpvf(sv, "IFMATCH[-%d]", o->flags);
3012         break;
3013     case SUCCEED:
3014         p = "SUCCEED";
3015         break;
3016     case WHILEM:
3017         p = "WHILEM";
3018         break;
3019     case DIGIT:
3020         p = "DIGIT";
3021         break;
3022     case NDIGIT:
3023         p = "NDIGIT";
3024         break;
3025     case ALNUM:
3026         p = "ALNUM";
3027         break;
3028     case NALNUM:
3029         p = "NALNUM";
3030         break;
3031     case SPACE:
3032         p = "SPACE";
3033         break;
3034     case NSPACE:
3035         p = "NSPACE";
3036         break;
3037     case ALNUML:
3038         p = "ALNUML";
3039         break;
3040     case NALNUML:
3041         p = "NALNUML";
3042         break;
3043     case SPACEL:
3044         p = "SPACEL";
3045         break;
3046     case NSPACEL:
3047         p = "NSPACEL";
3048         break;
3049     case EVAL:
3050         p = "EVAL";
3051         break;
3052     case LONGJMP:
3053         p = "LONGJMP";
3054         break;
3055     case BRANCHJ:
3056         p = "BRANCHJ";
3057         break;
3058     case IFTHEN:
3059         p = "IFTHEN";
3060         break;
3061     case GROUPP:
3062         sv_catpvf(sv, "GROUPP%d", ARG(o));
3063         break;
3064     case LOGICAL:
3065         sv_catpvf(sv, "LOGICAL[%d]", o->flags);
3066         break;
3067     case SUSPEND:
3068         p = "SUSPEND";
3069         break;
3070     case RENUM:
3071         p = "RENUM";
3072         break;
3073     case OPTIMIZED:
3074         p = "OPTIMIZED";
3075         break;
3076     default:
3077         FAIL("corrupted regexp opcode");
3078     }
3079     if (p)
3080         sv_catpv(sv, p);
3081 #endif  /* DEBUGGING */
3082 }
3083
3084 void
3085 pregfree(struct regexp *r)
3086 {
3087     dTHR;
3088     if (!r || (--r->refcnt > 0))
3089         return;
3090     if (r->precomp)
3091         Safefree(r->precomp);
3092     if (r->subbase)
3093         Safefree(r->subbase);
3094     if (r->substrs) {
3095         if (r->anchored_substr)
3096             SvREFCNT_dec(r->anchored_substr);
3097         if (r->float_substr)
3098             SvREFCNT_dec(r->float_substr);
3099         Safefree(r->substrs);
3100     }
3101     if (r->data) {
3102         int n = r->data->count;
3103         while (--n >= 0) {
3104             switch (r->data->what[n]) {
3105             case 's':
3106                 SvREFCNT_dec((SV*)r->data->data[n]);
3107                 break;
3108             case 'o':
3109                 op_free((OP_4tree*)r->data->data[n]);
3110                 break;
3111             case 'n':
3112                 break;
3113             default:
3114                 FAIL2("panic: regfree data code '%c'", r->data->what[n]);
3115             }
3116         }
3117         Safefree(r->data->what);
3118         Safefree(r->data);
3119     }
3120     Safefree(r->startp);
3121     Safefree(r->endp);
3122     Safefree(r);
3123 }
3124
3125 /*
3126  - regnext - dig the "next" pointer out of a node
3127  *
3128  * [Note, when REGALIGN is defined there are two places in regmatch()
3129  * that bypass this code for speed.]
3130  */
3131 regnode *
3132 regnext(register regnode *p)
3133 {
3134     dTHR;
3135     register I32 offset;
3136
3137     if (p == &PL_regdummy)
3138         return(NULL);
3139
3140     offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
3141     if (offset == 0)
3142         return(NULL);
3143
3144     return(p+offset);
3145 }
3146
3147 STATIC void     
3148 re_croak2(const char* pat1,const char* pat2,...)
3149 {
3150     va_list args;
3151     STRLEN l1 = strlen(pat1);
3152     STRLEN l2 = strlen(pat2);
3153     char buf[512];
3154     char *message;
3155
3156     if (l1 > 510)
3157         l1 = 510;
3158     if (l1 + l2 > 510)
3159         l2 = 510 - l1;
3160     Copy(pat1, buf, l1 , char);
3161     Copy(pat2, buf + l1, l2 , char);
3162     buf[l1 + l2] = '\n';
3163     buf[l1 + l2 + 1] = '\0';
3164     va_start(args, pat2);
3165     message = mess(buf, &args);
3166     va_end(args);
3167     l1 = strlen(message);
3168     if (l1 > 512)
3169         l1 = 512;
3170     Copy(message, buf, l1 , char);
3171     buf[l1] = '\0';                     /* Overwrite \n */
3172     croak("%s", buf);
3173 }
3174
3175 /* XXX Here's a total kludge.  But we need to re-enter for swash routines. */
3176
3177 void
3178 save_re_context(void)
3179 {                   
3180     dTHR;
3181     SAVEPPTR(PL_bostr);
3182     SAVEPPTR(PL_regprecomp);            /* uncompiled string. */
3183     SAVEI32(PL_regnpar);                /* () count. */
3184     SAVEI32(PL_regsize);                /* Code size. */
3185     SAVEI16(PL_regflags);               /* are we folding, multilining? */
3186     SAVEPPTR(PL_reginput);              /* String-input pointer. */
3187     SAVEPPTR(PL_regbol);                /* Beginning of input, for ^ check. */
3188     SAVEPPTR(PL_regeol);                /* End of input, for $ check. */
3189     SAVESPTR(PL_regstartp);             /* Pointer to startp array. */
3190     SAVESPTR(PL_regendp);               /* Ditto for endp. */
3191     SAVESPTR(PL_reglastparen);          /* Similarly for lastparen. */
3192     SAVEPPTR(PL_regtill);               /* How far we are required to go. */
3193     SAVEI32(PL_regprev);                /* char before regbol, \n if none */
3194     SAVESPTR(PL_reg_start_tmp);         /* from regexec.c */
3195     PL_reg_start_tmp = 0;
3196     SAVEFREEPV(PL_reg_start_tmp);
3197     SAVEI32(PL_reg_start_tmpl);         /* from regexec.c */
3198     PL_reg_start_tmpl = 0;
3199     SAVESPTR(PL_regdata);
3200     SAVEI32(PL_reg_flags);              /* from regexec.c */
3201     SAVEI32(PL_reg_eval_set);           /* from regexec.c */
3202     SAVEI32(PL_regnarrate);             /* from regexec.c */
3203     SAVESPTR(PL_regprogram);            /* from regexec.c */
3204     SAVEINT(PL_regindent);              /* from regexec.c */
3205     SAVESPTR(PL_regcc);                 /* from regexec.c */
3206     SAVESPTR(PL_curcop);
3207     SAVESPTR(PL_regcomp_rx);            /* from regcomp.c */
3208     SAVEI32(PL_regseen);                /* from regcomp.c */
3209     SAVEI32(PL_regsawback);             /* Did we see \1, ...? */
3210     SAVEI32(PL_regnaughty);             /* How bad is this pattern? */
3211     SAVESPTR(PL_regcode);               /* Code-emit pointer; &regdummy = don't */
3212     SAVEPPTR(PL_regxend);               /* End of input for compile */
3213     SAVEPPTR(PL_regcomp_parse);         /* Input-scan pointer. */
3214 }