Shave off about 5% (Digital UNIX, -g, pixie) of the op/regexp
[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 #  if defined(PERL_EXT_RE_DEBUG) && !defined(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 #  define Perl_pregfree my_regfree
39 #  define Perl_re_intuit_string my_re_intuit_string
40 /* *These* symbols are masked to allow static link. */
41 #  define Perl_regnext my_regnext
42 #  define Perl_save_re_context my_save_re_context
43 #  define Perl_reginitcolors my_reginitcolors 
44
45 #  define PERL_NO_GET_CONTEXT
46 #endif 
47
48 /*SUPPRESS 112*/
49 /*
50  * pregcomp and pregexec -- regsub and regerror are not used in perl
51  *
52  *      Copyright (c) 1986 by University of Toronto.
53  *      Written by Henry Spencer.  Not derived from licensed software.
54  *
55  *      Permission is granted to anyone to use this software for any
56  *      purpose on any computer system, and to redistribute it freely,
57  *      subject to the following restrictions:
58  *
59  *      1. The author is not responsible for the consequences of use of
60  *              this software, no matter how awful, even if they arise
61  *              from defects in it.
62  *
63  *      2. The origin of this software must not be misrepresented, either
64  *              by explicit claim or by omission.
65  *
66  *      3. Altered versions must be plainly marked as such, and must not
67  *              be misrepresented as being the original software.
68  *
69  *
70  ****    Alterations to Henry's code are...
71  ****
72  ****    Copyright (c) 1991-2000, Larry Wall
73  ****
74  ****    You may distribute under the terms of either the GNU General Public
75  ****    License or the Artistic License, as specified in the README file.
76
77  *
78  * Beware that some of this code is subtly aware of the way operator
79  * precedence is structured in regular expressions.  Serious changes in
80  * regular-expression syntax might require a total rethink.
81  */
82 #include "EXTERN.h"
83 #define PERL_IN_REGCOMP_C
84 #include "perl.h"
85
86 #ifdef PERL_IN_XSUB_RE
87 #  if defined(PERL_CAPI) || defined(PERL_OBJECT)
88 #    include "XSUB.h"
89 #  endif
90 #else
91 #  include "INTERN.h"
92 #endif
93
94 #define REG_COMP_C
95 #include "regcomp.h"
96
97 #ifdef op
98 #undef op
99 #endif /* op */
100
101 #ifdef MSDOS
102 # if defined(BUGGY_MSC6)
103  /* MSC 6.00A breaks on op/regexp.t test 85 unless we turn this off */
104  # pragma optimize("a",off)
105  /* But MSC 6.00A is happy with 'w', for aliases only across function calls*/
106  # pragma optimize("w",on )
107 # endif /* BUGGY_MSC6 */
108 #endif /* MSDOS */
109
110 #ifndef STATIC
111 #define STATIC  static
112 #endif
113
114 #define ISMULT1(c)      ((c) == '*' || (c) == '+' || (c) == '?')
115 #define ISMULT2(s)      ((*s) == '*' || (*s) == '+' || (*s) == '?' || \
116         ((*s) == '{' && regcurly(s)))
117 #ifdef atarist
118 #define PERL_META       "^$.[()|?+*\\"
119 #else
120 #define META    "^$.[()|?+*\\"
121 #endif
122
123 #ifdef SPSTART
124 #undef SPSTART          /* dratted cpp namespace... */
125 #endif
126 /*
127  * Flags to be passed up and down.
128  */
129 #define WORST           0       /* Worst case. */
130 #define HASWIDTH        0x1     /* Known to match non-null strings. */
131 #define SIMPLE          0x2     /* Simple enough to be STAR/PLUS operand. */
132 #define SPSTART         0x4     /* Starts with * or +. */
133 #define TRYAGAIN        0x8     /* Weeded out a declaration. */
134
135 /* Length of a variant. */
136
137 typedef struct scan_data_t {
138     I32 len_min;
139     I32 len_delta;
140     I32 pos_min;
141     I32 pos_delta;
142     SV *last_found;
143     I32 last_end;                       /* min value, <0 unless valid. */
144     I32 last_start_min;
145     I32 last_start_max;
146     SV **longest;                       /* Either &l_fixed, or &l_float. */
147     SV *longest_fixed;
148     I32 offset_fixed;
149     SV *longest_float;
150     I32 offset_float_min;
151     I32 offset_float_max;
152     I32 flags;
153     I32 whilem_c;
154     struct regnode_charclass_class *start_class;
155 } scan_data_t;
156
157 /*
158  * Forward declarations for pregcomp()'s friends.
159  */
160
161 static scan_data_t zero_scan_data = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
162                                       0, 0, 0, 0, 0 };
163
164 #define SF_BEFORE_EOL           (SF_BEFORE_SEOL|SF_BEFORE_MEOL)
165 #define SF_BEFORE_SEOL          0x1
166 #define SF_BEFORE_MEOL          0x2
167 #define SF_FIX_BEFORE_EOL       (SF_FIX_BEFORE_SEOL|SF_FIX_BEFORE_MEOL)
168 #define SF_FL_BEFORE_EOL        (SF_FL_BEFORE_SEOL|SF_FL_BEFORE_MEOL)
169
170 #ifdef NO_UNARY_PLUS
171 #  define SF_FIX_SHIFT_EOL      (0+2)
172 #  define SF_FL_SHIFT_EOL               (0+4)
173 #else
174 #  define SF_FIX_SHIFT_EOL      (+2)
175 #  define SF_FL_SHIFT_EOL               (+4)
176 #endif
177
178 #define SF_FIX_BEFORE_SEOL      (SF_BEFORE_SEOL << SF_FIX_SHIFT_EOL)
179 #define SF_FIX_BEFORE_MEOL      (SF_BEFORE_MEOL << SF_FIX_SHIFT_EOL)
180
181 #define SF_FL_BEFORE_SEOL       (SF_BEFORE_SEOL << SF_FL_SHIFT_EOL)
182 #define SF_FL_BEFORE_MEOL       (SF_BEFORE_MEOL << SF_FL_SHIFT_EOL) /* 0x20 */
183 #define SF_IS_INF               0x40
184 #define SF_HAS_PAR              0x80
185 #define SF_IN_PAR               0x100
186 #define SF_HAS_EVAL             0x200
187 #define SCF_DO_SUBSTR           0x400
188 #define SCF_DO_STCLASS_AND      0x0800
189 #define SCF_DO_STCLASS_OR       0x1000
190 #define SCF_DO_STCLASS          (SCF_DO_STCLASS_AND|SCF_DO_STCLASS_OR)
191
192 #define RF_utf8         8
193 #define UTF (PL_reg_flags & RF_utf8)
194 #define LOC (PL_regflags & PMf_LOCALE)
195 #define FOLD (PL_regflags & PMf_FOLD)
196
197 #define OOB_CHAR8               1234
198 #define OOB_UTF8                123456
199 #define OOB_NAMEDCLASS          -1
200
201 #define CHR_SVLEN(sv) (UTF ? sv_len_utf8(sv) : SvCUR(sv))
202 #define CHR_DIST(a,b) (UTF ? utf8_distance(a,b) : a - b)
203
204
205 /* length of regex to show in messages that don't mark a position within */
206 #define RegexLengthToShowInErrorMessages 127
207
208 /*
209  * If MARKER[12] are adjusted, be sure to adjust the constants at the top
210  * of t/op/regmesg.t, the tests in t/op/re_tests, and those in
211  * op/pragma/warn/regcomp.
212  */
213 #define MARKER1 "HERE"      /* marker as it appears in the description */
214 #define MARKER2 " << HERE "  /* marker as it appears within the regex */
215    
216 #define REPORT_LOCATION " before " MARKER1 " mark in regex m/%.*s" MARKER2 "%s/"
217
218 /*
219  * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
220  * arg. Show regex, up to a maximum length. If it's too long, chop and add
221  * "...".
222  */
223 #define FAIL(msg)                                                             \
224     STMT_START {                                                             \
225         char *ellipses = "";                                                 \
226         unsigned len = strlen(PL_regprecomp);                                \
227                                                                              \
228         if (!SIZE_ONLY)                                                      \
229             SAVEDESTRUCTOR_X(clear_re,(void*)PL_regcomp_rx);                 \
230                                                                              \
231         if (len > RegexLengthToShowInErrorMessages) {                        \
232             /* chop 10 shorter than the max, to ensure meaning of "..." */   \
233             len = RegexLengthToShowInErrorMessages - 10;                     \
234             ellipses = "...";                                                \
235         }                                                                    \
236         Perl_croak(aTHX_ "%s in regex m/%.*s%s/",                            \
237                    msg, (int)len, PL_regprecomp, ellipses);                  \
238     } STMT_END
239
240 /*
241  * Calls SAVEDESTRUCTOR_X if needed, then calls Perl_croak with the given
242  * args. Show regex, up to a maximum length. If it's too long, chop and add
243  * "...".
244  */
245 #define FAIL2(pat,msg)                                                        \
246     STMT_START {                                                             \
247         char *ellipses = "";                                                 \
248         unsigned len = strlen(PL_regprecomp);                                \
249                                                                              \
250         if (!SIZE_ONLY)                                                      \
251             SAVEDESTRUCTOR_X(clear_re,(void*)PL_regcomp_rx);                 \
252                                                                              \
253         if (len > RegexLengthToShowInErrorMessages) {                        \
254             /* chop 10 shorter than the max, to ensure meaning of "..." */   \
255             len = RegexLengthToShowInErrorMessages - 10;                     \
256             ellipses = "...";                                                \
257         }                                                                    \
258         S_re_croak2(aTHX_ pat, " in regex m/%.*s%s/",                        \
259                     msg, (int)len, PL_regprecomp, ellipses);                \
260     } STMT_END
261
262
263 /*
264  * Simple_vFAIL -- like FAIL, but marks the current location in the scan
265  */
266 #define Simple_vFAIL(m)                                                      \
267     STMT_START {                                                             \
268       unsigned offset = strlen(PL_regprecomp)-(PL_regxend-PL_regcomp_parse); \
269                                                                              \
270       Perl_croak(aTHX_ "%s" REPORT_LOCATION,               \
271                  m, (int)offset, PL_regprecomp, PL_regprecomp + offset);     \
272     } STMT_END
273
274 /*
275  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL()
276  */
277 #define vFAIL(m)                                                             \
278     STMT_START {                                                             \
279       if (!SIZE_ONLY)                                                        \
280             SAVEDESTRUCTOR_X(clear_re,(void*)PL_regcomp_rx);                 \
281       Simple_vFAIL(m);                                                       \
282     } STMT_END
283
284 /*
285  * Like Simple_vFAIL(), but accepts two arguments.
286  */
287 #define Simple_vFAIL2(m,a1)                                                  \
288     STMT_START {                                                             \
289       unsigned offset = strlen(PL_regprecomp)-(PL_regxend-PL_regcomp_parse); \
290                                                                              \
291       S_re_croak2(aTHX_ m, REPORT_LOCATION, a1,       \
292                   (int)offset, PL_regprecomp, PL_regprecomp + offset);       \
293     } STMT_END
294
295 /*
296  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL2().
297  */
298 #define vFAIL2(m,a1)                                                         \
299     STMT_START {                                                             \
300       if (!SIZE_ONLY)                                                        \
301             SAVEDESTRUCTOR_X(clear_re,(void*)PL_regcomp_rx);                 \
302       Simple_vFAIL2(m, a1);                                                  \
303     } STMT_END
304
305
306 /*
307  * Like Simple_vFAIL(), but accepts three arguments.
308  */
309 #define Simple_vFAIL3(m, a1, a2)                                             \
310     STMT_START {                                                             \
311       unsigned offset = strlen(PL_regprecomp)-(PL_regxend-PL_regcomp_parse); \
312                                                                              \
313       S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2,   \
314                   (int)offset, PL_regprecomp, PL_regprecomp + offset);       \
315     } STMT_END
316
317 /*
318  * Calls SAVEDESTRUCTOR_X if needed, then Simple_vFAIL3().
319  */
320 #define vFAIL3(m,a1,a2)                                                      \
321     STMT_START {                                                             \
322       if (!SIZE_ONLY)                                                        \
323             SAVEDESTRUCTOR_X(clear_re,(void*)PL_regcomp_rx);                 \
324       Simple_vFAIL3(m, a1, a2);                                              \
325     } STMT_END
326
327 /*
328  * Like Simple_vFAIL(), but accepts four arguments.
329  */
330 #define Simple_vFAIL4(m, a1, a2, a3)                                         \
331     STMT_START {                                                             \
332       unsigned offset = strlen(PL_regprecomp)-(PL_regxend-PL_regcomp_parse); \
333                                                                              \
334       S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, a3,\
335                   (int)offset, PL_regprecomp, PL_regprecomp + offset);       \
336     } STMT_END
337
338 /*
339  * Like Simple_vFAIL(), but accepts five arguments.
340  */
341 #define Simple_vFAIL5(m, a1, a2, a3, a4)                                     \
342     STMT_START {                                                             \
343       unsigned offset = strlen(PL_regprecomp)-(PL_regxend-PL_regcomp_parse); \
344       S_re_croak2(aTHX_ m, REPORT_LOCATION, a1, a2, a3, a4,\
345                   (int)offset, PL_regprecomp, PL_regprecomp + offset);       \
346     } STMT_END
347
348
349 #define vWARN(loc,m)                                                         \
350     STMT_START {                                                             \
351         unsigned offset = strlen(PL_regprecomp)-(PL_regxend-(loc));          \
352         Perl_warner(aTHX_ WARN_REGEXP, "%s" REPORT_LOCATION,\
353                  m, (int)offset, PL_regprecomp, PL_regprecomp + offset);          \
354     } STMT_END                                                               \
355
356
357 #define vWARN2(loc, m, a1)                                                   \
358     STMT_START {                                                             \
359         unsigned offset = strlen(PL_regprecomp)-(PL_regxend-(loc));          \
360         Perl_warner(aTHX_ WARN_REGEXP, m REPORT_LOCATION,\
361                  a1,                                                         \
362                  (int)offset, PL_regprecomp, PL_regprecomp + offset);        \
363     } STMT_END
364
365 #define vWARN3(loc, m, a1, a2)                                               \
366     STMT_START {                                                             \
367       unsigned offset = strlen(PL_regprecomp) - (PL_regxend - (loc));        \
368         Perl_warner(aTHX_ WARN_REGEXP, m REPORT_LOCATION,                    \
369                  a1, a2,                                                     \
370                  (int)offset, PL_regprecomp, PL_regprecomp + offset);        \
371     } STMT_END
372
373 #define vWARN4(loc, m, a1, a2, a3)                                           \
374     STMT_START {                                                             \
375       unsigned offset = strlen(PL_regprecomp)-(PL_regxend-(loc));            \
376         Perl_warner(aTHX_ WARN_REGEXP, m REPORT_LOCATION,\
377                  a1, a2, a3,                                                 \
378                  (int)offset, PL_regprecomp, PL_regprecomp + offset);        \
379     } STMT_END
380
381
382
383 /* Allow for side effects in s */
384 #define REGC(c,s) STMT_START { if (!SIZE_ONLY) *(s) = (c); else (s);} STMT_END
385
386 static void clear_re(pTHXo_ void *r);
387
388 /* Mark that we cannot extend a found fixed substring at this point.
389    Updata the longest found anchored substring and the longest found
390    floating substrings if needed. */
391
392 STATIC void
393 S_scan_commit(pTHX_ scan_data_t *data)
394 {
395     dTHR;
396     STRLEN l = CHR_SVLEN(data->last_found);
397     STRLEN old_l = CHR_SVLEN(*data->longest);
398     
399     if ((l >= old_l) && ((l > old_l) || (data->flags & SF_BEFORE_EOL))) {
400         sv_setsv(*data->longest, data->last_found);
401         if (*data->longest == data->longest_fixed) {
402             data->offset_fixed = l ? data->last_start_min : data->pos_min;
403             if (data->flags & SF_BEFORE_EOL)
404                 data->flags 
405                     |= ((data->flags & SF_BEFORE_EOL) << SF_FIX_SHIFT_EOL);
406             else
407                 data->flags &= ~SF_FIX_BEFORE_EOL;
408         }
409         else {
410             data->offset_float_min = l ? data->last_start_min : data->pos_min;
411             data->offset_float_max = (l 
412                                       ? data->last_start_max 
413                                       : data->pos_min + data->pos_delta);
414             if (data->flags & SF_BEFORE_EOL)
415                 data->flags 
416                     |= ((data->flags & SF_BEFORE_EOL) << SF_FL_SHIFT_EOL);
417             else
418                 data->flags &= ~SF_FL_BEFORE_EOL;
419         }
420     }
421     SvCUR_set(data->last_found, 0);
422     data->last_end = -1;
423     data->flags &= ~SF_BEFORE_EOL;
424 }
425
426 /* Can match anything (initialization) */
427 STATIC void
428 S_cl_anything(pTHX_ struct regnode_charclass_class *cl)
429 {
430     ANYOF_CLASS_ZERO(cl);
431     ANYOF_BITMAP_SETALL(cl);
432     cl->flags = ANYOF_EOS;
433     if (LOC)
434         cl->flags |= ANYOF_LOCALE;
435 }
436
437 /* Can match anything (initialization) */
438 STATIC int
439 S_cl_is_anything(pTHX_ struct regnode_charclass_class *cl)
440 {
441     int value;
442
443     for (value = 0; value <= ANYOF_MAX; value += 2)
444         if (ANYOF_CLASS_TEST(cl, value) && ANYOF_CLASS_TEST(cl, value + 1))
445             return 1;
446     for (value = 0; value < ANYOF_BITMAP_SIZE; ++value)
447         if (!ANYOF_BITMAP_BYTE(cl, value))
448             return 0;
449     return 1;
450 }
451
452 /* Can match anything (initialization) */
453 STATIC void
454 S_cl_init(pTHX_ struct regnode_charclass_class *cl)
455 {
456     Zero(cl, 1, struct regnode_charclass_class);
457     cl->type = ANYOF;
458     cl_anything(cl);
459 }
460
461 STATIC void
462 S_cl_init_zero(pTHX_ struct regnode_charclass_class *cl)
463 {
464     Zero(cl, 1, struct regnode_charclass_class);
465     cl->type = ANYOF;
466     cl_anything(cl);
467     if (LOC)
468         cl->flags |= ANYOF_LOCALE;
469 }
470
471 /* 'And' a given class with another one.  Can create false positives */
472 /* We assume that cl is not inverted */
473 STATIC void
474 S_cl_and(pTHX_ struct regnode_charclass_class *cl,
475          struct regnode_charclass_class *and_with)
476 {
477     if (!(and_with->flags & ANYOF_CLASS)
478         && !(cl->flags & ANYOF_CLASS)
479         && (and_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
480         && !(and_with->flags & ANYOF_FOLD)
481         && !(cl->flags & ANYOF_FOLD)) {
482         int i;
483
484         if (and_with->flags & ANYOF_INVERT)
485             for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
486                 cl->bitmap[i] &= ~and_with->bitmap[i];
487         else
488             for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
489                 cl->bitmap[i] &= and_with->bitmap[i];
490     } /* XXXX: logic is complicated otherwise, leave it along for a moment. */
491     if (!(and_with->flags & ANYOF_EOS))
492         cl->flags &= ~ANYOF_EOS;
493 }
494
495 /* 'OR' a given class with another one.  Can create false positives */
496 /* We assume that cl is not inverted */
497 STATIC void
498 S_cl_or(pTHX_ struct regnode_charclass_class *cl, struct regnode_charclass_class *or_with)
499 {
500     if (or_with->flags & ANYOF_INVERT) {
501         /* We do not use
502          * (B1 | CL1) | (!B2 & !CL2) = (B1 | !B2 & !CL2) | (CL1 | (!B2 & !CL2))
503          *   <= (B1 | !B2) | (CL1 | !CL2)
504          * which is wasteful if CL2 is small, but we ignore CL2:
505          *   (B1 | CL1) | (!B2 & !CL2) <= (B1 | CL1) | !B2 = (B1 | !B2) | CL1
506          * XXXX Can we handle case-fold?  Unclear:
507          *   (OK1(i) | OK1(i')) | !(OK1(i) | OK1(i')) =
508          *   (OK1(i) | OK1(i')) | (!OK1(i) & !OK1(i'))
509          */
510         if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
511              && !(or_with->flags & ANYOF_FOLD)
512              && !(cl->flags & ANYOF_FOLD) ) {
513             int i;
514
515             for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
516                 cl->bitmap[i] |= ~or_with->bitmap[i];
517         } /* XXXX: logic is complicated otherwise */
518         else {
519             cl_anything(cl);
520         }
521     } else {
522         /* (B1 | CL1) | (B2 | CL2) = (B1 | B2) | (CL1 | CL2)) */
523         if ( (or_with->flags & ANYOF_LOCALE) == (cl->flags & ANYOF_LOCALE)
524              && (!(or_with->flags & ANYOF_FOLD) 
525                  || (cl->flags & ANYOF_FOLD)) ) {
526             int i;
527
528             /* OR char bitmap and class bitmap separately */
529             for (i = 0; i < ANYOF_BITMAP_SIZE; i++)
530                 cl->bitmap[i] |= or_with->bitmap[i];
531             if (or_with->flags & ANYOF_CLASS) {
532                 for (i = 0; i < ANYOF_CLASSBITMAP_SIZE; i++)
533                     cl->classflags[i] |= or_with->classflags[i];
534                 cl->flags |= ANYOF_CLASS;
535             }
536         }
537         else { /* XXXX: logic is complicated, leave it along for a moment. */
538             cl_anything(cl);
539         }
540     }
541     if (or_with->flags & ANYOF_EOS)
542         cl->flags |= ANYOF_EOS;
543 }
544
545 /* REx optimizer.  Converts nodes into quickier variants "in place".
546    Finds fixed substrings.  */
547
548 /* Stops at toplevel WHILEM as well as at `last'. At end *scanp is set
549    to the position after last scanned or to NULL. */
550
551 STATIC I32
552 S_study_chunk(pTHX_ regnode **scanp, I32 *deltap, regnode *last, scan_data_t *data, U32 flags)
553                         /* scanp: Start here (read-write). */
554                         /* deltap: Write maxlen-minlen here. */
555                         /* last: Stop before this one. */
556 {
557     dTHR;
558     I32 min = 0, pars = 0, code;
559     regnode *scan = *scanp, *next;
560     I32 delta = 0;
561     int is_inf = (flags & SCF_DO_SUBSTR) && (data->flags & SF_IS_INF);
562     int is_inf_internal = 0;            /* The studied chunk is infinite */
563     I32 is_par = OP(scan) == OPEN ? ARG(scan) : 0;
564     scan_data_t data_fake;
565     struct regnode_charclass_class and_with; /* Valid if flags & SCF_DO_STCLASS_OR */
566     
567     while (scan && OP(scan) != END && scan < last) {
568         /* Peephole optimizer: */
569
570         if (PL_regkind[(U8)OP(scan)] == EXACT) {
571             /* Merge several consecutive EXACTish nodes into one. */
572             regnode *n = regnext(scan);
573             U32 stringok = 1;
574 #ifdef DEBUGGING
575             regnode *stop = scan;
576 #endif 
577
578             next = scan + NODE_SZ_STR(scan);
579             /* Skip NOTHING, merge EXACT*. */
580             while (n &&
581                    ( PL_regkind[(U8)OP(n)] == NOTHING || 
582                      (stringok && (OP(n) == OP(scan))))
583                    && NEXT_OFF(n)
584                    && NEXT_OFF(scan) + NEXT_OFF(n) < I16_MAX) {
585                 if (OP(n) == TAIL || n > next)
586                     stringok = 0;
587                 if (PL_regkind[(U8)OP(n)] == NOTHING) {
588                     NEXT_OFF(scan) += NEXT_OFF(n);
589                     next = n + NODE_STEP_REGNODE;
590 #ifdef DEBUGGING
591                     if (stringok)
592                         stop = n;
593 #endif 
594                     n = regnext(n);
595                 }
596                 else {
597                     int oldl = STR_LEN(scan);
598                     regnode *nnext = regnext(n);
599                     
600                     if (oldl + STR_LEN(n) > U8_MAX) 
601                         break;
602                     NEXT_OFF(scan) += NEXT_OFF(n);
603                     STR_LEN(scan) += STR_LEN(n);
604                     next = n + NODE_SZ_STR(n);
605                     /* Now we can overwrite *n : */
606                     Move(STRING(n), STRING(scan) + oldl,
607                          STR_LEN(n), char);
608 #ifdef DEBUGGING
609                     if (stringok)
610                         stop = next - 1;
611 #endif 
612                     n = nnext;
613                 }
614             }
615 #ifdef DEBUGGING
616             /* Allow dumping */
617             n = scan + NODE_SZ_STR(scan);
618             while (n <= stop) {
619                 if (PL_regkind[(U8)OP(n)] != NOTHING || OP(n) == NOTHING) {
620                     OP(n) = OPTIMIZED;
621                     NEXT_OFF(n) = 0;
622                 }
623                 n++;
624             }
625 #endif
626         }
627         /* Follow the next-chain of the current node and optimize
628            away all the NOTHINGs from it.  */
629         if (OP(scan) != CURLYX) {
630             int max = (reg_off_by_arg[OP(scan)]
631                        ? I32_MAX
632                        /* I32 may be smaller than U16 on CRAYs! */
633                        : (I32_MAX < U16_MAX ? I32_MAX : U16_MAX));
634             int off = (reg_off_by_arg[OP(scan)] ? ARG(scan) : NEXT_OFF(scan));
635             int noff;
636             regnode *n = scan;
637             
638             /* Skip NOTHING and LONGJMP. */
639             while ((n = regnext(n))
640                    && ((PL_regkind[(U8)OP(n)] == NOTHING && (noff = NEXT_OFF(n)))
641                        || ((OP(n) == LONGJMP) && (noff = ARG(n))))
642                    && off + noff < max)
643                 off += noff;
644             if (reg_off_by_arg[OP(scan)])
645                 ARG(scan) = off;
646             else 
647                 NEXT_OFF(scan) = off;
648         }
649         /* The principal pseudo-switch.  Cannot be a switch, since we
650            look into several different things.  */
651         if (OP(scan) == BRANCH || OP(scan) == BRANCHJ 
652                    || OP(scan) == IFTHEN || OP(scan) == SUSPEND) {
653             next = regnext(scan);
654             code = OP(scan);
655             
656             if (OP(next) == code || code == IFTHEN || code == SUSPEND) { 
657                 I32 max1 = 0, min1 = I32_MAX, num = 0;
658                 struct regnode_charclass_class accum;
659                 
660                 if (flags & SCF_DO_SUBSTR) /* XXXX Add !SUSPEND? */
661                     scan_commit(data);  /* Cannot merge strings after this. */
662                 if (flags & SCF_DO_STCLASS)
663                     cl_init_zero(&accum);
664                 while (OP(scan) == code) {
665                     I32 deltanext, minnext, f = 0;
666                     struct regnode_charclass_class this_class;
667
668                     num++;
669                     data_fake.flags = 0;
670                     if (data)
671                         data_fake.whilem_c = data->whilem_c;
672                     next = regnext(scan);
673                     scan = NEXTOPER(scan);
674                     if (code != BRANCH)
675                         scan = NEXTOPER(scan);
676                     if (flags & SCF_DO_STCLASS) {
677                         cl_init(&this_class);
678                         data_fake.start_class = &this_class;
679                         f = SCF_DO_STCLASS_AND;
680                     }               
681                     /* we suppose the run is continuous, last=next...*/
682                     minnext = study_chunk(&scan, &deltanext, next,
683                                           &data_fake, f);
684                     if (min1 > minnext) 
685                         min1 = minnext;
686                     if (max1 < minnext + deltanext)
687                         max1 = minnext + deltanext;
688                     if (deltanext == I32_MAX)
689                         is_inf = is_inf_internal = 1;
690                     scan = next;
691                     if (data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
692                         pars++;
693                     if (data && (data_fake.flags & SF_HAS_EVAL))
694                         data->flags |= SF_HAS_EVAL;
695                     if (data)
696                         data->whilem_c = data_fake.whilem_c;
697                     if (flags & SCF_DO_STCLASS)
698                         cl_or(&accum, &this_class);
699                     if (code == SUSPEND) 
700                         break;
701                 }
702                 if (code == IFTHEN && num < 2) /* Empty ELSE branch */
703                     min1 = 0;
704                 if (flags & SCF_DO_SUBSTR) {
705                     data->pos_min += min1;
706                     data->pos_delta += max1 - min1;
707                     if (max1 != min1 || is_inf)
708                         data->longest = &(data->longest_float);
709                 }
710                 min += min1;
711                 delta += max1 - min1;
712                 if (flags & SCF_DO_STCLASS_OR) {
713                     cl_or(data->start_class, &accum);
714                     if (min1) {
715                         cl_and(data->start_class, &and_with);
716                         flags &= ~SCF_DO_STCLASS;
717                     }
718                 }
719                 else if (flags & SCF_DO_STCLASS_AND) {
720                     if (min1) {
721                         cl_and(data->start_class, &accum);
722                         flags &= ~SCF_DO_STCLASS;
723                     }
724                     else {
725                         /* Switch to OR mode: cache the old value of 
726                          * data->start_class */
727                         StructCopy(data->start_class, &and_with,
728                                    struct regnode_charclass_class);
729                         flags &= ~SCF_DO_STCLASS_AND;
730                         StructCopy(&accum, data->start_class,
731                                    struct regnode_charclass_class);
732                         flags |= SCF_DO_STCLASS_OR;
733                         data->start_class->flags |= ANYOF_EOS;
734                     }
735                 }
736             }
737             else if (code == BRANCHJ)   /* single branch is optimized. */
738                 scan = NEXTOPER(NEXTOPER(scan));
739             else                        /* single branch is optimized. */
740                 scan = NEXTOPER(scan);
741             continue;
742         }
743         else if (OP(scan) == EXACT) {
744             I32 l = STR_LEN(scan);
745             if (UTF) {
746                 unsigned char *s = (unsigned char *)STRING(scan);
747                 unsigned char *e = s + l;
748                 I32 newl = 0;
749                 while (s < e) {
750                     newl++;
751                     s += UTF8SKIP(s);
752                 }
753                 l = newl;
754             }
755             min += l;
756             if (flags & SCF_DO_SUBSTR) { /* Update longest substr. */
757                 /* The code below prefers earlier match for fixed
758                    offset, later match for variable offset.  */
759                 if (data->last_end == -1) { /* Update the start info. */
760                     data->last_start_min = data->pos_min;
761                     data->last_start_max = is_inf
762                         ? I32_MAX : data->pos_min + data->pos_delta; 
763                 }
764                 sv_catpvn(data->last_found, STRING(scan), STR_LEN(scan));
765                 data->last_end = data->pos_min + l;
766                 data->pos_min += l; /* As in the first entry. */
767                 data->flags &= ~SF_BEFORE_EOL;
768             }
769             if (flags & SCF_DO_STCLASS_AND) {
770                 /* Check whether it is compatible with what we know already! */
771                 int compat = 1;
772
773                 if (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE)) 
774                     && !ANYOF_BITMAP_TEST(data->start_class, *STRING(scan))
775                     && (!(data->start_class->flags & ANYOF_FOLD)
776                         || !ANYOF_BITMAP_TEST(data->start_class,
777                                               PL_fold[*(U8*)STRING(scan)])))
778                     compat = 0;
779                 ANYOF_CLASS_ZERO(data->start_class);
780                 ANYOF_BITMAP_ZERO(data->start_class);
781                 if (compat)
782                     ANYOF_BITMAP_SET(data->start_class, *STRING(scan));
783                 data->start_class->flags &= ~ANYOF_EOS;
784             }
785             else if (flags & SCF_DO_STCLASS_OR) {
786                 /* false positive possible if the class is case-folded */
787                 ANYOF_BITMAP_SET(data->start_class, *STRING(scan));     
788                 data->start_class->flags &= ~ANYOF_EOS;
789                 cl_and(data->start_class, &and_with);
790             }
791             flags &= ~SCF_DO_STCLASS;
792         }
793         else if (PL_regkind[(U8)OP(scan)] == EXACT) { /* But OP != EXACT! */
794             I32 l = STR_LEN(scan);
795
796             /* Search for fixed substrings supports EXACT only. */
797             if (flags & SCF_DO_SUBSTR) 
798                 scan_commit(data);
799             if (UTF) {
800                 unsigned char *s = (unsigned char *)STRING(scan);
801                 unsigned char *e = s + l;
802                 I32 newl = 0;
803                 while (s < e) {
804                     newl++;
805                     s += UTF8SKIP(s);
806                 }
807                 l = newl;
808             }
809             min += l;
810             if (data && (flags & SCF_DO_SUBSTR))
811                 data->pos_min += l;
812             if (flags & SCF_DO_STCLASS_AND) {
813                 /* Check whether it is compatible with what we know already! */
814                 int compat = 1;
815
816                 if (!(data->start_class->flags & (ANYOF_CLASS | ANYOF_LOCALE)) 
817                     && !ANYOF_BITMAP_TEST(data->start_class, *STRING(scan))
818                     && !ANYOF_BITMAP_TEST(data->start_class, 
819                                           PL_fold[*(U8*)STRING(scan)]))
820                     compat = 0;
821                 ANYOF_CLASS_ZERO(data->start_class);
822                 ANYOF_BITMAP_ZERO(data->start_class);
823                 if (compat) {
824                     ANYOF_BITMAP_SET(data->start_class, *STRING(scan));
825                     data->start_class->flags &= ~ANYOF_EOS;
826                     data->start_class->flags |= ANYOF_FOLD;
827                     if (OP(scan) == EXACTFL)
828                         data->start_class->flags |= ANYOF_LOCALE;
829                 }
830             }
831             else if (flags & SCF_DO_STCLASS_OR) {
832                 if (data->start_class->flags & ANYOF_FOLD) {
833                     /* false positive possible if the class is case-folded.
834                        Assume that the locale settings are the same... */
835                     ANYOF_BITMAP_SET(data->start_class, *STRING(scan)); 
836                     data->start_class->flags &= ~ANYOF_EOS;
837                 }
838                 cl_and(data->start_class, &and_with);
839             }
840             flags &= ~SCF_DO_STCLASS;
841         }
842         else if (strchr((char*)PL_varies,OP(scan))) {
843             I32 mincount, maxcount, minnext, deltanext, fl;
844             I32 f = flags, pos_before = 0;
845             regnode *oscan = scan;
846             struct regnode_charclass_class this_class;
847             struct regnode_charclass_class *oclass = NULL;
848
849             switch (PL_regkind[(U8)OP(scan)]) {
850             case WHILEM:                /* End of (?:...)* . */
851                 scan = NEXTOPER(scan);
852                 goto finish;
853             case PLUS:
854                 if (flags & (SCF_DO_SUBSTR | SCF_DO_STCLASS)) {
855                     next = NEXTOPER(scan);
856                     if (OP(next) == EXACT || (flags & SCF_DO_STCLASS)) {
857                         mincount = 1; 
858                         maxcount = REG_INFTY; 
859                         next = regnext(scan);
860                         scan = NEXTOPER(scan);
861                         goto do_curly;
862                     }
863                 }
864                 if (flags & SCF_DO_SUBSTR)
865                     data->pos_min++;
866                 min++;
867                 /* Fall through. */
868             case STAR:
869                 if (flags & SCF_DO_STCLASS) {
870                     mincount = 0;
871                     maxcount = REG_INFTY; 
872                     next = regnext(scan);
873                     scan = NEXTOPER(scan);
874                     goto do_curly;
875                 }
876                 is_inf = is_inf_internal = 1; 
877                 scan = regnext(scan);
878                 if (flags & SCF_DO_SUBSTR) {
879                     scan_commit(data);  /* Cannot extend fixed substrings */
880                     data->longest = &(data->longest_float);
881                 }
882                 goto optimize_curly_tail;
883             case CURLY:
884                 mincount = ARG1(scan); 
885                 maxcount = ARG2(scan);
886                 next = regnext(scan);
887                 scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
888               do_curly:
889                 if (flags & SCF_DO_SUBSTR) {
890                     if (mincount == 0) scan_commit(data); /* Cannot extend fixed substrings */
891                     pos_before = data->pos_min;
892                 }
893                 if (data) {
894                     fl = data->flags;
895                     data->flags &= ~(SF_HAS_PAR|SF_IN_PAR|SF_HAS_EVAL);
896                     if (is_inf)
897                         data->flags |= SF_IS_INF;
898                 }
899                 if (flags & SCF_DO_STCLASS) {
900                     cl_init(&this_class);
901                     oclass = data->start_class;
902                     data->start_class = &this_class;
903                     f |= SCF_DO_STCLASS_AND;
904                     f &= ~SCF_DO_STCLASS_OR;
905                 }
906
907                 /* This will finish on WHILEM, setting scan, or on NULL: */
908                 minnext = study_chunk(&scan, &deltanext, last, data, 
909                                       mincount == 0 
910                                         ? (f & ~SCF_DO_SUBSTR) : f);
911
912                 if (flags & SCF_DO_STCLASS)
913                     data->start_class = oclass;
914                 if (mincount == 0 || minnext == 0) {
915                     if (flags & SCF_DO_STCLASS_OR) {
916                         cl_or(data->start_class, &this_class);
917                     }
918                     else if (flags & SCF_DO_STCLASS_AND) {
919                         /* Switch to OR mode: cache the old value of 
920                          * data->start_class */
921                         StructCopy(data->start_class, &and_with,
922                                    struct regnode_charclass_class);
923                         flags &= ~SCF_DO_STCLASS_AND;
924                         StructCopy(&this_class, data->start_class,
925                                    struct regnode_charclass_class);
926                         flags |= SCF_DO_STCLASS_OR;
927                         data->start_class->flags |= ANYOF_EOS;
928                     }
929                 } else {                /* Non-zero len */
930                     if (flags & SCF_DO_STCLASS_OR) {
931                         cl_or(data->start_class, &this_class);
932                         cl_and(data->start_class, &and_with);
933                     }
934                     else if (flags & SCF_DO_STCLASS_AND)
935                         cl_and(data->start_class, &this_class);
936                     flags &= ~SCF_DO_STCLASS;
937                 }
938                 if (!scan)              /* It was not CURLYX, but CURLY. */
939                     scan = next;
940                 if (ckWARN(WARN_REGEXP) && (minnext + deltanext == 0) 
941                     && !(data->flags & (SF_HAS_PAR|SF_IN_PAR))
942                     && maxcount <= REG_INFTY/3) /* Complement check for big count */
943                 {
944                     vWARN(PL_regcomp_parse,
945                           "Quantifier unexpected on zero-length expression");
946                 }
947
948                 min += minnext * mincount;
949                 is_inf_internal |= ((maxcount == REG_INFTY 
950                                      && (minnext + deltanext) > 0)
951                                     || deltanext == I32_MAX);
952                 is_inf |= is_inf_internal;
953                 delta += (minnext + deltanext) * maxcount - minnext * mincount;
954
955                 /* Try powerful optimization CURLYX => CURLYN. */
956                 if (  OP(oscan) == CURLYX && data 
957                       && data->flags & SF_IN_PAR
958                       && !(data->flags & SF_HAS_EVAL)
959                       && !deltanext && minnext == 1 ) {
960                     /* Try to optimize to CURLYN.  */
961                     regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
962                     regnode *nxt1 = nxt, *nxt2;
963
964                     /* Skip open. */
965                     nxt = regnext(nxt);
966                     if (!strchr((char*)PL_simple,OP(nxt))
967                         && !(PL_regkind[(U8)OP(nxt)] == EXACT
968                              && STR_LEN(nxt) == 1)) 
969                         goto nogo;
970                     nxt2 = nxt;
971                     nxt = regnext(nxt);
972                     if (OP(nxt) != CLOSE) 
973                         goto nogo;
974                     /* Now we know that nxt2 is the only contents: */
975                     oscan->flags = ARG(nxt);
976                     OP(oscan) = CURLYN;
977                     OP(nxt1) = NOTHING; /* was OPEN. */
978 #ifdef DEBUGGING
979                     OP(nxt1 + 1) = OPTIMIZED; /* was count. */
980                     NEXT_OFF(nxt1+ 1) = 0; /* just for consistancy. */
981                     NEXT_OFF(nxt2) = 0; /* just for consistancy with CURLY. */
982                     OP(nxt) = OPTIMIZED;        /* was CLOSE. */
983                     OP(nxt + 1) = OPTIMIZED; /* was count. */
984                     NEXT_OFF(nxt+ 1) = 0; /* just for consistancy. */
985 #endif 
986                 }
987               nogo:
988
989                 /* Try optimization CURLYX => CURLYM. */
990                 if (  OP(oscan) == CURLYX && data 
991                       && !(data->flags & SF_HAS_PAR)
992                       && !(data->flags & SF_HAS_EVAL)
993                       && !deltanext  ) {
994                     /* XXXX How to optimize if data == 0? */
995                     /* Optimize to a simpler form.  */
996                     regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN */
997                     regnode *nxt2;
998
999                     OP(oscan) = CURLYM;
1000                     while ( (nxt2 = regnext(nxt)) /* skip over embedded stuff*/
1001                             && (OP(nxt2) != WHILEM)) 
1002                         nxt = nxt2;
1003                     OP(nxt2)  = SUCCEED; /* Whas WHILEM */
1004                     /* Need to optimize away parenths. */
1005                     if (data->flags & SF_IN_PAR) {
1006                         /* Set the parenth number.  */
1007                         regnode *nxt1 = NEXTOPER(oscan) + EXTRA_STEP_2ARGS; /* OPEN*/
1008
1009                         if (OP(nxt) != CLOSE) 
1010                             FAIL("Panic opt close");
1011                         oscan->flags = ARG(nxt);
1012                         OP(nxt1) = OPTIMIZED;   /* was OPEN. */
1013                         OP(nxt) = OPTIMIZED;    /* was CLOSE. */
1014 #ifdef DEBUGGING
1015                         OP(nxt1 + 1) = OPTIMIZED; /* was count. */
1016                         OP(nxt + 1) = OPTIMIZED; /* was count. */
1017                         NEXT_OFF(nxt1 + 1) = 0; /* just for consistancy. */
1018                         NEXT_OFF(nxt + 1) = 0; /* just for consistancy. */
1019 #endif 
1020 #if 0
1021                         while ( nxt1 && (OP(nxt1) != WHILEM)) {
1022                             regnode *nnxt = regnext(nxt1);
1023                             
1024                             if (nnxt == nxt) {
1025                                 if (reg_off_by_arg[OP(nxt1)])
1026                                     ARG_SET(nxt1, nxt2 - nxt1);
1027                                 else if (nxt2 - nxt1 < U16_MAX)
1028                                     NEXT_OFF(nxt1) = nxt2 - nxt1;
1029                                 else
1030                                     OP(nxt) = NOTHING;  /* Cannot beautify */
1031                             }
1032                             nxt1 = nnxt;
1033                         }
1034 #endif
1035                         /* Optimize again: */
1036                         study_chunk(&nxt1, &deltanext, nxt, NULL, 0);
1037                     }
1038                     else
1039                         oscan->flags = 0;
1040                 }
1041                 else if (OP(oscan) == CURLYX && data && ++data->whilem_c < 16) {
1042                     /* This stays as CURLYX, and can put the count/of pair. */
1043                     /* Find WHILEM (as in regexec.c) */
1044                     regnode *nxt = oscan + NEXT_OFF(oscan);
1045
1046                     if (OP(PREVOPER(nxt)) == NOTHING) /* LONGJMP */
1047                         nxt += ARG(nxt);
1048                     PREVOPER(nxt)->flags = data->whilem_c
1049                         | (PL_reg_whilem_seen << 4); /* On WHILEM */
1050                 }
1051                 if (data && fl & (SF_HAS_PAR|SF_IN_PAR)) 
1052                     pars++;
1053                 if (flags & SCF_DO_SUBSTR) {
1054                     SV *last_str = Nullsv;
1055                     int counted = mincount != 0;
1056
1057                     if (data->last_end > 0 && mincount != 0) { /* Ends with a string. */
1058                         I32 b = pos_before >= data->last_start_min 
1059                             ? pos_before : data->last_start_min;
1060                         STRLEN l;
1061                         char *s = SvPV(data->last_found, l);
1062                         I32 old = b - data->last_start_min;
1063
1064                         if (UTF)
1065                             old = utf8_hop((U8*)s, old) - (U8*)s;
1066                         
1067                         l -= old;
1068                         /* Get the added string: */
1069                         last_str = newSVpvn(s  + old, l);
1070                         if (deltanext == 0 && pos_before == b) {
1071                             /* What was added is a constant string */
1072                             if (mincount > 1) {
1073                                 SvGROW(last_str, (mincount * l) + 1);
1074                                 repeatcpy(SvPVX(last_str) + l, 
1075                                           SvPVX(last_str), l, mincount - 1);
1076                                 SvCUR(last_str) *= mincount;
1077                                 /* Add additional parts. */
1078                                 SvCUR_set(data->last_found, 
1079                                           SvCUR(data->last_found) - l);
1080                                 sv_catsv(data->last_found, last_str);
1081                                 data->last_end += l * (mincount - 1);
1082                             }
1083                         } else {
1084                             /* start offset must point into the last copy */
1085                             data->last_start_min += minnext * (mincount - 1);
1086                             data->last_start_max += is_inf ? 0 : (maxcount - 1)
1087                                 * (minnext + data->pos_delta);
1088                         }
1089                     }
1090                     /* It is counted once already... */
1091                     data->pos_min += minnext * (mincount - counted);
1092                     data->pos_delta += - counted * deltanext +
1093                         (minnext + deltanext) * maxcount - minnext * mincount;
1094                     if (mincount != maxcount) {
1095                          /* Cannot extend fixed substrings found inside
1096                             the group.  */
1097                         scan_commit(data);
1098                         if (mincount && last_str) {
1099                             sv_setsv(data->last_found, last_str);
1100                             data->last_end = data->pos_min;
1101                             data->last_start_min = 
1102                                 data->pos_min - CHR_SVLEN(last_str);
1103                             data->last_start_max = is_inf 
1104                                 ? I32_MAX 
1105                                 : data->pos_min + data->pos_delta
1106                                 - CHR_SVLEN(last_str);
1107                         }
1108                         data->longest = &(data->longest_float);
1109                     }
1110                     SvREFCNT_dec(last_str);
1111                 }
1112                 if (data && (fl & SF_HAS_EVAL))
1113                     data->flags |= SF_HAS_EVAL;
1114               optimize_curly_tail:
1115                 if (OP(oscan) != CURLYX) {
1116                     while (PL_regkind[(U8)OP(next = regnext(oscan))] == NOTHING
1117                            && NEXT_OFF(next))
1118                         NEXT_OFF(oscan) += NEXT_OFF(next);
1119                 }
1120                 continue;
1121             default:                    /* REF and CLUMP only? */
1122                 if (flags & SCF_DO_SUBSTR) {
1123                     scan_commit(data);  /* Cannot expect anything... */
1124                     data->longest = &(data->longest_float);
1125                 }
1126                 is_inf = is_inf_internal = 1;
1127                 if (flags & SCF_DO_STCLASS_OR)
1128                     cl_anything(data->start_class);
1129                 flags &= ~SCF_DO_STCLASS;
1130                 break;
1131             }
1132         }
1133         else if (strchr((char*)PL_simple,OP(scan)) || PL_regkind[(U8)OP(scan)] == ANYUTF8) {
1134             int value;
1135
1136             if (flags & SCF_DO_SUBSTR) {
1137                 scan_commit(data);
1138                 data->pos_min++;
1139             }
1140             min++;
1141             if (flags & SCF_DO_STCLASS) {
1142                 data->start_class->flags &= ~ANYOF_EOS; /* No match on empty */
1143
1144                 /* Some of the logic below assumes that switching
1145                    locale on will only add false positives. */
1146                 switch (PL_regkind[(U8)OP(scan)]) {
1147                 case ANYUTF8:
1148                 case SANY:
1149                 case SANYUTF8:
1150                 case ALNUMUTF8:
1151                 case ANYOFUTF8:
1152                 case ALNUMLUTF8:
1153                 case NALNUMUTF8:
1154                 case NALNUMLUTF8:
1155                 case SPACEUTF8:
1156                 case NSPACEUTF8:
1157                 case SPACELUTF8:
1158                 case NSPACELUTF8:
1159                 case DIGITUTF8:
1160                 case NDIGITUTF8:
1161                 default:
1162                   do_default:
1163                     /* Perl_croak(aTHX_ "panic: unexpected simple REx opcode %d", OP(scan)); */
1164                     if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
1165                         cl_anything(data->start_class);
1166                     break;
1167                 case REG_ANY:
1168                     if (OP(scan) == SANY)
1169                         goto do_default;
1170                     if (flags & SCF_DO_STCLASS_OR) { /* Everything but \n */
1171                         value = (ANYOF_BITMAP_TEST(data->start_class,'\n')
1172                                  || (data->start_class->flags & ANYOF_CLASS));
1173                         cl_anything(data->start_class);
1174                     }
1175                     if (flags & SCF_DO_STCLASS_AND || !value)
1176                         ANYOF_BITMAP_CLEAR(data->start_class,'\n');
1177                     break;
1178                 case ANYOF:
1179                     if (flags & SCF_DO_STCLASS_AND)
1180                         cl_and(data->start_class,
1181                                (struct regnode_charclass_class*)scan);
1182                     else
1183                         cl_or(data->start_class,
1184                               (struct regnode_charclass_class*)scan);
1185                     break;
1186                 case ALNUM:
1187                     if (flags & SCF_DO_STCLASS_AND) {
1188                         if (!(data->start_class->flags & ANYOF_LOCALE)) {
1189                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
1190                             for (value = 0; value < 256; value++)
1191                                 if (!isALNUM(value))
1192                                     ANYOF_BITMAP_CLEAR(data->start_class, value);
1193                         }
1194                     }
1195                     else {
1196                         if (data->start_class->flags & ANYOF_LOCALE)
1197                             ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
1198                         else {
1199                             for (value = 0; value < 256; value++)
1200                                 if (isALNUM(value))
1201                                     ANYOF_BITMAP_SET(data->start_class, value);                     
1202                         }
1203                     }
1204                     break;
1205                 case ALNUML:
1206                     if (flags & SCF_DO_STCLASS_AND) {
1207                         if (data->start_class->flags & ANYOF_LOCALE)
1208                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NALNUM);
1209                     }
1210                     else {
1211                         ANYOF_CLASS_SET(data->start_class,ANYOF_ALNUM);
1212                         data->start_class->flags |= ANYOF_LOCALE;
1213                     }
1214                     break;
1215                 case NALNUM:
1216                     if (flags & SCF_DO_STCLASS_AND) {
1217                         if (!(data->start_class->flags & ANYOF_LOCALE)) {
1218                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
1219                             for (value = 0; value < 256; value++)
1220                                 if (isALNUM(value))
1221                                     ANYOF_BITMAP_CLEAR(data->start_class, value);
1222                         }
1223                     }
1224                     else {
1225                         if (data->start_class->flags & ANYOF_LOCALE)
1226                             ANYOF_CLASS_SET(data->start_class,ANYOF_NALNUM);
1227                         else {
1228                             for (value = 0; value < 256; value++)
1229                                 if (!isALNUM(value))
1230                                     ANYOF_BITMAP_SET(data->start_class, value);                     
1231                         }
1232                     }
1233                     break;
1234                 case NALNUML:
1235                     if (flags & SCF_DO_STCLASS_AND) {
1236                         if (data->start_class->flags & ANYOF_LOCALE)
1237                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_ALNUM);
1238                     }
1239                     else {
1240                         data->start_class->flags |= ANYOF_LOCALE;
1241                         ANYOF_CLASS_SET(data->start_class,ANYOF_NALNUM);
1242                     }
1243                     break;
1244                 case SPACE:
1245                     if (flags & SCF_DO_STCLASS_AND) {
1246                         if (!(data->start_class->flags & ANYOF_LOCALE)) {
1247                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NSPACE);
1248                             for (value = 0; value < 256; value++)
1249                                 if (!isSPACE(value))
1250                                     ANYOF_BITMAP_CLEAR(data->start_class, value);
1251                         }
1252                     }
1253                     else {
1254                         if (data->start_class->flags & ANYOF_LOCALE)
1255                             ANYOF_CLASS_SET(data->start_class,ANYOF_SPACE);
1256                         else {
1257                             for (value = 0; value < 256; value++)
1258                                 if (isSPACE(value))
1259                                     ANYOF_BITMAP_SET(data->start_class, value);                     
1260                         }
1261                     }
1262                     break;
1263                 case SPACEL:
1264                     if (flags & SCF_DO_STCLASS_AND) {
1265                         if (data->start_class->flags & ANYOF_LOCALE)
1266                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NSPACE);
1267                     }
1268                     else {
1269                         data->start_class->flags |= ANYOF_LOCALE;
1270                         ANYOF_CLASS_SET(data->start_class,ANYOF_SPACE);
1271                     }
1272                     break;
1273                 case NSPACE:
1274                     if (flags & SCF_DO_STCLASS_AND) {
1275                         if (!(data->start_class->flags & ANYOF_LOCALE)) {
1276                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_SPACE);
1277                             for (value = 0; value < 256; value++)
1278                                 if (isSPACE(value))
1279                                     ANYOF_BITMAP_CLEAR(data->start_class, value);
1280                         }
1281                     }
1282                     else {
1283                         if (data->start_class->flags & ANYOF_LOCALE)
1284                             ANYOF_CLASS_SET(data->start_class,ANYOF_NSPACE);
1285                         else {
1286                             for (value = 0; value < 256; value++)
1287                                 if (!isSPACE(value))
1288                                     ANYOF_BITMAP_SET(data->start_class, value);                     
1289                         }
1290                     }
1291                     break;
1292                 case NSPACEL:
1293                     if (flags & SCF_DO_STCLASS_AND) {
1294                         if (data->start_class->flags & ANYOF_LOCALE) {
1295                             ANYOF_CLASS_CLEAR(data->start_class,ANYOF_SPACE);
1296                             for (value = 0; value < 256; value++)
1297                                 if (!isSPACE(value))
1298                                     ANYOF_BITMAP_CLEAR(data->start_class, value);
1299                         }
1300                     }
1301                     else {
1302                         data->start_class->flags |= ANYOF_LOCALE;
1303                         ANYOF_CLASS_SET(data->start_class,ANYOF_NSPACE);
1304                     }
1305                     break;
1306                 case DIGIT:
1307                     if (flags & SCF_DO_STCLASS_AND) {
1308                         ANYOF_CLASS_CLEAR(data->start_class,ANYOF_NDIGIT);
1309                         for (value = 0; value < 256; value++)
1310                             if (!isDIGIT(value))
1311                                 ANYOF_BITMAP_CLEAR(data->start_class, value);
1312                     }
1313                     else {
1314                         if (data->start_class->flags & ANYOF_LOCALE)
1315                             ANYOF_CLASS_SET(data->start_class,ANYOF_DIGIT);
1316                         else {
1317                             for (value = 0; value < 256; value++)
1318                                 if (isDIGIT(value))
1319                                     ANYOF_BITMAP_SET(data->start_class, value);                     
1320                         }
1321                     }
1322                     break;
1323                 case NDIGIT:
1324                     if (flags & SCF_DO_STCLASS_AND) {
1325                         ANYOF_CLASS_CLEAR(data->start_class,ANYOF_DIGIT);
1326                         for (value = 0; value < 256; value++)
1327                             if (isDIGIT(value))
1328                                 ANYOF_BITMAP_CLEAR(data->start_class, value);
1329                     }
1330                     else {
1331                         if (data->start_class->flags & ANYOF_LOCALE)
1332                             ANYOF_CLASS_SET(data->start_class,ANYOF_NDIGIT);
1333                         else {
1334                             for (value = 0; value < 256; value++)
1335                                 if (!isDIGIT(value))
1336                                     ANYOF_BITMAP_SET(data->start_class, value);                     
1337                         }
1338                     }
1339                     break;
1340                 }
1341                 if (flags & SCF_DO_STCLASS_OR)
1342                     cl_and(data->start_class, &and_with);
1343                 flags &= ~SCF_DO_STCLASS;
1344             }
1345         }
1346         else if (PL_regkind[(U8)OP(scan)] == EOL && flags & SCF_DO_SUBSTR) {
1347             data->flags |= (OP(scan) == MEOL
1348                             ? SF_BEFORE_MEOL
1349                             : SF_BEFORE_SEOL);
1350         }
1351         else if (  PL_regkind[(U8)OP(scan)] == BRANCHJ
1352                  /* Lookbehind, or need to calculate parens/evals/stclass: */
1353                    && (scan->flags || data || (flags & SCF_DO_STCLASS))
1354                    && (OP(scan) == IFMATCH || OP(scan) == UNLESSM)) {
1355             /* Lookahead/lookbehind */
1356             I32 deltanext, minnext;
1357             regnode *nscan;
1358             struct regnode_charclass_class intrnl;
1359             int f = 0;
1360
1361             data_fake.flags = 0;
1362             if (data)
1363                 data_fake.whilem_c = data->whilem_c;
1364             if ( flags & SCF_DO_STCLASS && !scan->flags
1365                  && OP(scan) == IFMATCH ) { /* Lookahead */
1366                 cl_init(&intrnl);
1367                 data_fake.start_class = &intrnl;
1368                 f = SCF_DO_STCLASS_AND;
1369             }
1370             next = regnext(scan);
1371             nscan = NEXTOPER(NEXTOPER(scan));
1372             minnext = study_chunk(&nscan, &deltanext, last, &data_fake, f);
1373             if (scan->flags) {
1374                 if (deltanext) {
1375                     vFAIL("Variable length lookbehind not implemented");
1376                 }
1377                 else if (minnext > U8_MAX) {
1378                     vFAIL2("Lookbehind longer than %"UVuf" not implemented", (UV)U8_MAX);
1379                 }
1380                 scan->flags = minnext;
1381             }
1382             if (data && data_fake.flags & (SF_HAS_PAR|SF_IN_PAR))
1383                 pars++;
1384             if (data && (data_fake.flags & SF_HAS_EVAL))
1385                 data->flags |= SF_HAS_EVAL;
1386             if (data)
1387                 data->whilem_c = data_fake.whilem_c;
1388             if (f) {
1389                 int was = (data->start_class->flags & ANYOF_EOS);
1390
1391                 cl_and(data->start_class, &intrnl);
1392                 if (was)
1393                     data->start_class->flags |= ANYOF_EOS;
1394             }
1395         }
1396         else if (OP(scan) == OPEN) {
1397             pars++;
1398         }
1399         else if (OP(scan) == CLOSE && ARG(scan) == is_par) {
1400             next = regnext(scan);
1401
1402             if ( next && (OP(next) != WHILEM) && next < last)
1403                 is_par = 0;             /* Disable optimization */
1404         }
1405         else if (OP(scan) == EVAL) {
1406                 if (data)
1407                     data->flags |= SF_HAS_EVAL;
1408         }
1409         else if (OP(scan) == LOGICAL && scan->flags == 2) { /* Embedded follows */
1410                 if (flags & SCF_DO_SUBSTR) {
1411                     scan_commit(data);
1412                     data->longest = &(data->longest_float);
1413                 }
1414                 is_inf = is_inf_internal = 1;
1415                 if (flags & SCF_DO_STCLASS_OR) /* Allow everything */
1416                     cl_anything(data->start_class);
1417                 flags &= ~SCF_DO_STCLASS;
1418         }
1419         /* Else: zero-length, ignore. */
1420         scan = regnext(scan);
1421     }
1422
1423   finish:
1424     *scanp = scan;
1425     *deltap = is_inf_internal ? I32_MAX : delta;
1426     if (flags & SCF_DO_SUBSTR && is_inf) 
1427         data->pos_delta = I32_MAX - data->pos_min;
1428     if (is_par > U8_MAX)
1429         is_par = 0;
1430     if (is_par && pars==1 && data) {
1431         data->flags |= SF_IN_PAR;
1432         data->flags &= ~SF_HAS_PAR;
1433     }
1434     else if (pars && data) {
1435         data->flags |= SF_HAS_PAR;
1436         data->flags &= ~SF_IN_PAR;
1437     }
1438     if (flags & SCF_DO_STCLASS_OR)
1439         cl_and(data->start_class, &and_with);
1440     return min;
1441 }
1442
1443 STATIC I32
1444 S_add_data(pTHX_ I32 n, char *s)
1445 {
1446     dTHR;
1447     if (PL_regcomp_rx->data) {
1448         Renewc(PL_regcomp_rx->data, 
1449                sizeof(*PL_regcomp_rx->data) + sizeof(void*) * (PL_regcomp_rx->data->count + n - 1), 
1450                char, struct reg_data);
1451         Renew(PL_regcomp_rx->data->what, PL_regcomp_rx->data->count + n, U8);
1452         PL_regcomp_rx->data->count += n;
1453     }
1454     else {
1455         Newc(1207, PL_regcomp_rx->data, sizeof(*PL_regcomp_rx->data) + sizeof(void*) * (n - 1),
1456              char, struct reg_data);
1457         New(1208, PL_regcomp_rx->data->what, n, U8);
1458         PL_regcomp_rx->data->count = n;
1459     }
1460     Copy(s, PL_regcomp_rx->data->what + PL_regcomp_rx->data->count - n, n, U8);
1461     return PL_regcomp_rx->data->count - n;
1462 }
1463
1464 void
1465 Perl_reginitcolors(pTHX)
1466 {
1467     dTHR;
1468     int i = 0;
1469     char *s = PerlEnv_getenv("PERL_RE_COLORS");
1470             
1471     if (s) {
1472         PL_colors[0] = s = savepv(s);
1473         while (++i < 6) {
1474             s = strchr(s, '\t');
1475             if (s) {
1476                 *s = '\0';
1477                 PL_colors[i] = ++s;
1478             }
1479             else
1480                 PL_colors[i] = s = "";
1481         }
1482     } else {
1483         while (i < 6) 
1484             PL_colors[i++] = "";
1485     }
1486     PL_colorset = 1;
1487 }
1488
1489
1490 /*
1491  - pregcomp - compile a regular expression into internal code
1492  *
1493  * We can't allocate space until we know how big the compiled form will be,
1494  * but we can't compile it (and thus know how big it is) until we've got a
1495  * place to put the code.  So we cheat:  we compile it twice, once with code
1496  * generation turned off and size counting turned on, and once "for real".
1497  * This also means that we don't allocate space until we are sure that the
1498  * thing really will compile successfully, and we never have to move the
1499  * code and thus invalidate pointers into it.  (Note that it has to be in
1500  * one piece because free() must be able to free it all.) [NB: not true in perl]
1501  *
1502  * Beware that the optimization-preparation code in here knows about some
1503  * of the structure of the compiled regexp.  [I'll say.]
1504  */
1505 regexp *
1506 Perl_pregcomp(pTHX_ char *exp, char *xend, PMOP *pm)
1507 {
1508     dTHR;
1509     register regexp *r;
1510     regnode *scan;
1511     regnode *first;
1512     I32 flags;
1513     I32 minlen = 0;
1514     I32 sawplus = 0;
1515     I32 sawopen = 0;
1516     scan_data_t data;
1517
1518     if (exp == NULL)
1519         FAIL("NULL regexp argument");
1520
1521     if (pm->op_pmdynflags & PMdf_UTF8) {
1522         PL_reg_flags |= RF_utf8;
1523     }
1524     else
1525         PL_reg_flags = 0;
1526
1527     PL_regprecomp = savepvn(exp, xend - exp);
1528     DEBUG_r(if (!PL_colorset) reginitcolors());
1529     DEBUG_r(PerlIO_printf(Perl_debug_log, "%sCompiling REx%s `%s%*s%s'\n",
1530                       PL_colors[4],PL_colors[5],PL_colors[0],
1531                       (int)(xend - exp), PL_regprecomp, PL_colors[1]));
1532     PL_regflags = pm->op_pmflags;
1533     PL_regsawback = 0;
1534
1535     PL_regseen = 0;
1536     PL_seen_zerolen = *exp == '^' ? -1 : 0;
1537     PL_seen_evals = 0;
1538     PL_extralen = 0;
1539
1540     /* First pass: determine size, legality. */
1541     PL_regcomp_parse = exp;
1542     PL_regxend = xend;
1543     PL_regnaughty = 0;
1544     PL_regnpar = 1;
1545     PL_regsize = 0L;
1546     PL_regcode = &PL_regdummy;
1547     PL_reg_whilem_seen = 0;
1548 #if 0 /* REGC() is (currently) a NOP at the first pass.
1549        * Clever compilers notice this and complain. --jhi */
1550     REGC((U8)REG_MAGIC, (char*)PL_regcode);
1551 #endif
1552     if (reg(0, &flags) == NULL) {
1553         Safefree(PL_regprecomp);
1554         PL_regprecomp = Nullch;
1555         return(NULL);
1556     }
1557     DEBUG_r(PerlIO_printf(Perl_debug_log, "size %"IVdf" ", (IV)PL_regsize));
1558
1559     /* Small enough for pointer-storage convention?
1560        If extralen==0, this means that we will not need long jumps. */
1561     if (PL_regsize >= 0x10000L && PL_extralen)
1562         PL_regsize += PL_extralen;
1563     else
1564         PL_extralen = 0;
1565     if (PL_reg_whilem_seen > 15)
1566         PL_reg_whilem_seen = 15;
1567
1568     /* Allocate space and initialize. */
1569     Newc(1001, r, sizeof(regexp) + (unsigned)PL_regsize * sizeof(regnode),
1570          char, regexp);
1571     if (r == NULL)
1572         FAIL("Regexp out of space");
1573
1574 #ifdef DEBUGGING
1575     /* avoid reading uninitialized memory in DEBUGGING code in study_chunk() */
1576     Zero(r, sizeof(regexp) + (unsigned)PL_regsize * sizeof(regnode), char);
1577 #endif
1578     r->refcnt = 1;
1579     r->prelen = xend - exp;
1580     r->precomp = PL_regprecomp;
1581     r->subbeg = NULL;
1582     r->reganch = pm->op_pmflags & PMf_COMPILETIME;
1583     r->nparens = PL_regnpar - 1;        /* set early to validate backrefs */
1584
1585     r->substrs = 0;                     /* Useful during FAIL. */
1586     r->startp = 0;                      /* Useful during FAIL. */
1587     r->endp = 0;                        /* Useful during FAIL. */
1588
1589     PL_regcomp_rx = r;
1590
1591     /* Second pass: emit code. */
1592     PL_regcomp_parse = exp;
1593     PL_regxend = xend;
1594     PL_regnaughty = 0;
1595     PL_regnpar = 1;
1596     PL_regcode = r->program;
1597     /* Store the count of eval-groups for security checks: */
1598     PL_regcode->next_off = ((PL_seen_evals > U16_MAX) ? U16_MAX : PL_seen_evals);
1599     REGC((U8)REG_MAGIC, (char*) PL_regcode++);
1600     r->data = 0;
1601     if (reg(0, &flags) == NULL)
1602         return(NULL);
1603
1604     /* Dig out information for optimizations. */
1605     r->reganch = pm->op_pmflags & PMf_COMPILETIME; /* Again? */
1606     pm->op_pmflags = PL_regflags;
1607     if (UTF)
1608         r->reganch |= ROPT_UTF8;
1609     r->regstclass = NULL;
1610     if (PL_regnaughty >= 10)    /* Probably an expensive pattern. */
1611         r->reganch |= ROPT_NAUGHTY;
1612     scan = r->program + 1;              /* First BRANCH. */
1613
1614     /* XXXX To minimize changes to RE engine we always allocate
1615        3-units-long substrs field. */
1616     Newz(1004, r->substrs, 1, struct reg_substr_data);
1617
1618     StructCopy(&zero_scan_data, &data, scan_data_t);
1619     /* XXXX Should not we check for something else?  Usually it is OPEN1... */
1620     if (OP(scan) != BRANCH) {   /* Only one top-level choice. */
1621         I32 fake;
1622         STRLEN longest_float_length, longest_fixed_length;
1623         struct regnode_charclass_class ch_class;
1624         int stclass_flag;
1625
1626         first = scan;
1627         /* Skip introductions and multiplicators >= 1. */
1628         while ((OP(first) == OPEN && (sawopen = 1)) ||
1629                /* An OR of *one* alternative - should not happen now. */
1630             (OP(first) == BRANCH && OP(regnext(first)) != BRANCH) ||
1631             (OP(first) == PLUS) ||
1632             (OP(first) == MINMOD) ||
1633                /* An {n,m} with n>0 */
1634             (PL_regkind[(U8)OP(first)] == CURLY && ARG1(first) > 0) ) {
1635                 if (OP(first) == PLUS)
1636                     sawplus = 1;
1637                 else
1638                     first += regarglen[(U8)OP(first)];
1639                 first = NEXTOPER(first);
1640         }
1641
1642         /* Starting-point info. */
1643       again:
1644         if (PL_regkind[(U8)OP(first)] == EXACT) {
1645             if (OP(first) == EXACT);    /* Empty, get anchored substr later. */
1646             else if ((OP(first) == EXACTF || OP(first) == EXACTFL)
1647                      && !UTF)
1648                 r->regstclass = first;
1649         }
1650         else if (strchr((char*)PL_simple,OP(first)))
1651             r->regstclass = first;
1652         else if (PL_regkind[(U8)OP(first)] == BOUND ||
1653                  PL_regkind[(U8)OP(first)] == NBOUND)
1654             r->regstclass = first;
1655         else if (PL_regkind[(U8)OP(first)] == BOL) {
1656             r->reganch |= (OP(first) == MBOL
1657                            ? ROPT_ANCH_MBOL
1658                            : (OP(first) == SBOL
1659                               ? ROPT_ANCH_SBOL
1660                               : ROPT_ANCH_BOL));
1661             first = NEXTOPER(first);
1662             goto again;
1663         }
1664         else if (OP(first) == GPOS) {
1665             r->reganch |= ROPT_ANCH_GPOS;
1666             first = NEXTOPER(first);
1667             goto again;
1668         }
1669         else if ((OP(first) == STAR &&
1670             PL_regkind[(U8)OP(NEXTOPER(first))] == REG_ANY) &&
1671             !(r->reganch & ROPT_ANCH) )
1672         {
1673             /* turn .* into ^.* with an implied $*=1 */
1674             int type = OP(NEXTOPER(first));
1675
1676             if (type == REG_ANY || type == ANYUTF8)
1677                 type = ROPT_ANCH_MBOL;
1678             else
1679                 type = ROPT_ANCH_SBOL;
1680
1681             r->reganch |= type | ROPT_IMPLICIT;
1682             first = NEXTOPER(first);
1683             goto again;
1684         }
1685         if (sawplus && (!sawopen || !PL_regsawback) 
1686             && !(PL_regseen & REG_SEEN_EVAL)) /* May examine pos and $& */
1687             /* x+ must match at the 1st pos of run of x's */
1688             r->reganch |= ROPT_SKIP;
1689
1690         /* Scan is after the zeroth branch, first is atomic matcher. */
1691         DEBUG_r(PerlIO_printf(Perl_debug_log, "first at %"IVdf"\n", 
1692                               (IV)(first - scan + 1)));
1693         /*
1694         * If there's something expensive in the r.e., find the
1695         * longest literal string that must appear and make it the
1696         * regmust.  Resolve ties in favor of later strings, since
1697         * the regstart check works with the beginning of the r.e.
1698         * and avoiding duplication strengthens checking.  Not a
1699         * strong reason, but sufficient in the absence of others.
1700         * [Now we resolve ties in favor of the earlier string if
1701         * it happens that c_offset_min has been invalidated, since the
1702         * earlier string may buy us something the later one won't.]
1703         */
1704         minlen = 0;
1705
1706         data.longest_fixed = newSVpvn("",0);
1707         data.longest_float = newSVpvn("",0);
1708         data.last_found = newSVpvn("",0);
1709         data.longest = &(data.longest_fixed);
1710         first = scan;
1711         if (!r->regstclass) {
1712             cl_init(&ch_class);
1713             data.start_class = &ch_class;
1714             stclass_flag = SCF_DO_STCLASS_AND;
1715         } else                          /* XXXX Check for BOUND? */
1716             stclass_flag = 0;
1717
1718         minlen = study_chunk(&first, &fake, scan + PL_regsize, /* Up to end */
1719                              &data, SCF_DO_SUBSTR | stclass_flag);
1720         if ( PL_regnpar == 1 && data.longest == &(data.longest_fixed)
1721              && data.last_start_min == 0 && data.last_end > 0 
1722              && !PL_seen_zerolen
1723              && (!(PL_regseen & REG_SEEN_GPOS) || (r->reganch & ROPT_ANCH_GPOS)))
1724             r->reganch |= ROPT_CHECK_ALL;
1725         scan_commit(&data);
1726         SvREFCNT_dec(data.last_found);
1727
1728         longest_float_length = CHR_SVLEN(data.longest_float);
1729         if (longest_float_length
1730             || (data.flags & SF_FL_BEFORE_EOL
1731                 && (!(data.flags & SF_FL_BEFORE_MEOL)
1732                     || (PL_regflags & PMf_MULTILINE)))) {
1733             int t;
1734
1735             if (SvCUR(data.longest_fixed)                       /* ok to leave SvCUR */
1736                 && data.offset_fixed == data.offset_float_min
1737                 && SvCUR(data.longest_fixed) == SvCUR(data.longest_float))
1738                     goto remove_float;          /* As in (a)+. */
1739
1740             r->float_substr = data.longest_float;
1741             r->float_min_offset = data.offset_float_min;
1742             r->float_max_offset = data.offset_float_max;
1743             t = (data.flags & SF_FL_BEFORE_EOL /* Can't have SEOL and MULTI */
1744                        && (!(data.flags & SF_FL_BEFORE_MEOL)
1745                            || (PL_regflags & PMf_MULTILINE)));
1746             fbm_compile(r->float_substr, t ? FBMcf_TAIL : 0);
1747         }
1748         else {
1749           remove_float:
1750             r->float_substr = Nullsv;
1751             SvREFCNT_dec(data.longest_float);
1752             longest_float_length = 0;
1753         }
1754
1755         longest_fixed_length = CHR_SVLEN(data.longest_fixed);
1756         if (longest_fixed_length
1757             || (data.flags & SF_FIX_BEFORE_EOL /* Cannot have SEOL and MULTI */
1758                 && (!(data.flags & SF_FIX_BEFORE_MEOL)
1759                     || (PL_regflags & PMf_MULTILINE)))) {
1760             int t;
1761
1762             r->anchored_substr = data.longest_fixed;
1763             r->anchored_offset = data.offset_fixed;
1764             t = (data.flags & SF_FIX_BEFORE_EOL /* Can't have SEOL and MULTI */
1765                  && (!(data.flags & SF_FIX_BEFORE_MEOL)
1766                      || (PL_regflags & PMf_MULTILINE)));
1767             fbm_compile(r->anchored_substr, t ? FBMcf_TAIL : 0);
1768         }
1769         else {
1770             r->anchored_substr = Nullsv;
1771             SvREFCNT_dec(data.longest_fixed);
1772             longest_fixed_length = 0;
1773         }
1774         if (r->regstclass 
1775             && (OP(r->regstclass) == REG_ANY || OP(r->regstclass) == ANYUTF8
1776                 || OP(r->regstclass) == SANYUTF8 || OP(r->regstclass) == SANY))
1777             r->regstclass = NULL;
1778         if ((!r->anchored_substr || r->anchored_offset) && stclass_flag
1779             && !(data.start_class->flags & ANYOF_EOS)
1780             && !cl_is_anything(data.start_class)) {
1781             SV *sv;
1782             I32 n = add_data(1, "f");
1783
1784             New(1006, PL_regcomp_rx->data->data[n], 1, 
1785                 struct regnode_charclass_class);
1786             StructCopy(data.start_class,
1787                        (struct regnode_charclass_class*)PL_regcomp_rx->data->data[n],
1788                        struct regnode_charclass_class);
1789             r->regstclass = (regnode*)PL_regcomp_rx->data->data[n];
1790             r->reganch &= ~ROPT_SKIP;   /* Used in find_byclass(). */
1791             DEBUG_r((sv = sv_newmortal(),
1792                      regprop(sv, (regnode*)data.start_class),
1793                      PerlIO_printf(Perl_debug_log, "synthetic stclass `%s'.\n",
1794                                    SvPVX(sv))));
1795         }
1796
1797         /* A temporary algorithm prefers floated substr to fixed one to dig more info. */
1798         if (longest_fixed_length > longest_float_length) {
1799             r->check_substr = r->anchored_substr;
1800             r->check_offset_min = r->check_offset_max = r->anchored_offset;
1801             if (r->reganch & ROPT_ANCH_SINGLE)
1802                 r->reganch |= ROPT_NOSCAN;
1803         }
1804         else {
1805             r->check_substr = r->float_substr;
1806             r->check_offset_min = data.offset_float_min;
1807             r->check_offset_max = data.offset_float_max;
1808         }
1809         /* XXXX Currently intuiting is not compatible with ANCH_GPOS.
1810            This should be changed ASAP!  */
1811         if (r->check_substr && !(r->reganch & ROPT_ANCH_GPOS)) {
1812             r->reganch |= RE_USE_INTUIT;
1813             if (SvTAIL(r->check_substr))
1814                 r->reganch |= RE_INTUIT_TAIL;
1815         }
1816     }
1817     else {
1818         /* Several toplevels. Best we can is to set minlen. */
1819         I32 fake;
1820         struct regnode_charclass_class ch_class;
1821         
1822         DEBUG_r(PerlIO_printf(Perl_debug_log, "\n"));
1823         scan = r->program + 1;
1824         cl_init(&ch_class);
1825         data.start_class = &ch_class;
1826         minlen = study_chunk(&scan, &fake, scan + PL_regsize, &data, SCF_DO_STCLASS_AND);
1827         r->check_substr = r->anchored_substr = r->float_substr = Nullsv;
1828         if (!(data.start_class->flags & ANYOF_EOS)
1829             && !cl_is_anything(data.start_class)) {
1830             SV *sv;
1831             I32 n = add_data(1, "f");
1832
1833             New(1006, PL_regcomp_rx->data->data[n], 1, 
1834                 struct regnode_charclass_class);
1835             StructCopy(data.start_class,
1836                        (struct regnode_charclass_class*)PL_regcomp_rx->data->data[n],
1837                        struct regnode_charclass_class);
1838             r->regstclass = (regnode*)PL_regcomp_rx->data->data[n];
1839             r->reganch &= ~ROPT_SKIP;   /* Used in find_byclass(). */
1840             DEBUG_r((sv = sv_newmortal(),
1841                      regprop(sv, (regnode*)data.start_class),
1842                      PerlIO_printf(Perl_debug_log, "synthetic stclass `%s'.\n",
1843                                    SvPVX(sv))));
1844         }
1845     }
1846
1847     r->minlen = minlen;
1848     if (PL_regseen & REG_SEEN_GPOS) 
1849         r->reganch |= ROPT_GPOS_SEEN;
1850     if (PL_regseen & REG_SEEN_LOOKBEHIND)
1851         r->reganch |= ROPT_LOOKBEHIND_SEEN;
1852     if (PL_regseen & REG_SEEN_EVAL)
1853         r->reganch |= ROPT_EVAL_SEEN;
1854     Newz(1002, r->startp, PL_regnpar, I32);
1855     Newz(1002, r->endp, PL_regnpar, I32);
1856     DEBUG_r(regdump(r));
1857     return(r);
1858 }
1859
1860 /*
1861  - reg - regular expression, i.e. main body or parenthesized thing
1862  *
1863  * Caller must absorb opening parenthesis.
1864  *
1865  * Combining parenthesis handling with the base level of regular expression
1866  * is a trifle forced, but the need to tie the tails of the branches to what
1867  * follows makes it hard to avoid.
1868  */
1869 STATIC regnode *
1870 S_reg(pTHX_ I32 paren, I32 *flagp)
1871     /* paren: Parenthesized? 0=top, 1=(, inside: changed to letter. */
1872 {
1873     dTHR;
1874     register regnode *ret;              /* Will be the head of the group. */
1875     register regnode *br;
1876     register regnode *lastbr;
1877     register regnode *ender = 0;
1878     register I32 parno = 0;
1879     I32 flags, oregflags = PL_regflags, have_branch = 0, open = 0;
1880     char *oregcomp_parse = PL_regcomp_parse;
1881     char c;
1882
1883     *flagp = 0;                         /* Tentatively. */
1884
1885     /* Make an OPEN node, if parenthesized. */
1886     if (paren) {
1887         if (*PL_regcomp_parse == '?') {
1888             U16 posflags = 0, negflags = 0;
1889             U16 *flagsp = &posflags;
1890             int logical = 0;
1891             char *seqstart = PL_regcomp_parse;
1892
1893             PL_regcomp_parse++;
1894             paren = *PL_regcomp_parse++;
1895             ret = NULL;                 /* For look-ahead/behind. */
1896             switch (paren) {
1897             case '<':
1898                 PL_regseen |= REG_SEEN_LOOKBEHIND;
1899                 if (*PL_regcomp_parse == '!') 
1900                     paren = ',';
1901                 if (*PL_regcomp_parse != '=' && *PL_regcomp_parse != '!') 
1902                     goto unknown;
1903                 PL_regcomp_parse++;
1904             case '=':
1905             case '!':
1906                 PL_seen_zerolen++;
1907             case ':':
1908             case '>':
1909                 break;
1910             case '$':
1911             case '@':
1912                 vFAIL2("Sequence (?%c...) not implemented", (int)paren);
1913                 break;
1914             case '#':
1915                 while (*PL_regcomp_parse && *PL_regcomp_parse != ')')
1916                     PL_regcomp_parse++;
1917                 if (*PL_regcomp_parse != ')')
1918                     FAIL("Sequence (?#... not terminated");
1919                 nextchar();
1920                 *flagp = TRYAGAIN;
1921                 return NULL;
1922             case 'p':
1923                 if (SIZE_ONLY)
1924                     vWARN(PL_regcomp_parse, "(?p{}) is deprecated - use (??{})");
1925                 /* FALL THROUGH*/
1926             case '?':
1927                 logical = 1;
1928                 paren = *PL_regcomp_parse++;
1929                 /* FALL THROUGH */
1930             case '{':
1931             {
1932                 dTHR;
1933                 I32 count = 1, n = 0;
1934                 char c;
1935                 char *s = PL_regcomp_parse;
1936                 SV *sv;
1937                 OP_4tree *sop, *rop;
1938
1939                 PL_seen_zerolen++;
1940                 PL_regseen |= REG_SEEN_EVAL;
1941                 while (count && (c = *PL_regcomp_parse)) {
1942                     if (c == '\\' && PL_regcomp_parse[1])
1943                         PL_regcomp_parse++;
1944                     else if (c == '{') 
1945                         count++;
1946                     else if (c == '}') 
1947                         count--;
1948                     PL_regcomp_parse++;
1949                 }
1950                 if (*PL_regcomp_parse != ')')
1951                 {
1952                     PL_regcomp_parse = s;                   
1953                     vFAIL("Sequence (?{...}) not terminated or not {}-balanced");
1954                 }
1955                 if (!SIZE_ONLY) {
1956                     AV *av;
1957                     
1958                     if (PL_regcomp_parse - 1 - s) 
1959                         sv = newSVpvn(s, PL_regcomp_parse - 1 - s);
1960                     else
1961                         sv = newSVpvn("", 0);
1962
1963                     ENTER;
1964                     Perl_save_re_context(aTHX);
1965                     rop = sv_compile_2op(sv, &sop, "re", &av);
1966                     LEAVE;
1967
1968                     n = add_data(3, "nop");
1969                     PL_regcomp_rx->data->data[n] = (void*)rop;
1970                     PL_regcomp_rx->data->data[n+1] = (void*)sop;
1971                     PL_regcomp_rx->data->data[n+2] = (void*)av;
1972                     SvREFCNT_dec(sv);
1973                 }
1974                 else {                                          /* First pass */
1975                     if (PL_reginterp_cnt < ++PL_seen_evals
1976                         && PL_curcop != &PL_compiling)
1977                         /* No compiled RE interpolated, has runtime
1978                            components ===> unsafe.  */
1979                         FAIL("Eval-group not allowed at runtime, use re 'eval'");
1980                     if (PL_tainted)
1981                         FAIL("Eval-group in insecure regular expression");
1982                 }
1983                 
1984                 nextchar();
1985                 if (logical) {
1986                     ret = reg_node(LOGICAL);
1987                     if (!SIZE_ONLY)
1988                         ret->flags = 2;
1989                     regtail(ret, reganode(EVAL, n));
1990                     return ret;
1991                 }
1992                 return reganode(EVAL, n);
1993             }
1994             case '(':
1995             {
1996                 if (PL_regcomp_parse[0] == '?') {
1997                     if (PL_regcomp_parse[1] == '=' || PL_regcomp_parse[1] == '!' 
1998                         || PL_regcomp_parse[1] == '<' 
1999                         || PL_regcomp_parse[1] == '{') { /* Lookahead or eval. */
2000                         I32 flag;
2001                         
2002                         ret = reg_node(LOGICAL);
2003                         if (!SIZE_ONLY)
2004                             ret->flags = 1;
2005                         regtail(ret, reg(1, &flag));
2006                         goto insert_if;
2007                     } 
2008                 }
2009                 else if (PL_regcomp_parse[0] >= '1' && PL_regcomp_parse[0] <= '9' ) {
2010                     parno = atoi(PL_regcomp_parse++);
2011
2012                     while (isDIGIT(*PL_regcomp_parse))
2013                         PL_regcomp_parse++;
2014                     ret = reganode(GROUPP, parno);
2015                     if ((c = *nextchar()) != ')')
2016                         vFAIL("Switch condition not recognized");
2017                   insert_if:
2018                     regtail(ret, reganode(IFTHEN, 0));
2019                     br = regbranch(&flags, 1);
2020                     if (br == NULL)
2021                         br = reganode(LONGJMP, 0);
2022                     else
2023                         regtail(br, reganode(LONGJMP, 0));
2024                     c = *nextchar();
2025                     if (flags&HASWIDTH)
2026                         *flagp |= HASWIDTH;
2027                     if (c == '|') {
2028                         lastbr = reganode(IFTHEN, 0); /* Fake one for optimizer. */
2029                         regbranch(&flags, 1);
2030                         regtail(ret, lastbr);
2031                         if (flags&HASWIDTH)
2032                             *flagp |= HASWIDTH;
2033                         c = *nextchar();
2034                     }
2035                     else
2036                         lastbr = NULL;
2037                     if (c != ')')
2038                         vFAIL("Switch (?(condition)... contains too many branches");
2039                     ender = reg_node(TAIL);
2040                     regtail(br, ender);
2041                     if (lastbr) {
2042                         regtail(lastbr, ender);
2043                         regtail(NEXTOPER(NEXTOPER(lastbr)), ender);
2044                     }
2045                     else
2046                         regtail(ret, ender);
2047                     return ret;
2048                 }
2049                 else {
2050                     vFAIL2("Unknown switch condition (?(%.2s", PL_regcomp_parse);
2051                 }
2052             }
2053             case 0:
2054                 PL_regcomp_parse--; /* for vFAIL to print correctly */
2055                 vFAIL("Sequence (? incomplete");
2056                 break;
2057             default:
2058                 --PL_regcomp_parse;
2059               parse_flags:
2060                 while (*PL_regcomp_parse && strchr("iogcmsx", *PL_regcomp_parse)) {
2061                     if (*PL_regcomp_parse != 'o')
2062                         pmflag(flagsp, *PL_regcomp_parse);
2063                     ++PL_regcomp_parse;
2064                 }
2065                 if (*PL_regcomp_parse == '-') {
2066                     flagsp = &negflags;
2067                     ++PL_regcomp_parse;
2068                     goto parse_flags;
2069                 }
2070                 PL_regflags |= posflags;
2071                 PL_regflags &= ~negflags;
2072                 if (*PL_regcomp_parse == ':') {
2073                     PL_regcomp_parse++;
2074                     paren = ':';
2075                     break;
2076                 }               
2077               unknown:
2078                 if (*PL_regcomp_parse != ')') {
2079                     PL_regcomp_parse++;
2080                     vFAIL3("Sequence (%.*s...) not recognized", PL_regcomp_parse-seqstart, seqstart);
2081                 }
2082                 nextchar();
2083                 *flagp = TRYAGAIN;
2084                 return NULL;
2085             }
2086         }
2087         else {
2088             parno = PL_regnpar;
2089             PL_regnpar++;
2090             ret = reganode(OPEN, parno);
2091             open = 1;
2092         }
2093     }
2094     else
2095         ret = NULL;
2096
2097     /* Pick up the branches, linking them together. */
2098     br = regbranch(&flags, 1);
2099     if (br == NULL)
2100         return(NULL);
2101     if (*PL_regcomp_parse == '|') {
2102         if (!SIZE_ONLY && PL_extralen) {
2103             reginsert(BRANCHJ, br);
2104         }
2105         else
2106             reginsert(BRANCH, br);
2107         have_branch = 1;
2108         if (SIZE_ONLY)
2109             PL_extralen += 1;           /* For BRANCHJ-BRANCH. */
2110     }
2111     else if (paren == ':') {
2112         *flagp |= flags&SIMPLE;
2113     }
2114     if (open) {                         /* Starts with OPEN. */
2115         regtail(ret, br);               /* OPEN -> first. */
2116     }
2117     else if (paren != '?')              /* Not Conditional */
2118         ret = br;
2119     if (flags&HASWIDTH)
2120         *flagp |= HASWIDTH;
2121     *flagp |= flags&SPSTART;
2122     lastbr = br;
2123     while (*PL_regcomp_parse == '|') {
2124         if (!SIZE_ONLY && PL_extralen) {
2125             ender = reganode(LONGJMP,0);
2126             regtail(NEXTOPER(NEXTOPER(lastbr)), ender); /* Append to the previous. */
2127         }
2128         if (SIZE_ONLY)
2129             PL_extralen += 2;           /* Account for LONGJMP. */
2130         nextchar();
2131         br = regbranch(&flags, 0);
2132         if (br == NULL)
2133             return(NULL);
2134         regtail(lastbr, br);            /* BRANCH -> BRANCH. */
2135         lastbr = br;
2136         if (flags&HASWIDTH)
2137             *flagp |= HASWIDTH;
2138         *flagp |= flags&SPSTART;
2139     }
2140
2141     if (have_branch || paren != ':') {
2142         /* Make a closing node, and hook it on the end. */
2143         switch (paren) {
2144         case ':':
2145             ender = reg_node(TAIL);
2146             break;
2147         case 1:
2148             ender = reganode(CLOSE, parno);
2149             break;
2150         case '<':
2151         case ',':
2152         case '=':
2153         case '!':
2154             *flagp &= ~HASWIDTH;
2155             /* FALL THROUGH */
2156         case '>':
2157             ender = reg_node(SUCCEED);
2158             break;
2159         case 0:
2160             ender = reg_node(END);
2161             break;
2162         }
2163         regtail(lastbr, ender);
2164
2165         if (have_branch) {
2166             /* Hook the tails of the branches to the closing node. */
2167             for (br = ret; br != NULL; br = regnext(br)) {
2168                 regoptail(br, ender);
2169             }
2170         }
2171     }
2172
2173     {
2174         char *p;
2175         static char parens[] = "=!<,>";
2176
2177         if (paren && (p = strchr(parens, paren))) {
2178             int node = ((p - parens) % 2) ? UNLESSM : IFMATCH;
2179             int flag = (p - parens) > 1;
2180
2181             if (paren == '>')
2182                 node = SUSPEND, flag = 0;
2183             reginsert(node,ret);
2184             ret->flags = flag;
2185             regtail(ret, reg_node(TAIL));
2186         }
2187     }
2188
2189     /* Check for proper termination. */
2190     if (paren) {
2191         PL_regflags = oregflags;
2192         if (PL_regcomp_parse >= PL_regxend || *nextchar() != ')') {
2193             PL_regcomp_parse = oregcomp_parse;
2194             vFAIL("Unmatched (");
2195         }
2196     }
2197     else if (!paren && PL_regcomp_parse < PL_regxend) {
2198         if (*PL_regcomp_parse == ')') {
2199             PL_regcomp_parse++;
2200             vFAIL("Unmatched )");
2201         }
2202         else
2203             FAIL("Junk on end of regexp");      /* "Can't happen". */
2204         /* NOTREACHED */
2205     }
2206
2207     return(ret);
2208 }
2209
2210 /*
2211  - regbranch - one alternative of an | operator
2212  *
2213  * Implements the concatenation operator.
2214  */
2215 STATIC regnode *
2216 S_regbranch(pTHX_ I32 *flagp, I32 first)
2217 {
2218     dTHR;
2219     register regnode *ret;
2220     register regnode *chain = NULL;
2221     register regnode *latest;
2222     I32 flags = 0, c = 0;
2223
2224     if (first) 
2225         ret = NULL;
2226     else {
2227         if (!SIZE_ONLY && PL_extralen) 
2228             ret = reganode(BRANCHJ,0);
2229         else
2230             ret = reg_node(BRANCH);
2231     }
2232         
2233     if (!first && SIZE_ONLY) 
2234         PL_extralen += 1;                       /* BRANCHJ */
2235     
2236     *flagp = WORST;                     /* Tentatively. */
2237
2238     PL_regcomp_parse--;
2239     nextchar();
2240     while (PL_regcomp_parse < PL_regxend && *PL_regcomp_parse != '|' && *PL_regcomp_parse != ')') {
2241         flags &= ~TRYAGAIN;
2242         latest = regpiece(&flags);
2243         if (latest == NULL) {
2244             if (flags & TRYAGAIN)
2245                 continue;
2246             return(NULL);
2247         }
2248         else if (ret == NULL)
2249             ret = latest;
2250         *flagp |= flags&HASWIDTH;
2251         if (chain == NULL)      /* First piece. */
2252             *flagp |= flags&SPSTART;
2253         else {
2254             PL_regnaughty++;
2255             regtail(chain, latest);
2256         }
2257         chain = latest;
2258         c++;
2259     }
2260     if (chain == NULL) {        /* Loop ran zero times. */
2261         chain = reg_node(NOTHING);
2262         if (ret == NULL)
2263             ret = chain;
2264     }
2265     if (c == 1) {
2266         *flagp |= flags&SIMPLE;
2267     }
2268
2269     return(ret);
2270 }
2271
2272 /*
2273  - regpiece - something followed by possible [*+?]
2274  *
2275  * Note that the branching code sequences used for ? and the general cases
2276  * of * and + are somewhat optimized:  they use the same NOTHING node as
2277  * both the endmarker for their branch list and the body of the last branch.
2278  * It might seem that this node could be dispensed with entirely, but the
2279  * endmarker role is not redundant.
2280  */
2281 STATIC regnode *
2282 S_regpiece(pTHX_ I32 *flagp)
2283 {
2284     dTHR;
2285     register regnode *ret;
2286     register char op;
2287     register char *next;
2288     I32 flags;
2289     char *origparse = PL_regcomp_parse;
2290     char *maxpos;
2291     I32 min;
2292     I32 max = REG_INFTY;
2293
2294     ret = regatom(&flags);
2295     if (ret == NULL) {
2296         if (flags & TRYAGAIN)
2297             *flagp |= TRYAGAIN;
2298         return(NULL);
2299     }
2300
2301     op = *PL_regcomp_parse;
2302
2303     if (op == '{' && regcurly(PL_regcomp_parse)) {
2304         next = PL_regcomp_parse + 1;
2305         maxpos = Nullch;
2306         while (isDIGIT(*next) || *next == ',') {
2307             if (*next == ',') {
2308                 if (maxpos)
2309                     break;
2310                 else
2311                     maxpos = next;
2312             }
2313             next++;
2314         }
2315         if (*next == '}') {             /* got one */
2316             if (!maxpos)
2317                 maxpos = next;
2318             PL_regcomp_parse++;
2319             min = atoi(PL_regcomp_parse);
2320             if (*maxpos == ',')
2321                 maxpos++;
2322             else
2323                 maxpos = PL_regcomp_parse;
2324             max = atoi(maxpos);
2325             if (!max && *maxpos != '0')
2326                 max = REG_INFTY;                /* meaning "infinity" */
2327             else if (max >= REG_INFTY)
2328                 vFAIL2("Quantifier in {,} bigger than %d", REG_INFTY - 1);
2329             PL_regcomp_parse = next;
2330             nextchar();
2331
2332         do_curly:
2333             if ((flags&SIMPLE)) {
2334                 PL_regnaughty += 2 + PL_regnaughty / 2;
2335                 reginsert(CURLY, ret);
2336             }
2337             else {
2338                 regnode *w = reg_node(WHILEM);
2339
2340                 w->flags = 0;
2341                 regtail(ret, w);
2342                 if (!SIZE_ONLY && PL_extralen) {
2343                     reginsert(LONGJMP,ret);
2344                     reginsert(NOTHING,ret);
2345                     NEXT_OFF(ret) = 3;  /* Go over LONGJMP. */
2346                 }
2347                 reginsert(CURLYX,ret);
2348                 if (!SIZE_ONLY && PL_extralen)
2349                     NEXT_OFF(ret) = 3;  /* Go over NOTHING to LONGJMP. */
2350                 regtail(ret, reg_node(NOTHING));
2351                 if (SIZE_ONLY)
2352                     PL_reg_whilem_seen++, PL_extralen += 3;
2353                 PL_regnaughty += 4 + PL_regnaughty;     /* compound interest */
2354             }
2355             ret->flags = 0;
2356
2357             if (min > 0)
2358                 *flagp = WORST;
2359             if (max > 0)
2360                 *flagp |= HASWIDTH;
2361             if (max && max < min)
2362                 vFAIL("Can't do {n,m} with n > m");
2363             if (!SIZE_ONLY) {
2364                 ARG1_SET(ret, min);
2365                 ARG2_SET(ret, max);
2366             }
2367
2368             goto nest_check;
2369         }
2370     }
2371
2372     if (!ISMULT1(op)) {
2373         *flagp = flags;
2374         return(ret);
2375     }
2376
2377 #if 0                           /* Now runtime fix should be reliable. */
2378
2379     /* if this is reinstated, don't forget to put this back into perldiag:
2380
2381             =item Regexp *+ operand could be empty at {#} in regex m/%s/
2382
2383            (F) The part of the regexp subject to either the * or + quantifier
2384            could match an empty string. The {#} shows in the regular
2385            expression about where the problem was discovered.
2386
2387     */
2388
2389     if (!(flags&HASWIDTH) && op != '?')
2390       vFAIL("Regexp *+ operand could be empty");
2391 #endif 
2392
2393     nextchar();
2394
2395     *flagp = (op != '+') ? (WORST|SPSTART|HASWIDTH) : (WORST|HASWIDTH);
2396
2397     if (op == '*' && (flags&SIMPLE)) {
2398         reginsert(STAR, ret);
2399         ret->flags = 0;
2400         PL_regnaughty += 4;
2401     }
2402     else if (op == '*') {
2403         min = 0;
2404         goto do_curly;
2405     }
2406     else if (op == '+' && (flags&SIMPLE)) {
2407         reginsert(PLUS, ret);
2408         ret->flags = 0;
2409         PL_regnaughty += 3;
2410     }
2411     else if (op == '+') {
2412         min = 1;
2413         goto do_curly;
2414     }
2415     else if (op == '?') {
2416         min = 0; max = 1;
2417         goto do_curly;
2418     }
2419   nest_check:
2420     if (ckWARN(WARN_REGEXP) && !SIZE_ONLY && !(flags&HASWIDTH) && max > REG_INFTY/3) {
2421         vWARN3(PL_regcomp_parse,
2422                "%.*s matches null string many times",
2423                PL_regcomp_parse - origparse,
2424                origparse);
2425     }
2426
2427     if (*PL_regcomp_parse == '?') {
2428         nextchar();
2429         reginsert(MINMOD, ret);
2430         regtail(ret, ret + NODE_STEP_REGNODE);
2431     }
2432     if (ISMULT2(PL_regcomp_parse)) {
2433         PL_regcomp_parse++;
2434         vFAIL("Nested quantifiers");
2435     }
2436
2437     return(ret);
2438 }
2439
2440 /*
2441  - regatom - the lowest level
2442  *
2443  * Optimization:  gobbles an entire sequence of ordinary characters so that
2444  * it can turn them into a single node, which is smaller to store and
2445  * faster to run.  Backslashed characters are exceptions, each becoming a
2446  * separate node; the code is simpler that way and it's not worth fixing.
2447  *
2448  * [Yes, it is worth fixing, some scripts can run twice the speed.] */
2449 STATIC regnode *
2450 S_regatom(pTHX_ I32 *flagp)
2451 {
2452     dTHR;
2453     register regnode *ret = 0;
2454     I32 flags;
2455
2456     *flagp = WORST;             /* Tentatively. */
2457
2458 tryagain:
2459     switch (*PL_regcomp_parse) {
2460     case '^':
2461         PL_seen_zerolen++;
2462         nextchar();
2463         if (PL_regflags & PMf_MULTILINE)
2464             ret = reg_node(MBOL);
2465         else if (PL_regflags & PMf_SINGLELINE)
2466             ret = reg_node(SBOL);
2467         else
2468             ret = reg_node(BOL);
2469         break;
2470     case '$':
2471         nextchar();
2472         if (*PL_regcomp_parse) 
2473             PL_seen_zerolen++;
2474         if (PL_regflags & PMf_MULTILINE)
2475             ret = reg_node(MEOL);
2476         else if (PL_regflags & PMf_SINGLELINE)
2477             ret = reg_node(SEOL);
2478         else
2479             ret = reg_node(EOL);
2480         break;
2481     case '.':
2482         nextchar();
2483         if (UTF) {
2484             if (PL_regflags & PMf_SINGLELINE)
2485                 ret = reg_node(SANYUTF8);
2486             else
2487                 ret = reg_node(ANYUTF8);
2488             *flagp |= HASWIDTH;
2489         }
2490         else {
2491             if (PL_regflags & PMf_SINGLELINE)
2492                 ret = reg_node(SANY);
2493             else
2494                 ret = reg_node(REG_ANY);
2495             *flagp |= HASWIDTH|SIMPLE;
2496         }
2497         PL_regnaughty++;
2498         break;
2499     case '[':
2500     {
2501         char *oregcomp_parse = ++PL_regcomp_parse;
2502         ret = (UTF ? regclassutf8() : regclass());
2503         if (*PL_regcomp_parse != ']') {
2504             PL_regcomp_parse = oregcomp_parse;
2505             vFAIL("Unmatched [");
2506         }
2507         nextchar();
2508         *flagp |= HASWIDTH|SIMPLE;
2509         break;
2510     }
2511     case '(':
2512         nextchar();
2513         ret = reg(1, &flags);
2514         if (ret == NULL) {
2515                 if (flags & TRYAGAIN) {
2516                     if (PL_regcomp_parse == PL_regxend) {
2517                          /* Make parent create an empty node if needed. */
2518                         *flagp |= TRYAGAIN;
2519                         return(NULL);
2520                     }
2521                     goto tryagain;
2522                 }
2523                 return(NULL);
2524         }
2525         *flagp |= flags&(HASWIDTH|SPSTART|SIMPLE);
2526         break;
2527     case '|':
2528     case ')':
2529         if (flags & TRYAGAIN) {
2530             *flagp |= TRYAGAIN;
2531             return NULL;
2532         }
2533         vFAIL("Internal urp");
2534                                 /* Supposed to be caught earlier. */
2535         break;
2536     case '{':
2537         if (!regcurly(PL_regcomp_parse)) {
2538             PL_regcomp_parse++;
2539             goto defchar;
2540         }
2541         /* FALL THROUGH */
2542     case '?':
2543     case '+':
2544     case '*':
2545         PL_regcomp_parse++;
2546         vFAIL("Quantifier follows nothing");
2547         break;
2548     case '\\':
2549         switch (*++PL_regcomp_parse) {
2550         case 'A':
2551             PL_seen_zerolen++;
2552             ret = reg_node(SBOL);
2553             *flagp |= SIMPLE;
2554             nextchar();
2555             break;
2556         case 'G':
2557             ret = reg_node(GPOS);
2558             PL_regseen |= REG_SEEN_GPOS;
2559             *flagp |= SIMPLE;
2560             nextchar();
2561             break;
2562         case 'Z':
2563             ret = reg_node(SEOL);
2564             *flagp |= SIMPLE;
2565             nextchar();
2566             break;
2567         case 'z':
2568             ret = reg_node(EOS);
2569             *flagp |= SIMPLE;
2570             PL_seen_zerolen++;          /* Do not optimize RE away */
2571             nextchar();
2572             break;
2573         case 'C':
2574             ret = reg_node(SANY);
2575             *flagp |= HASWIDTH|SIMPLE;
2576             nextchar();
2577             break;
2578         case 'X':
2579             ret = reg_node(CLUMP);
2580             *flagp |= HASWIDTH;
2581             nextchar();
2582             if (UTF && !PL_utf8_mark)
2583                 is_utf8_mark((U8*)"~");         /* preload table */
2584             break;
2585         case 'w':
2586             ret = reg_node(
2587                 UTF
2588                     ? (LOC ? ALNUMLUTF8 : ALNUMUTF8)
2589                     : (LOC ? ALNUML     : ALNUM));
2590             *flagp |= HASWIDTH|SIMPLE;
2591             nextchar();
2592             if (UTF && !PL_utf8_alnum)
2593                 is_utf8_alnum((U8*)"a");        /* preload table */
2594             break;
2595         case 'W':
2596             ret = reg_node(
2597                 UTF
2598                     ? (LOC ? NALNUMLUTF8 : NALNUMUTF8)
2599                     : (LOC ? NALNUML     : NALNUM));
2600             *flagp |= HASWIDTH|SIMPLE;
2601             nextchar();
2602             if (UTF && !PL_utf8_alnum)
2603                 is_utf8_alnum((U8*)"a");        /* preload table */
2604             break;
2605         case 'b':
2606             PL_seen_zerolen++;
2607             PL_regseen |= REG_SEEN_LOOKBEHIND;
2608             ret = reg_node(
2609                 UTF
2610                     ? (LOC ? BOUNDLUTF8 : BOUNDUTF8)
2611                     : (LOC ? BOUNDL     : BOUND));
2612             *flagp |= SIMPLE;
2613             nextchar();
2614             if (UTF && !PL_utf8_alnum)
2615                 is_utf8_alnum((U8*)"a");        /* preload table */
2616             break;
2617         case 'B':
2618             PL_seen_zerolen++;
2619             PL_regseen |= REG_SEEN_LOOKBEHIND;
2620             ret = reg_node(
2621                 UTF
2622                     ? (LOC ? NBOUNDLUTF8 : NBOUNDUTF8)
2623                     : (LOC ? NBOUNDL     : NBOUND));
2624             *flagp |= SIMPLE;
2625             nextchar();
2626             if (UTF && !PL_utf8_alnum)
2627                 is_utf8_alnum((U8*)"a");        /* preload table */
2628             break;
2629         case 's':
2630             ret = reg_node(
2631                 UTF
2632                     ? (LOC ? SPACELUTF8 : SPACEUTF8)
2633                     : (LOC ? SPACEL     : SPACE));
2634             *flagp |= HASWIDTH|SIMPLE;
2635             nextchar();
2636             if (UTF && !PL_utf8_space)
2637                 is_utf8_space((U8*)" ");        /* preload table */
2638             break;
2639         case 'S':
2640             ret = reg_node(
2641                 UTF
2642                     ? (LOC ? NSPACELUTF8 : NSPACEUTF8)
2643                     : (LOC ? NSPACEL     : NSPACE));
2644             *flagp |= HASWIDTH|SIMPLE;
2645             nextchar();
2646             if (UTF && !PL_utf8_space)
2647                 is_utf8_space((U8*)" ");        /* preload table */
2648             break;
2649         case 'd':
2650             ret = reg_node(UTF ? DIGITUTF8 : DIGIT);
2651             *flagp |= HASWIDTH|SIMPLE;
2652             nextchar();
2653             if (UTF && !PL_utf8_digit)
2654                 is_utf8_digit((U8*)"1");        /* preload table */
2655             break;
2656         case 'D':
2657             ret = reg_node(UTF ? NDIGITUTF8 : NDIGIT);
2658             *flagp |= HASWIDTH|SIMPLE;
2659             nextchar();
2660             if (UTF && !PL_utf8_digit)
2661                 is_utf8_digit((U8*)"1");        /* preload table */
2662             break;
2663         case 'p':
2664         case 'P':
2665             {   /* a lovely hack--pretend we saw [\pX] instead */
2666                 char* oldregxend = PL_regxend;
2667
2668                 if (PL_regcomp_parse[1] == '{') {
2669                     PL_regxend = strchr(PL_regcomp_parse, '}');
2670                     if (!PL_regxend) {
2671                         PL_regcomp_parse += 2;
2672                         PL_regxend = oldregxend;
2673                         vFAIL("Missing right brace on \\p{}");
2674                     }
2675                     PL_regxend++;
2676                 }
2677                 else
2678                     PL_regxend = PL_regcomp_parse + 2;
2679                 PL_regcomp_parse--;
2680
2681                 ret = regclassutf8();
2682
2683                 PL_regxend = oldregxend;
2684                 PL_regcomp_parse--;
2685                 nextchar();
2686                 *flagp |= HASWIDTH|SIMPLE;
2687             }
2688             break;
2689         case 'n':
2690         case 'r':
2691         case 't':
2692         case 'f':
2693         case 'e':
2694         case 'a':
2695         case 'x':
2696         case 'c':
2697         case '0':
2698             goto defchar;
2699         case '1': case '2': case '3': case '4':
2700         case '5': case '6': case '7': case '8': case '9':
2701             {
2702                 I32 num = atoi(PL_regcomp_parse);
2703
2704                 if (num > 9 && num >= PL_regnpar)
2705                     goto defchar;
2706                 else {
2707                     while (isDIGIT(*PL_regcomp_parse))
2708                         PL_regcomp_parse++;
2709
2710                     if (!SIZE_ONLY && num > PL_regcomp_rx->nparens)
2711                         vFAIL("Reference to nonexistent group");
2712                     PL_regsawback = 1;
2713                     ret = reganode(FOLD
2714                                    ? (LOC ? REFFL : REFF)
2715                                    : REF, num);
2716                     *flagp |= HASWIDTH;
2717                     PL_regcomp_parse--;
2718                     nextchar();
2719                 }
2720             }
2721             break;
2722         case '\0':
2723             if (PL_regcomp_parse >= PL_regxend)
2724                 FAIL("Trailing \\");
2725             /* FALL THROUGH */
2726         default:
2727             /* Do not generate `unrecognized' warnings here, we fall
2728                back into the quick-grab loop below */
2729             goto defchar;
2730         }
2731         break;
2732
2733     case '#':
2734         if (PL_regflags & PMf_EXTENDED) {
2735             while (PL_regcomp_parse < PL_regxend && *PL_regcomp_parse != '\n') PL_regcomp_parse++;
2736             if (PL_regcomp_parse < PL_regxend)
2737                 goto tryagain;
2738         }
2739         /* FALL THROUGH */
2740
2741     default: {
2742             register STRLEN len;
2743             register UV ender;
2744             register char *p;
2745             char *oldp, *s;
2746             STRLEN numlen;
2747
2748             PL_regcomp_parse++;
2749
2750         defchar:
2751             ret = reg_node(FOLD
2752                           ? (LOC ? EXACTFL : EXACTF)
2753                           : EXACT);
2754             s = STRING(ret);
2755             for (len = 0, p = PL_regcomp_parse - 1;
2756               len < 127 && p < PL_regxend;
2757               len++)
2758             {
2759                 oldp = p;
2760
2761                 if (PL_regflags & PMf_EXTENDED)
2762                     p = regwhite(p, PL_regxend);
2763                 switch (*p) {
2764                 case '^':
2765                 case '$':
2766                 case '.':
2767                 case '[':
2768                 case '(':
2769                 case ')':
2770                 case '|':
2771                     goto loopdone;
2772                 case '\\':
2773                     switch (*++p) {
2774                     case 'A':
2775                     case 'G':
2776                     case 'Z':
2777                     case 'z':
2778                     case 'w':
2779                     case 'W':
2780                     case 'b':
2781                     case 'B':
2782                     case 's':
2783                     case 'S':
2784                     case 'd':
2785                     case 'D':
2786                     case 'p':
2787                     case 'P':
2788                         --p;
2789                         goto loopdone;
2790                     case 'n':
2791                         ender = '\n';
2792                         p++;
2793                         break;
2794                     case 'r':
2795                         ender = '\r';
2796                         p++;
2797                         break;
2798                     case 't':
2799                         ender = '\t';
2800                         p++;
2801                         break;
2802                     case 'f':
2803                         ender = '\f';
2804                         p++;
2805                         break;
2806                     case 'e':
2807 #ifdef ASCIIish
2808                           ender = '\033';
2809 #else
2810                           ender = '\047';
2811 #endif
2812                         p++;
2813                         break;
2814                     case 'a':
2815 #ifdef ASCIIish
2816                           ender = '\007';
2817 #else
2818                           ender = '\057';
2819 #endif
2820                         p++;
2821                         break;
2822                     case 'x':
2823                         if (*++p == '{') {
2824                             char* e = strchr(p, '}');
2825          
2826                             if (!e) {
2827                                 PL_regcomp_parse = p + 1;
2828                                 vFAIL("Missing right brace on \\x{}");
2829                             }
2830                             else if (UTF) {
2831                                 numlen = 1;     /* allow underscores */
2832                                 ender = (UV)scan_hex(p + 1, e - p - 1, &numlen);
2833                                 /* numlen is generous */
2834                                 if (numlen + len >= 127) {
2835                                     p--;
2836                                     goto loopdone;
2837                                 }
2838                                 p = e + 1;
2839                             }
2840                             else
2841                             {
2842                                 PL_regcomp_parse = e + 1;
2843                                 vFAIL("Can't use \\x{} without 'use utf8' declaration");
2844                             }
2845
2846                         }
2847                         else {
2848                             numlen = 0;         /* disallow underscores */
2849                             ender = (UV)scan_hex(p, 2, &numlen);
2850                             p += numlen;
2851                         }
2852                         break;
2853                     case 'c':
2854                         p++;
2855                         ender = UCHARAT(p++);
2856                         ender = toCTRL(ender);
2857                         break;
2858                     case '0': case '1': case '2': case '3':case '4':
2859                     case '5': case '6': case '7': case '8':case '9':
2860                         if (*p == '0' ||
2861                           (isDIGIT(p[1]) && atoi(p) >= PL_regnpar) ) {
2862                             numlen = 0;         /* disallow underscores */
2863                             ender = (UV)scan_oct(p, 3, &numlen);
2864                             p += numlen;
2865                         }
2866                         else {
2867                             --p;
2868                             goto loopdone;
2869                         }
2870                         break;
2871                     case '\0':
2872                         if (p >= PL_regxend)
2873                             FAIL("Trailing \\");
2874                         /* FALL THROUGH */
2875                     default:
2876                         if (!SIZE_ONLY && ckWARN(WARN_REGEXP) && isALPHA(*p))
2877                             vWARN2(p +1, "Unrecognized escape \\%c passed through", *p);
2878                         goto normal_default;
2879                     }
2880                     break;
2881                 default:
2882                   normal_default:
2883                     if ((*p & 0xc0) == 0xc0 && UTF) {
2884                         ender = utf8_to_uv((U8*)p, PL_regxend - p,
2885                                                &numlen, 0);
2886                         p += numlen;
2887                     }
2888                     else
2889                         ender = *p++;
2890                     break;
2891                 }
2892                 if (PL_regflags & PMf_EXTENDED)
2893                     p = regwhite(p, PL_regxend);
2894                 if (UTF && FOLD) {
2895                     if (LOC)
2896                         ender = toLOWER_LC_uni(ender);
2897                     else
2898                         ender = toLOWER_uni(ender);
2899                 }
2900                 if (ISMULT2(p)) { /* Back off on ?+*. */
2901                     if (len)
2902                         p = oldp;
2903                     else if (ender >= 0x80 && UTF) {
2904                         reguni(ender, s, &numlen);
2905                         s += numlen;
2906                         len += numlen;
2907                     }
2908                     else {
2909                         len++;
2910                         REGC(ender, s++);
2911                     }
2912                     break;
2913                 }
2914                 if (ender >= 0x80 && UTF) {
2915                     reguni(ender, s, &numlen);
2916                     s += numlen;
2917                     len += numlen - 1;
2918                 }
2919                 else
2920                     REGC(ender, s++);
2921             }
2922         loopdone:
2923             PL_regcomp_parse = p - 1;
2924             nextchar();
2925             if (len < 0)
2926                 vFAIL("Internal disaster");
2927             if (len > 0)
2928                 *flagp |= HASWIDTH;
2929             if (len == 1)
2930                 *flagp |= SIMPLE;
2931             if (!SIZE_ONLY)
2932                 STR_LEN(ret) = len;
2933             if (SIZE_ONLY)
2934                 PL_regsize += STR_SZ(len);
2935             else
2936                 PL_regcode += STR_SZ(len);
2937         }
2938         break;
2939     }
2940
2941     return(ret);
2942 }
2943
2944 STATIC char *
2945 S_regwhite(pTHX_ char *p, char *e)
2946 {
2947     while (p < e) {
2948         if (isSPACE(*p))
2949             ++p;
2950         else if (*p == '#') {
2951             do {
2952                 p++;
2953             } while (p < e && *p != '\n');
2954         }
2955         else
2956             break;
2957     }
2958     return p;
2959 }
2960
2961 /* Parse POSIX character classes: [[:foo:]], [[=foo=]], [[.foo.]].
2962    Character classes ([:foo:]) can also be negated ([:^foo:]).
2963    Returns a named class id (ANYOF_XXX) if successful, -1 otherwise.
2964    Equivalence classes ([=foo=]) and composites ([.foo.]) are parsed,
2965    but trigger warnings because they are currently unimplemented. */
2966 STATIC I32
2967 S_regpposixcc(pTHX_ I32 value)
2968 {
2969     dTHR;
2970     char *posixcc = 0;
2971     I32 namedclass = OOB_NAMEDCLASS;
2972
2973     if (value == '[' && PL_regcomp_parse + 1 < PL_regxend &&
2974         /* I smell either [: or [= or [. -- POSIX has been here, right? */
2975         (*PL_regcomp_parse == ':' ||
2976          *PL_regcomp_parse == '=' ||
2977          *PL_regcomp_parse == '.')) {
2978         char  c = *PL_regcomp_parse;
2979         char* s = PL_regcomp_parse++;
2980             
2981         while (PL_regcomp_parse < PL_regxend && *PL_regcomp_parse != c)
2982             PL_regcomp_parse++;
2983         if (PL_regcomp_parse == PL_regxend)
2984             /* Grandfather lone [:, [=, [. */
2985             PL_regcomp_parse = s;
2986         else {
2987             char* t = PL_regcomp_parse++; /* skip over the c */
2988
2989             if (*PL_regcomp_parse == ']') {
2990                 PL_regcomp_parse++; /* skip over the ending ] */
2991                 posixcc = s + 1;
2992                 if (*s == ':') {
2993                     I32 complement = *posixcc == '^' ? *posixcc++ : 0;
2994                     I32 skip = 5; /* the most common skip */
2995
2996                     switch (*posixcc) {
2997                     case 'a':
2998                         if (strnEQ(posixcc, "alnum", 5))
2999                             namedclass =
3000                                 complement ? ANYOF_NALNUMC : ANYOF_ALNUMC;
3001                         else if (strnEQ(posixcc, "alpha", 5))
3002                             namedclass =
3003                                 complement ? ANYOF_NALPHA : ANYOF_ALPHA;
3004                         else if (strnEQ(posixcc, "ascii", 5))
3005                             namedclass =
3006                                 complement ? ANYOF_NASCII : ANYOF_ASCII;
3007                         break;
3008                     case 'b':
3009                         if (strnEQ(posixcc, "blank", 5))
3010                             namedclass =
3011                                 complement ? ANYOF_NBLANK : ANYOF_BLANK;
3012                         break;
3013                     case 'c':
3014                         if (strnEQ(posixcc, "cntrl", 5))
3015                             namedclass =
3016                                 complement ? ANYOF_NCNTRL : ANYOF_CNTRL;
3017                         break;
3018                     case 'd':
3019                         if (strnEQ(posixcc, "digit", 5))
3020                             namedclass =
3021                                 complement ? ANYOF_NDIGIT : ANYOF_DIGIT;
3022                         break;
3023                     case 'g':
3024                         if (strnEQ(posixcc, "graph", 5))
3025                             namedclass =
3026                                 complement ? ANYOF_NGRAPH : ANYOF_GRAPH;
3027                         break;
3028                     case 'l':
3029                         if (strnEQ(posixcc, "lower", 5))
3030                             namedclass =
3031                                 complement ? ANYOF_NLOWER : ANYOF_LOWER;
3032                         break;
3033                     case 'p':
3034                         if (strnEQ(posixcc, "print", 5))
3035                             namedclass =
3036                                 complement ? ANYOF_NPRINT : ANYOF_PRINT;
3037                         else if (strnEQ(posixcc, "punct", 5))
3038                             namedclass =
3039                                 complement ? ANYOF_NPUNCT : ANYOF_PUNCT;
3040                         break;
3041                     case 's':
3042                         if (strnEQ(posixcc, "space", 5))
3043                             namedclass =
3044                                 complement ? ANYOF_NPSXSPC : ANYOF_PSXSPC;
3045                         break;
3046                     case 'u':
3047                         if (strnEQ(posixcc, "upper", 5))
3048                             namedclass =
3049                                 complement ? ANYOF_NUPPER : ANYOF_UPPER;
3050                         break;
3051                     case 'w': /* this is not POSIX, this is the Perl \w */
3052                         if (strnEQ(posixcc, "word", 4)) {
3053                             namedclass =
3054                                 complement ? ANYOF_NALNUM : ANYOF_ALNUM;
3055                             skip = 4;
3056                         }
3057                         break;
3058                     case 'x':
3059                         if (strnEQ(posixcc, "xdigit", 6)) {
3060                             namedclass =
3061                                 complement ? ANYOF_NXDIGIT : ANYOF_XDIGIT;
3062                             skip = 6;
3063                         }
3064                         break;
3065                     }
3066                     if (namedclass == OOB_NAMEDCLASS ||
3067                         posixcc[skip] != ':' ||
3068                         posixcc[skip+1] != ']')
3069                     {
3070                         Simple_vFAIL3("POSIX class [:%.*s:] unknown",
3071                                       t - s - 1, s + 1);
3072                     }
3073                 } else if (!SIZE_ONLY) {
3074                     /* [[=foo=]] and [[.foo.]] are still future. */
3075
3076                     /* adjust PL_regcomp_parse so the warning shows after
3077                        the class closes */
3078                     while (*PL_regcomp_parse && *PL_regcomp_parse != ']')
3079                         PL_regcomp_parse++;
3080                     Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
3081                 }
3082             } else {
3083                 /* Maternal grandfather:
3084                  * "[:" ending in ":" but not in ":]" */
3085                 PL_regcomp_parse = s;
3086             }
3087         }
3088     }
3089
3090     return namedclass;
3091 }
3092
3093 STATIC void
3094 S_checkposixcc(pTHX)
3095 {
3096     if (!SIZE_ONLY && ckWARN(WARN_REGEXP) &&
3097         (*PL_regcomp_parse == ':' ||
3098          *PL_regcomp_parse == '=' ||
3099          *PL_regcomp_parse == '.')) {
3100         char *s = PL_regcomp_parse;
3101         char  c = *s++;
3102
3103         while(*s && isALNUM(*s))
3104             s++;
3105         if (*s && c == *s && s[1] == ']') {
3106             vWARN3(s+2, "POSIX syntax [%c %c] belongs inside character classes", c, c);
3107
3108             /* [[=foo=]] and [[.foo.]] are still future. */
3109             if (c == '=' || c == '.')
3110             {
3111                 /* adjust PL_regcomp_parse so the error shows after
3112                    the class closes */
3113                 while (*PL_regcomp_parse && *PL_regcomp_parse++ != ']')
3114                     ;
3115                 Simple_vFAIL3("POSIX syntax [%c %c] is reserved for future extensions", c, c);
3116             }
3117         }
3118     }
3119 }
3120
3121 STATIC regnode *
3122 S_regclass(pTHX)
3123 {
3124     dTHR;
3125     register U32 value;
3126     register I32 lastvalue = OOB_CHAR8;
3127     register I32 range = 0;
3128     register regnode *ret;
3129     STRLEN numlen;
3130     I32 namedclass;
3131     char *rangebegin;
3132     bool need_class = 0;
3133
3134     ret = reg_node(ANYOF);
3135     if (SIZE_ONLY)
3136         PL_regsize += ANYOF_SKIP;
3137     else {
3138         ret->flags = 0;
3139         ANYOF_BITMAP_ZERO(ret);
3140         PL_regcode += ANYOF_SKIP;
3141         if (FOLD)
3142             ANYOF_FLAGS(ret) |= ANYOF_FOLD;
3143         if (LOC)
3144             ANYOF_FLAGS(ret) |= ANYOF_LOCALE;
3145     }
3146     if (*PL_regcomp_parse == '^') {     /* Complement of range. */
3147         PL_regnaughty++;
3148         PL_regcomp_parse++;
3149         if (!SIZE_ONLY)
3150             ANYOF_FLAGS(ret) |= ANYOF_INVERT;
3151     }
3152
3153     if (!SIZE_ONLY && ckWARN(WARN_REGEXP))
3154         checkposixcc();
3155
3156     if (*PL_regcomp_parse == ']' || *PL_regcomp_parse == '-')
3157         goto skipcond;          /* allow 1st char to be ] or - */
3158     while (PL_regcomp_parse < PL_regxend && *PL_regcomp_parse != ']') {
3159        skipcond:
3160         namedclass = OOB_NAMEDCLASS;
3161         if (!range)
3162             rangebegin = PL_regcomp_parse;
3163         value = UCHARAT(PL_regcomp_parse++);
3164         if (value == '[')
3165             namedclass = regpposixcc(value);
3166         else if (value == '\\') {
3167             value = UCHARAT(PL_regcomp_parse++);
3168             /* Some compilers cannot handle switching on 64-bit integer
3169              * values, therefore the 'value' cannot be an UV. --jhi */
3170             switch (value) {
3171             case 'w':   namedclass = ANYOF_ALNUM;       break;
3172             case 'W':   namedclass = ANYOF_NALNUM;      break;
3173             case 's':   namedclass = ANYOF_SPACE;       break;
3174             case 'S':   namedclass = ANYOF_NSPACE;      break;
3175             case 'd':   namedclass = ANYOF_DIGIT;       break;
3176             case 'D':   namedclass = ANYOF_NDIGIT;      break;
3177             case 'n':   value = '\n';                   break;
3178             case 'r':   value = '\r';                   break;
3179             case 't':   value = '\t';                   break;
3180             case 'f':   value = '\f';                   break;
3181             case 'b':   value = '\b';                   break;
3182 #ifdef ASCIIish
3183             case 'e':   value = '\033';                 break;
3184             case 'a':   value = '\007';                 break;
3185 #else
3186             case 'e':   value = '\047';                 break;
3187             case 'a':   value = '\057';                 break;
3188 #endif
3189             case 'x':
3190                 numlen = 0;             /* disallow underscores */
3191                 value = (UV)scan_hex(PL_regcomp_parse, 2, &numlen);
3192                 PL_regcomp_parse += numlen;
3193                 break;
3194             case 'c':
3195                 value = UCHARAT(PL_regcomp_parse++);
3196                 value = toCTRL(value);
3197                 break;
3198             case '0': case '1': case '2': case '3': case '4':
3199             case '5': case '6': case '7': case '8': case '9':
3200                 numlen = 0;             /* disallow underscores */
3201                 value = (UV)scan_oct(--PL_regcomp_parse, 3, &numlen);
3202                 PL_regcomp_parse += numlen;
3203                 break;
3204             default:
3205                 if (!SIZE_ONLY && ckWARN(WARN_REGEXP) && isALPHA(value))
3206
3207                     vWARN2(PL_regcomp_parse, "Unrecognized escape \\%c in character class passed through", (int)value);
3208                 break;
3209             }
3210         }
3211         if (namedclass > OOB_NAMEDCLASS) {
3212             if (!need_class && !SIZE_ONLY)
3213                 ANYOF_CLASS_ZERO(ret);
3214             need_class = 1;
3215             if (range) { /* a-\d, a-[:digit:] */
3216                 if (!SIZE_ONLY) {
3217                     if (ckWARN(WARN_REGEXP))
3218                         vWARN4(PL_regcomp_parse,
3219                                "False [] range \"%*.*s\"",
3220                                PL_regcomp_parse - rangebegin,
3221                                PL_regcomp_parse - rangebegin,
3222                                rangebegin);
3223                     ANYOF_BITMAP_SET(ret, lastvalue);
3224                     ANYOF_BITMAP_SET(ret, '-');
3225                 }
3226                 range = 0; /* this is not a true range */
3227             }
3228             if (!SIZE_ONLY) {
3229                 switch (namedclass) {
3230                 case ANYOF_ALNUM:
3231                     if (LOC)
3232                         ANYOF_CLASS_SET(ret, ANYOF_ALNUM);
3233                     else {
3234                         for (value = 0; value < 256; value++)
3235                             if (isALNUM(value))
3236                                 ANYOF_BITMAP_SET(ret, value);
3237                     }
3238                     break;
3239                 case ANYOF_NALNUM:
3240                     if (LOC)
3241                         ANYOF_CLASS_SET(ret, ANYOF_NALNUM);
3242                     else {
3243                         for (value = 0; value < 256; value++)
3244                             if (!isALNUM(value))
3245                                 ANYOF_BITMAP_SET(ret, value);
3246                     }
3247                     break;
3248                 case ANYOF_SPACE:
3249                     if (LOC)
3250                         ANYOF_CLASS_SET(ret, ANYOF_SPACE);
3251                     else {
3252                         for (value = 0; value < 256; value++)
3253                             if (isSPACE(value))
3254                                 ANYOF_BITMAP_SET(ret, value);
3255                     }
3256                     break;
3257                 case ANYOF_NSPACE:
3258                     if (LOC)
3259                         ANYOF_CLASS_SET(ret, ANYOF_NSPACE);
3260                     else {
3261                         for (value = 0; value < 256; value++)
3262                             if (!isSPACE(value))
3263                                 ANYOF_BITMAP_SET(ret, value);
3264                     }
3265                     break;
3266                 case ANYOF_DIGIT:
3267                     if (LOC)
3268                         ANYOF_CLASS_SET(ret, ANYOF_DIGIT);
3269                     else {
3270                         for (value = '0'; value <= '9'; value++)
3271                             ANYOF_BITMAP_SET(ret, value);
3272                     }
3273                     break;
3274                 case ANYOF_NDIGIT:
3275                     if (LOC)
3276                         ANYOF_CLASS_SET(ret, ANYOF_NDIGIT);
3277                     else {
3278                         for (value = 0; value < '0'; value++)
3279                             ANYOF_BITMAP_SET(ret, value);
3280                         for (value = '9' + 1; value < 256; value++)
3281                             ANYOF_BITMAP_SET(ret, value);
3282                     }
3283                     break;
3284                 case ANYOF_NALNUMC:
3285                     if (LOC)
3286                         ANYOF_CLASS_SET(ret, ANYOF_NALNUMC);
3287                     else {
3288                         for (value = 0; value < 256; value++)
3289                             if (!isALNUMC(value))
3290                                 ANYOF_BITMAP_SET(ret, value);
3291                     }
3292                     break;
3293                 case ANYOF_ALNUMC:
3294                     if (LOC)
3295                         ANYOF_CLASS_SET(ret, ANYOF_ALNUMC);
3296                     else {
3297                         for (value = 0; value < 256; value++)
3298                             if (isALNUMC(value))
3299                                 ANYOF_BITMAP_SET(ret, value);
3300                     }
3301                     break;
3302                 case ANYOF_ALPHA:
3303                     if (LOC)
3304                         ANYOF_CLASS_SET(ret, ANYOF_ALPHA);
3305                     else {
3306                         for (value = 0; value < 256; value++)
3307                             if (isALPHA(value))
3308                                 ANYOF_BITMAP_SET(ret, value);
3309                     }
3310                     break;
3311                 case ANYOF_NALPHA:
3312                     if (LOC)
3313                         ANYOF_CLASS_SET(ret, ANYOF_NALPHA);
3314                     else {
3315                         for (value = 0; value < 256; value++)
3316                             if (!isALPHA(value))
3317                                 ANYOF_BITMAP_SET(ret, value);
3318                     }
3319                     break;
3320                 case ANYOF_ASCII:
3321                     if (LOC)
3322                         ANYOF_CLASS_SET(ret, ANYOF_ASCII);
3323                     else {
3324 #ifdef ASCIIish
3325                         for (value = 0; value < 128; value++)
3326                             ANYOF_BITMAP_SET(ret, value);
3327 #else  /* EBCDIC */
3328                         for (value = 0; value < 256; value++)
3329                             if (isASCII(value))
3330                                 ANYOF_BITMAP_SET(ret, value);
3331 #endif /* EBCDIC */
3332                     }
3333                     break;
3334                 case ANYOF_NASCII:
3335                     if (LOC)
3336                         ANYOF_CLASS_SET(ret, ANYOF_NASCII);
3337                     else {
3338 #ifdef ASCIIish
3339                         for (value = 128; value < 256; value++)
3340                             ANYOF_BITMAP_SET(ret, value);
3341 #else  /* EBCDIC */
3342                         for (value = 0; value < 256; value++)
3343                             if (!isASCII(value))
3344                                 ANYOF_BITMAP_SET(ret, value);
3345 #endif /* EBCDIC */
3346                     }
3347                     break;
3348                 case ANYOF_BLANK:
3349                     if (LOC)
3350                         ANYOF_CLASS_SET(ret, ANYOF_BLANK);
3351                     else {
3352                         for (value = 0; value < 256; value++)
3353                             if (isBLANK(value))
3354                                 ANYOF_BITMAP_SET(ret, value);
3355                     }
3356                     break;
3357                 case ANYOF_NBLANK:
3358                     if (LOC)
3359                         ANYOF_CLASS_SET(ret, ANYOF_NBLANK);
3360                     else {
3361                         for (value = 0; value < 256; value++)
3362                             if (!isBLANK(value))
3363                                 ANYOF_BITMAP_SET(ret, value);
3364                     }
3365                     break;
3366                 case ANYOF_CNTRL:
3367                     if (LOC)
3368                         ANYOF_CLASS_SET(ret, ANYOF_CNTRL);
3369                     else {
3370                         for (value = 0; value < 256; value++)
3371                             if (isCNTRL(value))
3372                                 ANYOF_BITMAP_SET(ret, value);
3373                     }
3374                     lastvalue = OOB_CHAR8;
3375                     break;
3376                 case ANYOF_NCNTRL:
3377                     if (LOC)
3378                         ANYOF_CLASS_SET(ret, ANYOF_NCNTRL);
3379                     else {
3380                         for (value = 0; value < 256; value++)
3381                             if (!isCNTRL(value))
3382                                 ANYOF_BITMAP_SET(ret, value);
3383                     }
3384                     break;
3385                 case ANYOF_GRAPH:
3386                     if (LOC)
3387                         ANYOF_CLASS_SET(ret, ANYOF_GRAPH);
3388                     else {
3389                         for (value = 0; value < 256; value++)
3390                             if (isGRAPH(value))
3391                                 ANYOF_BITMAP_SET(ret, value);
3392                     }
3393                     break;
3394                 case ANYOF_NGRAPH:
3395                     if (LOC)
3396                         ANYOF_CLASS_SET(ret, ANYOF_NGRAPH);
3397                     else {
3398                         for (value = 0; value < 256; value++)
3399                             if (!isGRAPH(value))
3400                                 ANYOF_BITMAP_SET(ret, value);
3401                     }
3402                     break;
3403                 case ANYOF_LOWER:
3404                     if (LOC)
3405                         ANYOF_CLASS_SET(ret, ANYOF_LOWER);
3406                     else {
3407                         for (value = 0; value < 256; value++)
3408                             if (isLOWER(value))
3409                                 ANYOF_BITMAP_SET(ret, value);
3410                     }
3411                     break;
3412                 case ANYOF_NLOWER:
3413                     if (LOC)
3414                         ANYOF_CLASS_SET(ret, ANYOF_NLOWER);
3415                     else {
3416                         for (value = 0; value < 256; value++)
3417                             if (!isLOWER(value))
3418                                 ANYOF_BITMAP_SET(ret, value);
3419                     }
3420                     break;
3421                 case ANYOF_PRINT:
3422                     if (LOC)
3423                         ANYOF_CLASS_SET(ret, ANYOF_PRINT);
3424                     else {
3425                         for (value = 0; value < 256; value++)
3426                             if (isPRINT(value))
3427                                 ANYOF_BITMAP_SET(ret, value);
3428                     }
3429                     break;
3430                 case ANYOF_NPRINT:
3431                     if (LOC)
3432                         ANYOF_CLASS_SET(ret, ANYOF_NPRINT);
3433                     else {
3434                         for (value = 0; value < 256; value++)
3435                             if (!isPRINT(value))
3436                                 ANYOF_BITMAP_SET(ret, value);
3437                     }
3438                     break;
3439                 case ANYOF_PSXSPC:
3440                     if (LOC)
3441                         ANYOF_CLASS_SET(ret, ANYOF_PSXSPC);
3442                     else {
3443                         for (value = 0; value < 256; value++)
3444                             if (isPSXSPC(value))
3445                                 ANYOF_BITMAP_SET(ret, value);
3446                     }
3447                     break;
3448                 case ANYOF_NPSXSPC:
3449                     if (LOC)
3450                         ANYOF_CLASS_SET(ret, ANYOF_NPSXSPC);
3451                     else {
3452                         for (value = 0; value < 256; value++)
3453                             if (!isPSXSPC(value))
3454                                 ANYOF_BITMAP_SET(ret, value);
3455                     }
3456                     break;
3457                 case ANYOF_PUNCT:
3458                     if (LOC)
3459                         ANYOF_CLASS_SET(ret, ANYOF_PUNCT);
3460                     else {
3461                         for (value = 0; value < 256; value++)
3462                             if (isPUNCT(value))
3463                                 ANYOF_BITMAP_SET(ret, value);
3464                     }
3465                     break;
3466                 case ANYOF_NPUNCT:
3467                     if (LOC)
3468                         ANYOF_CLASS_SET(ret, ANYOF_NPUNCT);
3469                     else {
3470                         for (value = 0; value < 256; value++)
3471                             if (!isPUNCT(value))
3472                                 ANYOF_BITMAP_SET(ret, value);
3473                     }
3474                     break;
3475                 case ANYOF_UPPER:
3476                     if (LOC)
3477                         ANYOF_CLASS_SET(ret, ANYOF_UPPER);
3478                     else {
3479                         for (value = 0; value < 256; value++)
3480                             if (isUPPER(value))
3481                                 ANYOF_BITMAP_SET(ret, value);
3482                     }
3483                     break;
3484                 case ANYOF_NUPPER:
3485                     if (LOC)
3486                         ANYOF_CLASS_SET(ret, ANYOF_NUPPER);
3487                     else {
3488                         for (value = 0; value < 256; value++)
3489                             if (!isUPPER(value))
3490                                 ANYOF_BITMAP_SET(ret, value);
3491                     }
3492                     break;
3493                 case ANYOF_XDIGIT:
3494                     if (LOC)
3495                         ANYOF_CLASS_SET(ret, ANYOF_XDIGIT);
3496                     else {
3497                         for (value = 0; value < 256; value++)
3498                             if (isXDIGIT(value))
3499                                 ANYOF_BITMAP_SET(ret, value);
3500                     }
3501                     break;
3502                 case ANYOF_NXDIGIT:
3503                     if (LOC)
3504                         ANYOF_CLASS_SET(ret, ANYOF_NXDIGIT);
3505                     else {
3506                         for (value = 0; value < 256; value++)
3507                             if (!isXDIGIT(value))
3508                                 ANYOF_BITMAP_SET(ret, value);
3509                     }
3510                     break;
3511                 default:
3512                     vFAIL("Invalid [::] class");
3513                     break;
3514                 }
3515                 if (LOC)
3516                     ANYOF_FLAGS(ret) |= ANYOF_CLASS;
3517                 continue;
3518             }
3519         }
3520         if (range) {
3521             if (lastvalue > value) /* b-a */ {
3522                 Simple_vFAIL4("Invalid [] range \"%*.*s\"",
3523                               PL_regcomp_parse - rangebegin,
3524                               PL_regcomp_parse - rangebegin,
3525                               rangebegin);
3526             }
3527             range = 0;
3528         }
3529         else {
3530             lastvalue = value;
3531             if (*PL_regcomp_parse == '-' && PL_regcomp_parse+1 < PL_regxend &&
3532                 PL_regcomp_parse[1] != ']') {
3533                 PL_regcomp_parse++;
3534                 if (namedclass > OOB_NAMEDCLASS) { /* \w-, [:word:]- */
3535                     if (ckWARN(WARN_REGEXP))
3536                         vWARN4(PL_regcomp_parse,
3537                                "False [] range \"%*.*s\"",
3538                                PL_regcomp_parse - rangebegin,
3539                                PL_regcomp_parse - rangebegin,
3540                                rangebegin);
3541                     if (!SIZE_ONLY)
3542                         ANYOF_BITMAP_SET(ret, '-');
3543                 } else
3544                     range = 1;
3545                 continue;       /* do it next time */
3546             }
3547         }
3548         /* now is the next time */
3549         if (!SIZE_ONLY) {
3550 #ifndef ASCIIish /* EBCDIC, for example. */
3551             if ((isLOWER(lastvalue) && isLOWER(value)) ||
3552                 (isUPPER(lastvalue) && isUPPER(value)))
3553             {
3554                 I32 i;
3555                 if (isLOWER(lastvalue)) {
3556                     for (i = lastvalue; i <= value; i++)
3557                         if (isLOWER(i))
3558                             ANYOF_BITMAP_SET(ret, i);
3559                 } else {
3560                     for (i = lastvalue; i <= value; i++)
3561                         if (isUPPER(i))
3562                             ANYOF_BITMAP_SET(ret, i);
3563                 }
3564             }
3565             else
3566 #endif
3567                 for ( ; lastvalue <= value; lastvalue++)
3568                     ANYOF_BITMAP_SET(ret, lastvalue);
3569         }
3570         range = 0;
3571     }
3572     if (need_class) {
3573         if (SIZE_ONLY)
3574             PL_regsize += ANYOF_CLASS_ADD_SKIP;
3575         else
3576             PL_regcode += ANYOF_CLASS_ADD_SKIP;
3577     }
3578     /* optimize case-insensitive simple patterns (e.g. /[a-z]/i) */
3579     if (!SIZE_ONLY &&
3580         (ANYOF_FLAGS(ret) & (ANYOF_FLAGS_ALL ^ ANYOF_INVERT)) == ANYOF_FOLD) {
3581         for (value = 0; value < 256; ++value) {
3582             if (ANYOF_BITMAP_TEST(ret, value)) {
3583                 I32 cf = PL_fold[value];
3584                 ANYOF_BITMAP_SET(ret, cf);
3585             }
3586         }
3587         ANYOF_FLAGS(ret) &= ~ANYOF_FOLD;
3588     }
3589     /* optimize inverted simple patterns (e.g. [^a-z]) */
3590     if (!SIZE_ONLY && (ANYOF_FLAGS(ret) & ANYOF_FLAGS_ALL) == ANYOF_INVERT) {
3591         for (value = 0; value < ANYOF_BITMAP_SIZE; ++value)
3592             ANYOF_BITMAP(ret)[value] ^= ANYOF_FLAGS_ALL;
3593         ANYOF_FLAGS(ret) = 0;
3594     }
3595     return ret;
3596 }
3597
3598 STATIC regnode *
3599 S_regclassutf8(pTHX)
3600 {
3601     dTHR;
3602     register char *e;
3603     register U32 value;
3604     register U32 lastvalue = OOB_UTF8;
3605     register I32 range = 0;
3606     register regnode *ret;
3607     STRLEN numlen;
3608     I32 n;
3609     SV *listsv;
3610     U8 flags = 0;
3611     I32 namedclass;
3612     char *rangebegin;
3613
3614     if (*PL_regcomp_parse == '^') {     /* Complement of range. */
3615         PL_regnaughty++;
3616         PL_regcomp_parse++;
3617         if (!SIZE_ONLY)
3618             flags |= ANYOF_INVERT;
3619     }
3620     if (!SIZE_ONLY) {
3621         if (FOLD)
3622             flags |= ANYOF_FOLD;
3623         if (LOC)
3624             flags |= ANYOF_LOCALE;
3625         listsv = newSVpvn("# comment\n",10);
3626     }
3627
3628     if (!SIZE_ONLY && ckWARN(WARN_REGEXP))
3629         checkposixcc();
3630
3631     if (*PL_regcomp_parse == ']' || *PL_regcomp_parse == '-')
3632         goto skipcond;          /* allow 1st char to be ] or - */
3633
3634     while (PL_regcomp_parse < PL_regxend && *PL_regcomp_parse != ']') {
3635        skipcond:
3636         namedclass = OOB_NAMEDCLASS;
3637         if (!range)
3638             rangebegin = PL_regcomp_parse;
3639         value = utf8_to_uv((U8*)PL_regcomp_parse,
3640                                PL_regxend - PL_regcomp_parse,
3641                                &numlen, 0);
3642         PL_regcomp_parse += numlen;
3643         if (value == '[')
3644             namedclass = regpposixcc(value);
3645         else if (value == '\\') {
3646             value = (U32)utf8_to_uv((U8*)PL_regcomp_parse,
3647                                         PL_regxend - PL_regcomp_parse,
3648                                         &numlen, 0);
3649             PL_regcomp_parse += numlen;
3650             /* Some compilers cannot handle switching on 64-bit integer
3651              * values, therefore value cannot be an UV.  Yes, this will
3652              * be a problem later if we want switch on Unicode.  --jhi */
3653             switch (value) {
3654             case 'w':           namedclass = ANYOF_ALNUM;               break;
3655             case 'W':           namedclass = ANYOF_NALNUM;              break;
3656             case 's':           namedclass = ANYOF_SPACE;               break;
3657             case 'S':           namedclass = ANYOF_NSPACE;              break;
3658             case 'd':           namedclass = ANYOF_DIGIT;               break;
3659             case 'D':           namedclass = ANYOF_NDIGIT;              break;
3660             case 'p':
3661             case 'P':
3662                 if (*PL_regcomp_parse == '{') {
3663                     e = strchr(PL_regcomp_parse++, '}');
3664                     if (!e)
3665                         vFAIL("Missing right brace on \\p{}");
3666                     n = e - PL_regcomp_parse;
3667                 }
3668                 else {
3669                     e = PL_regcomp_parse;
3670                     n = 1;
3671                 }
3672                 if (!SIZE_ONLY) {
3673                     if (value == 'p')
3674                         Perl_sv_catpvf(aTHX_ listsv,
3675                                        "+utf8::%.*s\n", (int)n, PL_regcomp_parse);
3676                     else
3677                         Perl_sv_catpvf(aTHX_ listsv,
3678                                        "!utf8::%.*s\n", (int)n, PL_regcomp_parse);
3679                 }
3680                 PL_regcomp_parse = e + 1;
3681                 lastvalue = OOB_UTF8;
3682                 continue;
3683             case 'n':           value = '\n';           break;
3684             case 'r':           value = '\r';           break;
3685             case 't':           value = '\t';           break;
3686             case 'f':           value = '\f';           break;
3687             case 'b':           value = '\b';           break;
3688 #ifdef ASCIIish
3689             case 'e':           value = '\033';         break;
3690             case 'a':           value = '\007';         break;
3691 #else
3692             case 'e':           value = '\047';         break;
3693             case 'a':           value = '\057';         break;
3694 #endif
3695             case 'x':
3696                 if (*PL_regcomp_parse == '{') {
3697                     e = strchr(PL_regcomp_parse++, '}');
3698                     if (!e) 
3699                         vFAIL("Missing right brace on \\x{}");
3700                     numlen = 1;         /* allow underscores */
3701                     value = (UV)scan_hex(PL_regcomp_parse,
3702                                      e - PL_regcomp_parse,
3703                                      &numlen);
3704                     PL_regcomp_parse = e + 1;
3705                 }
3706                 else {
3707                     numlen = 0;         /* disallow underscores */
3708                     value = (UV)scan_hex(PL_regcomp_parse, 2, &numlen);
3709                     PL_regcomp_parse += numlen;
3710                 }
3711                 break;
3712             case 'c':
3713                 value = UCHARAT(PL_regcomp_parse++);
3714                 value = toCTRL(value);
3715                 break;
3716             case '0': case '1': case '2': case '3': case '4':
3717             case '5': case '6': case '7': case '8': case '9':
3718                 numlen = 0;             /* disallow underscores */
3719                 value = (UV)scan_oct(--PL_regcomp_parse, 3, &numlen);
3720                 PL_regcomp_parse += numlen;
3721                 break;
3722             default:
3723                 if (!SIZE_ONLY && ckWARN(WARN_REGEXP) && isALPHA(value))
3724                     vWARN2(PL_regcomp_parse,
3725                            "Unrecognized escape \\%c in character class passed through",
3726                            (int)value);
3727                 break;
3728             }
3729         }
3730         if (namedclass > OOB_NAMEDCLASS) {
3731             if (range) { /* a-\d, a-[:digit:] */
3732                 if (!SIZE_ONLY) {
3733                     if (ckWARN(WARN_REGEXP))
3734                         vWARN4(PL_regcomp_parse,
3735                                "False [] range \"%*.*s\"",
3736                                PL_regcomp_parse - rangebegin,
3737                                PL_regcomp_parse - rangebegin,
3738                                rangebegin);
3739                     Perl_sv_catpvf(aTHX_ listsv,
3740                                    /* 0x002D is Unicode for '-' */
3741                                    "%04"UVxf"\n002D\n", (UV)lastvalue);
3742                 }
3743                 range = 0;
3744             }
3745             if (!SIZE_ONLY) {
3746                 switch (namedclass) {
3747                 case ANYOF_ALNUM:
3748                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsWord\n");    break;
3749                 case ANYOF_NALNUM:
3750                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsWord\n");    break;
3751                 case ANYOF_ALNUMC:
3752                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsAlnum\n");   break;
3753                 case ANYOF_NALNUMC:
3754                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsAlnum\n");   break;
3755                 case ANYOF_ALPHA:
3756                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsAlpha\n");   break;
3757                 case ANYOF_NALPHA:
3758                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsAlpha\n");   break;
3759                 case ANYOF_ASCII:
3760                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsASCII\n");   break;
3761                 case ANYOF_NASCII:
3762                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsASCII\n");   break;
3763                 case ANYOF_CNTRL:
3764                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsCntrl\n");   break;
3765                 case ANYOF_NCNTRL:
3766                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsCntrl\n");   break;
3767                 case ANYOF_GRAPH:
3768                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsGraph\n");   break;
3769                 case ANYOF_NGRAPH:
3770                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsGraph\n");   break;
3771                 case ANYOF_DIGIT:
3772                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsDigit\n");   break;
3773                 case ANYOF_NDIGIT:
3774                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsDigit\n");   break;
3775                 case ANYOF_LOWER:
3776                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsLower\n");   break;
3777                 case ANYOF_NLOWER:
3778                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsLower\n");   break;
3779                 case ANYOF_PRINT:
3780                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsPrint\n");   break;
3781                 case ANYOF_NPRINT:
3782                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsPrint\n");   break;
3783                 case ANYOF_PUNCT:
3784                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsPunct\n");   break;
3785                 case ANYOF_NPUNCT:
3786                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsPunct\n");   break;
3787                 case ANYOF_SPACE:
3788                 case ANYOF_PSXSPC:
3789                 case ANYOF_BLANK:
3790                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsSpace\n");   break;
3791                 case ANYOF_NSPACE:
3792                 case ANYOF_NPSXSPC:
3793                 case ANYOF_NBLANK:
3794                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsSpace\n");   break;
3795                 case ANYOF_UPPER:
3796                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsUpper\n");   break;
3797                 case ANYOF_NUPPER:
3798                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsUpper\n");   break;
3799                 case ANYOF_XDIGIT:
3800                     Perl_sv_catpvf(aTHX_ listsv, "+utf8::IsXDigit\n");  break;
3801                 case ANYOF_NXDIGIT:
3802                     Perl_sv_catpvf(aTHX_ listsv, "!utf8::IsXDigit\n");  break;
3803                 }
3804                 continue;
3805             }
3806         }
3807         if (range) {
3808             if (lastvalue > value) { /* b-a */
3809                 Simple_vFAIL4("invalid [] range \"%*.*s\"",
3810                               PL_regcomp_parse - rangebegin,
3811                               PL_regcomp_parse - rangebegin,
3812                               rangebegin);
3813             }
3814             range = 0;
3815         }
3816         else {
3817             lastvalue = value;
3818             if (*PL_regcomp_parse == '-' && PL_regcomp_parse+1 < PL_regxend &&
3819                 PL_regcomp_parse[1] != ']') {
3820                 PL_regcomp_parse++;
3821                 if (namedclass > OOB_NAMEDCLASS) { /* \w-, [:word:]- */
3822                     if (ckWARN(WARN_REGEXP))
3823                         vWARN4(PL_regcomp_parse,
3824                                "False [] range \"%*.*s\"",
3825                                PL_regcomp_parse - rangebegin,
3826                                PL_regcomp_parse - rangebegin,
3827                                rangebegin);
3828                     if (!SIZE_ONLY)
3829                         Perl_sv_catpvf(aTHX_ listsv,
3830                                        /* 0x002D is Unicode for '-' */
3831                                        "002D\n");
3832                 } else
3833                     range = 1;
3834                 continue;       /* do it next time */
3835             }
3836         }
3837         /* now is the next time */
3838         if (!SIZE_ONLY)
3839             Perl_sv_catpvf(aTHX_ listsv, "%04"UVxf"\t%04"UVxf"\n",
3840                            (UV)lastvalue, (UV)value);
3841         range = 0;
3842     }
3843
3844     ret = reganode(ANYOFUTF8, 0);
3845
3846     if (!SIZE_ONLY) {
3847         SV *rv = swash_init("utf8", "", listsv, 1, 0);
3848         SvREFCNT_dec(listsv);
3849         n = add_data(1,"s");
3850         PL_regcomp_rx->data->data[n] = (void*)rv;
3851         ARG1_SET(ret, flags);
3852         ARG2_SET(ret, n);
3853     }
3854
3855     return ret;
3856 }
3857
3858 STATIC char*
3859 S_nextchar(pTHX)
3860 {
3861     dTHR;
3862     char* retval = PL_regcomp_parse++;
3863
3864     for (;;) {
3865         if (*PL_regcomp_parse == '(' && PL_regcomp_parse[1] == '?' &&
3866                 PL_regcomp_parse[2] == '#') {
3867             while (*PL_regcomp_parse && *PL_regcomp_parse != ')')
3868                 PL_regcomp_parse++;
3869             PL_regcomp_parse++;
3870             continue;
3871         }
3872         if (PL_regflags & PMf_EXTENDED) {
3873             if (isSPACE(*PL_regcomp_parse)) {
3874                 PL_regcomp_parse++;
3875                 continue;
3876             }
3877             else if (*PL_regcomp_parse == '#') {
3878                 while (*PL_regcomp_parse && *PL_regcomp_parse != '\n')
3879                     PL_regcomp_parse++;
3880                 PL_regcomp_parse++;
3881                 continue;
3882             }
3883         }
3884         return retval;
3885     }
3886 }
3887
3888 /*
3889 - reg_node - emit a node
3890 */
3891 STATIC regnode *                        /* Location. */
3892 S_reg_node(pTHX_ U8 op)
3893 {
3894     dTHR;
3895     register regnode *ret;
3896     register regnode *ptr;
3897
3898     ret = PL_regcode;
3899     if (SIZE_ONLY) {
3900         SIZE_ALIGN(PL_regsize);
3901         PL_regsize += 1;
3902         return(ret);
3903     }
3904
3905     NODE_ALIGN_FILL(ret);
3906     ptr = ret;
3907     FILL_ADVANCE_NODE(ptr, op);
3908     PL_regcode = ptr;
3909
3910     return(ret);
3911 }
3912
3913 /*
3914 - reganode - emit a node with an argument
3915 */
3916 STATIC regnode *                        /* Location. */
3917 S_reganode(pTHX_ U8 op, U32 arg)
3918 {
3919     dTHR;
3920     register regnode *ret;
3921     register regnode *ptr;
3922
3923     ret = PL_regcode;
3924     if (SIZE_ONLY) {
3925         SIZE_ALIGN(PL_regsize);
3926         PL_regsize += 2;
3927         return(ret);
3928     }
3929
3930     NODE_ALIGN_FILL(ret);
3931     ptr = ret;
3932     FILL_ADVANCE_NODE_ARG(ptr, op, arg);
3933     PL_regcode = ptr;
3934
3935     return(ret);
3936 }
3937
3938 /*
3939 - reguni - emit (if appropriate) a Unicode character
3940 */
3941 STATIC void
3942 S_reguni(pTHX_ UV uv, char* s, STRLEN* lenp)
3943 {
3944     dTHR;
3945     if (SIZE_ONLY) {
3946         U8 tmpbuf[UTF8_MAXLEN];
3947         *lenp = uv_to_utf8(tmpbuf, uv) - tmpbuf;
3948     }
3949     else
3950         *lenp = uv_to_utf8((U8*)s, uv) - (U8*)s;
3951
3952 }
3953
3954 /*
3955 - reginsert - insert an operator in front of already-emitted operand
3956 *
3957 * Means relocating the operand.
3958 */
3959 STATIC void
3960 S_reginsert(pTHX_ U8 op, regnode *opnd)
3961 {
3962     dTHR;
3963     register regnode *src;
3964     register regnode *dst;
3965     register regnode *place;
3966     register int offset = regarglen[(U8)op];
3967     
3968 /* (PL_regkind[(U8)op] == CURLY ? EXTRA_STEP_2ARGS : 0); */
3969
3970     if (SIZE_ONLY) {
3971         PL_regsize += NODE_STEP_REGNODE + offset;
3972         return;
3973     }
3974
3975     src = PL_regcode;
3976     PL_regcode += NODE_STEP_REGNODE + offset;
3977     dst = PL_regcode;
3978     while (src > opnd)
3979         StructCopy(--src, --dst, regnode);
3980
3981     place = opnd;               /* Op node, where operand used to be. */
3982     src = NEXTOPER(place);
3983     FILL_ADVANCE_NODE(place, op);
3984     Zero(src, offset, regnode);
3985 }
3986
3987 /*
3988 - regtail - set the next-pointer at the end of a node chain of p to val.
3989 */
3990 STATIC void
3991 S_regtail(pTHX_ regnode *p, regnode *val)
3992 {
3993     dTHR;
3994     register regnode *scan;
3995     register regnode *temp;
3996
3997     if (SIZE_ONLY)
3998         return;
3999
4000     /* Find last node. */
4001     scan = p;
4002     for (;;) {
4003         temp = regnext(scan);
4004         if (temp == NULL)
4005             break;
4006         scan = temp;
4007     }
4008
4009     if (reg_off_by_arg[OP(scan)]) {
4010         ARG_SET(scan, val - scan);
4011     }
4012     else {
4013         NEXT_OFF(scan) = val - scan;
4014     }
4015 }
4016
4017 /*
4018 - regoptail - regtail on operand of first argument; nop if operandless
4019 */
4020 STATIC void
4021 S_regoptail(pTHX_ regnode *p, regnode *val)
4022 {
4023     dTHR;
4024     /* "Operandless" and "op != BRANCH" are synonymous in practice. */
4025     if (p == NULL || SIZE_ONLY)
4026         return;
4027     if (PL_regkind[(U8)OP(p)] == BRANCH) {
4028         regtail(NEXTOPER(p), val);
4029     }
4030     else if ( PL_regkind[(U8)OP(p)] == BRANCHJ) {
4031         regtail(NEXTOPER(NEXTOPER(p)), val);
4032     }
4033     else
4034         return;
4035 }
4036
4037 /*
4038  - regcurly - a little FSA that accepts {\d+,?\d*}
4039  */
4040 STATIC I32
4041 S_regcurly(pTHX_ register char *s)
4042 {
4043     if (*s++ != '{')
4044         return FALSE;
4045     if (!isDIGIT(*s))
4046         return FALSE;
4047     while (isDIGIT(*s))
4048         s++;
4049     if (*s == ',')
4050         s++;
4051     while (isDIGIT(*s))
4052         s++;
4053     if (*s != '}')
4054         return FALSE;
4055     return TRUE;
4056 }
4057
4058
4059 STATIC regnode *
4060 S_dumpuntil(pTHX_ regnode *start, regnode *node, regnode *last, SV* sv, I32 l)
4061 {
4062 #ifdef DEBUGGING
4063     register U8 op = EXACT;     /* Arbitrary non-END op. */
4064     register regnode *next;
4065
4066     while (op != END && (!last || node < last)) {
4067         /* While that wasn't END last time... */
4068
4069         NODE_ALIGN(node);
4070         op = OP(node);
4071         if (op == CLOSE)
4072             l--;        
4073         next = regnext(node);
4074         /* Where, what. */
4075         if (OP(node) == OPTIMIZED)
4076             goto after_print;
4077         regprop(sv, node);
4078         PerlIO_printf(Perl_debug_log, "%4"IVdf":%*s%s", (IV)(node - start),
4079                       (int)(2*l + 1), "", SvPVX(sv));
4080         if (next == NULL)               /* Next ptr. */
4081             PerlIO_printf(Perl_debug_log, "(0)");
4082         else 
4083             PerlIO_printf(Perl_debug_log, "(%"IVdf")", (IV)(next - start));
4084         (void)PerlIO_putc(Perl_debug_log, '\n');
4085       after_print:
4086         if (PL_regkind[(U8)op] == BRANCHJ) {
4087             register regnode *nnode = (OP(next) == LONGJMP 
4088                                        ? regnext(next) 
4089                                        : next);
4090             if (last && nnode > last)
4091                 nnode = last;
4092             node = dumpuntil(start, NEXTOPER(NEXTOPER(node)), nnode, sv, l + 1);
4093         }
4094         else if (PL_regkind[(U8)op] == BRANCH) {
4095             node = dumpuntil(start, NEXTOPER(node), next, sv, l + 1);
4096         }
4097         else if ( op == CURLY) {   /* `next' might be very big: optimizer */
4098             node = dumpuntil(start, NEXTOPER(node) + EXTRA_STEP_2ARGS,
4099                              NEXTOPER(node) + EXTRA_STEP_2ARGS + 1, sv, l + 1);
4100         }
4101         else if (PL_regkind[(U8)op] == CURLY && op != CURLYX) {
4102             node = dumpuntil(start, NEXTOPER(node) + EXTRA_STEP_2ARGS,
4103                              next, sv, l + 1);
4104         }
4105         else if ( op == PLUS || op == STAR) {
4106             node = dumpuntil(start, NEXTOPER(node), NEXTOPER(node) + 1, sv, l + 1);
4107         }
4108         else if (op == ANYOF) {
4109             node = NEXTOPER(node);
4110             node += ANYOF_SKIP;
4111         }
4112         else if (PL_regkind[(U8)op] == EXACT) {
4113             /* Literal string, where present. */
4114             node += NODE_SZ_STR(node) - 1;
4115             node = NEXTOPER(node);
4116         }
4117         else {
4118             node = NEXTOPER(node);
4119             node += regarglen[(U8)op];
4120         }
4121         if (op == CURLYX || op == OPEN)
4122             l++;
4123         else if (op == WHILEM)
4124             l--;
4125     }
4126 #endif  /* DEBUGGING */
4127     return node;
4128 }
4129
4130 /*
4131  - regdump - dump a regexp onto Perl_debug_log in vaguely comprehensible form
4132  */
4133 void
4134 Perl_regdump(pTHX_ regexp *r)
4135 {
4136 #ifdef DEBUGGING
4137     dTHR;
4138     SV *sv = sv_newmortal();
4139
4140     (void)dumpuntil(r->program, r->program + 1, NULL, sv, 0);
4141
4142     /* Header fields of interest. */
4143     if (r->anchored_substr)
4144         PerlIO_printf(Perl_debug_log,
4145                       "anchored `%s%.*s%s'%s at %"IVdf" ", 
4146                       PL_colors[0],
4147                       (int)(SvCUR(r->anchored_substr) - (SvTAIL(r->anchored_substr)!=0)),
4148                       SvPVX(r->anchored_substr), 
4149                       PL_colors[1],
4150                       SvTAIL(r->anchored_substr) ? "$" : "",
4151                       (IV)r->anchored_offset);
4152     if (r->float_substr)
4153         PerlIO_printf(Perl_debug_log,
4154                       "floating `%s%.*s%s'%s at %"IVdf"..%"UVuf" ", 
4155                       PL_colors[0],
4156                       (int)(SvCUR(r->float_substr) - (SvTAIL(r->float_substr)!=0)), 
4157                       SvPVX(r->float_substr),
4158                       PL_colors[1],
4159                       SvTAIL(r->float_substr) ? "$" : "",
4160                       (IV)r->float_min_offset, (UV)r->float_max_offset);
4161     if (r->check_substr)
4162         PerlIO_printf(Perl_debug_log, 
4163                       r->check_substr == r->float_substr 
4164                       ? "(checking floating" : "(checking anchored");
4165     if (r->reganch & ROPT_NOSCAN)
4166         PerlIO_printf(Perl_debug_log, " noscan");
4167     if (r->reganch & ROPT_CHECK_ALL)
4168         PerlIO_printf(Perl_debug_log, " isall");
4169     if (r->check_substr)
4170         PerlIO_printf(Perl_debug_log, ") ");
4171
4172     if (r->regstclass) {
4173         regprop(sv, r->regstclass);
4174         PerlIO_printf(Perl_debug_log, "stclass `%s' ", SvPVX(sv));
4175     }
4176     if (r->reganch & ROPT_ANCH) {
4177         PerlIO_printf(Perl_debug_log, "anchored");
4178         if (r->reganch & ROPT_ANCH_BOL)
4179             PerlIO_printf(Perl_debug_log, "(BOL)");
4180         if (r->reganch & ROPT_ANCH_MBOL)
4181             PerlIO_printf(Perl_debug_log, "(MBOL)");
4182         if (r->reganch & ROPT_ANCH_SBOL)
4183             PerlIO_printf(Perl_debug_log, "(SBOL)");
4184         if (r->reganch & ROPT_ANCH_GPOS)
4185             PerlIO_printf(Perl_debug_log, "(GPOS)");
4186         PerlIO_putc(Perl_debug_log, ' ');
4187     }
4188     if (r->reganch & ROPT_GPOS_SEEN)
4189         PerlIO_printf(Perl_debug_log, "GPOS ");
4190     if (r->reganch & ROPT_SKIP)
4191         PerlIO_printf(Perl_debug_log, "plus ");
4192     if (r->reganch & ROPT_IMPLICIT)
4193         PerlIO_printf(Perl_debug_log, "implicit ");
4194     PerlIO_printf(Perl_debug_log, "minlen %ld ", (long) r->minlen);
4195     if (r->reganch & ROPT_EVAL_SEEN)
4196         PerlIO_printf(Perl_debug_log, "with eval ");
4197     PerlIO_printf(Perl_debug_log, "\n");
4198 #endif  /* DEBUGGING */
4199 }
4200
4201 STATIC void
4202 S_put_byte(pTHX_ SV *sv, int c)
4203 {
4204     if (c <= ' ' || c == 127 || c == 255)
4205         Perl_sv_catpvf(aTHX_ sv, "\\%o", c);
4206     else if (c == '-' || c == ']' || c == '\\' || c == '^')
4207         Perl_sv_catpvf(aTHX_ sv, "\\%c", c);
4208     else
4209         Perl_sv_catpvf(aTHX_ sv, "%c", c);
4210 }
4211
4212 /*
4213 - regprop - printable representation of opcode
4214 */
4215 void
4216 Perl_regprop(pTHX_ SV *sv, regnode *o)
4217 {
4218 #ifdef DEBUGGING
4219     dTHR;
4220     register int k;
4221
4222     sv_setpvn(sv, "", 0);
4223     if (OP(o) >= reg_num)               /* regnode.type is unsigned */
4224         FAIL("Corrupted regexp opcode");
4225     sv_catpv(sv, (char*)reg_name[OP(o)]); /* Take off const! */
4226
4227     k = PL_regkind[(U8)OP(o)];
4228
4229     if (k == EXACT)
4230         Perl_sv_catpvf(aTHX_ sv, " <%s%.*s%s>", PL_colors[0],
4231                        STR_LEN(o), STRING(o), PL_colors[1]);
4232     else if (k == CURLY) {
4233         if (OP(o) == CURLYM || OP(o) == CURLYN)
4234             Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags); /* Parenth number */
4235         Perl_sv_catpvf(aTHX_ sv, " {%d,%d}", ARG1(o), ARG2(o));
4236     }
4237     else if (k == WHILEM && o->flags)                   /* Ordinal/of */
4238         Perl_sv_catpvf(aTHX_ sv, "[%d/%d]", o->flags & 0xf, o->flags>>4);
4239     else if (k == REF || k == OPEN || k == CLOSE || k == GROUPP )
4240         Perl_sv_catpvf(aTHX_ sv, "%d", (int)ARG(o));    /* Parenth number */
4241     else if (k == LOGICAL)
4242         Perl_sv_catpvf(aTHX_ sv, "[%d]", o->flags);     /* 2: embedded, otherwise 1 */
4243     else if (k == ANYOF) {
4244         int i, rangestart = -1;
4245         const char * const out[] = {    /* Should be syncronized with
4246                                            ANYOF_ #xdefines in regcomp.h */
4247             "\\w",
4248             "\\W",
4249             "\\s",
4250             "\\S",
4251             "\\d",
4252             "\\D",
4253             "[:alnum:]",
4254             "[:^alnum:]",
4255             "[:alpha:]",
4256             "[:^alpha:]",
4257             "[:ascii:]",
4258             "[:^ascii:]",
4259             "[:ctrl:]",
4260             "[:^ctrl:]",
4261             "[:graph:]",
4262             "[:^graph:]",
4263             "[:lower:]",
4264             "[:^lower:]",
4265             "[:print:]",
4266             "[:^print:]",
4267             "[:punct:]",
4268             "[:^punct:]",
4269             "[:upper:]",
4270             "[:^upper:]",
4271             "[:xdigit:]",
4272             "[:^xdigit:]",
4273             "[:space:]",
4274             "[:^space:]",
4275             "[:blank:]",
4276             "[:^blank:]"
4277         };
4278
4279         if (o->flags & ANYOF_LOCALE)
4280             sv_catpv(sv, "{loc}");
4281         if (o->flags & ANYOF_FOLD)
4282             sv_catpv(sv, "{i}");
4283         Perl_sv_catpvf(aTHX_ sv, "[%s", PL_colors[0]);
4284         if (o->flags & ANYOF_INVERT)
4285             sv_catpv(sv, "^");
4286         for (i = 0; i <= 256; i++) {
4287             if (i < 256 && ANYOF_BITMAP_TEST(o,i)) {
4288                 if (rangestart == -1)
4289                     rangestart = i;
4290             } else if (rangestart != -1) {
4291                 if (i <= rangestart + 3)
4292                     for (; rangestart < i; rangestart++)
4293                         put_byte(sv, rangestart);
4294                 else {
4295                     put_byte(sv, rangestart);
4296                     sv_catpv(sv, "-");
4297                     put_byte(sv, i - 1);
4298                 }
4299                 rangestart = -1;
4300             }
4301         }
4302         if (o->flags & ANYOF_CLASS)
4303             for (i = 0; i < sizeof(out)/sizeof(char*); i++)
4304                 if (ANYOF_CLASS_TEST(o,i))
4305                     sv_catpv(sv, out[i]);
4306         Perl_sv_catpvf(aTHX_ sv, "%s]", PL_colors[1]);
4307     }
4308     else if (k == BRANCHJ && (OP(o) == UNLESSM || OP(o) == IFMATCH))
4309         Perl_sv_catpvf(aTHX_ sv, "[-%d]", o->flags);
4310 #endif  /* DEBUGGING */
4311 }
4312
4313 SV *
4314 Perl_re_intuit_string(pTHX_ regexp *prog)
4315 {                               /* Assume that RE_INTUIT is set */
4316     DEBUG_r(
4317         {   STRLEN n_a;
4318             char *s = SvPV(prog->check_substr,n_a);
4319
4320             if (!PL_colorset) reginitcolors();
4321             PerlIO_printf(Perl_debug_log,
4322                       "%sUsing REx substr:%s `%s%.60s%s%s'\n",
4323                       PL_colors[4],PL_colors[5],PL_colors[0],
4324                       s,
4325                       PL_colors[1],
4326                       (strlen(s) > 60 ? "..." : ""));
4327         } );
4328
4329     return prog->check_substr;
4330 }
4331
4332 void
4333 Perl_pregfree(pTHX_ struct regexp *r)
4334 {
4335     dTHR;
4336     DEBUG_r(if (!PL_colorset) reginitcolors());
4337
4338     if (!r || (--r->refcnt > 0))
4339         return;
4340     DEBUG_r(PerlIO_printf(Perl_debug_log,
4341                       "%sFreeing REx:%s `%s%.60s%s%s'\n",
4342                       PL_colors[4],PL_colors[5],PL_colors[0],
4343                       r->precomp,
4344                       PL_colors[1],
4345                       (strlen(r->precomp) > 60 ? "..." : "")));
4346
4347     if (r->precomp)
4348         Safefree(r->precomp);
4349     if (RX_MATCH_COPIED(r))
4350         Safefree(r->subbeg);
4351     if (r->substrs) {
4352         if (r->anchored_substr)
4353             SvREFCNT_dec(r->anchored_substr);
4354         if (r->float_substr)
4355             SvREFCNT_dec(r->float_substr);
4356         Safefree(r->substrs);
4357     }
4358     if (r->data) {
4359         int n = r->data->count;
4360         AV* new_comppad = NULL;
4361         AV* old_comppad;
4362         SV** old_curpad;
4363
4364         while (--n >= 0) {
4365             switch (r->data->what[n]) {
4366             case 's':
4367                 SvREFCNT_dec((SV*)r->data->data[n]);
4368                 break;
4369             case 'f':
4370                 Safefree(r->data->data[n]);
4371                 break;
4372             case 'p':
4373                 new_comppad = (AV*)r->data->data[n];
4374                 break;
4375             case 'o':
4376                 if (new_comppad == NULL)
4377                     Perl_croak(aTHX_ "panic: pregfree comppad");
4378                 old_comppad = PL_comppad;
4379                 old_curpad = PL_curpad;
4380                 /* Watch out for global destruction's random ordering. */
4381                 if (SvTYPE(new_comppad) == SVt_PVAV) {
4382                     PL_comppad = new_comppad;
4383                     PL_curpad = AvARRAY(new_comppad);
4384                 }
4385                 else
4386                     PL_curpad = NULL;
4387                 op_free((OP_4tree*)r->data->data[n]);
4388                 PL_comppad = old_comppad;
4389                 PL_curpad = old_curpad;
4390                 SvREFCNT_dec((SV*)new_comppad);
4391                 new_comppad = NULL;
4392                 break;
4393             case 'n':
4394                 break;
4395             default:
4396                 FAIL2("panic: regfree data code '%c'", r->data->what[n]);
4397             }
4398         }
4399         Safefree(r->data->what);
4400         Safefree(r->data);
4401     }
4402     Safefree(r->startp);
4403     Safefree(r->endp);
4404     Safefree(r);
4405 }
4406
4407 /*
4408  - regnext - dig the "next" pointer out of a node
4409  *
4410  * [Note, when REGALIGN is defined there are two places in regmatch()
4411  * that bypass this code for speed.]
4412  */
4413 regnode *
4414 Perl_regnext(pTHX_ register regnode *p)
4415 {
4416     dTHR;
4417     register I32 offset;
4418
4419     if (p == &PL_regdummy)
4420         return(NULL);
4421
4422     offset = (reg_off_by_arg[OP(p)] ? ARG(p) : NEXT_OFF(p));
4423     if (offset == 0)
4424         return(NULL);
4425
4426     return(p+offset);
4427 }
4428
4429 STATIC void     
4430 S_re_croak2(pTHX_ const char* pat1,const char* pat2,...)
4431 {
4432     va_list args;
4433     STRLEN l1 = strlen(pat1);
4434     STRLEN l2 = strlen(pat2);
4435     char buf[512];
4436     SV *msv;
4437     char *message;
4438
4439     if (l1 > 510)
4440         l1 = 510;
4441     if (l1 + l2 > 510)
4442         l2 = 510 - l1;
4443     Copy(pat1, buf, l1 , char);
4444     Copy(pat2, buf + l1, l2 , char);
4445     buf[l1 + l2] = '\n';
4446     buf[l1 + l2 + 1] = '\0';
4447 #ifdef I_STDARG
4448     /* ANSI variant takes additional second argument */
4449     va_start(args, pat2);
4450 #else
4451     va_start(args);
4452 #endif
4453     msv = vmess(buf, &args);
4454     va_end(args);
4455     message = SvPV(msv,l1);
4456     if (l1 > 512)
4457         l1 = 512;
4458     Copy(message, buf, l1 , char);
4459     buf[l1] = '\0';                     /* Overwrite \n */
4460     Perl_croak(aTHX_ "%s", buf);
4461 }
4462
4463 /* XXX Here's a total kludge.  But we need to re-enter for swash routines. */
4464
4465 void
4466 Perl_save_re_context(pTHX)
4467 {                   
4468     dTHR;
4469     SAVEPPTR(PL_bostr);
4470     SAVEPPTR(PL_regprecomp);            /* uncompiled string. */
4471     SAVEI32(PL_regnpar);                /* () count. */
4472     SAVEI32(PL_regsize);                /* Code size. */
4473     SAVEI16(PL_regflags);               /* are we folding, multilining? */
4474     SAVEPPTR(PL_reginput);              /* String-input pointer. */
4475     SAVEPPTR(PL_regbol);                /* Beginning of input, for ^ check. */
4476     SAVEPPTR(PL_regeol);                /* End of input, for $ check. */
4477     SAVEVPTR(PL_regstartp);             /* Pointer to startp array. */
4478     SAVEVPTR(PL_regendp);               /* Ditto for endp. */
4479     SAVEVPTR(PL_reglastparen);          /* Similarly for lastparen. */
4480     SAVEPPTR(PL_regtill);               /* How far we are required to go. */
4481     SAVEI8(PL_regprev);                 /* char before regbol, \n if none */
4482     SAVEVPTR(PL_reg_start_tmp);         /* from regexec.c */
4483     PL_reg_start_tmp = 0;
4484     SAVEFREEPV(PL_reg_start_tmp);
4485     SAVEI32(PL_reg_start_tmpl);         /* from regexec.c */
4486     PL_reg_start_tmpl = 0;
4487     SAVEVPTR(PL_regdata);
4488     SAVEI32(PL_reg_flags);              /* from regexec.c */
4489     SAVEI32(PL_reg_eval_set);           /* from regexec.c */
4490     SAVEI32(PL_regnarrate);             /* from regexec.c */
4491     SAVEVPTR(PL_regprogram);            /* from regexec.c */
4492     SAVEINT(PL_regindent);              /* from regexec.c */
4493     SAVEVPTR(PL_regcc);                 /* from regexec.c */
4494     SAVEVPTR(PL_curcop);
4495     SAVEVPTR(PL_regcomp_rx);            /* from regcomp.c */
4496     SAVEI32(PL_regseen);                /* from regcomp.c */
4497     SAVEI32(PL_regsawback);             /* Did we see \1, ...? */
4498     SAVEI32(PL_regnaughty);             /* How bad is this pattern? */
4499     SAVEVPTR(PL_regcode);               /* Code-emit pointer; &regdummy = don't */
4500     SAVEPPTR(PL_regxend);               /* End of input for compile */
4501     SAVEPPTR(PL_regcomp_parse);         /* Input-scan pointer. */
4502     SAVEVPTR(PL_reg_call_cc);           /* from regexec.c */
4503     SAVEVPTR(PL_reg_re);                /* from regexec.c */
4504     SAVEPPTR(PL_reg_ganch);             /* from regexec.c */
4505     SAVESPTR(PL_reg_sv);                /* from regexec.c */
4506     SAVEVPTR(PL_reg_magic);             /* from regexec.c */
4507     SAVEI32(PL_reg_oldpos);                     /* from regexec.c */
4508     SAVEVPTR(PL_reg_oldcurpm);          /* from regexec.c */
4509     SAVEVPTR(PL_reg_curpm);             /* from regexec.c */
4510 #ifdef DEBUGGING
4511     SAVEPPTR(PL_reg_starttry);          /* from regexec.c */    
4512 #endif
4513 }
4514
4515 #ifdef PERL_OBJECT
4516 #include "XSUB.h"
4517 #undef this
4518 #define this pPerl
4519 #endif
4520
4521 static void
4522 clear_re(pTHXo_ void *r)
4523 {
4524     ReREFCNT_dec((regexp *)r);
4525 }
4526