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