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