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