This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Integrate:
[perl5.git] / regexec.c
1 /*    regexec.c
2  */
3
4 /*
5  * "One Ring to rule them all, One Ring to find them..."
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_regexec_flags my_regexec
36 #  define Perl_regdump my_regdump
37 #  define Perl_regprop my_regprop
38 #  define Perl_re_intuit_start my_re_intuit_start
39 /* *These* symbols are masked to allow static link. */
40 #  define Perl_pregexec my_pregexec
41 #  define Perl_reginitcolors my_reginitcolors
42 #  define Perl_regclass_swash my_regclass_swash
43
44 #  define PERL_NO_GET_CONTEXT
45 #endif
46
47 /*SUPPRESS 112*/
48 /*
49  * pregcomp and pregexec -- regsub and regerror are not used in perl
50  *
51  *      Copyright (c) 1986 by University of Toronto.
52  *      Written by Henry Spencer.  Not derived from licensed software.
53  *
54  *      Permission is granted to anyone to use this software for any
55  *      purpose on any computer system, and to redistribute it freely,
56  *      subject to the following restrictions:
57  *
58  *      1. The author is not responsible for the consequences of use of
59  *              this software, no matter how awful, even if they arise
60  *              from defects in it.
61  *
62  *      2. The origin of this software must not be misrepresented, either
63  *              by explicit claim or by omission.
64  *
65  *      3. Altered versions must be plainly marked as such, and must not
66  *              be misrepresented as being the original software.
67  *
68  ****    Alterations to Henry's code are...
69  ****
70  ****    Copyright (c) 1991-2003, Larry Wall
71  ****
72  ****    You may distribute under the terms of either the GNU General Public
73  ****    License or the Artistic License, as specified in the README file.
74  *
75  * Beware that some of this code is subtly aware of the way operator
76  * precedence is structured in regular expressions.  Serious changes in
77  * regular-expression syntax might require a total rethink.
78  */
79 #include "EXTERN.h"
80 #define PERL_IN_REGEXEC_C
81 #include "perl.h"
82
83 #include "regcomp.h"
84
85 #define RF_tainted      1               /* tainted information used? */
86 #define RF_warned       2               /* warned about big count? */
87 #define RF_evaled       4               /* Did an EVAL with setting? */
88 #define RF_utf8         8               /* String contains multibyte chars? */
89
90 #define UTF ((PL_reg_flags & RF_utf8) != 0)
91
92 #define RS_init         1               /* eval environment created */
93 #define RS_set          2               /* replsv value is set */
94
95 #ifndef STATIC
96 #define STATIC  static
97 #endif
98
99 #define REGINCLASS(p,c)  (ANYOF_FLAGS(p) ? reginclass(p,c,0,0) : ANYOF_BITMAP_TEST(p,*(c)))
100
101 /*
102  * Forwards.
103  */
104
105 #define CHR_SVLEN(sv) (do_utf8 ? sv_len_utf8(sv) : SvCUR(sv))
106 #define CHR_DIST(a,b) (PL_reg_match_utf8 ? utf8_distance(a,b) : a - b)
107
108 #define reghop_c(pos,off) ((char*)reghop((U8*)pos, off))
109 #define reghopmaybe_c(pos,off) ((char*)reghopmaybe((U8*)pos, off))
110 #define HOP(pos,off) (PL_reg_match_utf8 ? reghop((U8*)pos, off) : (U8*)(pos + off))
111 #define HOPMAYBE(pos,off) (PL_reg_match_utf8 ? reghopmaybe((U8*)pos, off) : (U8*)(pos + off))
112 #define HOPc(pos,off) ((char*)HOP(pos,off))
113 #define HOPMAYBEc(pos,off) ((char*)HOPMAYBE(pos,off))
114
115 #define HOPBACK(pos, off) (             \
116     (PL_reg_match_utf8)                 \
117         ? reghopmaybe((U8*)pos, -off)   \
118     : (pos - off >= PL_bostr)           \
119         ? (U8*)(pos - off)              \
120     : (U8*)NULL                         \
121 )
122 #define HOPBACKc(pos, off) (char*)HOPBACK(pos, off)
123
124 #define reghop3_c(pos,off,lim) ((char*)reghop3((U8*)pos, off, (U8*)lim))
125 #define reghopmaybe3_c(pos,off,lim) ((char*)reghopmaybe3((U8*)pos, off, (U8*)lim))
126 #define HOP3(pos,off,lim) (PL_reg_match_utf8 ? reghop3((U8*)pos, off, (U8*)lim) : (U8*)(pos + off))
127 #define HOPMAYBE3(pos,off,lim) (PL_reg_match_utf8 ? reghopmaybe3((U8*)pos, off, (U8*)lim) : (U8*)(pos + off))
128 #define HOP3c(pos,off,lim) ((char*)HOP3(pos,off,lim))
129 #define HOPMAYBE3c(pos,off,lim) ((char*)HOPMAYBE3(pos,off,lim))
130
131 #define LOAD_UTF8_CHARCLASS(a,b) STMT_START { if (!CAT2(PL_utf8_,a)) { ENTER; save_re_context(); (void)CAT2(is_utf8_, a)((U8*)b); LEAVE; } } STMT_END
132
133 /* for use after a quantifier and before an EXACT-like node -- japhy */
134 #define JUMPABLE(rn) ( \
135     OP(rn) == OPEN || OP(rn) == CLOSE || OP(rn) == EVAL || \
136     OP(rn) == SUSPEND || OP(rn) == IFMATCH || \
137     OP(rn) == PLUS || OP(rn) == MINMOD || \
138     (PL_regkind[(U8)OP(rn)] == CURLY && ARG1(rn) > 0) \
139 )
140
141 #define HAS_TEXT(rn) ( \
142     PL_regkind[(U8)OP(rn)] == EXACT || PL_regkind[(U8)OP(rn)] == REF \
143 )
144
145 /*
146   Search for mandatory following text node; for lookahead, the text must
147   follow but for lookbehind (rn->flags != 0) we skip to the next step.
148 */
149 #define FIND_NEXT_IMPT(rn) STMT_START { \
150     while (JUMPABLE(rn)) \
151         if (OP(rn) == SUSPEND || PL_regkind[(U8)OP(rn)] == CURLY) \
152             rn = NEXTOPER(NEXTOPER(rn)); \
153         else if (OP(rn) == PLUS) \
154             rn = NEXTOPER(rn); \
155         else if (OP(rn) == IFMATCH) \
156             rn = (rn->flags == 0) ? NEXTOPER(NEXTOPER(rn)) : rn + ARG(rn); \
157         else rn += NEXT_OFF(rn); \
158 } STMT_END 
159
160 static void restore_pos(pTHX_ void *arg);
161
162 STATIC CHECKPOINT
163 S_regcppush(pTHX_ I32 parenfloor)
164 {
165     int retval = PL_savestack_ix;
166 #define REGCP_PAREN_ELEMS 4
167     int paren_elems_to_push = (PL_regsize - parenfloor) * REGCP_PAREN_ELEMS;
168     int p;
169
170     if (paren_elems_to_push < 0)
171         Perl_croak(aTHX_ "panic: paren_elems_to_push < 0");
172
173 #define REGCP_OTHER_ELEMS 6
174     SSCHECK(paren_elems_to_push + REGCP_OTHER_ELEMS);
175     for (p = PL_regsize; p > parenfloor; p--) {
176 /* REGCP_PARENS_ELEMS are pushed per pairs of parentheses. */
177         SSPUSHINT(PL_regendp[p]);
178         SSPUSHINT(PL_regstartp[p]);
179         SSPUSHPTR(PL_reg_start_tmp[p]);
180         SSPUSHINT(p);
181     }
182 /* REGCP_OTHER_ELEMS are pushed in any case, parentheses or no. */
183     SSPUSHINT(PL_regsize);
184     SSPUSHINT(*PL_reglastparen);
185     SSPUSHINT(*PL_reglastcloseparen);
186     SSPUSHPTR(PL_reginput);
187 #define REGCP_FRAME_ELEMS 2
188 /* REGCP_FRAME_ELEMS are part of the REGCP_OTHER_ELEMS and
189  * are needed for the regexp context stack bookkeeping. */
190     SSPUSHINT(paren_elems_to_push + REGCP_OTHER_ELEMS - REGCP_FRAME_ELEMS);
191     SSPUSHINT(SAVEt_REGCONTEXT); /* Magic cookie. */
192
193     return retval;
194 }
195
196 /* These are needed since we do not localize EVAL nodes: */
197 #  define REGCP_SET(cp)  DEBUG_r(PerlIO_printf(Perl_debug_log,          \
198                              "  Setting an EVAL scope, savestack=%"IVdf"\n",    \
199                              (IV)PL_savestack_ix)); cp = PL_savestack_ix
200
201 #  define REGCP_UNWIND(cp)  DEBUG_r(cp != PL_savestack_ix ?             \
202                                 PerlIO_printf(Perl_debug_log,           \
203                                 "  Clearing an EVAL scope, savestack=%"IVdf"..%"IVdf"\n", \
204                                 (IV)(cp), (IV)PL_savestack_ix) : 0); regcpblow(cp)
205
206 STATIC char *
207 S_regcppop(pTHX)
208 {
209     I32 i;
210     U32 paren = 0;
211     char *input;
212     I32 tmps;
213
214     /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
215     i = SSPOPINT;
216     assert(i == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
217     i = SSPOPINT; /* Parentheses elements to pop. */
218     input = (char *) SSPOPPTR;
219     *PL_reglastcloseparen = SSPOPINT;
220     *PL_reglastparen = SSPOPINT;
221     PL_regsize = SSPOPINT;
222
223     /* Now restore the parentheses context. */
224     for (i -= (REGCP_OTHER_ELEMS - REGCP_FRAME_ELEMS);
225          i > 0; i -= REGCP_PAREN_ELEMS) {
226         paren = (U32)SSPOPINT;
227         PL_reg_start_tmp[paren] = (char *) SSPOPPTR;
228         PL_regstartp[paren] = SSPOPINT;
229         tmps = SSPOPINT;
230         if (paren <= *PL_reglastparen)
231             PL_regendp[paren] = tmps;
232         DEBUG_r(
233             PerlIO_printf(Perl_debug_log,
234                           "     restoring \\%"UVuf" to %"IVdf"(%"IVdf")..%"IVdf"%s\n",
235                           (UV)paren, (IV)PL_regstartp[paren],
236                           (IV)(PL_reg_start_tmp[paren] - PL_bostr),
237                           (IV)PL_regendp[paren],
238                           (paren > *PL_reglastparen ? "(no)" : ""));
239         );
240     }
241     DEBUG_r(
242         if ((I32)(*PL_reglastparen + 1) <= PL_regnpar) {
243             PerlIO_printf(Perl_debug_log,
244                           "     restoring \\%"IVdf"..\\%"IVdf" to undef\n",
245                           (IV)(*PL_reglastparen + 1), (IV)PL_regnpar);
246         }
247     );
248 #if 1
249     /* It would seem that the similar code in regtry()
250      * already takes care of this, and in fact it is in
251      * a better location to since this code can #if 0-ed out
252      * but the code in regtry() is needed or otherwise tests
253      * requiring null fields (pat.t#187 and split.t#{13,14}
254      * (as of patchlevel 7877)  will fail.  Then again,
255      * this code seems to be necessary or otherwise
256      * building DynaLoader will fail:
257      * "Error: '*' not in typemap in DynaLoader.xs, line 164"
258      * --jhi */
259     for (paren = *PL_reglastparen + 1; (I32)paren <= PL_regnpar; paren++) {
260         if ((I32)paren > PL_regsize)
261             PL_regstartp[paren] = -1;
262         PL_regendp[paren] = -1;
263     }
264 #endif
265     return input;
266 }
267
268 STATIC char *
269 S_regcp_set_to(pTHX_ I32 ss)
270 {
271     I32 tmp = PL_savestack_ix;
272
273     PL_savestack_ix = ss;
274     regcppop();
275     PL_savestack_ix = tmp;
276     return Nullch;
277 }
278
279 typedef struct re_cc_state
280 {
281     I32 ss;
282     regnode *node;
283     struct re_cc_state *prev;
284     CURCUR *cc;
285     regexp *re;
286 } re_cc_state;
287
288 #define regcpblow(cp) LEAVE_SCOPE(cp)   /* Ignores regcppush()ed data. */
289
290 #define TRYPAREN(paren, n, input) {                             \
291     if (paren) {                                                \
292         if (n) {                                                \
293             PL_regstartp[paren] = HOPc(input, -1) - PL_bostr;   \
294             PL_regendp[paren] = input - PL_bostr;               \
295         }                                                       \
296         else                                                    \
297             PL_regendp[paren] = -1;                             \
298     }                                                           \
299     if (regmatch(next))                                         \
300         sayYES;                                                 \
301     if (paren && n)                                             \
302         PL_regendp[paren] = -1;                                 \
303 }
304
305
306 /*
307  * pregexec and friends
308  */
309
310 /*
311  - pregexec - match a regexp against a string
312  */
313 I32
314 Perl_pregexec(pTHX_ register regexp *prog, char *stringarg, register char *strend,
315          char *strbeg, I32 minend, SV *screamer, U32 nosave)
316 /* strend: pointer to null at end of string */
317 /* strbeg: real beginning of string */
318 /* minend: end of match must be >=minend after stringarg. */
319 /* nosave: For optimizations. */
320 {
321     return
322         regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
323                       nosave ? 0 : REXEC_COPY_STR);
324 }
325
326 STATIC void
327 S_cache_re(pTHX_ regexp *prog)
328 {
329     PL_regprecomp = prog->precomp;              /* Needed for FAIL. */
330 #ifdef DEBUGGING
331     PL_regprogram = prog->program;
332 #endif
333     PL_regnpar = prog->nparens;
334     PL_regdata = prog->data;
335     PL_reg_re = prog;
336 }
337
338 /*
339  * Need to implement the following flags for reg_anch:
340  *
341  * USE_INTUIT_NOML              - Useful to call re_intuit_start() first
342  * USE_INTUIT_ML
343  * INTUIT_AUTORITATIVE_NOML     - Can trust a positive answer
344  * INTUIT_AUTORITATIVE_ML
345  * INTUIT_ONCE_NOML             - Intuit can match in one location only.
346  * INTUIT_ONCE_ML
347  *
348  * Another flag for this function: SECOND_TIME (so that float substrs
349  * with giant delta may be not rechecked).
350  */
351
352 /* Assumptions: if ANCH_GPOS, then strpos is anchored. XXXX Check GPOS logic */
353
354 /* If SCREAM, then SvPVX(sv) should be compatible with strpos and strend.
355    Otherwise, only SvCUR(sv) is used to get strbeg. */
356
357 /* XXXX We assume that strpos is strbeg unless sv. */
358
359 /* XXXX Some places assume that there is a fixed substring.
360         An update may be needed if optimizer marks as "INTUITable"
361         RExen without fixed substrings.  Similarly, it is assumed that
362         lengths of all the strings are no more than minlen, thus they
363         cannot come from lookahead.
364         (Or minlen should take into account lookahead.) */
365
366 /* A failure to find a constant substring means that there is no need to make
367    an expensive call to REx engine, thus we celebrate a failure.  Similarly,
368    finding a substring too deep into the string means that less calls to
369    regtry() should be needed.
370
371    REx compiler's optimizer found 4 possible hints:
372         a) Anchored substring;
373         b) Fixed substring;
374         c) Whether we are anchored (beginning-of-line or \G);
375         d) First node (of those at offset 0) which may distingush positions;
376    We use a)b)d) and multiline-part of c), and try to find a position in the
377    string which does not contradict any of them.
378  */
379
380 /* Most of decisions we do here should have been done at compile time.
381    The nodes of the REx which we used for the search should have been
382    deleted from the finite automaton. */
383
384 char *
385 Perl_re_intuit_start(pTHX_ regexp *prog, SV *sv, char *strpos,
386                      char *strend, U32 flags, re_scream_pos_data *data)
387 {
388     register I32 start_shift = 0;
389     /* Should be nonnegative! */
390     register I32 end_shift   = 0;
391     register char *s;
392     register SV *check;
393     char *strbeg;
394     char *t;
395     int do_utf8 = sv ? SvUTF8(sv) : 0;  /* if no sv we have to assume bytes */
396     I32 ml_anch;
397     register char *other_last = Nullch; /* other substr checked before this */
398     char *check_at = Nullch;            /* check substr found at this pos */
399 #ifdef DEBUGGING
400     char *i_strpos = strpos;
401     SV *dsv = PERL_DEBUG_PAD_ZERO(0);
402 #endif
403     RX_MATCH_UTF8_set(prog,do_utf8);
404
405     if (prog->reganch & ROPT_UTF8) {
406         DEBUG_r(PerlIO_printf(Perl_debug_log,
407                               "UTF-8 regex...\n"));
408         PL_reg_flags |= RF_utf8;
409     }
410
411     DEBUG_r({
412          char *s   = PL_reg_match_utf8 ?
413                          sv_uni_display(dsv, sv, 60, UNI_DISPLAY_REGEX) :
414                          strpos;
415          int   len = PL_reg_match_utf8 ?
416                          strlen(s) : strend - strpos;
417          if (!PL_colorset)
418               reginitcolors();
419          if (PL_reg_match_utf8)
420              DEBUG_r(PerlIO_printf(Perl_debug_log,
421                                    "UTF-8 target...\n"));
422          PerlIO_printf(Perl_debug_log,
423                        "%sGuessing start of match, REx%s `%s%.60s%s%s' against `%s%.*s%s%s'...\n",
424                        PL_colors[4],PL_colors[5],PL_colors[0],
425                        prog->precomp,
426                        PL_colors[1],
427                        (strlen(prog->precomp) > 60 ? "..." : ""),
428                        PL_colors[0],
429                        (int)(len > 60 ? 60 : len),
430                        s, PL_colors[1],
431                        (len > 60 ? "..." : "")
432               );
433     });
434
435     /* CHR_DIST() would be more correct here but it makes things slow. */
436     if (prog->minlen > strend - strpos) {
437         DEBUG_r(PerlIO_printf(Perl_debug_log,
438                               "String too short... [re_intuit_start]\n"));
439         goto fail;
440     }
441     strbeg = (sv && SvPOK(sv)) ? strend - SvCUR(sv) : strpos;
442     PL_regeol = strend;
443     if (do_utf8) {
444         if (!prog->check_utf8 && prog->check_substr)
445             to_utf8_substr(prog);
446         check = prog->check_utf8;
447     } else {
448         if (!prog->check_substr && prog->check_utf8)
449             to_byte_substr(prog);
450         check = prog->check_substr;
451     }
452    if (check == &PL_sv_undef) {
453         DEBUG_r(PerlIO_printf(Perl_debug_log,
454                 "Non-utf string cannot match utf check string\n"));
455         goto fail;
456     }
457     if (prog->reganch & ROPT_ANCH) {    /* Match at beg-of-str or after \n */
458         ml_anch = !( (prog->reganch & ROPT_ANCH_SINGLE)
459                      || ( (prog->reganch & ROPT_ANCH_BOL)
460                           && !PL_multiline ) ); /* Check after \n? */
461
462         if (!ml_anch) {
463           if ( !(prog->reganch & (ROPT_ANCH_GPOS /* Checked by the caller */
464                                   | ROPT_IMPLICIT)) /* not a real BOL */
465                /* SvCUR is not set on references: SvRV and SvPVX overlap */
466                && sv && !SvROK(sv)
467                && (strpos != strbeg)) {
468               DEBUG_r(PerlIO_printf(Perl_debug_log, "Not at start...\n"));
469               goto fail;
470           }
471           if (prog->check_offset_min == prog->check_offset_max &&
472               !(prog->reganch & ROPT_CANY_SEEN)) {
473             /* Substring at constant offset from beg-of-str... */
474             I32 slen;
475
476             s = HOP3c(strpos, prog->check_offset_min, strend);
477             if (SvTAIL(check)) {
478                 slen = SvCUR(check);    /* >= 1 */
479
480                 if ( strend - s > slen || strend - s < slen - 1
481                      || (strend - s == slen && strend[-1] != '\n')) {
482                     DEBUG_r(PerlIO_printf(Perl_debug_log, "String too long...\n"));
483                     goto fail_finish;
484                 }
485                 /* Now should match s[0..slen-2] */
486                 slen--;
487                 if (slen && (*SvPVX(check) != *s
488                              || (slen > 1
489                                  && memNE(SvPVX(check), s, slen)))) {
490                   report_neq:
491                     DEBUG_r(PerlIO_printf(Perl_debug_log, "String not equal...\n"));
492                     goto fail_finish;
493                 }
494             }
495             else if (*SvPVX(check) != *s
496                      || ((slen = SvCUR(check)) > 1
497                          && memNE(SvPVX(check), s, slen)))
498                 goto report_neq;
499             goto success_at_start;
500           }
501         }
502         /* Match is anchored, but substr is not anchored wrt beg-of-str. */
503         s = strpos;
504         start_shift = prog->check_offset_min; /* okay to underestimate on CC */
505         end_shift = prog->minlen - start_shift -
506             CHR_SVLEN(check) + (SvTAIL(check) != 0);
507         if (!ml_anch) {
508             I32 end = prog->check_offset_max + CHR_SVLEN(check)
509                                          - (SvTAIL(check) != 0);
510             I32 eshift = CHR_DIST((U8*)strend, (U8*)s) - end;
511
512             if (end_shift < eshift)
513                 end_shift = eshift;
514         }
515     }
516     else {                              /* Can match at random position */
517         ml_anch = 0;
518         s = strpos;
519         start_shift = prog->check_offset_min; /* okay to underestimate on CC */
520         /* Should be nonnegative! */
521         end_shift = prog->minlen - start_shift -
522             CHR_SVLEN(check) + (SvTAIL(check) != 0);
523     }
524
525 #ifdef DEBUGGING        /* 7/99: reports of failure (with the older version) */
526     if (end_shift < 0)
527         Perl_croak(aTHX_ "panic: end_shift");
528 #endif
529
530   restart:
531     /* Find a possible match in the region s..strend by looking for
532        the "check" substring in the region corrected by start/end_shift. */
533     if (flags & REXEC_SCREAM) {
534         I32 p = -1;                     /* Internal iterator of scream. */
535         I32 *pp = data ? data->scream_pos : &p;
536
537         if (PL_screamfirst[BmRARE(check)] >= 0
538             || ( BmRARE(check) == '\n'
539                  && (BmPREVIOUS(check) == SvCUR(check) - 1)
540                  && SvTAIL(check) ))
541             s = screaminstr(sv, check,
542                             start_shift + (s - strbeg), end_shift, pp, 0);
543         else
544             goto fail_finish;
545         /* we may be pointing at the wrong string */
546         if (s && RX_MATCH_COPIED(prog))
547             s = strbeg + (s - SvPVX(sv));
548         if (data)
549             *data->scream_olds = s;
550     }
551     else if (prog->reganch & ROPT_CANY_SEEN)
552         s = fbm_instr((U8*)(s + start_shift),
553                       (U8*)(strend - end_shift),
554                       check, PL_multiline ? FBMrf_MULTILINE : 0);
555     else
556         s = fbm_instr(HOP3(s, start_shift, strend),
557                       HOP3(strend, -end_shift, strbeg),
558                       check, PL_multiline ? FBMrf_MULTILINE : 0);
559
560     /* Update the count-of-usability, remove useless subpatterns,
561         unshift s.  */
562
563     DEBUG_r(PerlIO_printf(Perl_debug_log, "%s %s substr `%s%.*s%s'%s%s",
564                           (s ? "Found" : "Did not find"),
565                           (check == (do_utf8 ? prog->anchored_utf8 : prog->anchored_substr) ? "anchored" : "floating"),
566                           PL_colors[0],
567                           (int)(SvCUR(check) - (SvTAIL(check)!=0)),
568                           SvPVX(check),
569                           PL_colors[1], (SvTAIL(check) ? "$" : ""),
570                           (s ? " at offset " : "...\n") ) );
571
572     if (!s)
573         goto fail_finish;
574
575     check_at = s;
576
577     /* Finish the diagnostic message */
578     DEBUG_r(PerlIO_printf(Perl_debug_log, "%ld...\n", (long)(s - i_strpos)) );
579
580     /* Got a candidate.  Check MBOL anchoring, and the *other* substr.
581        Start with the other substr.
582        XXXX no SCREAM optimization yet - and a very coarse implementation
583        XXXX /ttx+/ results in anchored=`ttx', floating=`x'.  floating will
584                 *always* match.  Probably should be marked during compile...
585        Probably it is right to do no SCREAM here...
586      */
587
588     if (do_utf8 ? (prog->float_utf8 && prog->anchored_utf8) : (prog->float_substr && prog->anchored_substr)) {
589         /* Take into account the "other" substring. */
590         /* XXXX May be hopelessly wrong for UTF... */
591         if (!other_last)
592             other_last = strpos;
593         if (check == (do_utf8 ? prog->float_utf8 : prog->float_substr)) {
594           do_other_anchored:
595             {
596                 char *last = HOP3c(s, -start_shift, strbeg), *last1, *last2;
597                 char *s1 = s;
598                 SV* must;
599
600                 t = s - prog->check_offset_max;
601                 if (s - strpos > prog->check_offset_max  /* signed-corrected t > strpos */
602                     && (!do_utf8
603                         || ((t = reghopmaybe3_c(s, -(prog->check_offset_max), strpos))
604                             && t > strpos)))
605                     /* EMPTY */;
606                 else
607                     t = strpos;
608                 t = HOP3c(t, prog->anchored_offset, strend);
609                 if (t < other_last)     /* These positions already checked */
610                     t = other_last;
611                 last2 = last1 = HOP3c(strend, -prog->minlen, strbeg);
612                 if (last < last1)
613                     last1 = last;
614  /* XXXX It is not documented what units *_offsets are in.  Assume bytes.  */
615                 /* On end-of-str: see comment below. */
616                 must = do_utf8 ? prog->anchored_utf8 : prog->anchored_substr;
617                 if (must == &PL_sv_undef) {
618                     s = (char*)NULL;
619                     DEBUG_r(must = prog->anchored_utf8);        /* for debug */
620                 }
621                 else
622                     s = fbm_instr(
623                         (unsigned char*)t,
624                         HOP3(HOP3(last1, prog->anchored_offset, strend)
625                                 + SvCUR(must), -(SvTAIL(must)!=0), strbeg),
626                         must,
627                         PL_multiline ? FBMrf_MULTILINE : 0
628                     );
629                 DEBUG_r(PerlIO_printf(Perl_debug_log,
630                         "%s anchored substr `%s%.*s%s'%s",
631                         (s ? "Found" : "Contradicts"),
632                         PL_colors[0],
633                           (int)(SvCUR(must)
634                           - (SvTAIL(must)!=0)),
635                           SvPVX(must),
636                           PL_colors[1], (SvTAIL(must) ? "$" : "")));
637                 if (!s) {
638                     if (last1 >= last2) {
639                         DEBUG_r(PerlIO_printf(Perl_debug_log,
640                                                 ", giving up...\n"));
641                         goto fail_finish;
642                     }
643                     DEBUG_r(PerlIO_printf(Perl_debug_log,
644                         ", trying floating at offset %ld...\n",
645                         (long)(HOP3c(s1, 1, strend) - i_strpos)));
646                     other_last = HOP3c(last1, prog->anchored_offset+1, strend);
647                     s = HOP3c(last, 1, strend);
648                     goto restart;
649                 }
650                 else {
651                     DEBUG_r(PerlIO_printf(Perl_debug_log, " at offset %ld...\n",
652                           (long)(s - i_strpos)));
653                     t = HOP3c(s, -prog->anchored_offset, strbeg);
654                     other_last = HOP3c(s, 1, strend);
655                     s = s1;
656                     if (t == strpos)
657                         goto try_at_start;
658                     goto try_at_offset;
659                 }
660             }
661         }
662         else {          /* Take into account the floating substring. */
663             char *last, *last1;
664             char *s1 = s;
665             SV* must;
666
667             t = HOP3c(s, -start_shift, strbeg);
668             last1 = last =
669                 HOP3c(strend, -prog->minlen + prog->float_min_offset, strbeg);
670             if (CHR_DIST((U8*)last, (U8*)t) > prog->float_max_offset)
671                 last = HOP3c(t, prog->float_max_offset, strend);
672             s = HOP3c(t, prog->float_min_offset, strend);
673             if (s < other_last)
674                 s = other_last;
675  /* XXXX It is not documented what units *_offsets are in.  Assume bytes.  */
676             must = do_utf8 ? prog->float_utf8 : prog->float_substr;
677             /* fbm_instr() takes into account exact value of end-of-str
678                if the check is SvTAIL(ed).  Since false positives are OK,
679                and end-of-str is not later than strend we are OK. */
680             if (must == &PL_sv_undef) {
681                 s = (char*)NULL;
682                 DEBUG_r(must = prog->float_utf8);       /* for debug message */
683             }
684             else
685                 s = fbm_instr((unsigned char*)s,
686                               (unsigned char*)last + SvCUR(must)
687                                   - (SvTAIL(must)!=0),
688                               must, PL_multiline ? FBMrf_MULTILINE : 0);
689             DEBUG_r(PerlIO_printf(Perl_debug_log, "%s floating substr `%s%.*s%s'%s",
690                     (s ? "Found" : "Contradicts"),
691                     PL_colors[0],
692                       (int)(SvCUR(must) - (SvTAIL(must)!=0)),
693                       SvPVX(must),
694                       PL_colors[1], (SvTAIL(must) ? "$" : "")));
695             if (!s) {
696                 if (last1 == last) {
697                     DEBUG_r(PerlIO_printf(Perl_debug_log,
698                                             ", giving up...\n"));
699                     goto fail_finish;
700                 }
701                 DEBUG_r(PerlIO_printf(Perl_debug_log,
702                     ", trying anchored starting at offset %ld...\n",
703                     (long)(s1 + 1 - i_strpos)));
704                 other_last = last;
705                 s = HOP3c(t, 1, strend);
706                 goto restart;
707             }
708             else {
709                 DEBUG_r(PerlIO_printf(Perl_debug_log, " at offset %ld...\n",
710                       (long)(s - i_strpos)));
711                 other_last = s; /* Fix this later. --Hugo */
712                 s = s1;
713                 if (t == strpos)
714                     goto try_at_start;
715                 goto try_at_offset;
716             }
717         }
718     }
719
720     t = s - prog->check_offset_max;
721     if (s - strpos > prog->check_offset_max  /* signed-corrected t > strpos */
722         && (!do_utf8
723             || ((t = reghopmaybe3_c(s, -prog->check_offset_max, strpos))
724                  && t > strpos))) {
725         /* Fixed substring is found far enough so that the match
726            cannot start at strpos. */
727       try_at_offset:
728         if (ml_anch && t[-1] != '\n') {
729             /* Eventually fbm_*() should handle this, but often
730                anchored_offset is not 0, so this check will not be wasted. */
731             /* XXXX In the code below we prefer to look for "^" even in
732                presence of anchored substrings.  And we search even
733                beyond the found float position.  These pessimizations
734                are historical artefacts only.  */
735           find_anchor:
736             while (t < strend - prog->minlen) {
737                 if (*t == '\n') {
738                     if (t < check_at - prog->check_offset_min) {
739                         if (do_utf8 ? prog->anchored_utf8 : prog->anchored_substr) {
740                             /* Since we moved from the found position,
741                                we definitely contradict the found anchored
742                                substr.  Due to the above check we do not
743                                contradict "check" substr.
744                                Thus we can arrive here only if check substr
745                                is float.  Redo checking for "other"=="fixed".
746                              */
747                             strpos = t + 1;                     
748                             DEBUG_r(PerlIO_printf(Perl_debug_log, "Found /%s^%s/m at offset %ld, rescanning for anchored from offset %ld...\n",
749                                 PL_colors[0],PL_colors[1], (long)(strpos - i_strpos), (long)(strpos - i_strpos + prog->anchored_offset)));
750                             goto do_other_anchored;
751                         }
752                         /* We don't contradict the found floating substring. */
753                         /* XXXX Why not check for STCLASS? */
754                         s = t + 1;
755                         DEBUG_r(PerlIO_printf(Perl_debug_log, "Found /%s^%s/m at offset %ld...\n",
756                             PL_colors[0],PL_colors[1], (long)(s - i_strpos)));
757                         goto set_useful;
758                     }
759                     /* Position contradicts check-string */
760                     /* XXXX probably better to look for check-string
761                        than for "\n", so one should lower the limit for t? */
762                     DEBUG_r(PerlIO_printf(Perl_debug_log, "Found /%s^%s/m, restarting lookup for check-string at offset %ld...\n",
763                         PL_colors[0],PL_colors[1], (long)(t + 1 - i_strpos)));
764                     other_last = strpos = s = t + 1;
765                     goto restart;
766                 }
767                 t++;
768             }
769             DEBUG_r(PerlIO_printf(Perl_debug_log, "Did not find /%s^%s/m...\n",
770                         PL_colors[0],PL_colors[1]));
771             goto fail_finish;
772         }
773         else {
774             DEBUG_r(PerlIO_printf(Perl_debug_log, "Starting position does not contradict /%s^%s/m...\n",
775                         PL_colors[0],PL_colors[1]));
776         }
777         s = t;
778       set_useful:
779         ++BmUSEFUL(do_utf8 ? prog->check_utf8 : prog->check_substr);    /* hooray/5 */
780     }
781     else {
782         /* The found string does not prohibit matching at strpos,
783            - no optimization of calling REx engine can be performed,
784            unless it was an MBOL and we are not after MBOL,
785            or a future STCLASS check will fail this. */
786       try_at_start:
787         /* Even in this situation we may use MBOL flag if strpos is offset
788            wrt the start of the string. */
789         if (ml_anch && sv && !SvROK(sv) /* See prev comment on SvROK */
790             && (strpos != strbeg) && strpos[-1] != '\n'
791             /* May be due to an implicit anchor of m{.*foo}  */
792             && !(prog->reganch & ROPT_IMPLICIT))
793         {
794             t = strpos;
795             goto find_anchor;
796         }
797         DEBUG_r( if (ml_anch)
798             PerlIO_printf(Perl_debug_log, "Position at offset %ld does not contradict /%s^%s/m...\n",
799                         (long)(strpos - i_strpos), PL_colors[0],PL_colors[1]);
800         );
801       success_at_start:
802         if (!(prog->reganch & ROPT_NAUGHTY)     /* XXXX If strpos moved? */
803             && (do_utf8 ? (
804                 prog->check_utf8                /* Could be deleted already */
805                 && --BmUSEFUL(prog->check_utf8) < 0
806                 && (prog->check_utf8 == prog->float_utf8)
807             ) : (
808                 prog->check_substr              /* Could be deleted already */
809                 && --BmUSEFUL(prog->check_substr) < 0
810                 && (prog->check_substr == prog->float_substr)
811             )))
812         {
813             /* If flags & SOMETHING - do not do it many times on the same match */
814             DEBUG_r(PerlIO_printf(Perl_debug_log, "... Disabling check substring...\n"));
815             SvREFCNT_dec(do_utf8 ? prog->check_utf8 : prog->check_substr);
816             if (do_utf8 ? prog->check_substr : prog->check_utf8)
817                 SvREFCNT_dec(do_utf8 ? prog->check_substr : prog->check_utf8);
818             prog->check_substr = prog->check_utf8 = Nullsv;     /* disable */
819             prog->float_substr = prog->float_utf8 = Nullsv;     /* clear */
820             check = Nullsv;                     /* abort */
821             s = strpos;
822             /* XXXX This is a remnant of the old implementation.  It
823                     looks wasteful, since now INTUIT can use many
824                     other heuristics. */
825             prog->reganch &= ~RE_USE_INTUIT;
826         }
827         else
828             s = strpos;
829     }
830
831     /* Last resort... */
832     /* XXXX BmUSEFUL already changed, maybe multiple change is meaningful... */
833     if (prog->regstclass) {
834         /* minlen == 0 is possible if regstclass is \b or \B,
835            and the fixed substr is ''$.
836            Since minlen is already taken into account, s+1 is before strend;
837            accidentally, minlen >= 1 guaranties no false positives at s + 1
838            even for \b or \B.  But (minlen? 1 : 0) below assumes that
839            regstclass does not come from lookahead...  */
840         /* If regstclass takes bytelength more than 1: If charlength==1, OK.
841            This leaves EXACTF only, which is dealt with in find_byclass().  */
842         U8* str = (U8*)STRING(prog->regstclass);
843         int cl_l = (PL_regkind[(U8)OP(prog->regstclass)] == EXACT
844                     ? CHR_DIST(str+STR_LEN(prog->regstclass), str)
845                     : 1);
846         char *endpos = (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
847                 ? HOP3c(s, (prog->minlen ? cl_l : 0), strend)
848                 : (prog->float_substr || prog->float_utf8
849                    ? HOP3c(HOP3c(check_at, -start_shift, strbeg),
850                            cl_l, strend)
851                    : strend);
852         char *startpos = strbeg;
853
854         t = s;
855         cache_re(prog);
856         s = find_byclass(prog, prog->regstclass, s, endpos, startpos, 1);
857         if (!s) {
858 #ifdef DEBUGGING
859             char *what = 0;
860 #endif
861             if (endpos == strend) {
862                 DEBUG_r( PerlIO_printf(Perl_debug_log,
863                                 "Could not match STCLASS...\n") );
864                 goto fail;
865             }
866             DEBUG_r( PerlIO_printf(Perl_debug_log,
867                                    "This position contradicts STCLASS...\n") );
868             if ((prog->reganch & ROPT_ANCH) && !ml_anch)
869                 goto fail;
870             /* Contradict one of substrings */
871             if (prog->anchored_substr || prog->anchored_utf8) {
872                 if ((do_utf8 ? prog->anchored_utf8 : prog->anchored_substr) == check) {
873                     DEBUG_r( what = "anchored" );
874                   hop_and_restart:
875                     s = HOP3c(t, 1, strend);
876                     if (s + start_shift + end_shift > strend) {
877                         /* XXXX Should be taken into account earlier? */
878                         DEBUG_r( PerlIO_printf(Perl_debug_log,
879                                                "Could not match STCLASS...\n") );
880                         goto fail;
881                     }
882                     if (!check)
883                         goto giveup;
884                     DEBUG_r( PerlIO_printf(Perl_debug_log,
885                                 "Looking for %s substr starting at offset %ld...\n",
886                                  what, (long)(s + start_shift - i_strpos)) );
887                     goto restart;
888                 }
889                 /* Have both, check_string is floating */
890                 if (t + start_shift >= check_at) /* Contradicts floating=check */
891                     goto retry_floating_check;
892                 /* Recheck anchored substring, but not floating... */
893                 s = check_at;
894                 if (!check)
895                     goto giveup;
896                 DEBUG_r( PerlIO_printf(Perl_debug_log,
897                           "Looking for anchored substr starting at offset %ld...\n",
898                           (long)(other_last - i_strpos)) );
899                 goto do_other_anchored;
900             }
901             /* Another way we could have checked stclass at the
902                current position only: */
903             if (ml_anch) {
904                 s = t = t + 1;
905                 if (!check)
906                     goto giveup;
907                 DEBUG_r( PerlIO_printf(Perl_debug_log,
908                           "Looking for /%s^%s/m starting at offset %ld...\n",
909                           PL_colors[0],PL_colors[1], (long)(t - i_strpos)) );
910                 goto try_at_offset;
911             }
912             if (!(do_utf8 ? prog->float_utf8 : prog->float_substr))     /* Could have been deleted */
913                 goto fail;
914             /* Check is floating subtring. */
915           retry_floating_check:
916             t = check_at - start_shift;
917             DEBUG_r( what = "floating" );
918             goto hop_and_restart;
919         }
920         if (t != s) {
921             DEBUG_r(PerlIO_printf(Perl_debug_log,
922                         "By STCLASS: moving %ld --> %ld\n",
923                                   (long)(t - i_strpos), (long)(s - i_strpos))
924                    );
925         }
926         else {
927             DEBUG_r(PerlIO_printf(Perl_debug_log,
928                                   "Does not contradict STCLASS...\n"); 
929                    );
930         }
931     }
932   giveup:
933     DEBUG_r(PerlIO_printf(Perl_debug_log, "%s%s:%s match at offset %ld\n",
934                           PL_colors[4], (check ? "Guessed" : "Giving up"),
935                           PL_colors[5], (long)(s - i_strpos)) );
936     return s;
937
938   fail_finish:                          /* Substring not found */
939     if (prog->check_substr || prog->check_utf8)         /* could be removed already */
940         BmUSEFUL(do_utf8 ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
941   fail:
942     DEBUG_r(PerlIO_printf(Perl_debug_log, "%sMatch rejected by optimizer%s\n",
943                           PL_colors[4],PL_colors[5]));
944     return Nullch;
945 }
946
947 /* We know what class REx starts with.  Try to find this position... */
948 STATIC char *
949 S_find_byclass(pTHX_ regexp * prog, regnode *c, char *s, char *strend, char *startpos, I32 norun)
950 {
951         I32 doevery = (prog->reganch & ROPT_SKIP) == 0;
952         char *m;
953         STRLEN ln;
954         unsigned int c1;
955         unsigned int c2;
956         char *e;
957         register I32 tmp = 1;   /* Scratch variable? */
958         register bool do_utf8 = PL_reg_match_utf8;
959
960         /* We know what class it must start with. */
961         switch (OP(c)) {
962         case ANYOF:
963             if (do_utf8) {
964                  while (s < strend) {
965                       if ((ANYOF_FLAGS(c) & ANYOF_UNICODE) ||
966                           !UTF8_IS_INVARIANT((U8)s[0]) ?
967                           reginclass(c, (U8*)s, 0, do_utf8) :
968                           REGINCLASS(c, (U8*)s)) {
969                            if (tmp && (norun || regtry(prog, s)))
970                                 goto got_it;
971                            else
972                                 tmp = doevery;
973                       }
974                       else 
975                            tmp = 1;
976                       s += UTF8SKIP(s);
977                  }
978             }
979             else {
980                  while (s < strend) {
981                       STRLEN skip = 1;
982
983                       if (REGINCLASS(c, (U8*)s) ||
984                           (ANYOF_FOLD_SHARP_S(c, s, strend) &&
985                            /* The assignment of 2 is intentional:
986                             * for the folded sharp s, the skip is 2. */
987                            (skip = SHARP_S_SKIP))) {
988                            if (tmp && (norun || regtry(prog, s)))
989                                 goto got_it;
990                            else
991                                 tmp = doevery;
992                       }
993                       else 
994                            tmp = 1;
995                       s += skip;
996                  }
997             }
998             break;
999         case CANY:
1000             while (s < strend) {
1001                 if (tmp && (norun || regtry(prog, s)))
1002                     goto got_it;
1003                 else
1004                     tmp = doevery;
1005                 s++;
1006             }
1007             break;
1008         case EXACTF:
1009             m = STRING(c);
1010             ln = STR_LEN(c);
1011             if (UTF) {
1012                 STRLEN ulen1, ulen2;
1013                 U8 tmpbuf1[UTF8_MAXLEN_UCLC+1];
1014                 U8 tmpbuf2[UTF8_MAXLEN_UCLC+1];
1015
1016                 to_utf8_lower((U8*)m, tmpbuf1, &ulen1);
1017                 to_utf8_upper((U8*)m, tmpbuf2, &ulen2);
1018
1019                 c1 = utf8n_to_uvchr(tmpbuf1, UTF8_MAXLEN_UCLC, 
1020                                     0, ckWARN(WARN_UTF8) ? 0 : UTF8_ALLOW_ANY);
1021                 c2 = utf8n_to_uvchr(tmpbuf2, UTF8_MAXLEN_UCLC,
1022                                     0, ckWARN(WARN_UTF8) ? 0 : UTF8_ALLOW_ANY);
1023             }
1024             else {
1025                 c1 = *(U8*)m;
1026                 c2 = PL_fold[c1];
1027             }
1028             goto do_exactf;
1029         case EXACTFL:
1030             m = STRING(c);
1031             ln = STR_LEN(c);
1032             c1 = *(U8*)m;
1033             c2 = PL_fold_locale[c1];
1034           do_exactf:
1035             e = HOP3c(strend, -(I32)ln, s);
1036
1037             if (norun && e < s)
1038                 e = s;                  /* Due to minlen logic of intuit() */
1039
1040             /* The idea in the EXACTF* cases is to first find the
1041              * first character of the EXACTF* node and then, if
1042              * necessary, case-insensitively compare the full
1043              * text of the node.  The c1 and c2 are the first
1044              * characters (though in Unicode it gets a bit
1045              * more complicated because there are more cases
1046              * than just upper and lower: one needs to use
1047              * the so-called folding case for case-insensitive
1048              * matching (called "loose matching" in Unicode).
1049              * ibcmp_utf8() will do just that. */
1050
1051             if (do_utf8) {
1052                 UV c, f;
1053                 U8 tmpbuf [UTF8_MAXLEN+1];
1054                 U8 foldbuf[UTF8_MAXLEN_FOLD+1];
1055                 STRLEN len, foldlen;
1056                 
1057                 if (c1 == c2) {
1058                     while (s <= e) {
1059                         c = utf8n_to_uvchr((U8*)s, UTF8_MAXLEN, &len,
1060                                            ckWARN(WARN_UTF8) ?
1061                                            0 : UTF8_ALLOW_ANY);
1062                         if ( c == c1
1063                              && (ln == len ||
1064                                  ibcmp_utf8(s, (char **)0, 0,  do_utf8,
1065                                             m, (char **)0, ln, (bool)UTF))
1066                              && (norun || regtry(prog, s)) )
1067                             goto got_it;
1068                         else {
1069                              uvchr_to_utf8(tmpbuf, c);
1070                              f = to_utf8_fold(tmpbuf, foldbuf, &foldlen);
1071                              if ( f != c
1072                                   && (f == c1 || f == c2)
1073                                   && (ln == foldlen ||
1074                                       !ibcmp_utf8((char *) foldbuf,
1075                                                   (char **)0, foldlen, do_utf8,
1076                                                   m,
1077                                                   (char **)0, ln, (bool)UTF))
1078                                   && (norun || regtry(prog, s)) )
1079                                   goto got_it;
1080                         }
1081                         s += len;
1082                     }
1083                 }
1084                 else {
1085                     while (s <= e) {
1086                       c = utf8n_to_uvchr((U8*)s, UTF8_MAXLEN, &len,
1087                                            ckWARN(WARN_UTF8) ?
1088                                            0 : UTF8_ALLOW_ANY);
1089
1090                         /* Handle some of the three Greek sigmas cases.
1091                          * Note that not all the possible combinations
1092                          * are handled here: some of them are handled
1093                          * by the standard folding rules, and some of
1094                          * them (the character class or ANYOF cases)
1095                          * are handled during compiletime in
1096                          * regexec.c:S_regclass(). */
1097                         if (c == (UV)UNICODE_GREEK_CAPITAL_LETTER_SIGMA ||
1098                             c == (UV)UNICODE_GREEK_SMALL_LETTER_FINAL_SIGMA)
1099                             c = (UV)UNICODE_GREEK_SMALL_LETTER_SIGMA;
1100
1101                         if ( (c == c1 || c == c2)
1102                              && (ln == len ||
1103                                  ibcmp_utf8(s, (char **)0, 0,  do_utf8,
1104                                             m, (char **)0, ln, (bool)UTF))
1105                              && (norun || regtry(prog, s)) )
1106                             goto got_it;
1107                         else {
1108                              uvchr_to_utf8(tmpbuf, c);
1109                              f = to_utf8_fold(tmpbuf, foldbuf, &foldlen);
1110                              if ( f != c
1111                                   && (f == c1 || f == c2)
1112                                   && (ln == foldlen ||
1113                                       !ibcmp_utf8((char *) foldbuf,
1114                                                   (char **)0, foldlen, do_utf8,
1115                                                   m,
1116                                                   (char **)0, ln, (bool)UTF))
1117                                   && (norun || regtry(prog, s)) )
1118                                   goto got_it;
1119                         }
1120                         s += len;
1121                     }
1122                 }
1123             }
1124             else {
1125                 if (c1 == c2)
1126                     while (s <= e) {
1127                         if ( *(U8*)s == c1
1128                              && (ln == 1 || !(OP(c) == EXACTF
1129                                               ? ibcmp(s, m, ln)
1130                                               : ibcmp_locale(s, m, ln)))
1131                              && (norun || regtry(prog, s)) )
1132                             goto got_it;
1133                         s++;
1134                     }
1135                 else
1136                     while (s <= e) {
1137                         if ( (*(U8*)s == c1 || *(U8*)s == c2)
1138                              && (ln == 1 || !(OP(c) == EXACTF
1139                                               ? ibcmp(s, m, ln)
1140                                               : ibcmp_locale(s, m, ln)))
1141                              && (norun || regtry(prog, s)) )
1142                             goto got_it;
1143                         s++;
1144                     }
1145             }
1146             break;
1147         case BOUNDL:
1148             PL_reg_flags |= RF_tainted;
1149             /* FALL THROUGH */
1150         case BOUND:
1151             if (do_utf8) {
1152                 if (s == PL_bostr)
1153                     tmp = '\n';
1154                 else {
1155                     U8 *r = reghop3((U8*)s, -1, (U8*)PL_bostr);
1156                 
1157                     tmp = utf8n_to_uvchr(r, UTF8SKIP(r), 0, 0);
1158                 }
1159                 tmp = ((OP(c) == BOUND ?
1160                         isALNUM_uni(tmp) : isALNUM_LC_uvchr(UNI_TO_NATIVE(tmp))) != 0);
1161                 LOAD_UTF8_CHARCLASS(alnum,"a");
1162                 while (s < strend) {
1163                     if (tmp == !(OP(c) == BOUND ?
1164                                  swash_fetch(PL_utf8_alnum, (U8*)s, do_utf8) :
1165                                  isALNUM_LC_utf8((U8*)s)))
1166                     {
1167                         tmp = !tmp;
1168                         if ((norun || regtry(prog, s)))
1169                             goto got_it;
1170                     }
1171                     s += UTF8SKIP(s);
1172                 }
1173             }
1174             else {
1175                 tmp = (s != PL_bostr) ? UCHARAT(s - 1) : '\n';
1176                 tmp = ((OP(c) == BOUND ? isALNUM(tmp) : isALNUM_LC(tmp)) != 0);
1177                 while (s < strend) {
1178                     if (tmp ==
1179                         !(OP(c) == BOUND ? isALNUM(*s) : isALNUM_LC(*s))) {
1180                         tmp = !tmp;
1181                         if ((norun || regtry(prog, s)))
1182                             goto got_it;
1183                     }
1184                     s++;
1185                 }
1186             }
1187             if ((!prog->minlen && tmp) && (norun || regtry(prog, s)))
1188                 goto got_it;
1189             break;
1190         case NBOUNDL:
1191             PL_reg_flags |= RF_tainted;
1192             /* FALL THROUGH */
1193         case NBOUND:
1194             if (do_utf8) {
1195                 if (s == PL_bostr)
1196                     tmp = '\n';
1197                 else {
1198                     U8 *r = reghop3((U8*)s, -1, (U8*)PL_bostr);
1199                 
1200                     tmp = utf8n_to_uvchr(r, UTF8SKIP(r), 0, 0);
1201                 }
1202                 tmp = ((OP(c) == NBOUND ?
1203                         isALNUM_uni(tmp) : isALNUM_LC_uvchr(UNI_TO_NATIVE(tmp))) != 0);
1204                 LOAD_UTF8_CHARCLASS(alnum,"a");
1205                 while (s < strend) {
1206                     if (tmp == !(OP(c) == NBOUND ?
1207                                  swash_fetch(PL_utf8_alnum, (U8*)s, do_utf8) :
1208                                  isALNUM_LC_utf8((U8*)s)))
1209                         tmp = !tmp;
1210                     else if ((norun || regtry(prog, s)))
1211                         goto got_it;
1212                     s += UTF8SKIP(s);
1213                 }
1214             }
1215             else {
1216                 tmp = (s != PL_bostr) ? UCHARAT(s - 1) : '\n';
1217                 tmp = ((OP(c) == NBOUND ?
1218                         isALNUM(tmp) : isALNUM_LC(tmp)) != 0);
1219                 while (s < strend) {
1220                     if (tmp ==
1221                         !(OP(c) == NBOUND ? isALNUM(*s) : isALNUM_LC(*s)))
1222                         tmp = !tmp;
1223                     else if ((norun || regtry(prog, s)))
1224                         goto got_it;
1225                     s++;
1226                 }
1227             }
1228             if ((!prog->minlen && !tmp) && (norun || regtry(prog, s)))
1229                 goto got_it;
1230             break;
1231         case ALNUM:
1232             if (do_utf8) {
1233                 LOAD_UTF8_CHARCLASS(alnum,"a");
1234                 while (s < strend) {
1235                     if (swash_fetch(PL_utf8_alnum, (U8*)s, do_utf8)) {
1236                         if (tmp && (norun || regtry(prog, s)))
1237                             goto got_it;
1238                         else
1239                             tmp = doevery;
1240                     }
1241                     else
1242                         tmp = 1;
1243                     s += UTF8SKIP(s);
1244                 }
1245             }
1246             else {
1247                 while (s < strend) {
1248                     if (isALNUM(*s)) {
1249                         if (tmp && (norun || regtry(prog, s)))
1250                             goto got_it;
1251                         else
1252                             tmp = doevery;
1253                     }
1254                     else
1255                         tmp = 1;
1256                     s++;
1257                 }
1258             }
1259             break;
1260         case ALNUML:
1261             PL_reg_flags |= RF_tainted;
1262             if (do_utf8) {
1263                 while (s < strend) {
1264                     if (isALNUM_LC_utf8((U8*)s)) {
1265                         if (tmp && (norun || regtry(prog, s)))
1266                             goto got_it;
1267                         else
1268                             tmp = doevery;
1269                     }
1270                     else
1271                         tmp = 1;
1272                     s += UTF8SKIP(s);
1273                 }
1274             }
1275             else {
1276                 while (s < strend) {
1277                     if (isALNUM_LC(*s)) {
1278                         if (tmp && (norun || regtry(prog, s)))
1279                             goto got_it;
1280                         else
1281                             tmp = doevery;
1282                     }
1283                     else
1284                         tmp = 1;
1285                     s++;
1286                 }
1287             }
1288             break;
1289         case NALNUM:
1290             if (do_utf8) {
1291                 LOAD_UTF8_CHARCLASS(alnum,"a");
1292                 while (s < strend) {
1293                     if (!swash_fetch(PL_utf8_alnum, (U8*)s, do_utf8)) {
1294                         if (tmp && (norun || regtry(prog, s)))
1295                             goto got_it;
1296                         else
1297                             tmp = doevery;
1298                     }
1299                     else
1300                         tmp = 1;
1301                     s += UTF8SKIP(s);
1302                 }
1303             }
1304             else {
1305                 while (s < strend) {
1306                     if (!isALNUM(*s)) {
1307                         if (tmp && (norun || regtry(prog, s)))
1308                             goto got_it;
1309                         else
1310                             tmp = doevery;
1311                     }
1312                     else
1313                         tmp = 1;
1314                     s++;
1315                 }
1316             }
1317             break;
1318         case NALNUML:
1319             PL_reg_flags |= RF_tainted;
1320             if (do_utf8) {
1321                 while (s < strend) {
1322                     if (!isALNUM_LC_utf8((U8*)s)) {
1323                         if (tmp && (norun || regtry(prog, s)))
1324                             goto got_it;
1325                         else
1326                             tmp = doevery;
1327                     }
1328                     else
1329                         tmp = 1;
1330                     s += UTF8SKIP(s);
1331                 }
1332             }
1333             else {
1334                 while (s < strend) {
1335                     if (!isALNUM_LC(*s)) {
1336                         if (tmp && (norun || regtry(prog, s)))
1337                             goto got_it;
1338                         else
1339                             tmp = doevery;
1340                     }
1341                     else
1342                         tmp = 1;
1343                     s++;
1344                 }
1345             }
1346             break;
1347         case SPACE:
1348             if (do_utf8) {
1349                 LOAD_UTF8_CHARCLASS(space," ");
1350                 while (s < strend) {
1351                     if (*s == ' ' || swash_fetch(PL_utf8_space,(U8*)s, do_utf8)) {
1352                         if (tmp && (norun || regtry(prog, s)))
1353                             goto got_it;
1354                         else
1355                             tmp = doevery;
1356                     }
1357                     else
1358                         tmp = 1;
1359                     s += UTF8SKIP(s);
1360                 }
1361             }
1362             else {
1363                 while (s < strend) {
1364                     if (isSPACE(*s)) {
1365                         if (tmp && (norun || regtry(prog, s)))
1366                             goto got_it;
1367                         else
1368                             tmp = doevery;
1369                     }
1370                     else
1371                         tmp = 1;
1372                     s++;
1373                 }
1374             }
1375             break;
1376         case SPACEL:
1377             PL_reg_flags |= RF_tainted;
1378             if (do_utf8) {
1379                 while (s < strend) {
1380                     if (*s == ' ' || isSPACE_LC_utf8((U8*)s)) {
1381                         if (tmp && (norun || regtry(prog, s)))
1382                             goto got_it;
1383                         else
1384                             tmp = doevery;
1385                     }
1386                     else
1387                         tmp = 1;
1388                     s += UTF8SKIP(s);
1389                 }
1390             }
1391             else {
1392                 while (s < strend) {
1393                     if (isSPACE_LC(*s)) {
1394                         if (tmp && (norun || regtry(prog, s)))
1395                             goto got_it;
1396                         else
1397                             tmp = doevery;
1398                     }
1399                     else
1400                         tmp = 1;
1401                     s++;
1402                 }
1403             }
1404             break;
1405         case NSPACE:
1406             if (do_utf8) {
1407                 LOAD_UTF8_CHARCLASS(space," ");
1408                 while (s < strend) {
1409                     if (!(*s == ' ' || swash_fetch(PL_utf8_space,(U8*)s, do_utf8))) {
1410                         if (tmp && (norun || regtry(prog, s)))
1411                             goto got_it;
1412                         else
1413                             tmp = doevery;
1414                     }
1415                     else
1416                         tmp = 1;
1417                     s += UTF8SKIP(s);
1418                 }
1419             }
1420             else {
1421                 while (s < strend) {
1422                     if (!isSPACE(*s)) {
1423                         if (tmp && (norun || regtry(prog, s)))
1424                             goto got_it;
1425                         else
1426                             tmp = doevery;
1427                     }
1428                     else
1429                         tmp = 1;
1430                     s++;
1431                 }
1432             }
1433             break;
1434         case NSPACEL:
1435             PL_reg_flags |= RF_tainted;
1436             if (do_utf8) {
1437                 while (s < strend) {
1438                     if (!(*s == ' ' || isSPACE_LC_utf8((U8*)s))) {
1439                         if (tmp && (norun || regtry(prog, s)))
1440                             goto got_it;
1441                         else
1442                             tmp = doevery;
1443                     }
1444                     else
1445                         tmp = 1;
1446                     s += UTF8SKIP(s);
1447                 }
1448             }
1449             else {
1450                 while (s < strend) {
1451                     if (!isSPACE_LC(*s)) {
1452                         if (tmp && (norun || regtry(prog, s)))
1453                             goto got_it;
1454                         else
1455                             tmp = doevery;
1456                     }
1457                     else
1458                         tmp = 1;
1459                     s++;
1460                 }
1461             }
1462             break;
1463         case DIGIT:
1464             if (do_utf8) {
1465                 LOAD_UTF8_CHARCLASS(digit,"0");
1466                 while (s < strend) {
1467                     if (swash_fetch(PL_utf8_digit,(U8*)s, do_utf8)) {
1468                         if (tmp && (norun || regtry(prog, s)))
1469                             goto got_it;
1470                         else
1471                             tmp = doevery;
1472                     }
1473                     else
1474                         tmp = 1;
1475                     s += UTF8SKIP(s);
1476                 }
1477             }
1478             else {
1479                 while (s < strend) {
1480                     if (isDIGIT(*s)) {
1481                         if (tmp && (norun || regtry(prog, s)))
1482                             goto got_it;
1483                         else
1484                             tmp = doevery;
1485                     }
1486                     else
1487                         tmp = 1;
1488                     s++;
1489                 }
1490             }
1491             break;
1492         case DIGITL:
1493             PL_reg_flags |= RF_tainted;
1494             if (do_utf8) {
1495                 while (s < strend) {
1496                     if (isDIGIT_LC_utf8((U8*)s)) {
1497                         if (tmp && (norun || regtry(prog, s)))
1498                             goto got_it;
1499                         else
1500                             tmp = doevery;
1501                     }
1502                     else
1503                         tmp = 1;
1504                     s += UTF8SKIP(s);
1505                 }
1506             }
1507             else {
1508                 while (s < strend) {
1509                     if (isDIGIT_LC(*s)) {
1510                         if (tmp && (norun || regtry(prog, s)))
1511                             goto got_it;
1512                         else
1513                             tmp = doevery;
1514                     }
1515                     else
1516                         tmp = 1;
1517                     s++;
1518                 }
1519             }
1520             break;
1521         case NDIGIT:
1522             if (do_utf8) {
1523                 LOAD_UTF8_CHARCLASS(digit,"0");
1524                 while (s < strend) {
1525                     if (!swash_fetch(PL_utf8_digit,(U8*)s, do_utf8)) {
1526                         if (tmp && (norun || regtry(prog, s)))
1527                             goto got_it;
1528                         else
1529                             tmp = doevery;
1530                     }
1531                     else
1532                         tmp = 1;
1533                     s += UTF8SKIP(s);
1534                 }
1535             }
1536             else {
1537                 while (s < strend) {
1538                     if (!isDIGIT(*s)) {
1539                         if (tmp && (norun || regtry(prog, s)))
1540                             goto got_it;
1541                         else
1542                             tmp = doevery;
1543                     }
1544                     else
1545                         tmp = 1;
1546                     s++;
1547                 }
1548             }
1549             break;
1550         case NDIGITL:
1551             PL_reg_flags |= RF_tainted;
1552             if (do_utf8) {
1553                 while (s < strend) {
1554                     if (!isDIGIT_LC_utf8((U8*)s)) {
1555                         if (tmp && (norun || regtry(prog, s)))
1556                             goto got_it;
1557                         else
1558                             tmp = doevery;
1559                     }
1560                     else
1561                         tmp = 1;
1562                     s += UTF8SKIP(s);
1563                 }
1564             }
1565             else {
1566                 while (s < strend) {
1567                     if (!isDIGIT_LC(*s)) {
1568                         if (tmp && (norun || regtry(prog, s)))
1569                             goto got_it;
1570                         else
1571                             tmp = doevery;
1572                     }
1573                     else
1574                         tmp = 1;
1575                     s++;
1576                 }
1577             }
1578             break;
1579         default:
1580             Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
1581             break;
1582         }
1583         return 0;
1584       got_it:
1585         return s;
1586 }
1587
1588 /*
1589  - regexec_flags - match a regexp against a string
1590  */
1591 I32
1592 Perl_regexec_flags(pTHX_ register regexp *prog, char *stringarg, register char *strend,
1593               char *strbeg, I32 minend, SV *sv, void *data, U32 flags)
1594 /* strend: pointer to null at end of string */
1595 /* strbeg: real beginning of string */
1596 /* minend: end of match must be >=minend after stringarg. */
1597 /* data: May be used for some additional optimizations. */
1598 /* nosave: For optimizations. */
1599 {
1600     register char *s;
1601     register regnode *c;
1602     register char *startpos = stringarg;
1603     I32 minlen;         /* must match at least this many chars */
1604     I32 dontbother = 0; /* how many characters not to try at end */
1605     /* I32 start_shift = 0; */          /* Offset of the start to find
1606                                          constant substr. */            /* CC */
1607     I32 end_shift = 0;                  /* Same for the end. */         /* CC */
1608     I32 scream_pos = -1;                /* Internal iterator of scream. */
1609     char *scream_olds;
1610     SV* oreplsv = GvSV(PL_replgv);
1611     bool do_utf8 = DO_UTF8(sv);
1612 #ifdef DEBUGGING
1613     SV *dsv0 = PERL_DEBUG_PAD_ZERO(0);
1614     SV *dsv1 = PERL_DEBUG_PAD_ZERO(1);
1615 #endif
1616     RX_MATCH_UTF8_set(prog,do_utf8);
1617
1618     PL_regcc = 0;
1619
1620     cache_re(prog);
1621 #ifdef DEBUGGING
1622     PL_regnarrate = DEBUG_r_TEST;
1623 #endif
1624
1625     /* Be paranoid... */
1626     if (prog == NULL || startpos == NULL) {
1627         Perl_croak(aTHX_ "NULL regexp parameter");
1628         return 0;
1629     }
1630
1631     minlen = prog->minlen;
1632     if (strend - startpos < minlen) {
1633         DEBUG_r(PerlIO_printf(Perl_debug_log,
1634                               "String too short [regexec_flags]...\n"));
1635         goto phooey;
1636     }
1637
1638     /* Check validity of program. */
1639     if (UCHARAT(prog->program) != REG_MAGIC) {
1640         Perl_croak(aTHX_ "corrupted regexp program");
1641     }
1642
1643     PL_reg_flags = 0;
1644     PL_reg_eval_set = 0;
1645     PL_reg_maxiter = 0;
1646
1647     if (prog->reganch & ROPT_UTF8)
1648         PL_reg_flags |= RF_utf8;
1649
1650     /* Mark beginning of line for ^ and lookbehind. */
1651     PL_regbol = startpos;
1652     PL_bostr  = strbeg;
1653     PL_reg_sv = sv;
1654
1655     /* Mark end of line for $ (and such) */
1656     PL_regeol = strend;
1657
1658     /* see how far we have to get to not match where we matched before */
1659     PL_regtill = startpos+minend;
1660
1661     /* We start without call_cc context.  */
1662     PL_reg_call_cc = 0;
1663
1664     /* If there is a "must appear" string, look for it. */
1665     s = startpos;
1666
1667     if (prog->reganch & ROPT_GPOS_SEEN) { /* Need to have PL_reg_ganch */
1668         MAGIC *mg;
1669
1670         if (flags & REXEC_IGNOREPOS)    /* Means: check only at start */
1671             PL_reg_ganch = startpos;
1672         else if (sv && SvTYPE(sv) >= SVt_PVMG
1673                   && SvMAGIC(sv)
1674                   && (mg = mg_find(sv, PERL_MAGIC_regex_global))
1675                   && mg->mg_len >= 0) {
1676             PL_reg_ganch = strbeg + mg->mg_len; /* Defined pos() */
1677             if (prog->reganch & ROPT_ANCH_GPOS) {
1678                 if (s > PL_reg_ganch)
1679                     goto phooey;
1680                 s = PL_reg_ganch;
1681             }
1682         }
1683         else                            /* pos() not defined */
1684             PL_reg_ganch = strbeg;
1685     }
1686
1687     if (!(flags & REXEC_CHECKED) && (prog->check_substr != Nullsv || prog->check_utf8 != Nullsv)) {
1688         re_scream_pos_data d;
1689
1690         d.scream_olds = &scream_olds;
1691         d.scream_pos = &scream_pos;
1692         s = re_intuit_start(prog, sv, s, strend, flags, &d);
1693         if (!s) {
1694             DEBUG_r(PerlIO_printf(Perl_debug_log, "Not present...\n"));
1695             goto phooey;        /* not present */
1696         }
1697     }
1698
1699     DEBUG_r({
1700          char *s0   = UTF ?
1701            pv_uni_display(dsv0, (U8*)prog->precomp, prog->prelen, 60,
1702                           UNI_DISPLAY_REGEX) :
1703            prog->precomp;
1704          int   len0 = UTF ? SvCUR(dsv0) : prog->prelen;
1705          char *s1   = do_utf8 ? sv_uni_display(dsv1, sv, 60,
1706                                                UNI_DISPLAY_REGEX) : startpos;
1707          int   len1 = do_utf8 ? SvCUR(dsv1) : strend - startpos;
1708          if (!PL_colorset)
1709              reginitcolors();
1710          PerlIO_printf(Perl_debug_log,
1711                        "%sMatching REx%s `%s%*.*s%s%s' against `%s%.*s%s%s'\n",
1712                        PL_colors[4],PL_colors[5],PL_colors[0],
1713                        len0, len0, s0,
1714                        PL_colors[1],
1715                        len0 > 60 ? "..." : "",
1716                        PL_colors[0],
1717                        (int)(len1 > 60 ? 60 : len1),
1718                        s1, PL_colors[1],
1719                        (len1 > 60 ? "..." : "")
1720               );
1721     });
1722
1723     /* Simplest case:  anchored match need be tried only once. */
1724     /*  [unless only anchor is BOL and multiline is set] */
1725     if (prog->reganch & (ROPT_ANCH & ~ROPT_ANCH_GPOS)) {
1726         if (s == startpos && regtry(prog, startpos))
1727             goto got_it;
1728         else if (PL_multiline || (prog->reganch & ROPT_IMPLICIT)
1729                  || (prog->reganch & ROPT_ANCH_MBOL)) /* XXXX SBOL? */
1730         {
1731             char *end;
1732
1733             if (minlen)
1734                 dontbother = minlen - 1;
1735             end = HOP3c(strend, -dontbother, strbeg) - 1;
1736             /* for multiline we only have to try after newlines */
1737             if (prog->check_substr || prog->check_utf8) {
1738                 if (s == startpos)
1739                     goto after_try;
1740                 while (1) {
1741                     if (regtry(prog, s))
1742                         goto got_it;
1743                   after_try:
1744                     if (s >= end)
1745                         goto phooey;
1746                     if (prog->reganch & RE_USE_INTUIT) {
1747                         s = re_intuit_start(prog, sv, s + 1, strend, flags, NULL);
1748                         if (!s)
1749                             goto phooey;
1750                     }
1751                     else
1752                         s++;
1753                 }               
1754             } else {
1755                 if (s > startpos)
1756                     s--;
1757                 while (s < end) {
1758                     if (*s++ == '\n') { /* don't need PL_utf8skip here */
1759                         if (regtry(prog, s))
1760                             goto got_it;
1761                     }
1762                 }               
1763             }
1764         }
1765         goto phooey;
1766     } else if (prog->reganch & ROPT_ANCH_GPOS) {
1767         if (regtry(prog, PL_reg_ganch))
1768             goto got_it;
1769         goto phooey;
1770     }
1771
1772     /* Messy cases:  unanchored match. */
1773     if ((prog->anchored_substr || prog->anchored_utf8) && prog->reganch & ROPT_SKIP) {
1774         /* we have /x+whatever/ */
1775         /* it must be a one character string (XXXX Except UTF?) */
1776         char ch;
1777 #ifdef DEBUGGING
1778         int did_match = 0;
1779 #endif
1780         if (!(do_utf8 ? prog->anchored_utf8 : prog->anchored_substr))
1781             do_utf8 ? to_utf8_substr(prog) : to_byte_substr(prog);
1782         ch = SvPVX(do_utf8 ? prog->anchored_utf8 : prog->anchored_substr)[0];
1783
1784         if (do_utf8) {
1785             while (s < strend) {
1786                 if (*s == ch) {
1787                     DEBUG_r( did_match = 1 );
1788                     if (regtry(prog, s)) goto got_it;
1789                     s += UTF8SKIP(s);
1790                     while (s < strend && *s == ch)
1791                         s += UTF8SKIP(s);
1792                 }
1793                 s += UTF8SKIP(s);
1794             }
1795         }
1796         else {
1797             while (s < strend) {
1798                 if (*s == ch) {
1799                     DEBUG_r( did_match = 1 );
1800                     if (regtry(prog, s)) goto got_it;
1801                     s++;
1802                     while (s < strend && *s == ch)
1803                         s++;
1804                 }
1805                 s++;
1806             }
1807         }
1808         DEBUG_r(if (!did_match)
1809                 PerlIO_printf(Perl_debug_log,
1810                                   "Did not find anchored character...\n")
1811                );
1812     }
1813     /*SUPPRESS 560*/
1814     else if (prog->anchored_substr != Nullsv
1815               || prog->anchored_utf8 != Nullsv
1816               || ((prog->float_substr != Nullsv || prog->float_utf8 != Nullsv)
1817                   && prog->float_max_offset < strend - s)) {
1818         SV *must;
1819         I32 back_max;
1820         I32 back_min;
1821         char *last;
1822         char *last1;            /* Last position checked before */
1823 #ifdef DEBUGGING
1824         int did_match = 0;
1825 #endif
1826         if (prog->anchored_substr || prog->anchored_utf8) {
1827             if (!(do_utf8 ? prog->anchored_utf8 : prog->anchored_substr))
1828                 do_utf8 ? to_utf8_substr(prog) : to_byte_substr(prog);
1829             must = do_utf8 ? prog->anchored_utf8 : prog->anchored_substr;
1830             back_max = back_min = prog->anchored_offset;
1831         } else {
1832             if (!(do_utf8 ? prog->float_utf8 : prog->float_substr))
1833                 do_utf8 ? to_utf8_substr(prog) : to_byte_substr(prog);
1834             must = do_utf8 ? prog->float_utf8 : prog->float_substr;
1835             back_max = prog->float_max_offset;
1836             back_min = prog->float_min_offset;
1837         }
1838         if (must == &PL_sv_undef)
1839             /* could not downgrade utf8 check substring, so must fail */
1840             goto phooey;
1841
1842         last = HOP3c(strend,    /* Cannot start after this */
1843                           -(I32)(CHR_SVLEN(must)
1844                                  - (SvTAIL(must) != 0) + back_min), strbeg);
1845
1846         if (s > PL_bostr)
1847             last1 = HOPc(s, -1);
1848         else
1849             last1 = s - 1;      /* bogus */
1850
1851         /* XXXX check_substr already used to find `s', can optimize if
1852            check_substr==must. */
1853         scream_pos = -1;
1854         dontbother = end_shift;
1855         strend = HOPc(strend, -dontbother);
1856         while ( (s <= last) &&
1857                 ((flags & REXEC_SCREAM)
1858                  ? (s = screaminstr(sv, must, HOP3c(s, back_min, strend) - strbeg,
1859                                     end_shift, &scream_pos, 0))
1860                  : (s = fbm_instr((unsigned char*)HOP3(s, back_min, strend),
1861                                   (unsigned char*)strend, must,
1862                                   PL_multiline ? FBMrf_MULTILINE : 0))) ) {
1863             /* we may be pointing at the wrong string */
1864             if ((flags & REXEC_SCREAM) && RX_MATCH_COPIED(prog))
1865                 s = strbeg + (s - SvPVX(sv));
1866             DEBUG_r( did_match = 1 );
1867             if (HOPc(s, -back_max) > last1) {
1868                 last1 = HOPc(s, -back_min);
1869                 s = HOPc(s, -back_max);
1870             }
1871             else {
1872                 char *t = (last1 >= PL_bostr) ? HOPc(last1, 1) : last1 + 1;
1873
1874                 last1 = HOPc(s, -back_min);
1875                 s = t;          
1876             }
1877             if (do_utf8) {
1878                 while (s <= last1) {
1879                     if (regtry(prog, s))
1880                         goto got_it;
1881                     s += UTF8SKIP(s);
1882                 }
1883             }
1884             else {
1885                 while (s <= last1) {
1886                     if (regtry(prog, s))
1887                         goto got_it;
1888                     s++;
1889                 }
1890             }
1891         }
1892         DEBUG_r(if (!did_match)
1893                     PerlIO_printf(Perl_debug_log, 
1894                                   "Did not find %s substr `%s%.*s%s'%s...\n",
1895                               ((must == prog->anchored_substr || must == prog->anchored_utf8)
1896                                ? "anchored" : "floating"),
1897                               PL_colors[0],
1898                               (int)(SvCUR(must) - (SvTAIL(must)!=0)),
1899                               SvPVX(must),
1900                                   PL_colors[1], (SvTAIL(must) ? "$" : ""))
1901                );
1902         goto phooey;
1903     }
1904     else if ((c = prog->regstclass)) {
1905         if (minlen) {
1906             I32 op = (U8)OP(prog->regstclass);
1907             /* don't bother with what can't match */
1908             if (PL_regkind[op] != EXACT && op != CANY)
1909                 strend = HOPc(strend, -(minlen - 1));
1910         }
1911         DEBUG_r({
1912             SV *prop = sv_newmortal();
1913             char *s0;
1914             char *s1;
1915             int len0;
1916             int len1;
1917
1918             regprop(prop, c);
1919             s0 = UTF ?
1920               pv_uni_display(dsv0, (U8*)SvPVX(prop), SvCUR(prop), 60,
1921                              UNI_DISPLAY_REGEX) :
1922               SvPVX(prop);
1923             len0 = UTF ? SvCUR(dsv0) : SvCUR(prop);
1924             s1 = UTF ?
1925               sv_uni_display(dsv1, sv, 60, UNI_DISPLAY_REGEX) : s;
1926             len1 = UTF ? SvCUR(dsv1) : strend - s;
1927             PerlIO_printf(Perl_debug_log,
1928                           "Matching stclass `%*.*s' against `%*.*s'\n",
1929                           len0, len0, s0,
1930                           len1, len1, s1);
1931         });
1932         if (find_byclass(prog, c, s, strend, startpos, 0))
1933             goto got_it;
1934         DEBUG_r(PerlIO_printf(Perl_debug_log, "Contradicts stclass...\n"));
1935     }
1936     else {
1937         dontbother = 0;
1938         if (prog->float_substr != Nullsv || prog->float_utf8 != Nullsv) {
1939             /* Trim the end. */
1940             char *last;
1941             SV* float_real;
1942
1943             if (!(do_utf8 ? prog->float_utf8 : prog->float_substr))
1944                 do_utf8 ? to_utf8_substr(prog) : to_byte_substr(prog);
1945             float_real = do_utf8 ? prog->float_utf8 : prog->float_substr;
1946
1947             if (flags & REXEC_SCREAM) {
1948                 last = screaminstr(sv, float_real, s - strbeg,
1949                                    end_shift, &scream_pos, 1); /* last one */
1950                 if (!last)
1951                     last = scream_olds; /* Only one occurrence. */
1952                 /* we may be pointing at the wrong string */
1953                 else if (RX_MATCH_COPIED(prog))
1954                     s = strbeg + (s - SvPVX(sv));
1955             }
1956             else {
1957                 STRLEN len;
1958                 char *little = SvPV(float_real, len);
1959
1960                 if (SvTAIL(float_real)) {
1961                     if (memEQ(strend - len + 1, little, len - 1))
1962                         last = strend - len + 1;
1963                     else if (!PL_multiline)
1964                         last = memEQ(strend - len, little, len)
1965                             ? strend - len : Nullch;
1966                     else
1967                         goto find_last;
1968                 } else {
1969                   find_last:
1970                     if (len)
1971                         last = rninstr(s, strend, little, little + len);
1972                     else
1973                         last = strend;  /* matching `$' */
1974                 }
1975             }
1976             if (last == NULL) {
1977                 DEBUG_r(PerlIO_printf(Perl_debug_log,
1978                                       "%sCan't trim the tail, match fails (should not happen)%s\n",
1979                                       PL_colors[4],PL_colors[5]));
1980                 goto phooey; /* Should not happen! */
1981             }
1982             dontbother = strend - last + prog->float_min_offset;
1983         }
1984         if (minlen && (dontbother < minlen))
1985             dontbother = minlen - 1;
1986         strend -= dontbother;              /* this one's always in bytes! */
1987         /* We don't know much -- general case. */
1988         if (do_utf8) {
1989             for (;;) {
1990                 if (regtry(prog, s))
1991                     goto got_it;
1992                 if (s >= strend)
1993                     break;
1994                 s += UTF8SKIP(s);
1995             };
1996         }
1997         else {
1998             do {
1999                 if (regtry(prog, s))
2000                     goto got_it;
2001             } while (s++ < strend);
2002         }
2003     }
2004
2005     /* Failure. */
2006     goto phooey;
2007
2008 got_it:
2009     RX_MATCH_TAINTED_set(prog, PL_reg_flags & RF_tainted);
2010
2011     if (PL_reg_eval_set) {
2012         /* Preserve the current value of $^R */
2013         if (oreplsv != GvSV(PL_replgv))
2014             sv_setsv(oreplsv, GvSV(PL_replgv));/* So that when GvSV(replgv) is
2015                                                   restored, the value remains
2016                                                   the same. */
2017         restore_pos(aTHX_ 0);
2018     }
2019
2020     /* make sure $`, $&, $', and $digit will work later */
2021     if ( !(flags & REXEC_NOT_FIRST) ) {
2022         if (RX_MATCH_COPIED(prog)) {
2023             Safefree(prog->subbeg);
2024             RX_MATCH_COPIED_off(prog);
2025         }
2026         if (flags & REXEC_COPY_STR) {
2027             I32 i = PL_regeol - startpos + (stringarg - strbeg);
2028
2029             s = savepvn(strbeg, i);
2030             prog->subbeg = s;
2031             prog->sublen = i;
2032             RX_MATCH_COPIED_on(prog);
2033         }
2034         else {
2035             prog->subbeg = strbeg;
2036             prog->sublen = PL_regeol - strbeg;  /* strend may have been modified */
2037         }
2038     }
2039
2040     return 1;
2041
2042 phooey:
2043     DEBUG_r(PerlIO_printf(Perl_debug_log, "%sMatch failed%s\n",
2044                           PL_colors[4],PL_colors[5]));
2045     if (PL_reg_eval_set)
2046         restore_pos(aTHX_ 0);
2047     return 0;
2048 }
2049
2050 /*
2051  - regtry - try match at specific point
2052  */
2053 STATIC I32                      /* 0 failure, 1 success */
2054 S_regtry(pTHX_ regexp *prog, char *startpos)
2055 {
2056     register I32 i;
2057     register I32 *sp;
2058     register I32 *ep;
2059     CHECKPOINT lastcp;
2060
2061 #ifdef DEBUGGING
2062     PL_regindent = 0;   /* XXXX Not good when matches are reenterable... */
2063 #endif
2064     if ((prog->reganch & ROPT_EVAL_SEEN) && !PL_reg_eval_set) {
2065         MAGIC *mg;
2066
2067         PL_reg_eval_set = RS_init;
2068         DEBUG_r(DEBUG_s(
2069             PerlIO_printf(Perl_debug_log, "  setting stack tmpbase at %"IVdf"\n",
2070                           (IV)(PL_stack_sp - PL_stack_base));
2071             ));
2072         SAVEI32(cxstack[cxstack_ix].blk_oldsp);
2073         cxstack[cxstack_ix].blk_oldsp = PL_stack_sp - PL_stack_base;
2074         /* Otherwise OP_NEXTSTATE will free whatever on stack now.  */
2075         SAVETMPS;
2076         /* Apparently this is not needed, judging by wantarray. */
2077         /* SAVEI8(cxstack[cxstack_ix].blk_gimme);
2078            cxstack[cxstack_ix].blk_gimme = G_SCALAR; */
2079
2080         if (PL_reg_sv) {
2081             /* Make $_ available to executed code. */
2082             if (PL_reg_sv != DEFSV) {
2083                 /* SAVE_DEFSV does *not* suffice here for USE_5005THREADS */
2084                 SAVESPTR(DEFSV);
2085                 DEFSV = PL_reg_sv;
2086             }
2087         
2088             if (!(SvTYPE(PL_reg_sv) >= SVt_PVMG && SvMAGIC(PL_reg_sv)
2089                   && (mg = mg_find(PL_reg_sv, PERL_MAGIC_regex_global)))) {
2090                 /* prepare for quick setting of pos */
2091                 sv_magic(PL_reg_sv, (SV*)0,
2092                         PERL_MAGIC_regex_global, Nullch, 0);
2093                 mg = mg_find(PL_reg_sv, PERL_MAGIC_regex_global);
2094                 mg->mg_len = -1;
2095             }
2096             PL_reg_magic    = mg;
2097             PL_reg_oldpos   = mg->mg_len;
2098             SAVEDESTRUCTOR_X(restore_pos, 0);
2099         }
2100         if (!PL_reg_curpm) {
2101             Newz(22,PL_reg_curpm, 1, PMOP);
2102 #ifdef USE_ITHREADS
2103             {
2104                 SV* repointer = newSViv(0);
2105                 /* so we know which PL_regex_padav element is PL_reg_curpm */
2106                 SvFLAGS(repointer) |= SVf_BREAK;
2107                 av_push(PL_regex_padav,repointer);
2108                 PL_reg_curpm->op_pmoffset = av_len(PL_regex_padav);
2109                 PL_regex_pad = AvARRAY(PL_regex_padav);
2110             }
2111 #endif      
2112         }
2113         PM_SETRE(PL_reg_curpm, prog);
2114         PL_reg_oldcurpm = PL_curpm;
2115         PL_curpm = PL_reg_curpm;
2116         if (RX_MATCH_COPIED(prog)) {
2117             /*  Here is a serious problem: we cannot rewrite subbeg,
2118                 since it may be needed if this match fails.  Thus
2119                 $` inside (?{}) could fail... */
2120             PL_reg_oldsaved = prog->subbeg;
2121             PL_reg_oldsavedlen = prog->sublen;
2122             RX_MATCH_COPIED_off(prog);
2123         }
2124         else
2125             PL_reg_oldsaved = Nullch;
2126         prog->subbeg = PL_bostr;
2127         prog->sublen = PL_regeol - PL_bostr; /* strend may have been modified */
2128     }
2129     prog->startp[0] = startpos - PL_bostr;
2130     PL_reginput = startpos;
2131     PL_regstartp = prog->startp;
2132     PL_regendp = prog->endp;
2133     PL_reglastparen = &prog->lastparen;
2134     PL_reglastcloseparen = &prog->lastcloseparen;
2135     prog->lastparen = 0;
2136     prog->lastcloseparen = 0;
2137     PL_regsize = 0;
2138     DEBUG_r(PL_reg_starttry = startpos);
2139     if (PL_reg_start_tmpl <= prog->nparens) {
2140         PL_reg_start_tmpl = prog->nparens*3/2 + 3;
2141         if(PL_reg_start_tmp)
2142             Renew(PL_reg_start_tmp, PL_reg_start_tmpl, char*);
2143         else
2144             New(22,PL_reg_start_tmp, PL_reg_start_tmpl, char*);
2145     }
2146
2147     /* XXXX What this code is doing here?!!!  There should be no need
2148        to do this again and again, PL_reglastparen should take care of
2149        this!  --ilya*/
2150
2151     /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
2152      * Actually, the code in regcppop() (which Ilya may be meaning by
2153      * PL_reglastparen), is not needed at all by the test suite
2154      * (op/regexp, op/pat, op/split), but that code is needed, oddly
2155      * enough, for building DynaLoader, or otherwise this
2156      * "Error: '*' not in typemap in DynaLoader.xs, line 164"
2157      * will happen.  Meanwhile, this code *is* needed for the
2158      * above-mentioned test suite tests to succeed.  The common theme
2159      * on those tests seems to be returning null fields from matches.
2160      * --jhi */
2161 #if 1
2162     sp = prog->startp;
2163     ep = prog->endp;
2164     if (prog->nparens) {
2165         for (i = prog->nparens; i > (I32)*PL_reglastparen; i--) {
2166             *++sp = -1;
2167             *++ep = -1;
2168         }
2169     }
2170 #endif
2171     REGCP_SET(lastcp);
2172     if (regmatch(prog->program + 1)) {
2173         prog->endp[0] = PL_reginput - PL_bostr;
2174         return 1;
2175     }
2176     REGCP_UNWIND(lastcp);
2177     return 0;
2178 }
2179
2180 #define RE_UNWIND_BRANCH        1
2181 #define RE_UNWIND_BRANCHJ       2
2182
2183 union re_unwind_t;
2184
2185 typedef struct {                /* XX: makes sense to enlarge it... */
2186     I32 type;
2187     I32 prev;
2188     CHECKPOINT lastcp;
2189 } re_unwind_generic_t;
2190
2191 typedef struct {
2192     I32 type;
2193     I32 prev;
2194     CHECKPOINT lastcp;
2195     I32 lastparen;
2196     regnode *next;
2197     char *locinput;
2198     I32 nextchr;
2199 #ifdef DEBUGGING
2200     int regindent;
2201 #endif
2202 } re_unwind_branch_t;
2203
2204 typedef union re_unwind_t {
2205     I32 type;
2206     re_unwind_generic_t generic;
2207     re_unwind_branch_t branch;
2208 } re_unwind_t;
2209
2210 #define sayYES goto yes
2211 #define sayNO goto no
2212 #define sayNO_ANYOF goto no_anyof
2213 #define sayYES_FINAL goto yes_final
2214 #define sayYES_LOUD  goto yes_loud
2215 #define sayNO_FINAL  goto no_final
2216 #define sayNO_SILENT goto do_no
2217 #define saySAME(x) if (x) goto yes; else goto no
2218
2219 #define REPORT_CODE_OFF 24
2220
2221 /*
2222  - regmatch - main matching routine
2223  *
2224  * Conceptually the strategy is simple:  check to see whether the current
2225  * node matches, call self recursively to see whether the rest matches,
2226  * and then act accordingly.  In practice we make some effort to avoid
2227  * recursion, in particular by going through "ordinary" nodes (that don't
2228  * need to know whether the rest of the match failed) by a loop instead of
2229  * by recursion.
2230  */
2231 /* [lwall] I've hoisted the register declarations to the outer block in order to
2232  * maybe save a little bit of pushing and popping on the stack.  It also takes
2233  * advantage of machines that use a register save mask on subroutine entry.
2234  */
2235 STATIC I32                      /* 0 failure, 1 success */
2236 S_regmatch(pTHX_ regnode *prog)
2237 {
2238     register regnode *scan;     /* Current node. */
2239     regnode *next;              /* Next node. */
2240     regnode *inner;             /* Next node in internal branch. */
2241     register I32 nextchr;       /* renamed nextchr - nextchar colides with
2242                                    function of same name */
2243     register I32 n;             /* no or next */
2244     register I32 ln = 0;        /* len or last */
2245     register char *s = Nullch;  /* operand or save */
2246     register char *locinput = PL_reginput;
2247     register I32 c1 = 0, c2 = 0, paren; /* case fold search, parenth */
2248     int minmod = 0, sw = 0, logical = 0;
2249     I32 unwind = 0;
2250 #if 0
2251     I32 firstcp = PL_savestack_ix;
2252 #endif
2253     register bool do_utf8 = PL_reg_match_utf8;
2254 #ifdef DEBUGGING
2255     SV *dsv0 = PERL_DEBUG_PAD_ZERO(0);
2256     SV *dsv1 = PERL_DEBUG_PAD_ZERO(1);
2257     SV *dsv2 = PERL_DEBUG_PAD_ZERO(2);
2258 #endif
2259
2260 #ifdef DEBUGGING
2261     PL_regindent++;
2262 #endif
2263
2264     /* Note that nextchr is a byte even in UTF */
2265     nextchr = UCHARAT(locinput);
2266     scan = prog;
2267     while (scan != NULL) {
2268
2269         DEBUG_r( {
2270             SV *prop = sv_newmortal();
2271             int docolor = *PL_colors[0];
2272             int taill = (docolor ? 10 : 7); /* 3 chars for "> <" */
2273             int l = (PL_regeol - locinput) > taill ? taill : (PL_regeol - locinput);
2274             /* The part of the string before starttry has one color
2275                (pref0_len chars), between starttry and current
2276                position another one (pref_len - pref0_len chars),
2277                after the current position the third one.
2278                We assume that pref0_len <= pref_len, otherwise we
2279                decrease pref0_len.  */
2280             int pref_len = (locinput - PL_bostr) > (5 + taill) - l
2281                 ? (5 + taill) - l : locinput - PL_bostr;
2282             int pref0_len;
2283
2284             while (do_utf8 && UTF8_IS_CONTINUATION(*(U8*)(locinput - pref_len)))
2285                 pref_len++;
2286             pref0_len = pref_len  - (locinput - PL_reg_starttry);
2287             if (l + pref_len < (5 + taill) && l < PL_regeol - locinput)
2288                 l = ( PL_regeol - locinput > (5 + taill) - pref_len
2289                       ? (5 + taill) - pref_len : PL_regeol - locinput);
2290             while (do_utf8 && UTF8_IS_CONTINUATION(*(U8*)(locinput + l)))
2291                 l--;
2292             if (pref0_len < 0)
2293                 pref0_len = 0;
2294             if (pref0_len > pref_len)
2295                 pref0_len = pref_len;
2296             regprop(prop, scan);
2297             {
2298               char *s0 =
2299                 do_utf8 && OP(scan) != CANY ?
2300                 pv_uni_display(dsv0, (U8*)(locinput - pref_len),
2301                                pref0_len, 60, UNI_DISPLAY_REGEX) :
2302                 locinput - pref_len;
2303               int len0 = do_utf8 ? strlen(s0) : pref0_len;
2304               char *s1 = do_utf8 && OP(scan) != CANY ?
2305                 pv_uni_display(dsv1, (U8*)(locinput - pref_len + pref0_len),
2306                                pref_len - pref0_len, 60, UNI_DISPLAY_REGEX) :
2307                 locinput - pref_len + pref0_len;
2308               int len1 = do_utf8 ? strlen(s1) : pref_len - pref0_len;
2309               char *s2 = do_utf8 && OP(scan) != CANY ?
2310                 pv_uni_display(dsv2, (U8*)locinput,
2311                                PL_regeol - locinput, 60, UNI_DISPLAY_REGEX) :
2312                 locinput;
2313               int len2 = do_utf8 ? strlen(s2) : l;
2314               PerlIO_printf(Perl_debug_log,
2315                             "%4"IVdf" <%s%.*s%s%s%.*s%s%s%s%.*s%s>%*s|%3"IVdf":%*s%s\n",
2316                             (IV)(locinput - PL_bostr),
2317                             PL_colors[4],
2318                             len0, s0,
2319                             PL_colors[5],
2320                             PL_colors[2],
2321                             len1, s1,
2322                             PL_colors[3],
2323                             (docolor ? "" : "> <"),
2324                             PL_colors[0],
2325                             len2, s2,
2326                             PL_colors[1],
2327                             15 - l - pref_len + 1,
2328                             "",
2329                             (IV)(scan - PL_regprogram), PL_regindent*2, "",
2330                             SvPVX(prop));
2331             }
2332         });
2333
2334         next = scan + NEXT_OFF(scan);
2335         if (next == scan)
2336             next = NULL;
2337
2338         switch (OP(scan)) {
2339         case BOL:
2340             if (locinput == PL_bostr || (PL_multiline &&
2341                 (nextchr || locinput < PL_regeol) && locinput[-1] == '\n') )
2342             {
2343                 /* regtill = regbol; */
2344                 break;
2345             }
2346             sayNO;
2347         case MBOL:
2348             if (locinput == PL_bostr ||
2349                 ((nextchr || locinput < PL_regeol) && locinput[-1] == '\n'))
2350             {
2351                 break;
2352             }
2353             sayNO;
2354         case SBOL:
2355             if (locinput == PL_bostr)
2356                 break;
2357             sayNO;
2358         case GPOS:
2359             if (locinput == PL_reg_ganch)
2360                 break;
2361             sayNO;
2362         case EOL:
2363             if (PL_multiline)
2364                 goto meol;
2365             else
2366                 goto seol;
2367         case MEOL:
2368           meol:
2369             if ((nextchr || locinput < PL_regeol) && nextchr != '\n')
2370                 sayNO;
2371             break;
2372         case SEOL:
2373           seol:
2374             if ((nextchr || locinput < PL_regeol) && nextchr != '\n')
2375                 sayNO;
2376             if (PL_regeol - locinput > 1)
2377                 sayNO;
2378             break;
2379         case EOS:
2380             if (PL_regeol != locinput)
2381                 sayNO;
2382             break;
2383         case SANY:
2384             if (!nextchr && locinput >= PL_regeol)
2385                 sayNO;
2386             if (do_utf8) {
2387                 locinput += PL_utf8skip[nextchr];
2388                 if (locinput > PL_regeol)
2389                     sayNO;
2390                 nextchr = UCHARAT(locinput);
2391             }
2392             else
2393                 nextchr = UCHARAT(++locinput);
2394             break;
2395         case CANY:
2396             if (!nextchr && locinput >= PL_regeol)
2397                 sayNO;
2398             nextchr = UCHARAT(++locinput);
2399             break;
2400         case REG_ANY:
2401             if ((!nextchr && locinput >= PL_regeol) || nextchr == '\n')
2402                 sayNO;
2403             if (do_utf8) {
2404                 locinput += PL_utf8skip[nextchr];
2405                 if (locinput > PL_regeol)
2406                     sayNO;
2407                 nextchr = UCHARAT(locinput);
2408             }
2409             else
2410                 nextchr = UCHARAT(++locinput);
2411             break;
2412         case EXACT:
2413             s = STRING(scan);
2414             ln = STR_LEN(scan);
2415             if (do_utf8 != UTF) {
2416                 /* The target and the pattern have differing utf8ness. */
2417                 char *l = locinput;
2418                 char *e = s + ln;
2419                 STRLEN ulen;
2420
2421                 if (do_utf8) {
2422                     /* The target is utf8, the pattern is not utf8. */
2423                     while (s < e) {
2424                         if (l >= PL_regeol)
2425                              sayNO;
2426                         if (NATIVE_TO_UNI(*(U8*)s) !=
2427                             utf8n_to_uvuni((U8*)l, UTF8_MAXLEN, &ulen,
2428                                            ckWARN(WARN_UTF8) ?
2429                                            0 : UTF8_ALLOW_ANY))
2430                              sayNO;
2431                         l += ulen;
2432                         s ++;
2433                     }
2434                 }
2435                 else {
2436                     /* The target is not utf8, the pattern is utf8. */
2437                     while (s < e) {
2438                         if (l >= PL_regeol)
2439                             sayNO;
2440                         if (NATIVE_TO_UNI(*((U8*)l)) !=
2441                             utf8n_to_uvuni((U8*)s, UTF8_MAXLEN, &ulen,
2442                                            ckWARN(WARN_UTF8) ?
2443                                            0 : UTF8_ALLOW_ANY))
2444                             sayNO;
2445                         s += ulen;
2446                         l ++;
2447                     }
2448                 }
2449                 locinput = l;
2450                 nextchr = UCHARAT(locinput);
2451                 break;
2452             }
2453             /* The target and the pattern have the same utf8ness. */
2454             /* Inline the first character, for speed. */
2455             if (UCHARAT(s) != nextchr)
2456                 sayNO;
2457             if (PL_regeol - locinput < ln)
2458                 sayNO;
2459             if (ln > 1 && memNE(s, locinput, ln))
2460                 sayNO;
2461             locinput += ln;
2462             nextchr = UCHARAT(locinput);
2463             break;
2464         case EXACTFL:
2465             PL_reg_flags |= RF_tainted;
2466             /* FALL THROUGH */
2467         case EXACTF:
2468             s = STRING(scan);
2469             ln = STR_LEN(scan);
2470
2471             if (do_utf8 || UTF) {
2472               /* Either target or the pattern are utf8. */
2473                 char *l = locinput;
2474                 char *e = PL_regeol;
2475
2476                 if (ibcmp_utf8(s, 0,  ln, (bool)UTF,
2477                                l, &e, 0,  do_utf8)) {
2478                      /* One more case for the sharp s:
2479                       * pack("U0U*", 0xDF) =~ /ss/i,
2480                       * the 0xC3 0x9F are the UTF-8
2481                       * byte sequence for the U+00DF. */
2482                      if (!(do_utf8 &&
2483                            toLOWER(s[0]) == 's' &&
2484                            ln >= 2 &&
2485                            toLOWER(s[1]) == 's' &&
2486                            (U8)l[0] == 0xC3 &&
2487                            e - l >= 2 &&
2488                            (U8)l[1] == 0x9F))
2489                           sayNO;
2490                 }
2491                 locinput = e;
2492                 nextchr = UCHARAT(locinput);
2493                 break;
2494             }
2495
2496             /* Neither the target and the pattern are utf8. */
2497
2498             /* Inline the first character, for speed. */
2499             if (UCHARAT(s) != nextchr &&
2500                 UCHARAT(s) != ((OP(scan) == EXACTF)
2501                                ? PL_fold : PL_fold_locale)[nextchr])
2502                 sayNO;
2503             if (PL_regeol - locinput < ln)
2504                 sayNO;
2505             if (ln > 1 && (OP(scan) == EXACTF
2506                            ? ibcmp(s, locinput, ln)
2507                            : ibcmp_locale(s, locinput, ln)))
2508                 sayNO;
2509             locinput += ln;
2510             nextchr = UCHARAT(locinput);
2511             break;
2512         case ANYOF:
2513             if (do_utf8) {
2514                 STRLEN inclasslen = PL_regeol - locinput;
2515
2516                 if (!reginclass(scan, (U8*)locinput, &inclasslen, do_utf8))
2517                     sayNO_ANYOF;
2518                 if (locinput >= PL_regeol)
2519                     sayNO;
2520                 locinput += inclasslen ? inclasslen : UTF8SKIP(locinput);
2521                 nextchr = UCHARAT(locinput);
2522                 break;
2523             }
2524             else {
2525                 if (nextchr < 0)
2526                     nextchr = UCHARAT(locinput);
2527                 if (!REGINCLASS(scan, (U8*)locinput))
2528                     sayNO_ANYOF;
2529                 if (!nextchr && locinput >= PL_regeol)
2530                     sayNO;
2531                 nextchr = UCHARAT(++locinput);
2532                 break;
2533             }
2534         no_anyof:
2535             /* If we might have the case of the German sharp s
2536              * in a casefolding Unicode character class. */
2537
2538             if (ANYOF_FOLD_SHARP_S(scan, locinput, PL_regeol)) {
2539                  locinput += SHARP_S_SKIP;
2540                  nextchr = UCHARAT(locinput);
2541             }
2542             else
2543                  sayNO;
2544             break;
2545         case ALNUML:
2546             PL_reg_flags |= RF_tainted;
2547             /* FALL THROUGH */
2548         case ALNUM:
2549             if (!nextchr)
2550                 sayNO;
2551             if (do_utf8) {
2552                 LOAD_UTF8_CHARCLASS(alnum,"a");
2553                 if (!(OP(scan) == ALNUM
2554                       ? swash_fetch(PL_utf8_alnum, (U8*)locinput, do_utf8)
2555                       : isALNUM_LC_utf8((U8*)locinput)))
2556                 {
2557                     sayNO;
2558                 }
2559                 locinput += PL_utf8skip[nextchr];
2560                 nextchr = UCHARAT(locinput);
2561                 break;
2562             }
2563             if (!(OP(scan) == ALNUM
2564                   ? isALNUM(nextchr) : isALNUM_LC(nextchr)))
2565                 sayNO;
2566             nextchr = UCHARAT(++locinput);
2567             break;
2568         case NALNUML:
2569             PL_reg_flags |= RF_tainted;
2570             /* FALL THROUGH */
2571         case NALNUM:
2572             if (!nextchr && locinput >= PL_regeol)
2573                 sayNO;
2574             if (do_utf8) {
2575                 LOAD_UTF8_CHARCLASS(alnum,"a");
2576                 if (OP(scan) == NALNUM
2577                     ? swash_fetch(PL_utf8_alnum, (U8*)locinput, do_utf8)
2578                     : isALNUM_LC_utf8((U8*)locinput))
2579                 {
2580                     sayNO;
2581                 }
2582                 locinput += PL_utf8skip[nextchr];
2583                 nextchr = UCHARAT(locinput);
2584                 break;
2585             }
2586             if (OP(scan) == NALNUM
2587                 ? isALNUM(nextchr) : isALNUM_LC(nextchr))
2588                 sayNO;
2589             nextchr = UCHARAT(++locinput);
2590             break;
2591         case BOUNDL:
2592         case NBOUNDL:
2593             PL_reg_flags |= RF_tainted;
2594             /* FALL THROUGH */
2595         case BOUND:
2596         case NBOUND:
2597             /* was last char in word? */
2598             if (do_utf8) {
2599                 if (locinput == PL_bostr)
2600                     ln = '\n';
2601                 else {
2602                     U8 *r = reghop3((U8*)locinput, -1, (U8*)PL_bostr);
2603                 
2604                     ln = utf8n_to_uvchr(r, UTF8SKIP(r), 0, 0);
2605                 }
2606                 if (OP(scan) == BOUND || OP(scan) == NBOUND) {
2607                     ln = isALNUM_uni(ln);
2608                     LOAD_UTF8_CHARCLASS(alnum,"a");
2609                     n = swash_fetch(PL_utf8_alnum, (U8*)locinput, do_utf8);
2610                 }
2611                 else {
2612                     ln = isALNUM_LC_uvchr(UNI_TO_NATIVE(ln));
2613                     n = isALNUM_LC_utf8((U8*)locinput);
2614                 }
2615             }
2616             else {
2617                 ln = (locinput != PL_bostr) ?
2618                     UCHARAT(locinput - 1) : '\n';
2619                 if (OP(scan) == BOUND || OP(scan) == NBOUND) {
2620                     ln = isALNUM(ln);
2621                     n = isALNUM(nextchr);
2622                 }
2623                 else {
2624                     ln = isALNUM_LC(ln);
2625                     n = isALNUM_LC(nextchr);
2626                 }
2627             }
2628             if (((!ln) == (!n)) == (OP(scan) == BOUND ||
2629                                     OP(scan) == BOUNDL))
2630                     sayNO;
2631             break;
2632         case SPACEL:
2633             PL_reg_flags |= RF_tainted;
2634             /* FALL THROUGH */
2635         case SPACE:
2636             if (!nextchr)
2637                 sayNO;
2638             if (do_utf8) {
2639                 if (UTF8_IS_CONTINUED(nextchr)) {
2640                     LOAD_UTF8_CHARCLASS(space," ");
2641                     if (!(OP(scan) == SPACE
2642                           ? swash_fetch(PL_utf8_space, (U8*)locinput, do_utf8)
2643                           : isSPACE_LC_utf8((U8*)locinput)))
2644                     {
2645                         sayNO;
2646                     }
2647                     locinput += PL_utf8skip[nextchr];
2648                     nextchr = UCHARAT(locinput);
2649                     break;
2650                 }
2651                 if (!(OP(scan) == SPACE
2652                       ? isSPACE(nextchr) : isSPACE_LC(nextchr)))
2653                     sayNO;
2654                 nextchr = UCHARAT(++locinput);
2655             }
2656             else {
2657                 if (!(OP(scan) == SPACE
2658                       ? isSPACE(nextchr) : isSPACE_LC(nextchr)))
2659                     sayNO;
2660                 nextchr = UCHARAT(++locinput);
2661             }
2662             break;
2663         case NSPACEL:
2664             PL_reg_flags |= RF_tainted;
2665             /* FALL THROUGH */
2666         case NSPACE:
2667             if (!nextchr && locinput >= PL_regeol)
2668                 sayNO;
2669             if (do_utf8) {
2670                 LOAD_UTF8_CHARCLASS(space," ");
2671                 if (OP(scan) == NSPACE
2672                     ? swash_fetch(PL_utf8_space, (U8*)locinput, do_utf8)
2673                     : isSPACE_LC_utf8((U8*)locinput))
2674                 {
2675                     sayNO;
2676                 }
2677                 locinput += PL_utf8skip[nextchr];
2678                 nextchr = UCHARAT(locinput);
2679                 break;
2680             }
2681             if (OP(scan) == NSPACE
2682                 ? isSPACE(nextchr) : isSPACE_LC(nextchr))
2683                 sayNO;
2684             nextchr = UCHARAT(++locinput);
2685             break;
2686         case DIGITL:
2687             PL_reg_flags |= RF_tainted;
2688             /* FALL THROUGH */
2689         case DIGIT:
2690             if (!nextchr)
2691                 sayNO;
2692             if (do_utf8) {
2693                 LOAD_UTF8_CHARCLASS(digit,"0");
2694                 if (!(OP(scan) == DIGIT
2695                       ? swash_fetch(PL_utf8_digit, (U8*)locinput, do_utf8)
2696                       : isDIGIT_LC_utf8((U8*)locinput)))
2697                 {
2698                     sayNO;
2699                 }
2700                 locinput += PL_utf8skip[nextchr];
2701                 nextchr = UCHARAT(locinput);
2702                 break;
2703             }
2704             if (!(OP(scan) == DIGIT
2705                   ? isDIGIT(nextchr) : isDIGIT_LC(nextchr)))
2706                 sayNO;
2707             nextchr = UCHARAT(++locinput);
2708             break;
2709         case NDIGITL:
2710             PL_reg_flags |= RF_tainted;
2711             /* FALL THROUGH */
2712         case NDIGIT:
2713             if (!nextchr && locinput >= PL_regeol)
2714                 sayNO;
2715             if (do_utf8) {
2716                 LOAD_UTF8_CHARCLASS(digit,"0");
2717                 if (OP(scan) == NDIGIT
2718                     ? swash_fetch(PL_utf8_digit, (U8*)locinput, do_utf8)
2719                     : isDIGIT_LC_utf8((U8*)locinput))
2720                 {
2721                     sayNO;
2722                 }
2723                 locinput += PL_utf8skip[nextchr];
2724                 nextchr = UCHARAT(locinput);
2725                 break;
2726             }
2727             if (OP(scan) == NDIGIT
2728                 ? isDIGIT(nextchr) : isDIGIT_LC(nextchr))
2729                 sayNO;
2730             nextchr = UCHARAT(++locinput);
2731             break;
2732         case CLUMP:
2733             if (locinput >= PL_regeol)
2734                 sayNO;
2735             if  (do_utf8) {
2736                 LOAD_UTF8_CHARCLASS(mark,"~");
2737                 if (swash_fetch(PL_utf8_mark,(U8*)locinput, do_utf8))
2738                     sayNO;
2739                 locinput += PL_utf8skip[nextchr];
2740                 while (locinput < PL_regeol &&
2741                        swash_fetch(PL_utf8_mark,(U8*)locinput, do_utf8))
2742                     locinput += UTF8SKIP(locinput);
2743                 if (locinput > PL_regeol)
2744                     sayNO;
2745             } 
2746             else
2747                locinput++;
2748             nextchr = UCHARAT(locinput);
2749             break;
2750         case REFFL:
2751             PL_reg_flags |= RF_tainted;
2752             /* FALL THROUGH */
2753         case REF:
2754         case REFF:
2755             n = ARG(scan);  /* which paren pair */
2756             ln = PL_regstartp[n];
2757             PL_reg_leftiter = PL_reg_maxiter;           /* Void cache */
2758             if ((I32)*PL_reglastparen < n || ln == -1)
2759                 sayNO;                  /* Do not match unless seen CLOSEn. */
2760             if (ln == PL_regendp[n])
2761                 break;
2762
2763             s = PL_bostr + ln;
2764             if (do_utf8 && OP(scan) != REF) {   /* REF can do byte comparison */
2765                 char *l = locinput;
2766                 char *e = PL_bostr + PL_regendp[n];
2767                 /*
2768                  * Note that we can't do the "other character" lookup trick as
2769                  * in the 8-bit case (no pun intended) because in Unicode we
2770                  * have to map both upper and title case to lower case.
2771                  */
2772                 if (OP(scan) == REFF) {
2773                     STRLEN ulen1, ulen2;
2774                     U8 tmpbuf1[UTF8_MAXLEN_UCLC+1];
2775                     U8 tmpbuf2[UTF8_MAXLEN_UCLC+1];
2776                     while (s < e) {
2777                         if (l >= PL_regeol)
2778                             sayNO;
2779                         toLOWER_utf8((U8*)s, tmpbuf1, &ulen1);
2780                         toLOWER_utf8((U8*)l, tmpbuf2, &ulen2);
2781                         if (ulen1 != ulen2 || memNE((char *)tmpbuf1, (char *)tmpbuf2, ulen1))
2782                             sayNO;
2783                         s += ulen1;
2784                         l += ulen2;
2785                     }
2786                 }
2787                 locinput = l;
2788                 nextchr = UCHARAT(locinput);
2789                 break;
2790             }
2791
2792             /* Inline the first character, for speed. */
2793             if (UCHARAT(s) != nextchr &&
2794                 (OP(scan) == REF ||
2795                  (UCHARAT(s) != ((OP(scan) == REFF
2796                                   ? PL_fold : PL_fold_locale)[nextchr]))))
2797                 sayNO;
2798             ln = PL_regendp[n] - ln;
2799             if (locinput + ln > PL_regeol)
2800                 sayNO;
2801             if (ln > 1 && (OP(scan) == REF
2802                            ? memNE(s, locinput, ln)
2803                            : (OP(scan) == REFF
2804                               ? ibcmp(s, locinput, ln)
2805                               : ibcmp_locale(s, locinput, ln))))
2806                 sayNO;
2807             locinput += ln;
2808             nextchr = UCHARAT(locinput);
2809             break;
2810
2811         case NOTHING:
2812         case TAIL:
2813             break;
2814         case BACK:
2815             break;
2816         case EVAL:
2817         {
2818             dSP;
2819             OP_4tree *oop = PL_op;
2820             COP *ocurcop = PL_curcop;
2821             PAD *old_comppad;
2822             SV *ret;
2823         
2824             n = ARG(scan);
2825             PL_op = (OP_4tree*)PL_regdata->data[n];
2826             DEBUG_r( PerlIO_printf(Perl_debug_log, "  re_eval 0x%"UVxf"\n", PTR2UV(PL_op)) );
2827             PAD_SAVE_LOCAL(old_comppad, (PAD*)PL_regdata->data[n + 2]);
2828             PL_regendp[0] = PL_reg_magic->mg_len = locinput - PL_bostr;
2829
2830             {
2831                 SV **before = SP;
2832                 CALLRUNOPS(aTHX);                       /* Scalar context. */
2833                 SPAGAIN;
2834                 if (SP == before)
2835                     ret = &PL_sv_undef;   /* protect against empty (?{}) blocks. */
2836                 else {
2837                     ret = POPs;
2838                     PUTBACK;
2839                 }
2840             }
2841
2842             PL_op = oop;
2843             PAD_RESTORE_LOCAL(old_comppad);
2844             PL_curcop = ocurcop;
2845             if (logical) {
2846                 if (logical == 2) {     /* Postponed subexpression. */
2847                     regexp *re;
2848                     MAGIC *mg = Null(MAGIC*);
2849                     re_cc_state state;
2850                     CHECKPOINT cp, lastcp;
2851                     int toggleutf;
2852                     register SV *sv;
2853
2854                     if(SvROK(ret) && SvSMAGICAL(sv = SvRV(ret)))
2855                         mg = mg_find(sv, PERL_MAGIC_qr);
2856                     else if (SvSMAGICAL(ret)) {
2857                         if (SvGMAGICAL(ret))
2858                             sv_unmagic(ret, PERL_MAGIC_qr);
2859                         else
2860                             mg = mg_find(ret, PERL_MAGIC_qr);
2861                     }
2862
2863                     if (mg) {
2864                         re = (regexp *)mg->mg_obj;
2865                         (void)ReREFCNT_inc(re);
2866                     }
2867                     else {
2868                         STRLEN len;
2869                         char *t = SvPV(ret, len);
2870                         PMOP pm;
2871                         char *oprecomp = PL_regprecomp;
2872                         I32 osize = PL_regsize;
2873                         I32 onpar = PL_regnpar;
2874
2875                         Zero(&pm, 1, PMOP);
2876                         if (DO_UTF8(ret)) pm.op_pmdynflags |= PMdf_DYN_UTF8;
2877                         re = CALLREGCOMP(aTHX_ t, t + len, &pm);
2878                         if (!(SvFLAGS(ret)
2879                               & (SVs_TEMP | SVs_PADTMP | SVf_READONLY
2880                                 | SVs_GMG)))
2881                             sv_magic(ret,(SV*)ReREFCNT_inc(re),
2882                                         PERL_MAGIC_qr,0,0);
2883                         PL_regprecomp = oprecomp;
2884                         PL_regsize = osize;
2885                         PL_regnpar = onpar;
2886                     }
2887                     DEBUG_r(
2888                         PerlIO_printf(Perl_debug_log,
2889                                       "Entering embedded `%s%.60s%s%s'\n",
2890                                       PL_colors[0],
2891                                       re->precomp,
2892                                       PL_colors[1],
2893                                       (strlen(re->precomp) > 60 ? "..." : ""))
2894                         );
2895                     state.node = next;
2896                     state.prev = PL_reg_call_cc;
2897                     state.cc = PL_regcc;
2898                     state.re = PL_reg_re;
2899
2900                     PL_regcc = 0;
2901                 
2902                     cp = regcppush(0);  /* Save *all* the positions. */
2903                     REGCP_SET(lastcp);
2904                     cache_re(re);
2905                     state.ss = PL_savestack_ix;
2906                     *PL_reglastparen = 0;
2907                     *PL_reglastcloseparen = 0;
2908                     PL_reg_call_cc = &state;
2909                     PL_reginput = locinput;
2910                     toggleutf = ((PL_reg_flags & RF_utf8) != 0) ^
2911                                 ((re->reganch & ROPT_UTF8) != 0);
2912                     if (toggleutf) PL_reg_flags ^= RF_utf8;
2913
2914                     /* XXXX This is too dramatic a measure... */
2915                     PL_reg_maxiter = 0;
2916
2917                     if (regmatch(re->program + 1)) {
2918                         /* Even though we succeeded, we need to restore
2919                            global variables, since we may be wrapped inside
2920                            SUSPEND, thus the match may be not finished yet. */
2921
2922                         /* XXXX Do this only if SUSPENDed? */
2923                         PL_reg_call_cc = state.prev;
2924                         PL_regcc = state.cc;
2925                         PL_reg_re = state.re;
2926                         cache_re(PL_reg_re);
2927                         if (toggleutf) PL_reg_flags ^= RF_utf8;
2928
2929                         /* XXXX This is too dramatic a measure... */
2930                         PL_reg_maxiter = 0;
2931
2932                         /* These are needed even if not SUSPEND. */
2933                         ReREFCNT_dec(re);
2934                         regcpblow(cp);
2935                         sayYES;
2936                     }
2937                     ReREFCNT_dec(re);
2938                     REGCP_UNWIND(lastcp);
2939                     regcppop();
2940                     PL_reg_call_cc = state.prev;
2941                     PL_regcc = state.cc;
2942                     PL_reg_re = state.re;
2943                     cache_re(PL_reg_re);
2944                     if (toggleutf) PL_reg_flags ^= RF_utf8;
2945
2946                     /* XXXX This is too dramatic a measure... */
2947                     PL_reg_maxiter = 0;
2948
2949                     logical = 0;
2950                     sayNO;
2951                 }
2952                 sw = SvTRUE(ret);
2953                 logical = 0;
2954             }
2955             else
2956                 sv_setsv(save_scalar(PL_replgv), ret);
2957             break;
2958         }
2959         case OPEN:
2960             n = ARG(scan);  /* which paren pair */
2961             PL_reg_start_tmp[n] = locinput;
2962             if (n > PL_regsize)
2963                 PL_regsize = n;
2964             break;
2965         case CLOSE:
2966             n = ARG(scan);  /* which paren pair */
2967             PL_regstartp[n] = PL_reg_start_tmp[n] - PL_bostr;
2968             PL_regendp[n] = locinput - PL_bostr;
2969             if (n > (I32)*PL_reglastparen)
2970                 *PL_reglastparen = n;
2971             *PL_reglastcloseparen = n;
2972             break;
2973         case GROUPP:
2974             n = ARG(scan);  /* which paren pair */
2975             sw = ((I32)*PL_reglastparen >= n && PL_regendp[n] != -1);
2976             break;
2977         case IFTHEN:
2978             PL_reg_leftiter = PL_reg_maxiter;           /* Void cache */
2979             if (sw)
2980                 next = NEXTOPER(NEXTOPER(scan));
2981             else {
2982                 next = scan + ARG(scan);
2983                 if (OP(next) == IFTHEN) /* Fake one. */
2984                     next = NEXTOPER(NEXTOPER(next));
2985             }
2986             break;
2987         case LOGICAL:
2988             logical = scan->flags;
2989             break;
2990 /*******************************************************************
2991  PL_regcc contains infoblock about the innermost (...)* loop, and
2992  a pointer to the next outer infoblock.
2993
2994  Here is how Y(A)*Z is processed (if it is compiled into CURLYX/WHILEM):
2995
2996    1) After matching X, regnode for CURLYX is processed;
2997
2998    2) This regnode creates infoblock on the stack, and calls
2999       regmatch() recursively with the starting point at WHILEM node;
3000
3001    3) Each hit of WHILEM node tries to match A and Z (in the order
3002       depending on the current iteration, min/max of {min,max} and
3003       greediness).  The information about where are nodes for "A"
3004       and "Z" is read from the infoblock, as is info on how many times "A"
3005       was already matched, and greediness.
3006
3007    4) After A matches, the same WHILEM node is hit again.
3008
3009    5) Each time WHILEM is hit, PL_regcc is the infoblock created by CURLYX
3010       of the same pair.  Thus when WHILEM tries to match Z, it temporarily
3011       resets PL_regcc, since this Y(A)*Z can be a part of some other loop:
3012       as in (Y(A)*Z)*.  If Z matches, the automaton will hit the WHILEM node
3013       of the external loop.
3014
3015  Currently present infoblocks form a tree with a stem formed by PL_curcc
3016  and whatever it mentions via ->next, and additional attached trees
3017  corresponding to temporarily unset infoblocks as in "5" above.
3018
3019  In the following picture infoblocks for outer loop of
3020  (Y(A)*?Z)*?T are denoted O, for inner I.  NULL starting block
3021  is denoted by x.  The matched string is YAAZYAZT.  Temporarily postponed
3022  infoblocks are drawn below the "reset" infoblock.
3023
3024  In fact in the picture below we do not show failed matches for Z and T
3025  by WHILEM blocks.  [We illustrate minimal matches, since for them it is
3026  more obvious *why* one needs to *temporary* unset infoblocks.]
3027
3028   Matched       REx position    InfoBlocks      Comment
3029                 (Y(A)*?Z)*?T    x
3030                 Y(A)*?Z)*?T     x <- O
3031   Y             (A)*?Z)*?T      x <- O
3032   Y             A)*?Z)*?T       x <- O <- I
3033   YA            )*?Z)*?T        x <- O <- I
3034   YA            A)*?Z)*?T       x <- O <- I
3035   YAA           )*?Z)*?T        x <- O <- I
3036   YAA           Z)*?T           x <- O          # Temporary unset I
3037                                      I
3038
3039   YAAZ          Y(A)*?Z)*?T     x <- O
3040                                      I
3041
3042   YAAZY         (A)*?Z)*?T      x <- O
3043                                      I
3044
3045   YAAZY         A)*?Z)*?T       x <- O <- I
3046                                      I
3047
3048   YAAZYA        )*?Z)*?T        x <- O <- I     
3049                                      I
3050
3051   YAAZYA        Z)*?T           x <- O          # Temporary unset I
3052                                      I,I
3053
3054   YAAZYAZ       )*?T            x <- O
3055                                      I,I
3056
3057   YAAZYAZ       T               x               # Temporary unset O
3058                                 O
3059                                 I,I
3060
3061   YAAZYAZT                      x
3062                                 O
3063                                 I,I
3064  *******************************************************************/
3065         case CURLYX: {
3066                 CURCUR cc;
3067                 CHECKPOINT cp = PL_savestack_ix;
3068                 /* No need to save/restore up to this paren */
3069                 I32 parenfloor = scan->flags;
3070
3071                 if (OP(PREVOPER(next)) == NOTHING) /* LONGJMP */
3072                     next += ARG(next);
3073                 cc.oldcc = PL_regcc;
3074                 PL_regcc = &cc;
3075                 /* XXXX Probably it is better to teach regpush to support
3076                    parenfloor > PL_regsize... */
3077                 if (parenfloor > (I32)*PL_reglastparen)
3078                     parenfloor = *PL_reglastparen; /* Pessimization... */
3079                 cc.parenfloor = parenfloor;
3080                 cc.cur = -1;
3081                 cc.min = ARG1(scan);
3082                 cc.max  = ARG2(scan);
3083                 cc.scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
3084                 cc.next = next;
3085                 cc.minmod = minmod;
3086                 cc.lastloc = 0;
3087                 PL_reginput = locinput;
3088                 n = regmatch(PREVOPER(next));   /* start on the WHILEM */
3089                 regcpblow(cp);
3090                 PL_regcc = cc.oldcc;
3091                 saySAME(n);
3092             }
3093             /* NOT REACHED */
3094         case WHILEM: {
3095                 /*
3096                  * This is really hard to understand, because after we match
3097                  * what we're trying to match, we must make sure the rest of
3098                  * the REx is going to match for sure, and to do that we have
3099                  * to go back UP the parse tree by recursing ever deeper.  And
3100                  * if it fails, we have to reset our parent's current state
3101                  * that we can try again after backing off.
3102                  */
3103
3104                 CHECKPOINT cp, lastcp;
3105                 CURCUR* cc = PL_regcc;
3106                 char *lastloc = cc->lastloc; /* Detection of 0-len. */
3107                 
3108                 n = cc->cur + 1;        /* how many we know we matched */
3109                 PL_reginput = locinput;
3110
3111                 DEBUG_r(
3112                     PerlIO_printf(Perl_debug_log,
3113                                   "%*s  %ld out of %ld..%ld  cc=%"UVxf"\n",
3114                                   REPORT_CODE_OFF+PL_regindent*2, "",
3115                                   (long)n, (long)cc->min,
3116                                   (long)cc->max, PTR2UV(cc))
3117                     );
3118
3119                 /* If degenerate scan matches "", assume scan done. */
3120
3121                 if (locinput == cc->lastloc && n >= cc->min) {
3122                     PL_regcc = cc->oldcc;
3123                     if (PL_regcc)
3124                         ln = PL_regcc->cur;
3125                     DEBUG_r(
3126                         PerlIO_printf(Perl_debug_log,
3127                            "%*s  empty match detected, try continuation...\n",
3128                            REPORT_CODE_OFF+PL_regindent*2, "")
3129                         );
3130                     if (regmatch(cc->next))
3131                         sayYES;
3132                     if (PL_regcc)
3133                         PL_regcc->cur = ln;
3134                     PL_regcc = cc;
3135                     sayNO;
3136                 }
3137
3138                 /* First just match a string of min scans. */
3139
3140                 if (n < cc->min) {
3141                     cc->cur = n;
3142                     cc->lastloc = locinput;
3143                     if (regmatch(cc->scan))
3144                         sayYES;
3145                     cc->cur = n - 1;
3146                     cc->lastloc = lastloc;
3147                     sayNO;
3148                 }
3149
3150                 if (scan->flags) {
3151                     /* Check whether we already were at this position.
3152                         Postpone detection until we know the match is not
3153                         *that* much linear. */
3154                 if (!PL_reg_maxiter) {
3155                     PL_reg_maxiter = (PL_regeol - PL_bostr + 1) * (scan->flags>>4);
3156                     PL_reg_leftiter = PL_reg_maxiter;
3157                 }
3158                 if (PL_reg_leftiter-- == 0) {
3159                     I32 size = (PL_reg_maxiter + 7)/8;
3160                     if (PL_reg_poscache) {
3161                         if ((I32)PL_reg_poscache_size < size) {
3162                             Renew(PL_reg_poscache, size, char);
3163                             PL_reg_poscache_size = size;
3164                         }
3165                         Zero(PL_reg_poscache, size, char);
3166                     }
3167                     else {
3168                         PL_reg_poscache_size = size;
3169                         Newz(29, PL_reg_poscache, size, char);
3170                     }
3171                     DEBUG_r(
3172                         PerlIO_printf(Perl_debug_log,
3173               "%sDetected a super-linear match, switching on caching%s...\n",
3174                                       PL_colors[4], PL_colors[5])
3175                         );
3176                 }
3177                 if (PL_reg_leftiter < 0) {
3178                     I32 o = locinput - PL_bostr, b;
3179
3180                     o = (scan->flags & 0xf) - 1 + o * (scan->flags>>4);
3181                     b = o % 8;
3182                     o /= 8;
3183                     if (PL_reg_poscache[o] & (1<<b)) {
3184                     DEBUG_r(
3185                         PerlIO_printf(Perl_debug_log,
3186                                       "%*s  already tried at this position...\n",
3187                                       REPORT_CODE_OFF+PL_regindent*2, "")
3188                         );
3189                         sayNO_SILENT;
3190                     }
3191                     PL_reg_poscache[o] |= (1<<b);
3192                 }
3193                 }
3194
3195                 /* Prefer next over scan for minimal matching. */
3196
3197                 if (cc->minmod) {
3198                     PL_regcc = cc->oldcc;
3199                     if (PL_regcc)
3200                         ln = PL_regcc->cur;
3201                     cp = regcppush(cc->parenfloor);
3202                     REGCP_SET(lastcp);
3203                     if (regmatch(cc->next)) {
3204                         regcpblow(cp);
3205                         sayYES; /* All done. */
3206                     }
3207                     REGCP_UNWIND(lastcp);
3208                     regcppop();
3209                     if (PL_regcc)
3210                         PL_regcc->cur = ln;
3211                     PL_regcc = cc;
3212
3213                     if (n >= cc->max) { /* Maximum greed exceeded? */
3214                         if (ckWARN(WARN_REGEXP) && n >= REG_INFTY
3215                             && !(PL_reg_flags & RF_warned)) {
3216                             PL_reg_flags |= RF_warned;
3217                             Perl_warner(aTHX_ packWARN(WARN_REGEXP), "%s limit (%d) exceeded",
3218                                  "Complex regular subexpression recursion",
3219                                  REG_INFTY - 1);
3220                         }
3221                         sayNO;
3222                     }
3223
3224                     DEBUG_r(
3225                         PerlIO_printf(Perl_debug_log,
3226                                       "%*s  trying longer...\n",
3227                                       REPORT_CODE_OFF+PL_regindent*2, "")
3228                         );
3229                     /* Try scanning more and see if it helps. */
3230                     PL_reginput = locinput;
3231                     cc->cur = n;
3232                     cc->lastloc = locinput;
3233                     cp = regcppush(cc->parenfloor);
3234                     REGCP_SET(lastcp);
3235                     if (regmatch(cc->scan)) {
3236                         regcpblow(cp);
3237                         sayYES;
3238                     }
3239                     REGCP_UNWIND(lastcp);
3240                     regcppop();
3241                     cc->cur = n - 1;
3242                     cc->lastloc = lastloc;
3243                     sayNO;
3244                 }
3245
3246                 /* Prefer scan over next for maximal matching. */
3247
3248                 if (n < cc->max) {      /* More greed allowed? */
3249                     cp = regcppush(cc->parenfloor);
3250                     cc->cur = n;
3251                     cc->lastloc = locinput;
3252                     REGCP_SET(lastcp);
3253                     if (regmatch(cc->scan)) {
3254                         regcpblow(cp);
3255                         sayYES;
3256                     }
3257                     REGCP_UNWIND(lastcp);
3258                     regcppop();         /* Restore some previous $<digit>s? */
3259                     PL_reginput = locinput;
3260                     DEBUG_r(
3261                         PerlIO_printf(Perl_debug_log,
3262                                       "%*s  failed, try continuation...\n",
3263                                       REPORT_CODE_OFF+PL_regindent*2, "")
3264                         );
3265                 }
3266                 if (ckWARN(WARN_REGEXP) && n >= REG_INFTY
3267                         && !(PL_reg_flags & RF_warned)) {
3268                     PL_reg_flags |= RF_warned;
3269                     Perl_warner(aTHX_ packWARN(WARN_REGEXP), "%s limit (%d) exceeded",
3270                          "Complex regular subexpression recursion",
3271                          REG_INFTY - 1);
3272                 }
3273
3274                 /* Failed deeper matches of scan, so see if this one works. */
3275                 PL_regcc = cc->oldcc;
3276                 if (PL_regcc)
3277                     ln = PL_regcc->cur;
3278                 if (regmatch(cc->next))
3279                     sayYES;
3280                 if (PL_regcc)
3281                     PL_regcc->cur = ln;
3282                 PL_regcc = cc;
3283                 cc->cur = n - 1;
3284                 cc->lastloc = lastloc;
3285                 sayNO;
3286             }
3287             /* NOT REACHED */
3288         case BRANCHJ:
3289             next = scan + ARG(scan);
3290             if (next == scan)
3291                 next = NULL;
3292             inner = NEXTOPER(NEXTOPER(scan));
3293             goto do_branch;
3294         case BRANCH:
3295             inner = NEXTOPER(scan);
3296           do_branch:
3297             {
3298                 c1 = OP(scan);
3299                 if (OP(next) != c1)     /* No choice. */
3300                     next = inner;       /* Avoid recursion. */
3301                 else {
3302                     I32 lastparen = *PL_reglastparen;
3303                     I32 unwind1;
3304                     re_unwind_branch_t *uw;
3305
3306                     /* Put unwinding data on stack */
3307                     unwind1 = SSNEWt(1,re_unwind_branch_t);
3308                     uw = SSPTRt(unwind1,re_unwind_branch_t);
3309                     uw->prev = unwind;
3310                     unwind = unwind1;
3311                     uw->type = ((c1 == BRANCH)
3312                                 ? RE_UNWIND_BRANCH
3313                                 : RE_UNWIND_BRANCHJ);
3314                     uw->lastparen = lastparen;
3315                     uw->next = next;
3316                     uw->locinput = locinput;
3317                     uw->nextchr = nextchr;
3318 #ifdef DEBUGGING
3319                     uw->regindent = ++PL_regindent;
3320 #endif
3321
3322                     REGCP_SET(uw->lastcp);
3323
3324                     /* Now go into the first branch */
3325                     next = inner;
3326                 }
3327             }
3328             break;
3329         case MINMOD:
3330             minmod = 1;
3331             break;
3332         case CURLYM:
3333         {
3334             I32 l = 0;
3335             CHECKPOINT lastcp;
3336         
3337             /* We suppose that the next guy does not need
3338                backtracking: in particular, it is of constant length,
3339                and has no parenths to influence future backrefs. */
3340             ln = ARG1(scan);  /* min to match */
3341             n  = ARG2(scan);  /* max to match */
3342             paren = scan->flags;
3343             if (paren) {
3344                 if (paren > PL_regsize)
3345                     PL_regsize = paren;
3346                 if (paren > (I32)*PL_reglastparen)
3347                     *PL_reglastparen = paren;
3348             }
3349             scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
3350             if (paren)
3351                 scan += NEXT_OFF(scan); /* Skip former OPEN. */
3352             PL_reginput = locinput;
3353             if (minmod) {
3354                 minmod = 0;
3355                 if (ln && regrepeat_hard(scan, ln, &l) < ln)
3356                     sayNO;
3357                 /* if we matched something zero-length we don't need to
3358                    backtrack - capturing parens are already defined, so
3359                    the caveat in the maximal case doesn't apply
3360
3361                    XXXX if ln == 0, we can redo this check first time
3362                    through the following loop
3363                 */
3364                 if (ln && l == 0)
3365                     n = ln;     /* don't backtrack */
3366                 locinput = PL_reginput;
3367                 if (HAS_TEXT(next) || JUMPABLE(next)) {
3368                     regnode *text_node = next;
3369
3370                     if (! HAS_TEXT(text_node)) FIND_NEXT_IMPT(text_node);
3371
3372                     if (! HAS_TEXT(text_node)) c1 = c2 = -1000;
3373                     else {
3374                         if (PL_regkind[(U8)OP(text_node)] == REF) {
3375                             I32 n, ln;
3376                             n = ARG(text_node);  /* which paren pair */
3377                             ln = PL_regstartp[n];
3378                             /* assume yes if we haven't seen CLOSEn */
3379                             if (
3380                                 (I32)*PL_reglastparen < n ||
3381                                 ln == -1 ||
3382                                 ln == PL_regendp[n]
3383                             ) {
3384                                 c1 = c2 = -1000;
3385                                 goto assume_ok_MM;
3386                             }
3387                             c1 = *(PL_bostr + ln);
3388                         }
3389                         else { c1 = (U8)*STRING(text_node); }
3390                         if (OP(text_node) == EXACTF || OP(text_node) == REFF)
3391                             c2 = PL_fold[c1];
3392                         else if (OP(text_node) == EXACTFL || OP(text_node) == REFFL)
3393                             c2 = PL_fold_locale[c1];
3394                         else
3395                             c2 = c1;
3396                     }
3397                 }
3398                 else
3399                     c1 = c2 = -1000;
3400             assume_ok_MM:
3401                 REGCP_SET(lastcp);
3402                 /* This may be improved if l == 0.  */
3403                 while (n >= ln || (n == REG_INFTY && ln > 0 && l)) { /* ln overflow ? */
3404                     /* If it could work, try it. */
3405                     if (c1 == -1000 ||
3406                         UCHARAT(PL_reginput) == c1 ||
3407                         UCHARAT(PL_reginput) == c2)
3408                     {
3409                         if (paren) {
3410                             if (ln) {
3411                                 PL_regstartp[paren] =
3412                                     HOPc(PL_reginput, -l) - PL_bostr;
3413                                 PL_regendp[paren] = PL_reginput - PL_bostr;
3414                             }
3415                             else
3416                                 PL_regendp[paren] = -1;
3417                         }
3418                         if (regmatch(next))
3419                             sayYES;
3420                         REGCP_UNWIND(lastcp);
3421                     }
3422                     /* Couldn't or didn't -- move forward. */
3423                     PL_reginput = locinput;
3424                     if (regrepeat_hard(scan, 1, &l)) {
3425                         ln++;
3426                         locinput = PL_reginput;
3427                     }
3428                     else
3429                         sayNO;
3430                 }
3431             }
3432             else {
3433                 n = regrepeat_hard(scan, n, &l);
3434                 /* if we matched something zero-length we don't need to
3435                    backtrack, unless the minimum count is zero and we
3436                    are capturing the result - in that case the capture
3437                    being defined or not may affect later execution
3438                 */
3439                 if (n != 0 && l == 0 && !(paren && ln == 0))
3440                     ln = n;     /* don't backtrack */
3441                 locinput = PL_reginput;
3442                 DEBUG_r(
3443                     PerlIO_printf(Perl_debug_log,
3444                                   "%*s  matched %"IVdf" times, len=%"IVdf"...\n",
3445                                   (int)(REPORT_CODE_OFF+PL_regindent*2), "",
3446                                   (IV) n, (IV)l)
3447                     );
3448                 if (n >= ln) {
3449                     if (HAS_TEXT(next) || JUMPABLE(next)) {
3450                         regnode *text_node = next;
3451
3452                         if (! HAS_TEXT(text_node)) FIND_NEXT_IMPT(text_node);
3453
3454                         if (! HAS_TEXT(text_node)) c1 = c2 = -1000;
3455                         else {
3456                             if (PL_regkind[(U8)OP(text_node)] == REF) {
3457                                 I32 n, ln;
3458                                 n = ARG(text_node);  /* which paren pair */
3459                                 ln = PL_regstartp[n];
3460                                 /* assume yes if we haven't seen CLOSEn */
3461                                 if (
3462                                     (I32)*PL_reglastparen < n ||
3463                                     ln == -1 ||
3464                                     ln == PL_regendp[n]
3465                                 ) {
3466                                     c1 = c2 = -1000;
3467                                     goto assume_ok_REG;
3468                                 }
3469                                 c1 = *(PL_bostr + ln);
3470                             }
3471                             else { c1 = (U8)*STRING(text_node); }
3472
3473                             if (OP(text_node) == EXACTF || OP(text_node) == REFF)
3474                                 c2 = PL_fold[c1];
3475                             else if (OP(text_node) == EXACTFL || OP(text_node) == REFFL)
3476                                 c2 = PL_fold_locale[c1];
3477                             else
3478                                 c2 = c1;
3479                         }
3480                     }
3481                     else
3482                         c1 = c2 = -1000;
3483                 }
3484             assume_ok_REG:
3485                 REGCP_SET(lastcp);
3486                 while (n >= ln) {
3487                     /* If it could work, try it. */
3488                     if (c1 == -1000 ||
3489                         UCHARAT(PL_reginput) == c1 ||
3490                         UCHARAT(PL_reginput) == c2)
3491                     {
3492                         DEBUG_r(
3493                                 PerlIO_printf(Perl_debug_log,
3494                                               "%*s  trying tail with n=%"IVdf"...\n",
3495                                               (int)(REPORT_CODE_OFF+PL_regindent*2), "", (IV)n)
3496                             );
3497                         if (paren) {
3498                             if (n) {
3499                                 PL_regstartp[paren] = HOPc(PL_reginput, -l) - PL_bostr;
3500                                 PL_regendp[paren] = PL_reginput - PL_bostr;
3501                             }
3502                             else
3503                                 PL_regendp[paren] = -1;
3504                         }
3505                         if (regmatch(next))
3506                             sayYES;
3507                         REGCP_UNWIND(lastcp);
3508                     }
3509                     /* Couldn't or didn't -- back up. */
3510                     n--;
3511                     locinput = HOPc(locinput, -l);
3512                     PL_reginput = locinput;
3513                 }
3514             }
3515             sayNO;
3516             break;
3517         }
3518         case CURLYN:
3519             paren = scan->flags;        /* Which paren to set */
3520             if (paren > PL_regsize)
3521                 PL_regsize = paren;
3522             if (paren > (I32)*PL_reglastparen)
3523                 *PL_reglastparen = paren;
3524             ln = ARG1(scan);  /* min to match */
3525             n  = ARG2(scan);  /* max to match */
3526             scan = regnext(NEXTOPER(scan) + NODE_STEP_REGNODE);
3527             goto repeat;
3528         case CURLY:
3529             paren = 0;
3530             ln = ARG1(scan);  /* min to match */
3531             n  = ARG2(scan);  /* max to match */
3532             scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
3533             goto repeat;
3534         case STAR:
3535             ln = 0;
3536             n = REG_INFTY;
3537             scan = NEXTOPER(scan);
3538             paren = 0;
3539             goto repeat;
3540         case PLUS:
3541             ln = 1;
3542             n = REG_INFTY;
3543             scan = NEXTOPER(scan);
3544             paren = 0;
3545           repeat:
3546             /*
3547             * Lookahead to avoid useless match attempts
3548             * when we know what character comes next.
3549             */
3550
3551             /*
3552             * Used to only do .*x and .*?x, but now it allows
3553             * for )'s, ('s and (?{ ... })'s to be in the way
3554             * of the quantifier and the EXACT-like node.  -- japhy
3555             */
3556
3557             if (HAS_TEXT(next) || JUMPABLE(next)) {
3558                 U8 *s;
3559                 regnode *text_node = next;
3560
3561                 if (! HAS_TEXT(text_node)) FIND_NEXT_IMPT(text_node);
3562
3563                 if (! HAS_TEXT(text_node)) c1 = c2 = -1000;
3564                 else {
3565                     if (PL_regkind[(U8)OP(text_node)] == REF) {
3566                         I32 n, ln;
3567                         n = ARG(text_node);  /* which paren pair */
3568                         ln = PL_regstartp[n];
3569                         /* assume yes if we haven't seen CLOSEn */
3570                         if (
3571                             (I32)*PL_reglastparen < n ||
3572                             ln == -1 ||
3573                             ln == PL_regendp[n]
3574                         ) {
3575                             c1 = c2 = -1000;
3576                             goto assume_ok_easy;
3577                         }
3578                         s = (U8*)PL_bostr + ln;
3579                     }
3580                     else { s = (U8*)STRING(text_node); }
3581
3582                     if (!UTF) {
3583                         c2 = c1 = *s;
3584                         if (OP(text_node) == EXACTF || OP(text_node) == REFF)
3585                             c2 = PL_fold[c1];
3586                         else if (OP(text_node) == EXACTFL || OP(text_node) == REFFL)
3587                             c2 = PL_fold_locale[c1];
3588                     }
3589                     else { /* UTF */
3590                         if (OP(text_node) == EXACTF || OP(text_node) == REFF) {
3591                              STRLEN ulen1, ulen2;
3592                              U8 tmpbuf1[UTF8_MAXLEN_UCLC+1];
3593                              U8 tmpbuf2[UTF8_MAXLEN_UCLC+1];
3594
3595                              to_utf8_lower((U8*)s, tmpbuf1, &ulen1);
3596                              to_utf8_upper((U8*)s, tmpbuf2, &ulen2);
3597
3598                              c1 = utf8n_to_uvuni(tmpbuf1, UTF8_MAXLEN, 0,
3599                                                  ckWARN(WARN_UTF8) ?
3600                                                  0 : UTF8_ALLOW_ANY);
3601                              c2 = utf8n_to_uvuni(tmpbuf2, UTF8_MAXLEN, 0,
3602                                                  ckWARN(WARN_UTF8) ?
3603                                                  0 : UTF8_ALLOW_ANY);
3604                         }
3605                         else {
3606                             c2 = c1 = utf8n_to_uvchr(s, UTF8_MAXLEN, 0,
3607                                                      ckWARN(WARN_UTF8) ?
3608                                                      0 : UTF8_ALLOW_ANY);
3609                         }
3610                     }
3611                 }
3612             }
3613             else
3614                 c1 = c2 = -1000;
3615         assume_ok_easy:
3616             PL_reginput = locinput;
3617             if (minmod) {
3618                 CHECKPOINT lastcp;
3619                 minmod = 0;
3620                 if (ln && regrepeat(scan, ln) < ln)
3621                     sayNO;
3622                 locinput = PL_reginput;
3623                 REGCP_SET(lastcp);
3624                 if (c1 != -1000) {
3625                     char *e; /* Should not check after this */
3626                     char *old = locinput;
3627                     int count = 0;
3628
3629                     if  (n == REG_INFTY) {
3630                         e = PL_regeol - 1;
3631                         if (do_utf8)
3632                             while (UTF8_IS_CONTINUATION(*(U8*)e))
3633                                 e--;
3634                     }
3635                     else if (do_utf8) {
3636                         int m = n - ln;
3637                         for (e = locinput;
3638                              m >0 && e + UTF8SKIP(e) <= PL_regeol; m--)
3639                             e += UTF8SKIP(e);
3640                     }
3641                     else {
3642                         e = locinput + n - ln;
3643                         if (e >= PL_regeol)
3644                             e = PL_regeol - 1;
3645                     }
3646                     while (1) {
3647                         /* Find place 'next' could work */
3648                         if (!do_utf8) {
3649                             if (c1 == c2) {
3650                                 while (locinput <= e &&
3651                                        UCHARAT(locinput) != c1)
3652                                     locinput++;
3653                             } else {
3654                                 while (locinput <= e
3655                                        && UCHARAT(locinput) != c1
3656                                        && UCHARAT(locinput) != c2)
3657                                     locinput++;
3658                             }
3659                             count = locinput - old;
3660                         }
3661                         else {
3662                             STRLEN len;
3663                             if (c1 == c2) {
3664                                 /* count initialised to
3665                                  * utf8_distance(old, locinput) */
3666                                 while (locinput <= e &&
3667                                        utf8n_to_uvchr((U8*)locinput,
3668                                                       UTF8_MAXLEN, &len,
3669                                                       ckWARN(WARN_UTF8) ?
3670                                                       0 : UTF8_ALLOW_ANY) != (UV)c1) {
3671                                     locinput += len;
3672                                     count++;
3673                                 }
3674                             } else {
3675                                 /* count initialised to
3676                                  * utf8_distance(old, locinput) */
3677                                 while (locinput <= e) {
3678                                     UV c = utf8n_to_uvchr((U8*)locinput,
3679                                                           UTF8_MAXLEN, &len,
3680                                                           ckWARN(WARN_UTF8) ?
3681                                                           0 : UTF8_ALLOW_ANY);
3682                                     if (c == (UV)c1 || c == (UV)c2)
3683                                         break;
3684                                     locinput += len;
3685                                     count++;
3686                                 }
3687                             }
3688                         }
3689                         if (locinput > e)
3690                             sayNO;
3691                         /* PL_reginput == old now */
3692                         if (locinput != old) {
3693                             ln = 1;     /* Did some */
3694                             if (regrepeat(scan, count) < count)
3695                                 sayNO;
3696                         }
3697                         /* PL_reginput == locinput now */
3698                         TRYPAREN(paren, ln, locinput);
3699                         PL_reginput = locinput; /* Could be reset... */
3700                         REGCP_UNWIND(lastcp);
3701                         /* Couldn't or didn't -- move forward. */
3702                         old = locinput;
3703                         if (do_utf8)
3704                             locinput += UTF8SKIP(locinput);
3705                         else
3706                             locinput++;
3707                         count = 1;
3708                     }
3709                 }
3710                 else
3711                 while (n >= ln || (n == REG_INFTY && ln > 0)) { /* ln overflow ? */
3712                     UV c;
3713                     if (c1 != -1000) {
3714                         if (do_utf8)
3715                             c = utf8n_to_uvchr((U8*)PL_reginput,
3716                                                UTF8_MAXLEN, 0,
3717                                                ckWARN(WARN_UTF8) ?
3718                                                0 : UTF8_ALLOW_ANY);
3719                         else
3720                             c = UCHARAT(PL_reginput);
3721                         /* If it could work, try it. */
3722                         if (c == (UV)c1 || c == (UV)c2)
3723                         {
3724                             TRYPAREN(paren, ln, PL_reginput);
3725                             REGCP_UNWIND(lastcp);
3726                         }
3727                     }
3728                     /* If it could work, try it. */
3729                     else if (c1 == -1000)
3730                     {
3731                         TRYPAREN(paren, ln, PL_reginput);
3732                         REGCP_UNWIND(lastcp);
3733                     }
3734                     /* Couldn't or didn't -- move forward. */
3735                     PL_reginput = locinput;
3736                     if (regrepeat(scan, 1)) {
3737                         ln++;
3738                         locinput = PL_reginput;
3739                     }
3740                     else
3741                         sayNO;
3742                 }
3743             }
3744             else {
3745                 CHECKPOINT lastcp;
3746                 n = regrepeat(scan, n);
3747                 locinput = PL_reginput;
3748                 if (ln < n && PL_regkind[(U8)OP(next)] == EOL &&
3749                     ((!PL_multiline && OP(next) != MEOL) ||
3750                         OP(next) == SEOL || OP(next) == EOS))
3751                 {
3752                     ln = n;                     /* why back off? */
3753                     /* ...because $ and \Z can match before *and* after
3754                        newline at the end.  Consider "\n\n" =~ /\n+\Z\n/.
3755                        We should back off by one in this case. */
3756                     if (UCHARAT(PL_reginput - 1) == '\n' && OP(next) != EOS)
3757                         ln--;
3758                 }
3759                 REGCP_SET(lastcp);
3760                 if (paren) {
3761                     UV c = 0;
3762                     while (n >= ln) {
3763                         if (c1 != -1000) {
3764                             if (do_utf8)
3765                                 c = utf8n_to_uvchr((U8*)PL_reginput,
3766                                                    UTF8_MAXLEN, 0,
3767                                                    ckWARN(WARN_UTF8) ?
3768                                                    0 : UTF8_ALLOW_ANY);
3769                             else
3770                                 c = UCHARAT(PL_reginput);
3771                         }
3772                         /* If it could work, try it. */
3773                         if (c1 == -1000 || c == (UV)c1 || c == (UV)c2)
3774                             {
3775                                 TRYPAREN(paren, n, PL_reginput);
3776                                 REGCP_UNWIND(lastcp);
3777                             }
3778                         /* Couldn't or didn't -- back up. */
3779                         n--;
3780                         PL_reginput = locinput = HOPc(locinput, -1);
3781                     }
3782                 }
3783                 else {
3784                     UV c = 0;
3785                     while (n >= ln) {
3786                         if (c1 != -1000) {
3787                             if (do_utf8)
3788                                 c = utf8n_to_uvchr((U8*)PL_reginput,
3789                                                    UTF8_MAXLEN, 0,
3790                                                    ckWARN(WARN_UTF8) ?
3791                                                    0 : UTF8_ALLOW_ANY);
3792                             else
3793                                 c = UCHARAT(PL_reginput);
3794                         }
3795                         /* If it could work, try it. */
3796                         if (c1 == -1000 || c == (UV)c1 || c == (UV)c2)
3797                             {
3798                                 TRYPAREN(paren, n, PL_reginput);
3799                                 REGCP_UNWIND(lastcp);
3800                             }
3801                         /* Couldn't or didn't -- back up. */
3802                         n--;
3803                         PL_reginput = locinput = HOPc(locinput, -1);
3804                     }
3805                 }
3806             }
3807             sayNO;
3808             break;
3809         case END:
3810             if (PL_reg_call_cc) {
3811                 re_cc_state *cur_call_cc = PL_reg_call_cc;
3812                 CURCUR *cctmp = PL_regcc;
3813                 regexp *re = PL_reg_re;
3814                 CHECKPOINT cp, lastcp;
3815                 
3816                 cp = regcppush(0);      /* Save *all* the positions. */
3817                 REGCP_SET(lastcp);
3818                 regcp_set_to(PL_reg_call_cc->ss); /* Restore parens of
3819                                                     the caller. */
3820                 PL_reginput = locinput; /* Make position available to
3821                                            the callcc. */
3822                 cache_re(PL_reg_call_cc->re);
3823                 PL_regcc = PL_reg_call_cc->cc;
3824                 PL_reg_call_cc = PL_reg_call_cc->prev;
3825                 if (regmatch(cur_call_cc->node)) {
3826                     PL_reg_call_cc = cur_call_cc;
3827                     regcpblow(cp);
3828                     sayYES;
3829                 }
3830                 REGCP_UNWIND(lastcp);
3831                 regcppop();
3832                 PL_reg_call_cc = cur_call_cc;
3833                 PL_regcc = cctmp;
3834                 PL_reg_re = re;
3835                 cache_re(re);
3836
3837                 DEBUG_r(
3838                     PerlIO_printf(Perl_debug_log,
3839                                   "%*s  continuation failed...\n",
3840                                   REPORT_CODE_OFF+PL_regindent*2, "")
3841                     );
3842                 sayNO_SILENT;
3843             }
3844             if (locinput < PL_regtill) {
3845                 DEBUG_r(PerlIO_printf(Perl_debug_log,
3846                                       "%sMatch possible, but length=%ld is smaller than requested=%ld, failing!%s\n",
3847                                       PL_colors[4],
3848                                       (long)(locinput - PL_reg_starttry),
3849                                       (long)(PL_regtill - PL_reg_starttry),
3850                                       PL_colors[5]));
3851                 sayNO_FINAL;            /* Cannot match: too short. */
3852             }
3853             PL_reginput = locinput;     /* put where regtry can find it */
3854             sayYES_FINAL;               /* Success! */
3855         case SUCCEED:
3856             PL_reginput = locinput;     /* put where regtry can find it */
3857             sayYES_LOUD;                /* Success! */
3858         case SUSPEND:
3859             n = 1;
3860             PL_reginput = locinput;
3861             goto do_ifmatch;    
3862         case UNLESSM:
3863             n = 0;
3864             if (scan->flags) {
3865                 s = HOPBACKc(locinput, scan->flags);
3866                 if (!s)
3867                     goto say_yes;
3868                 PL_reginput = s;
3869             }
3870             else
3871                 PL_reginput = locinput;
3872             goto do_ifmatch;
3873         case IFMATCH:
3874             n = 1;
3875             if (scan->flags) {
3876                 s = HOPBACKc(locinput, scan->flags);
3877                 if (!s)
3878                     goto say_no;
3879                 PL_reginput = s;
3880             }
3881             else
3882                 PL_reginput = locinput;
3883
3884           do_ifmatch:
3885             inner = NEXTOPER(NEXTOPER(scan));
3886             if (regmatch(inner) != n) {
3887               say_no:
3888                 if (logical) {
3889                     logical = 0;
3890                     sw = 0;
3891                     goto do_longjump;
3892                 }
3893                 else
3894                     sayNO;
3895             }
3896           say_yes:
3897             if (logical) {
3898                 logical = 0;
3899                 sw = 1;
3900             }
3901             if (OP(scan) == SUSPEND) {
3902                 locinput = PL_reginput;
3903                 nextchr = UCHARAT(locinput);
3904             }
3905             /* FALL THROUGH. */
3906         case LONGJMP:
3907           do_longjump:
3908             next = scan + ARG(scan);
3909             if (next == scan)
3910                 next = NULL;
3911             break;
3912         default:
3913             PerlIO_printf(Perl_error_log, "%"UVxf" %d\n",
3914                           PTR2UV(scan), OP(scan));
3915             Perl_croak(aTHX_ "regexp memory corruption");
3916         }
3917       reenter:
3918         scan = next;
3919     }
3920
3921     /*
3922     * We get here only if there's trouble -- normally "case END" is
3923     * the terminating point.
3924     */
3925     Perl_croak(aTHX_ "corrupted regexp pointers");
3926     /*NOTREACHED*/
3927     sayNO;
3928
3929 yes_loud:
3930     DEBUG_r(
3931         PerlIO_printf(Perl_debug_log,
3932                       "%*s  %scould match...%s\n",
3933                       REPORT_CODE_OFF+PL_regindent*2, "", PL_colors[4],PL_colors[5])
3934         );
3935     goto yes;
3936 yes_final:
3937     DEBUG_r(PerlIO_printf(Perl_debug_log, "%sMatch successful!%s\n",
3938                           PL_colors[4],PL_colors[5]));
3939 yes:
3940 #ifdef DEBUGGING
3941     PL_regindent--;
3942 #endif
3943
3944 #if 0                                   /* Breaks $^R */
3945     if (unwind)
3946         regcpblow(firstcp);
3947 #endif
3948     return 1;
3949
3950 no:
3951     DEBUG_r(
3952         PerlIO_printf(Perl_debug_log,
3953                       "%*s  %sfailed...%s\n",
3954                       REPORT_CODE_OFF+PL_regindent*2, "",PL_colors[4],PL_colors[5])
3955         );
3956     goto do_no;
3957 no_final:
3958 do_no:
3959     if (unwind) {
3960         re_unwind_t *uw = SSPTRt(unwind,re_unwind_t);
3961
3962         switch (uw->type) {
3963         case RE_UNWIND_BRANCH:
3964         case RE_UNWIND_BRANCHJ:
3965         {
3966             re_unwind_branch_t *uwb = &(uw->branch);
3967             I32 lastparen = uwb->lastparen;
3968         
3969             REGCP_UNWIND(uwb->lastcp);
3970             for (n = *PL_reglastparen; n > lastparen; n--)
3971                 PL_regendp[n] = -1;
3972             *PL_reglastparen = n;
3973             scan = next = uwb->next;
3974             if ( !scan ||
3975                  OP(scan) != (uwb->type == RE_UNWIND_BRANCH
3976                               ? BRANCH : BRANCHJ) ) {           /* Failure */
3977                 unwind = uwb->prev;
3978 #ifdef DEBUGGING
3979                 PL_regindent--;
3980 #endif
3981                 goto do_no;
3982             }
3983             /* Have more choice yet.  Reuse the same uwb.  */
3984             /*SUPPRESS 560*/
3985             if ((n = (uwb->type == RE_UNWIND_BRANCH
3986                       ? NEXT_OFF(next) : ARG(next))))
3987                 next += n;
3988             else
3989                 next = NULL;    /* XXXX Needn't unwinding in this case... */
3990             uwb->next = next;
3991             next = NEXTOPER(scan);
3992             if (uwb->type == RE_UNWIND_BRANCHJ)
3993                 next = NEXTOPER(next);
3994             locinput = uwb->locinput;
3995             nextchr = uwb->nextchr;
3996 #ifdef DEBUGGING
3997             PL_regindent = uwb->regindent;
3998 #endif
3999
4000             goto reenter;
4001         }
4002         /* NOT REACHED */
4003         default:
4004             Perl_croak(aTHX_ "regexp unwind memory corruption");
4005         }
4006         /* NOT REACHED */
4007     }
4008 #ifdef DEBUGGING
4009     PL_regindent--;
4010 #endif
4011     return 0;
4012 }
4013
4014 /*
4015  - regrepeat - repeatedly match something simple, report how many
4016  */
4017 /*
4018  * [This routine now assumes that it will only match on things of length 1.
4019  * That was true before, but now we assume scan - reginput is the count,
4020  * rather than incrementing count on every character.  [Er, except utf8.]]
4021  */
4022 STATIC I32
4023 S_regrepeat(pTHX_ regnode *p, I32 max)
4024 {
4025     register char *scan;
4026     register I32 c;
4027     register char *loceol = PL_regeol;
4028     register I32 hardcount = 0;
4029     register bool do_utf8 = PL_reg_match_utf8;
4030
4031     scan = PL_reginput;
4032     if (max == REG_INFTY)
4033         max = I32_MAX;
4034     else if (max < loceol - scan)
4035       loceol = scan + max;
4036     switch (OP(p)) {
4037     case REG_ANY:
4038         if (do_utf8) {
4039             loceol = PL_regeol;
4040             while (scan < loceol && hardcount < max && *scan != '\n') {
4041                 scan += UTF8SKIP(scan);
4042                 hardcount++;
4043             }
4044         } else {
4045             while (scan < loceol && *scan != '\n')
4046                 scan++;
4047         }
4048         break;
4049     case SANY:
4050         if (do_utf8) {
4051             loceol = PL_regeol;
4052             while (scan < loceol && hardcount < max) {
4053                 scan += UTF8SKIP(scan);
4054                 hardcount++;
4055             }
4056         }
4057         else
4058             scan = loceol;
4059         break;
4060     case CANY:
4061         scan = loceol;
4062         break;
4063     case EXACT:         /* length of string is 1 */
4064         c = (U8)*STRING(p);
4065         while (scan < loceol && UCHARAT(scan) == c)
4066             scan++;
4067         break;
4068     case EXACTF:        /* length of string is 1 */
4069         c = (U8)*STRING(p);
4070         while (scan < loceol &&
4071                (UCHARAT(scan) == c || UCHARAT(scan) == PL_fold[c]))
4072             scan++;
4073         break;
4074     case EXACTFL:       /* length of string is 1 */
4075         PL_reg_flags |= RF_tainted;
4076         c = (U8)*STRING(p);
4077         while (scan < loceol &&
4078                (UCHARAT(scan) == c || UCHARAT(scan) == PL_fold_locale[c]))
4079             scan++;
4080         break;
4081     case ANYOF:
4082         if (do_utf8) {
4083             loceol = PL_regeol;
4084             while (hardcount < max && scan < loceol &&
4085                    reginclass(p, (U8*)scan, 0, do_utf8)) {
4086                 scan += UTF8SKIP(scan);
4087                 hardcount++;
4088             }
4089         } else {
4090             while (scan < loceol && REGINCLASS(p, (U8*)scan))
4091                 scan++;
4092         }
4093         break;
4094     case ALNUM:
4095         if (do_utf8) {
4096             loceol = PL_regeol;
4097             LOAD_UTF8_CHARCLASS(alnum,"a");
4098             while (hardcount < max && scan < loceol &&
4099                    swash_fetch(PL_utf8_alnum, (U8*)scan, do_utf8)) {
4100                 scan += UTF8SKIP(scan);
4101                 hardcount++;
4102             }
4103         } else {
4104             while (scan < loceol && isALNUM(*scan))
4105                 scan++;
4106         }
4107         break;
4108     case ALNUML:
4109         PL_reg_flags |= RF_tainted;
4110         if (do_utf8) {
4111             loceol = PL_regeol;
4112             while (hardcount < max && scan < loceol &&
4113                    isALNUM_LC_utf8((U8*)scan)) {
4114                 scan += UTF8SKIP(scan);
4115                 hardcount++;
4116             }
4117         } else {
4118             while (scan < loceol && isALNUM_LC(*scan))
4119                 scan++;
4120         }
4121         break;
4122     case NALNUM:
4123         if (do_utf8) {
4124             loceol = PL_regeol;
4125             LOAD_UTF8_CHARCLASS(alnum,"a");
4126             while (hardcount < max && scan < loceol &&
4127                    !swash_fetch(PL_utf8_alnum, (U8*)scan, do_utf8)) {
4128                 scan += UTF8SKIP(scan);
4129                 hardcount++;
4130             }
4131         } else {
4132             while (scan < loceol && !isALNUM(*scan))
4133                 scan++;
4134         }
4135         break;
4136     case NALNUML:
4137         PL_reg_flags |= RF_tainted;
4138         if (do_utf8) {
4139             loceol = PL_regeol;
4140             while (hardcount < max && scan < loceol &&
4141                    !isALNUM_LC_utf8((U8*)scan)) {
4142                 scan += UTF8SKIP(scan);
4143                 hardcount++;
4144             }
4145         } else {
4146             while (scan < loceol && !isALNUM_LC(*scan))
4147                 scan++;
4148         }
4149         break;
4150     case SPACE:
4151         if (do_utf8) {
4152             loceol = PL_regeol;
4153             LOAD_UTF8_CHARCLASS(space," ");
4154             while (hardcount < max && scan < loceol &&
4155                    (*scan == ' ' ||
4156                     swash_fetch(PL_utf8_space,(U8*)scan, do_utf8))) {
4157                 scan += UTF8SKIP(scan);
4158                 hardcount++;
4159             }
4160         } else {
4161             while (scan < loceol && isSPACE(*scan))
4162                 scan++;
4163         }
4164         break;
4165     case SPACEL:
4166         PL_reg_flags |= RF_tainted;
4167         if (do_utf8) {
4168             loceol = PL_regeol;
4169             while (hardcount < max && scan < loceol &&
4170                    (*scan == ' ' || isSPACE_LC_utf8((U8*)scan))) {
4171                 scan += UTF8SKIP(scan);
4172                 hardcount++;
4173             }
4174         } else {
4175             while (scan < loceol && isSPACE_LC(*scan))
4176                 scan++;
4177         }
4178         break;
4179     case NSPACE:
4180         if (do_utf8) {
4181             loceol = PL_regeol;
4182             LOAD_UTF8_CHARCLASS(space," ");
4183             while (hardcount < max && scan < loceol &&
4184                    !(*scan == ' ' ||
4185                      swash_fetch(PL_utf8_space,(U8*)scan, do_utf8))) {
4186                 scan += UTF8SKIP(scan);
4187                 hardcount++;
4188             }
4189         } else {
4190             while (scan < loceol && !isSPACE(*scan))
4191                 scan++;
4192             break;
4193         }
4194     case NSPACEL:
4195         PL_reg_flags |= RF_tainted;
4196         if (do_utf8) {
4197             loceol = PL_regeol;
4198             while (hardcount < max && scan < loceol &&
4199                    !(*scan == ' ' || isSPACE_LC_utf8((U8*)scan))) {
4200                 scan += UTF8SKIP(scan);
4201                 hardcount++;
4202             }
4203         } else {
4204             while (scan < loceol && !isSPACE_LC(*scan))
4205                 scan++;
4206         }
4207         break;
4208     case DIGIT:
4209         if (do_utf8) {
4210             loceol = PL_regeol;
4211             LOAD_UTF8_CHARCLASS(digit,"0");
4212             while (hardcount < max && scan < loceol &&
4213                    swash_fetch(PL_utf8_digit, (U8*)scan, do_utf8)) {
4214                 scan += UTF8SKIP(scan);
4215                 hardcount++;
4216             }
4217         } else {
4218             while (scan < loceol && isDIGIT(*scan))
4219                 scan++;
4220         }
4221         break;
4222     case NDIGIT:
4223         if (do_utf8) {
4224             loceol = PL_regeol;
4225             LOAD_UTF8_CHARCLASS(digit,"0");
4226             while (hardcount < max && scan < loceol &&
4227                    !swash_fetch(PL_utf8_digit, (U8*)scan, do_utf8)) {
4228                 scan += UTF8SKIP(scan);
4229                 hardcount++;
4230             }
4231         } else {
4232             while (scan < loceol && !isDIGIT(*scan))
4233                 scan++;
4234         }
4235         break;
4236     default:            /* Called on something of 0 width. */
4237         break;          /* So match right here or not at all. */
4238     }
4239
4240     if (hardcount)
4241         c = hardcount;
4242     else
4243         c = scan - PL_reginput;
4244     PL_reginput = scan;
4245
4246     DEBUG_r(
4247         {
4248                 SV *prop = sv_newmortal();
4249
4250                 regprop(prop, p);
4251                 PerlIO_printf(Perl_debug_log,
4252                               "%*s  %s can match %"IVdf" times out of %"IVdf"...\n",
4253                               REPORT_CODE_OFF+1, "", SvPVX(prop),(IV)c,(IV)max);
4254         });
4255
4256     return(c);
4257 }
4258
4259 /*
4260  - regrepeat_hard - repeatedly match something, report total lenth and length
4261  *
4262  * The repeater is supposed to have constant length.
4263  */
4264
4265 STATIC I32
4266 S_regrepeat_hard(pTHX_ regnode *p, I32 max, I32 *lp)
4267 {
4268     register char *scan = Nullch;
4269     register char *start;
4270     register char *loceol = PL_regeol;
4271     I32 l = 0;
4272     I32 count = 0, res = 1;
4273
4274     if (!max)
4275         return 0;
4276
4277     start = PL_reginput;
4278     if (PL_reg_match_utf8) {
4279         while (PL_reginput < loceol && (scan = PL_reginput, res = regmatch(p))) {
4280             if (!count++) {
4281                 l = 0;
4282                 while (start < PL_reginput) {
4283                     l++;
4284                     start += UTF8SKIP(start);
4285                 }
4286                 *lp = l;
4287                 if (l == 0)
4288                     return max;
4289             }
4290             if (count == max)
4291                 return count;
4292         }
4293     }
4294     else {
4295         while (PL_reginput < loceol && (scan = PL_reginput, res = regmatch(p))) {
4296             if (!count++) {
4297                 *lp = l = PL_reginput - start;
4298                 if (max != REG_INFTY && l*max < loceol - scan)
4299                     loceol = scan + l*max;
4300                 if (l == 0)
4301                     return max;
4302             }
4303         }
4304     }
4305     if (!res)
4306         PL_reginput = scan;
4307
4308     return count;
4309 }
4310
4311 /*
4312 - regclass_swash - prepare the utf8 swash
4313 */
4314
4315 SV *
4316 Perl_regclass_swash(pTHX_ register regnode* node, bool doinit, SV** listsvp, SV **altsvp)
4317 {
4318     SV *sw  = NULL;
4319     SV *si  = NULL;
4320     SV *alt = NULL;
4321
4322     if (PL_regdata && PL_regdata->count) {
4323         U32 n = ARG(node);
4324
4325         if (PL_regdata->what[n] == 's') {
4326             SV *rv = (SV*)PL_regdata->data[n];
4327             AV *av = (AV*)SvRV((SV*)rv);
4328             SV **ary = AvARRAY(av);
4329             SV **a, **b;
4330         
4331             /* See the end of regcomp.c:S_reglass() for
4332              * documentation of these array elements. */
4333
4334             si = *ary;
4335             a  = SvTYPE(ary[1]) == SVt_RV   ? &ary[1] : 0;
4336             b  = SvTYPE(ary[2]) == SVt_PVAV ? &ary[2] : 0;
4337
4338             if (a)
4339                 sw = *a;
4340             else if (si && doinit) {
4341                 sw = swash_init("utf8", "", si, 1, 0);
4342                 (void)av_store(av, 1, sw);
4343             }
4344             if (b)
4345                 alt = *b;
4346         }
4347     }
4348         
4349     if (listsvp)
4350         *listsvp = si;
4351     if (altsvp)
4352         *altsvp  = alt;
4353
4354     return sw;
4355 }
4356
4357 /*
4358  - reginclass - determine if a character falls into a character class
4359  
4360   The n is the ANYOF regnode, the p is the target string, lenp
4361   is pointer to the maximum length of how far to go in the p
4362   (if the lenp is zero, UTF8SKIP(p) is used),
4363   do_utf8 tells whether the target string is in UTF-8.
4364
4365  */
4366
4367 STATIC bool
4368 S_reginclass(pTHX_ register regnode *n, register U8* p, STRLEN* lenp, register bool do_utf8)
4369 {
4370     char flags = ANYOF_FLAGS(n);
4371     bool match = FALSE;
4372     UV c = *p;
4373     STRLEN len = 0;
4374     STRLEN plen;
4375
4376     if (do_utf8 && !UTF8_IS_INVARIANT(c))
4377          c = utf8n_to_uvchr(p, UTF8_MAXLEN, &len,
4378                             ckWARN(WARN_UTF8) ? 0 : UTF8_ALLOW_ANY);
4379
4380     plen = lenp ? *lenp : UNISKIP(NATIVE_TO_UNI(c));
4381     if (do_utf8 || (flags & ANYOF_UNICODE)) {
4382         if (lenp)
4383             *lenp = 0;
4384         if (do_utf8 && !ANYOF_RUNTIME(n)) {
4385             if (len != (STRLEN)-1 && c < 256 && ANYOF_BITMAP_TEST(n, c))
4386                 match = TRUE;
4387         }
4388         if (!match && do_utf8 && (flags & ANYOF_UNICODE_ALL) && c >= 256)
4389             match = TRUE;
4390         if (!match) {
4391             AV *av;
4392             SV *sw = regclass_swash(n, TRUE, 0, (SV**)&av);
4393         
4394             if (sw) {
4395                 if (swash_fetch(sw, p, do_utf8))
4396                     match = TRUE;
4397                 else if (flags & ANYOF_FOLD) {
4398                     if (!match && lenp && av) {
4399                         I32 i;
4400                       
4401                         for (i = 0; i <= av_len(av); i++) {
4402                             SV* sv = *av_fetch(av, i, FALSE);
4403                             STRLEN len;
4404                             char *s = SvPV(sv, len);
4405                         
4406                             if (len <= plen && memEQ(s, (char*)p, len)) {
4407                                 *lenp = len;
4408                                 match = TRUE;
4409                                 break;
4410                             }
4411                         }
4412                     }
4413                     if (!match) {
4414                         U8 tmpbuf[UTF8_MAXLEN_FOLD+1];
4415                         STRLEN tmplen;
4416
4417                         to_utf8_fold(p, tmpbuf, &tmplen);
4418                         if (swash_fetch(sw, tmpbuf, do_utf8))
4419                             match = TRUE;
4420                     }
4421                 }
4422             }
4423         }
4424         if (match && lenp && *lenp == 0)
4425             *lenp = UNISKIP(NATIVE_TO_UNI(c));
4426     }
4427     if (!match && c < 256) {
4428         if (ANYOF_BITMAP_TEST(n, c))
4429             match = TRUE;
4430         else if (flags & ANYOF_FOLD) {
4431             U8 f;
4432
4433             if (flags & ANYOF_LOCALE) {
4434                 PL_reg_flags |= RF_tainted;
4435                 f = PL_fold_locale[c];
4436             }
4437             else
4438                 f = PL_fold[c];
4439             if (f != c && ANYOF_BITMAP_TEST(n, f))
4440                 match = TRUE;
4441         }
4442         
4443         if (!match && (flags & ANYOF_CLASS)) {
4444             PL_reg_flags |= RF_tainted;
4445             if (
4446                 (ANYOF_CLASS_TEST(n, ANYOF_ALNUM)   &&  isALNUM_LC(c))  ||
4447                 (ANYOF_CLASS_TEST(n, ANYOF_NALNUM)  && !isALNUM_LC(c))  ||
4448                 (ANYOF_CLASS_TEST(n, ANYOF_SPACE)   &&  isSPACE_LC(c))  ||
4449                 (ANYOF_CLASS_TEST(n, ANYOF_NSPACE)  && !isSPACE_LC(c))  ||
4450                 (ANYOF_CLASS_TEST(n, ANYOF_DIGIT)   &&  isDIGIT_LC(c))  ||
4451                 (ANYOF_CLASS_TEST(n, ANYOF_NDIGIT)  && !isDIGIT_LC(c))  ||
4452                 (ANYOF_CLASS_TEST(n, ANYOF_ALNUMC)  &&  isALNUMC_LC(c)) ||
4453                 (ANYOF_CLASS_TEST(n, ANYOF_NALNUMC) && !isALNUMC_LC(c)) ||
4454                 (ANYOF_CLASS_TEST(n, ANYOF_ALPHA)   &&  isALPHA_LC(c))  ||
4455                 (ANYOF_CLASS_TEST(n, ANYOF_NALPHA)  && !isALPHA_LC(c))  ||
4456                 (ANYOF_CLASS_TEST(n, ANYOF_ASCII)   &&  isASCII(c))     ||
4457                 (ANYOF_CLASS_TEST(n, ANYOF_NASCII)  && !isASCII(c))     ||
4458                 (ANYOF_CLASS_TEST(n, ANYOF_CNTRL)   &&  isCNTRL_LC(c))  ||
4459                 (ANYOF_CLASS_TEST(n, ANYOF_NCNTRL)  && !isCNTRL_LC(c))  ||
4460                 (ANYOF_CLASS_TEST(n, ANYOF_GRAPH)   &&  isGRAPH_LC(c))  ||
4461                 (ANYOF_CLASS_TEST(n, ANYOF_NGRAPH)  && !isGRAPH_LC(c))  ||
4462                 (ANYOF_CLASS_TEST(n, ANYOF_LOWER)   &&  isLOWER_LC(c))  ||
4463                 (ANYOF_CLASS_TEST(n, ANYOF_NLOWER)  && !isLOWER_LC(c))  ||
4464                 (ANYOF_CLASS_TEST(n, ANYOF_PRINT)   &&  isPRINT_LC(c))  ||
4465                 (ANYOF_CLASS_TEST(n, ANYOF_NPRINT)  && !isPRINT_LC(c))  ||
4466                 (ANYOF_CLASS_TEST(n, ANYOF_PUNCT)   &&  isPUNCT_LC(c))  ||
4467                 (ANYOF_CLASS_TEST(n, ANYOF_NPUNCT)  && !isPUNCT_LC(c))  ||
4468                 (ANYOF_CLASS_TEST(n, ANYOF_UPPER)   &&  isUPPER_LC(c))  ||
4469                 (ANYOF_CLASS_TEST(n, ANYOF_NUPPER)  && !isUPPER_LC(c))  ||
4470                 (ANYOF_CLASS_TEST(n, ANYOF_XDIGIT)  &&  isXDIGIT(c))    ||
4471                 (ANYOF_CLASS_TEST(n, ANYOF_NXDIGIT) && !isXDIGIT(c))    ||
4472                 (ANYOF_CLASS_TEST(n, ANYOF_PSXSPC)  &&  isPSXSPC(c))    ||
4473                 (ANYOF_CLASS_TEST(n, ANYOF_NPSXSPC) && !isPSXSPC(c))    ||
4474                 (ANYOF_CLASS_TEST(n, ANYOF_BLANK)   &&  isBLANK(c))     ||
4475                 (ANYOF_CLASS_TEST(n, ANYOF_NBLANK)  && !isBLANK(c))
4476                 ) /* How's that for a conditional? */
4477             {
4478                 match = TRUE;
4479             }
4480         }
4481     }
4482
4483     return (flags & ANYOF_INVERT) ? !match : match;
4484 }
4485
4486 STATIC U8 *
4487 S_reghop(pTHX_ U8 *s, I32 off)
4488 {
4489     return S_reghop3(aTHX_ s, off, (U8*)(off >= 0 ? PL_regeol : PL_bostr));
4490 }
4491
4492 STATIC U8 *
4493 S_reghop3(pTHX_ U8 *s, I32 off, U8* lim)
4494 {
4495     if (off >= 0) {
4496         while (off-- && s < lim) {
4497             /* XXX could check well-formedness here */
4498             s += UTF8SKIP(s);
4499         }
4500     }
4501     else {
4502         while (off++) {
4503             if (s > lim) {
4504                 s--;
4505                 if (UTF8_IS_CONTINUED(*s)) {
4506                     while (s > (U8*)lim && UTF8_IS_CONTINUATION(*s))
4507                         s--;
4508                 }
4509                 /* XXX could check well-formedness here */
4510             }
4511         }
4512     }
4513     return s;
4514 }
4515
4516 STATIC U8 *
4517 S_reghopmaybe(pTHX_ U8 *s, I32 off)
4518 {
4519     return S_reghopmaybe3(aTHX_ s, off, (U8*)(off >= 0 ? PL_regeol : PL_bostr));
4520 }
4521
4522 STATIC U8 *
4523 S_reghopmaybe3(pTHX_ U8* s, I32 off, U8* lim)
4524 {
4525     if (off >= 0) {
4526         while (off-- && s < lim) {
4527             /* XXX could check well-formedness here */
4528             s += UTF8SKIP(s);
4529         }
4530         if (off >= 0)
4531             return 0;
4532     }
4533     else {
4534         while (off++) {
4535             if (s > lim) {
4536                 s--;
4537                 if (UTF8_IS_CONTINUED(*s)) {
4538                     while (s > (U8*)lim && UTF8_IS_CONTINUATION(*s))
4539                         s--;
4540                 }
4541                 /* XXX could check well-formedness here */
4542             }
4543             else
4544                 break;
4545         }
4546         if (off <= 0)
4547             return 0;
4548     }
4549     return s;
4550 }
4551
4552 static void
4553 restore_pos(pTHX_ void *arg)
4554 {
4555     if (PL_reg_eval_set) {
4556         if (PL_reg_oldsaved) {
4557             PL_reg_re->subbeg = PL_reg_oldsaved;
4558             PL_reg_re->sublen = PL_reg_oldsavedlen;
4559             RX_MATCH_COPIED_on(PL_reg_re);
4560         }
4561         PL_reg_magic->mg_len = PL_reg_oldpos;
4562         PL_reg_eval_set = 0;
4563         PL_curpm = PL_reg_oldcurpm;
4564     }   
4565 }
4566
4567 STATIC void
4568 S_to_utf8_substr(pTHX_ register regexp *prog)
4569 {
4570     SV* sv;
4571     if (prog->float_substr && !prog->float_utf8) {
4572         prog->float_utf8 = sv = NEWSV(117, 0);
4573         SvSetSV(sv, prog->float_substr);
4574         sv_utf8_upgrade(sv);
4575         if (SvTAIL(prog->float_substr))
4576             SvTAIL_on(sv);
4577         if (prog->float_substr == prog->check_substr)
4578             prog->check_utf8 = sv;
4579     }
4580     if (prog->anchored_substr && !prog->anchored_utf8) {
4581         prog->anchored_utf8 = sv = NEWSV(118, 0);
4582         SvSetSV(sv, prog->anchored_substr);
4583         sv_utf8_upgrade(sv);
4584         if (SvTAIL(prog->anchored_substr))
4585             SvTAIL_on(sv);
4586         if (prog->anchored_substr == prog->check_substr)
4587             prog->check_utf8 = sv;
4588     }
4589 }
4590
4591 STATIC void
4592 S_to_byte_substr(pTHX_ register regexp *prog)
4593 {
4594     SV* sv;
4595     if (prog->float_utf8 && !prog->float_substr) {
4596         prog->float_substr = sv = NEWSV(117, 0);
4597         SvSetSV(sv, prog->float_utf8);
4598         if (sv_utf8_downgrade(sv, TRUE)) {
4599             if (SvTAIL(prog->float_utf8))
4600                 SvTAIL_on(sv);
4601         } else {
4602             SvREFCNT_dec(sv);
4603             prog->float_substr = sv = &PL_sv_undef;
4604         }
4605         if (prog->float_utf8 == prog->check_utf8)
4606             prog->check_substr = sv;
4607     }
4608     if (prog->anchored_utf8 && !prog->anchored_substr) {
4609         prog->anchored_substr = sv = NEWSV(118, 0);
4610         SvSetSV(sv, prog->anchored_utf8);
4611         if (sv_utf8_downgrade(sv, TRUE)) {
4612             if (SvTAIL(prog->anchored_utf8))
4613                 SvTAIL_on(sv);
4614         } else {
4615             SvREFCNT_dec(sv);
4616             prog->anchored_substr = sv = &PL_sv_undef;
4617         }
4618         if (prog->anchored_utf8 == prog->check_utf8)
4619             prog->check_substr = sv;
4620     }
4621 }