]> git.vpit.fr Git - perl/modules/re-engine-Hooks.git/blob - src/5017003/regexec.c
Add support for perl 5.16.1, 5.17.3 and 5.17.4
[perl/modules/re-engine-Hooks.git] / src / 5017003 / regexec.c
1 /*    regexec.c
2  */
3
4 /*
5  *      One Ring to rule them all, One Ring to find them
6  &
7  *     [p.v of _The Lord of the Rings_, opening poem]
8  *     [p.50 of _The Lord of the Rings_, I/iii: "The Shadow of the Past"]
9  *     [p.254 of _The Lord of the Rings_, II/ii: "The Council of Elrond"]
10  */
11
12 /* This file contains functions for executing a regular expression.  See
13  * also regcomp.c which funnily enough, contains functions for compiling
14  * a regular expression.
15  *
16  * This file is also copied at build time to ext/re/re_exec.c, where
17  * it's built with -DPERL_EXT_RE_BUILD -DPERL_EXT_RE_DEBUG -DPERL_EXT.
18  * This causes the main functions to be compiled under new names and with
19  * debugging support added, which makes "use re 'debug'" work.
20  */
21
22 /* NOTE: this is derived from Henry Spencer's regexp code, and should not
23  * confused with the original package (see point 3 below).  Thanks, Henry!
24  */
25
26 /* Additional note: this code is very heavily munged from Henry's version
27  * in places.  In some spots I've traded clarity for efficiency, so don't
28  * blame Henry for some of the lack of readability.
29  */
30
31 /* The names of the functions have been changed from regcomp and
32  * regexec to  pregcomp and pregexec in order to avoid conflicts
33  * with the POSIX routines of the same names.
34 */
35
36 #ifdef PERL_EXT_RE_BUILD
37 #include "re_top.h"
38 #endif
39
40 /*
41  * pregcomp and pregexec -- regsub and regerror are not used in perl
42  *
43  *      Copyright (c) 1986 by University of Toronto.
44  *      Written by Henry Spencer.  Not derived from licensed software.
45  *
46  *      Permission is granted to anyone to use this software for any
47  *      purpose on any computer system, and to redistribute it freely,
48  *      subject to the following restrictions:
49  *
50  *      1. The author is not responsible for the consequences of use of
51  *              this software, no matter how awful, even if they arise
52  *              from defects in it.
53  *
54  *      2. The origin of this software must not be misrepresented, either
55  *              by explicit claim or by omission.
56  *
57  *      3. Altered versions must be plainly marked as such, and must not
58  *              be misrepresented as being the original software.
59  *
60  ****    Alterations to Henry's code are...
61  ****
62  ****    Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
63  ****    2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
64  ****    by Larry Wall and others
65  ****
66  ****    You may distribute under the terms of either the GNU General Public
67  ****    License or the Artistic License, as specified in the README file.
68  *
69  * Beware that some of this code is subtly aware of the way operator
70  * precedence is structured in regular expressions.  Serious changes in
71  * regular-expression syntax might require a total rethink.
72  */
73 #include "EXTERN.h"
74 #define PERL_IN_REGEXEC_C
75 #include "perl.h"
76 #include "re_defs.h"
77
78 #ifdef PERL_IN_XSUB_RE
79 #  include "re_comp.h"
80 #else
81 #  include "regcomp.h"
82 #endif
83
84 #define RF_tainted      1       /* tainted information used? e.g. locale */
85 #define RF_warned       2               /* warned about big count? */
86
87 #define RF_utf8         8               /* Pattern contains multibyte chars? */
88
89 #define UTF_PATTERN ((PL_reg_flags & RF_utf8) != 0)
90
91 #ifndef STATIC
92 #define STATIC  static
93 #endif
94
95 /* Valid for non-utf8 strings, non-ANYOFV nodes only: avoids the reginclass
96  * call if there are no complications: i.e., if everything matchable is
97  * straight forward in the bitmap */
98 #define REGINCLASS(prog,p,c)  (ANYOF_FLAGS(p) ? reginclass(prog,p,c,0,0)   \
99                                               : ANYOF_BITMAP_TEST(p,*(c)))
100
101 /*
102  * Forwards.
103  */
104
105 #define CHR_SVLEN(sv) (utf8_target ? sv_len_utf8(sv) : SvCUR(sv))
106 #define CHR_DIST(a,b) (PL_reg_match_utf8 ? utf8_distance(a,b) : a - b)
107
108 #define HOPc(pos,off) \
109         (char *)(PL_reg_match_utf8 \
110             ? reghop3((U8*)pos, off, (U8*)(off >= 0 ? PL_regeol : PL_bostr)) \
111             : (U8*)(pos + off))
112 #define HOPBACKc(pos, off) \
113         (char*)(PL_reg_match_utf8\
114             ? reghopmaybe3((U8*)pos, -off, (U8*)PL_bostr) \
115             : (pos - off >= PL_bostr)           \
116                 ? (U8*)pos - off                \
117                 : NULL)
118
119 #define HOP3(pos,off,lim) (PL_reg_match_utf8 ? reghop3((U8*)(pos), off, (U8*)(lim)) : (U8*)(pos + off))
120 #define HOP3c(pos,off,lim) ((char*)HOP3(pos,off,lim))
121
122 /* these are unrolled below in the CCC_TRY_XXX defined */
123 #ifdef EBCDIC
124     /* Often 'str' is a hard-coded utf8 string instead of utfebcdic. so just
125      * skip the check on EBCDIC platforms */
126 #   define LOAD_UTF8_CHARCLASS(class,str) LOAD_UTF8_CHARCLASS_NO_CHECK(class)
127 #else
128 #   define LOAD_UTF8_CHARCLASS(class,str) STMT_START { \
129     if (!CAT2(PL_utf8_,class)) { \
130         bool ok; \
131         ENTER; save_re_context(); \
132         ok=CAT2(is_utf8_,class)((const U8*)str); \
133         PERL_UNUSED_VAR(ok); \
134         assert(ok); assert(CAT2(PL_utf8_,class)); LEAVE; } } STMT_END
135 #endif
136
137 /* Doesn't do an assert to verify that is correct */
138 #define LOAD_UTF8_CHARCLASS_NO_CHECK(class) STMT_START { \
139     if (!CAT2(PL_utf8_,class)) { \
140         bool throw_away PERL_UNUSED_DECL; \
141         ENTER; save_re_context(); \
142         throw_away = CAT2(is_utf8_,class)((const U8*)" "); \
143         LEAVE; } } STMT_END
144
145 #define LOAD_UTF8_CHARCLASS_ALNUM() LOAD_UTF8_CHARCLASS(alnum,"a")
146 #define LOAD_UTF8_CHARCLASS_DIGIT() LOAD_UTF8_CHARCLASS(digit,"0")
147 #define LOAD_UTF8_CHARCLASS_SPACE() LOAD_UTF8_CHARCLASS(space," ")
148
149 #define LOAD_UTF8_CHARCLASS_GCB()  /* Grapheme cluster boundaries */        \
150         LOAD_UTF8_CHARCLASS(X_begin, " ");                                  \
151         LOAD_UTF8_CHARCLASS(X_non_hangul, "A");                             \
152         /* These are utf8 constants, and not utf-ebcdic constants, so the   \
153             * assert should likely and hopefully fail on an EBCDIC machine */ \
154         LOAD_UTF8_CHARCLASS(X_extend, "\xcc\x80"); /* U+0300 */             \
155                                                                             \
156         /* No asserts are done for these, in case called on an early        \
157             * Unicode version in which they map to nothing */               \
158         LOAD_UTF8_CHARCLASS_NO_CHECK(X_prepend);/* U+0E40 "\xe0\xb9\x80" */ \
159         LOAD_UTF8_CHARCLASS_NO_CHECK(X_L);          /* U+1100 "\xe1\x84\x80" */ \
160         LOAD_UTF8_CHARCLASS_NO_CHECK(X_LV);     /* U+AC00 "\xea\xb0\x80" */ \
161         LOAD_UTF8_CHARCLASS_NO_CHECK(X_LVT);    /* U+AC01 "\xea\xb0\x81" */ \
162         LOAD_UTF8_CHARCLASS_NO_CHECK(X_LV_LVT_V);/* U+AC01 "\xea\xb0\x81" */\
163         LOAD_UTF8_CHARCLASS_NO_CHECK(X_T);      /* U+11A8 "\xe1\x86\xa8" */ \
164         LOAD_UTF8_CHARCLASS_NO_CHECK(X_V)       /* U+1160 "\xe1\x85\xa0" */  
165
166 #define PLACEHOLDER     /* Something for the preprocessor to grab onto */
167
168 /* The actual code for CCC_TRY, which uses several variables from the routine
169  * it's callable from.  It is designed to be the bulk of a case statement.
170  * FUNC is the macro or function to call on non-utf8 targets that indicate if
171  *      nextchr matches the class.
172  * UTF8_TEST is the whole test string to use for utf8 targets
173  * LOAD is what to use to test, and if not present to load in the swash for the
174  *      class
175  * POS_OR_NEG is either empty or ! to complement the results of FUNC or
176  *      UTF8_TEST test.
177  * The logic is: Fail if we're at the end-of-string; otherwise if the target is
178  * utf8 and a variant, load the swash if necessary and test using the utf8
179  * test.  Advance to the next character if test is ok, otherwise fail; If not
180  * utf8 or an invariant under utf8, use the non-utf8 test, and fail if it
181  * fails, or advance to the next character */
182
183 #define _CCC_TRY_CODE(POS_OR_NEG, FUNC, UTF8_TEST, CLASS, STR)                \
184     if (locinput >= PL_regeol) {                                              \
185         sayNO;                                                                \
186     }                                                                         \
187     if (utf8_target && UTF8_IS_CONTINUED(nextchr)) {                          \
188         LOAD_UTF8_CHARCLASS(CLASS, STR);                                      \
189         if (POS_OR_NEG (UTF8_TEST)) {                                         \
190             sayNO;                                                            \
191         }                                                                     \
192         locinput += PL_utf8skip[nextchr];                                     \
193         nextchr = UCHARAT(locinput);                                          \
194         break;                                                                \
195     }                                                                         \
196     if (POS_OR_NEG (FUNC(nextchr))) {                                         \
197         sayNO;                                                                \
198     }                                                                         \
199     nextchr = UCHARAT(++locinput);                                            \
200     break;
201
202 /* Handle the non-locale cases for a character class and its complement.  It
203  * calls _CCC_TRY_CODE with a ! to complement the test for the character class.
204  * This is because that code fails when the test succeeds, so we want to have
205  * the test fail so that the code succeeds.  The swash is stored in a
206  * predictable PL_ place */
207 #define _CCC_TRY_NONLOCALE(NAME,  NNAME,  FUNC,                               \
208                            CLASS, STR)                                        \
209     case NAME:                                                                \
210         _CCC_TRY_CODE( !, FUNC,                                               \
211                           cBOOL(swash_fetch(CAT2(PL_utf8_,CLASS),             \
212                                             (U8*)locinput, TRUE)),            \
213                           CLASS, STR)                                         \
214     case NNAME:                                                               \
215         _CCC_TRY_CODE(  PLACEHOLDER , FUNC,                                   \
216                           cBOOL(swash_fetch(CAT2(PL_utf8_,CLASS),             \
217                                             (U8*)locinput, TRUE)),            \
218                           CLASS, STR)                                         \
219
220 /* Generate the case statements for both locale and non-locale character
221  * classes in regmatch for classes that don't have special unicode semantics.
222  * Locales don't use an immediate swash, but an intermediary special locale
223  * function that is called on the pointer to the current place in the input
224  * string.  That function will resolve to needing the same swash.  One might
225  * think that because we don't know what the locale will match, we shouldn't
226  * check with the swash loading function that it loaded properly; ie, that we
227  * should use LOAD_UTF8_CHARCLASS_NO_CHECK for those, but what is passed to the
228  * regular LOAD_UTF8_CHARCLASS is in non-locale terms, and so locale is
229  * irrelevant here */
230 #define CCC_TRY(NAME,  NNAME,  FUNC,                                          \
231                 NAMEL, NNAMEL, LCFUNC, LCFUNC_utf8,                           \
232                 NAMEA, NNAMEA, FUNCA,                                         \
233                 CLASS, STR)                                                   \
234     case NAMEL:                                                               \
235         PL_reg_flags |= RF_tainted;                                           \
236         _CCC_TRY_CODE( !, LCFUNC, LCFUNC_utf8((U8*)locinput), CLASS, STR)     \
237     case NNAMEL:                                                              \
238         PL_reg_flags |= RF_tainted;                                           \
239         _CCC_TRY_CODE( PLACEHOLDER, LCFUNC, LCFUNC_utf8((U8*)locinput),       \
240                        CLASS, STR)                                            \
241     case NAMEA:                                                               \
242         if (locinput >= PL_regeol || ! FUNCA(nextchr)) {                      \
243             sayNO;                                                            \
244         }                                                                     \
245         /* Matched a utf8-invariant, so don't have to worry about utf8 */     \
246         nextchr = UCHARAT(++locinput);                                        \
247         break;                                                                \
248     case NNAMEA:                                                              \
249         if (locinput >= PL_regeol || FUNCA(nextchr)) {                        \
250             sayNO;                                                            \
251         }                                                                     \
252         if (utf8_target) {                                                    \
253             locinput += PL_utf8skip[nextchr];                                 \
254             nextchr = UCHARAT(locinput);                                      \
255         }                                                                     \
256         else {                                                                \
257             nextchr = UCHARAT(++locinput);                                    \
258         }                                                                     \
259         break;                                                                \
260     /* Generate the non-locale cases */                                       \
261     _CCC_TRY_NONLOCALE(NAME, NNAME, FUNC, CLASS, STR)
262
263 /* This is like CCC_TRY, but has an extra set of parameters for generating case
264  * statements to handle separate Unicode semantics nodes */
265 #define CCC_TRY_U(NAME,  NNAME,  FUNC,                                         \
266                   NAMEL, NNAMEL, LCFUNC, LCFUNC_utf8,                          \
267                   NAMEU, NNAMEU, FUNCU,                                        \
268                   NAMEA, NNAMEA, FUNCA,                                        \
269                   CLASS, STR)                                                  \
270     CCC_TRY(NAME, NNAME, FUNC,                                                 \
271             NAMEL, NNAMEL, LCFUNC, LCFUNC_utf8,                                \
272             NAMEA, NNAMEA, FUNCA,                                              \
273             CLASS, STR)                                                        \
274     _CCC_TRY_NONLOCALE(NAMEU, NNAMEU, FUNCU, CLASS, STR)
275
276 /* TODO: Combine JUMPABLE and HAS_TEXT to cache OP(rn) */
277
278 /* for use after a quantifier and before an EXACT-like node -- japhy */
279 /* it would be nice to rework regcomp.sym to generate this stuff. sigh
280  *
281  * NOTE that *nothing* that affects backtracking should be in here, specifically
282  * VERBS must NOT be included. JUMPABLE is used to determine  if we can ignore a
283  * node that is in between two EXACT like nodes when ascertaining what the required
284  * "follow" character is. This should probably be moved to regex compile time
285  * although it may be done at run time beause of the REF possibility - more
286  * investigation required. -- demerphq
287 */
288 #define JUMPABLE(rn) (      \
289     OP(rn) == OPEN ||       \
290     (OP(rn) == CLOSE && (!cur_eval || cur_eval->u.eval.close_paren != ARG(rn))) || \
291     OP(rn) == EVAL ||   \
292     OP(rn) == SUSPEND || OP(rn) == IFMATCH || \
293     OP(rn) == PLUS || OP(rn) == MINMOD || \
294     OP(rn) == KEEPS || \
295     (PL_regkind[OP(rn)] == CURLY && ARG1(rn) > 0) \
296 )
297 #define IS_EXACT(rn) (PL_regkind[OP(rn)] == EXACT)
298
299 #define HAS_TEXT(rn) ( IS_EXACT(rn) || PL_regkind[OP(rn)] == REF )
300
301 #if 0 
302 /* Currently these are only used when PL_regkind[OP(rn)] == EXACT so
303    we don't need this definition. */
304 #define IS_TEXT(rn)   ( OP(rn)==EXACT   || OP(rn)==REF   || OP(rn)==NREF   )
305 #define IS_TEXTF(rn)  ( OP(rn)==EXACTFU || OP(rn)==EXACTFU_SS || OP(rn)==EXACTFU_TRICKYFOLD || OP(rn)==EXACTFA || OP(rn)==EXACTF || OP(rn)==REFF  || OP(rn)==NREFF )
306 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL || OP(rn)==REFFL || OP(rn)==NREFFL )
307
308 #else
309 /* ... so we use this as its faster. */
310 #define IS_TEXT(rn)   ( OP(rn)==EXACT   )
311 #define IS_TEXTFU(rn)  ( OP(rn)==EXACTFU || OP(rn)==EXACTFU_SS || OP(rn)==EXACTFU_TRICKYFOLD || OP(rn) == EXACTFA)
312 #define IS_TEXTF(rn)  ( OP(rn)==EXACTF  )
313 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL )
314
315 #endif
316
317 /*
318   Search for mandatory following text node; for lookahead, the text must
319   follow but for lookbehind (rn->flags != 0) we skip to the next step.
320 */
321 #define FIND_NEXT_IMPT(rn) STMT_START { \
322     while (JUMPABLE(rn)) { \
323         const OPCODE type = OP(rn); \
324         if (type == SUSPEND || PL_regkind[type] == CURLY) \
325             rn = NEXTOPER(NEXTOPER(rn)); \
326         else if (type == PLUS) \
327             rn = NEXTOPER(rn); \
328         else if (type == IFMATCH) \
329             rn = (rn->flags == 0) ? NEXTOPER(NEXTOPER(rn)) : rn + ARG(rn); \
330         else rn += NEXT_OFF(rn); \
331     } \
332 } STMT_END 
333
334
335 static void restore_pos(pTHX_ void *arg);
336
337 #define REGCP_PAREN_ELEMS 3
338 #define REGCP_OTHER_ELEMS 3
339 #define REGCP_FRAME_ELEMS 1
340 /* REGCP_FRAME_ELEMS are not part of the REGCP_OTHER_ELEMS and
341  * are needed for the regexp context stack bookkeeping. */
342
343 STATIC CHECKPOINT
344 S_regcppush(pTHX_ const regexp *rex, I32 parenfloor)
345 {
346     dVAR;
347     const int retval = PL_savestack_ix;
348     const int paren_elems_to_push = (PL_regsize - parenfloor) * REGCP_PAREN_ELEMS;
349     const UV total_elems = paren_elems_to_push + REGCP_OTHER_ELEMS;
350     const UV elems_shifted = total_elems << SAVE_TIGHT_SHIFT;
351     I32 p;
352     GET_RE_DEBUG_FLAGS_DECL;
353
354     PERL_ARGS_ASSERT_REGCPPUSH;
355
356     if (paren_elems_to_push < 0)
357         Perl_croak(aTHX_ "panic: paren_elems_to_push, %i < 0",
358                    paren_elems_to_push);
359
360     if ((elems_shifted >> SAVE_TIGHT_SHIFT) != total_elems)
361         Perl_croak(aTHX_ "panic: paren_elems_to_push offset %"UVuf
362                    " out of range (%lu-%ld)",
363                    total_elems, (unsigned long)PL_regsize, (long)parenfloor);
364
365     SSGROW(total_elems + REGCP_FRAME_ELEMS);
366     
367     DEBUG_BUFFERS_r(
368         if ((int)PL_regsize > (int)parenfloor)
369             PerlIO_printf(Perl_debug_log,
370                 "rex=0x%"UVxf" offs=0x%"UVxf": saving capture indices:\n",
371                 PTR2UV(rex),
372                 PTR2UV(rex->offs)
373             );
374     );
375     for (p = parenfloor+1; p <= (I32)PL_regsize;  p++) {
376 /* REGCP_PARENS_ELEMS are pushed per pairs of parentheses. */
377         SSPUSHINT(rex->offs[p].end);
378         SSPUSHINT(rex->offs[p].start);
379         SSPUSHINT(rex->offs[p].start_tmp);
380         DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
381             "    \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"\n",
382             (UV)p,
383             (IV)rex->offs[p].start,
384             (IV)rex->offs[p].start_tmp,
385             (IV)rex->offs[p].end
386         ));
387     }
388 /* REGCP_OTHER_ELEMS are pushed in any case, parentheses or no. */
389     SSPUSHINT(PL_regsize);
390     SSPUSHINT(rex->lastparen);
391     SSPUSHINT(rex->lastcloseparen);
392     SSPUSHUV(SAVEt_REGCONTEXT | elems_shifted); /* Magic cookie. */
393
394     return retval;
395 }
396
397 /* These are needed since we do not localize EVAL nodes: */
398 #define REGCP_SET(cp)                                           \
399     DEBUG_STATE_r(                                              \
400             PerlIO_printf(Perl_debug_log,                       \
401                 "  Setting an EVAL scope, savestack=%"IVdf"\n", \
402                 (IV)PL_savestack_ix));                          \
403     cp = PL_savestack_ix
404
405 #define REGCP_UNWIND(cp)                                        \
406     DEBUG_STATE_r(                                              \
407         if (cp != PL_savestack_ix)                              \
408             PerlIO_printf(Perl_debug_log,                       \
409                 "  Clearing an EVAL scope, savestack=%"IVdf"..%"IVdf"\n", \
410                 (IV)(cp), (IV)PL_savestack_ix));                \
411     regcpblow(cp)
412
413 #define UNWIND_PAREN(lp, lcp)               \
414     for (n = rex->lastparen; n > lp; n--)   \
415         rex->offs[n].end = -1;              \
416     rex->lastparen = n;                     \
417     rex->lastcloseparen = lcp;
418
419
420 STATIC void
421 S_regcppop(pTHX_ regexp *rex)
422 {
423     dVAR;
424     UV i;
425     U32 paren;
426     GET_RE_DEBUG_FLAGS_DECL;
427
428     PERL_ARGS_ASSERT_REGCPPOP;
429
430     /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
431     i = SSPOPUV;
432     assert((i & SAVE_MASK) == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
433     i >>= SAVE_TIGHT_SHIFT; /* Parentheses elements to pop. */
434     rex->lastcloseparen = SSPOPINT;
435     rex->lastparen = SSPOPINT;
436     PL_regsize = SSPOPINT;
437
438     i -= REGCP_OTHER_ELEMS;
439     /* Now restore the parentheses context. */
440     DEBUG_BUFFERS_r(
441         if (i || rex->lastparen + 1 <= rex->nparens)
442             PerlIO_printf(Perl_debug_log,
443                 "rex=0x%"UVxf" offs=0x%"UVxf": restoring capture indices to:\n",
444                 PTR2UV(rex),
445                 PTR2UV(rex->offs)
446             );
447     );
448     paren = PL_regsize;
449     for ( ; i > 0; i -= REGCP_PAREN_ELEMS) {
450         I32 tmps;
451         rex->offs[paren].start_tmp = SSPOPINT;
452         rex->offs[paren].start = SSPOPINT;
453         tmps = SSPOPINT;
454         if (paren <= rex->lastparen)
455             rex->offs[paren].end = tmps;
456         DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
457             "    \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"%s\n",
458             (UV)paren,
459             (IV)rex->offs[paren].start,
460             (IV)rex->offs[paren].start_tmp,
461             (IV)rex->offs[paren].end,
462             (paren > rex->lastparen ? "(skipped)" : ""));
463         );
464         paren--;
465     }
466 #if 1
467     /* It would seem that the similar code in regtry()
468      * already takes care of this, and in fact it is in
469      * a better location to since this code can #if 0-ed out
470      * but the code in regtry() is needed or otherwise tests
471      * requiring null fields (pat.t#187 and split.t#{13,14}
472      * (as of patchlevel 7877)  will fail.  Then again,
473      * this code seems to be necessary or otherwise
474      * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
475      * --jhi updated by dapm */
476     for (i = rex->lastparen + 1; i <= rex->nparens; i++) {
477         if (i > PL_regsize)
478             rex->offs[i].start = -1;
479         rex->offs[i].end = -1;
480         DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
481             "    \\%"UVuf": %s   ..-1 undeffing\n",
482             (UV)i,
483             (i > PL_regsize) ? "-1" : "  "
484         ));
485     }
486 #endif
487 }
488
489 /* restore the parens and associated vars at savestack position ix,
490  * but without popping the stack */
491
492 STATIC void
493 S_regcp_restore(pTHX_ regexp *rex, I32 ix)
494 {
495     I32 tmpix = PL_savestack_ix;
496     PL_savestack_ix = ix;
497     regcppop(rex);
498     PL_savestack_ix = tmpix;
499 }
500
501 #define regcpblow(cp) LEAVE_SCOPE(cp)   /* Ignores regcppush()ed data. */
502
503 /*
504  * pregexec and friends
505  */
506
507 #ifndef PERL_IN_XSUB_RE
508 /*
509  - pregexec - match a regexp against a string
510  */
511 I32
512 Perl_pregexec(pTHX_ REGEXP * const prog, char* stringarg, register char *strend,
513          char *strbeg, I32 minend, SV *screamer, U32 nosave)
514 /* strend: pointer to null at end of string */
515 /* strbeg: real beginning of string */
516 /* minend: end of match must be >=minend after stringarg. */
517 /* nosave: For optimizations. */
518 {
519     PERL_ARGS_ASSERT_PREGEXEC;
520
521     return
522         regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
523                       nosave ? 0 : REXEC_COPY_STR);
524 }
525 #endif
526
527 /*
528  * Need to implement the following flags for reg_anch:
529  *
530  * USE_INTUIT_NOML              - Useful to call re_intuit_start() first
531  * USE_INTUIT_ML
532  * INTUIT_AUTORITATIVE_NOML     - Can trust a positive answer
533  * INTUIT_AUTORITATIVE_ML
534  * INTUIT_ONCE_NOML             - Intuit can match in one location only.
535  * INTUIT_ONCE_ML
536  *
537  * Another flag for this function: SECOND_TIME (so that float substrs
538  * with giant delta may be not rechecked).
539  */
540
541 /* Assumptions: if ANCH_GPOS, then strpos is anchored. XXXX Check GPOS logic */
542
543 /* If SCREAM, then SvPVX_const(sv) should be compatible with strpos and strend.
544    Otherwise, only SvCUR(sv) is used to get strbeg. */
545
546 /* XXXX We assume that strpos is strbeg unless sv. */
547
548 /* XXXX Some places assume that there is a fixed substring.
549         An update may be needed if optimizer marks as "INTUITable"
550         RExen without fixed substrings.  Similarly, it is assumed that
551         lengths of all the strings are no more than minlen, thus they
552         cannot come from lookahead.
553         (Or minlen should take into account lookahead.) 
554   NOTE: Some of this comment is not correct. minlen does now take account
555   of lookahead/behind. Further research is required. -- demerphq
556
557 */
558
559 /* A failure to find a constant substring means that there is no need to make
560    an expensive call to REx engine, thus we celebrate a failure.  Similarly,
561    finding a substring too deep into the string means that less calls to
562    regtry() should be needed.
563
564    REx compiler's optimizer found 4 possible hints:
565         a) Anchored substring;
566         b) Fixed substring;
567         c) Whether we are anchored (beginning-of-line or \G);
568         d) First node (of those at offset 0) which may distinguish positions;
569    We use a)b)d) and multiline-part of c), and try to find a position in the
570    string which does not contradict any of them.
571  */
572
573 /* Most of decisions we do here should have been done at compile time.
574    The nodes of the REx which we used for the search should have been
575    deleted from the finite automaton. */
576
577 char *
578 Perl_re_intuit_start(pTHX_ REGEXP * const rx, SV *sv, char *strpos,
579                      char *strend, const U32 flags, re_scream_pos_data *data)
580 {
581     dVAR;
582     struct regexp *const prog = (struct regexp *)SvANY(rx);
583     I32 start_shift = 0;
584     /* Should be nonnegative! */
585     I32 end_shift   = 0;
586     char *s;
587     SV *check;
588     char *strbeg;
589     char *t;
590     const bool utf8_target = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
591     I32 ml_anch;
592     char *other_last = NULL;    /* other substr checked before this */
593     char *check_at = NULL;              /* check substr found at this pos */
594     char *checked_upto = NULL;          /* how far into the string we have already checked using find_byclass*/
595     const I32 multiline = prog->extflags & RXf_PMf_MULTILINE;
596     RXi_GET_DECL(prog,progi);
597 #ifdef DEBUGGING
598     const char * const i_strpos = strpos;
599 #endif
600     GET_RE_DEBUG_FLAGS_DECL;
601
602     PERL_ARGS_ASSERT_RE_INTUIT_START;
603     PERL_UNUSED_ARG(flags);
604     PERL_UNUSED_ARG(data);
605
606     RX_MATCH_UTF8_set(rx,utf8_target);
607
608     if (RX_UTF8(rx)) {
609         PL_reg_flags |= RF_utf8;
610     }
611     DEBUG_EXECUTE_r( 
612         debug_start_match(rx, utf8_target, strpos, strend,
613             sv ? "Guessing start of match in sv for"
614                : "Guessing start of match in string for");
615               );
616
617     /* CHR_DIST() would be more correct here but it makes things slow. */
618     if (prog->minlen > strend - strpos) {
619         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
620                               "String too short... [re_intuit_start]\n"));
621         goto fail;
622     }
623                 
624     strbeg = (sv && SvPOK(sv)) ? strend - SvCUR(sv) : strpos;
625     PL_regeol = strend;
626     if (utf8_target) {
627         if (!prog->check_utf8 && prog->check_substr)
628             to_utf8_substr(prog);
629         check = prog->check_utf8;
630     } else {
631         if (!prog->check_substr && prog->check_utf8)
632             to_byte_substr(prog);
633         check = prog->check_substr;
634     }
635     if (check == &PL_sv_undef) {
636         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
637                 "Non-utf8 string cannot match utf8 check string\n"));
638         goto fail;
639     }
640     if (prog->extflags & RXf_ANCH) {    /* Match at beg-of-str or after \n */
641         ml_anch = !( (prog->extflags & RXf_ANCH_SINGLE)
642                      || ( (prog->extflags & RXf_ANCH_BOL)
643                           && !multiline ) );    /* Check after \n? */
644
645         if (!ml_anch) {
646           if ( !(prog->extflags & RXf_ANCH_GPOS) /* Checked by the caller */
647                 && !(prog->intflags & PREGf_IMPLICIT) /* not a real BOL */
648                /* SvCUR is not set on references: SvRV and SvPVX_const overlap */
649                && sv && !SvROK(sv)
650                && (strpos != strbeg)) {
651               DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Not at start...\n"));
652               goto fail;
653           }
654           if (prog->check_offset_min == prog->check_offset_max &&
655               !(prog->extflags & RXf_CANY_SEEN)) {
656             /* Substring at constant offset from beg-of-str... */
657             I32 slen;
658
659             s = HOP3c(strpos, prog->check_offset_min, strend);
660             
661             if (SvTAIL(check)) {
662                 slen = SvCUR(check);    /* >= 1 */
663
664                 if ( strend - s > slen || strend - s < slen - 1
665                      || (strend - s == slen && strend[-1] != '\n')) {
666                     DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "String too long...\n"));
667                     goto fail_finish;
668                 }
669                 /* Now should match s[0..slen-2] */
670                 slen--;
671                 if (slen && (*SvPVX_const(check) != *s
672                              || (slen > 1
673                                  && memNE(SvPVX_const(check), s, slen)))) {
674                   report_neq:
675                     DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "String not equal...\n"));
676                     goto fail_finish;
677                 }
678             }
679             else if (*SvPVX_const(check) != *s
680                      || ((slen = SvCUR(check)) > 1
681                          && memNE(SvPVX_const(check), s, slen)))
682                 goto report_neq;
683             check_at = s;
684             goto success_at_start;
685           }
686         }
687         /* Match is anchored, but substr is not anchored wrt beg-of-str. */
688         s = strpos;
689         start_shift = prog->check_offset_min; /* okay to underestimate on CC */
690         end_shift = prog->check_end_shift;
691         
692         if (!ml_anch) {
693             const I32 end = prog->check_offset_max + CHR_SVLEN(check)
694                                          - (SvTAIL(check) != 0);
695             const I32 eshift = CHR_DIST((U8*)strend, (U8*)s) - end;
696
697             if (end_shift < eshift)
698                 end_shift = eshift;
699         }
700     }
701     else {                              /* Can match at random position */
702         ml_anch = 0;
703         s = strpos;
704         start_shift = prog->check_offset_min;  /* okay to underestimate on CC */
705         end_shift = prog->check_end_shift;
706         
707         /* end shift should be non negative here */
708     }
709
710 #ifdef QDEBUGGING       /* 7/99: reports of failure (with the older version) */
711     if (end_shift < 0)
712         Perl_croak(aTHX_ "panic: end_shift: %"IVdf" pattern:\n%s\n ",
713                    (IV)end_shift, RX_PRECOMP(prog));
714 #endif
715
716   restart:
717     /* Find a possible match in the region s..strend by looking for
718        the "check" substring in the region corrected by start/end_shift. */
719     
720     {
721         I32 srch_start_shift = start_shift;
722         I32 srch_end_shift = end_shift;
723         U8* start_point;
724         U8* end_point;
725         if (srch_start_shift < 0 && strbeg - s > srch_start_shift) {
726             srch_end_shift -= ((strbeg - s) - srch_start_shift); 
727             srch_start_shift = strbeg - s;
728         }
729     DEBUG_OPTIMISE_MORE_r({
730         PerlIO_printf(Perl_debug_log, "Check offset min: %"IVdf" Start shift: %"IVdf" End shift %"IVdf" Real End Shift: %"IVdf"\n",
731             (IV)prog->check_offset_min,
732             (IV)srch_start_shift,
733             (IV)srch_end_shift, 
734             (IV)prog->check_end_shift);
735     });       
736         
737         if (prog->extflags & RXf_CANY_SEEN) {
738             start_point= (U8*)(s + srch_start_shift);
739             end_point= (U8*)(strend - srch_end_shift);
740         } else {
741             start_point= HOP3(s, srch_start_shift, srch_start_shift < 0 ? strbeg : strend);
742             end_point= HOP3(strend, -srch_end_shift, strbeg);
743         }
744         DEBUG_OPTIMISE_MORE_r({
745             PerlIO_printf(Perl_debug_log, "fbm_instr len=%d str=<%.*s>\n", 
746                 (int)(end_point - start_point),
747                 (int)(end_point - start_point) > 20 ? 20 : (int)(end_point - start_point), 
748                 start_point);
749         });
750
751         s = fbm_instr( start_point, end_point,
752                       check, multiline ? FBMrf_MULTILINE : 0);
753     }
754     /* Update the count-of-usability, remove useless subpatterns,
755         unshift s.  */
756
757     DEBUG_EXECUTE_r({
758         RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
759             SvPVX_const(check), RE_SV_DUMPLEN(check), 30);
760         PerlIO_printf(Perl_debug_log, "%s %s substr %s%s%s",
761                           (s ? "Found" : "Did not find"),
762             (check == (utf8_target ? prog->anchored_utf8 : prog->anchored_substr)
763                 ? "anchored" : "floating"),
764             quoted,
765             RE_SV_TAIL(check),
766             (s ? " at offset " : "...\n") ); 
767     });
768
769     if (!s)
770         goto fail_finish;
771     /* Finish the diagnostic message */
772     DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%ld...\n", (long)(s - i_strpos)) );
773
774     /* XXX dmq: first branch is for positive lookbehind...
775        Our check string is offset from the beginning of the pattern.
776        So we need to do any stclass tests offset forward from that 
777        point. I think. :-(
778      */
779     
780         
781     
782     check_at=s;
783      
784
785     /* Got a candidate.  Check MBOL anchoring, and the *other* substr.
786        Start with the other substr.
787        XXXX no SCREAM optimization yet - and a very coarse implementation
788        XXXX /ttx+/ results in anchored="ttx", floating="x".  floating will
789                 *always* match.  Probably should be marked during compile...
790        Probably it is right to do no SCREAM here...
791      */
792
793     if (utf8_target ? (prog->float_utf8 && prog->anchored_utf8)
794                 : (prog->float_substr && prog->anchored_substr)) 
795     {
796         /* Take into account the "other" substring. */
797         /* XXXX May be hopelessly wrong for UTF... */
798         if (!other_last)
799             other_last = strpos;
800         if (check == (utf8_target ? prog->float_utf8 : prog->float_substr)) {
801           do_other_anchored:
802             {
803                 char * const last = HOP3c(s, -start_shift, strbeg);
804                 char *last1, *last2;
805                 char * const saved_s = s;
806                 SV* must;
807
808                 t = s - prog->check_offset_max;
809                 if (s - strpos > prog->check_offset_max  /* signed-corrected t > strpos */
810                     && (!utf8_target
811                         || ((t = (char*)reghopmaybe3((U8*)s, -(prog->check_offset_max), (U8*)strpos))
812                             && t > strpos)))
813                     NOOP;
814                 else
815                     t = strpos;
816                 t = HOP3c(t, prog->anchored_offset, strend);
817                 if (t < other_last)     /* These positions already checked */
818                     t = other_last;
819                 last2 = last1 = HOP3c(strend, -prog->minlen, strbeg);
820                 if (last < last1)
821                     last1 = last;
822                 /* XXXX It is not documented what units *_offsets are in.  
823                    We assume bytes, but this is clearly wrong. 
824                    Meaning this code needs to be carefully reviewed for errors.
825                    dmq.
826                   */
827  
828                 /* On end-of-str: see comment below. */
829                 must = utf8_target ? prog->anchored_utf8 : prog->anchored_substr;
830                 if (must == &PL_sv_undef) {
831                     s = (char*)NULL;
832                     DEBUG_r(must = prog->anchored_utf8);        /* for debug */
833                 }
834                 else
835                     s = fbm_instr(
836                         (unsigned char*)t,
837                         HOP3(HOP3(last1, prog->anchored_offset, strend)
838                                 + SvCUR(must), -(SvTAIL(must)!=0), strbeg),
839                         must,
840                         multiline ? FBMrf_MULTILINE : 0
841                     );
842                 DEBUG_EXECUTE_r({
843                     RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
844                         SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
845                     PerlIO_printf(Perl_debug_log, "%s anchored substr %s%s",
846                         (s ? "Found" : "Contradicts"),
847                         quoted, RE_SV_TAIL(must));
848                 });                 
849                 
850                             
851                 if (!s) {
852                     if (last1 >= last2) {
853                         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
854                                                 ", giving up...\n"));
855                         goto fail_finish;
856                     }
857                     DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
858                         ", trying floating at offset %ld...\n",
859                         (long)(HOP3c(saved_s, 1, strend) - i_strpos)));
860                     other_last = HOP3c(last1, prog->anchored_offset+1, strend);
861                     s = HOP3c(last, 1, strend);
862                     goto restart;
863                 }
864                 else {
865                     DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " at offset %ld...\n",
866                           (long)(s - i_strpos)));
867                     t = HOP3c(s, -prog->anchored_offset, strbeg);
868                     other_last = HOP3c(s, 1, strend);
869                     s = saved_s;
870                     if (t == strpos)
871                         goto try_at_start;
872                     goto try_at_offset;
873                 }
874             }
875         }
876         else {          /* Take into account the floating substring. */
877             char *last, *last1;
878             char * const saved_s = s;
879             SV* must;
880
881             t = HOP3c(s, -start_shift, strbeg);
882             last1 = last =
883                 HOP3c(strend, -prog->minlen + prog->float_min_offset, strbeg);
884             if (CHR_DIST((U8*)last, (U8*)t) > prog->float_max_offset)
885                 last = HOP3c(t, prog->float_max_offset, strend);
886             s = HOP3c(t, prog->float_min_offset, strend);
887             if (s < other_last)
888                 s = other_last;
889  /* XXXX It is not documented what units *_offsets are in.  Assume bytes.  */
890             must = utf8_target ? prog->float_utf8 : prog->float_substr;
891             /* fbm_instr() takes into account exact value of end-of-str
892                if the check is SvTAIL(ed).  Since false positives are OK,
893                and end-of-str is not later than strend we are OK. */
894             if (must == &PL_sv_undef) {
895                 s = (char*)NULL;
896                 DEBUG_r(must = prog->float_utf8);       /* for debug message */
897             }
898             else
899                 s = fbm_instr((unsigned char*)s,
900                               (unsigned char*)last + SvCUR(must)
901                                   - (SvTAIL(must)!=0),
902                               must, multiline ? FBMrf_MULTILINE : 0);
903             DEBUG_EXECUTE_r({
904                 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
905                     SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
906                 PerlIO_printf(Perl_debug_log, "%s floating substr %s%s",
907                     (s ? "Found" : "Contradicts"),
908                     quoted, RE_SV_TAIL(must));
909             });
910             if (!s) {
911                 if (last1 == last) {
912                     DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
913                                             ", giving up...\n"));
914                     goto fail_finish;
915                 }
916                 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
917                     ", trying anchored starting at offset %ld...\n",
918                     (long)(saved_s + 1 - i_strpos)));
919                 other_last = last;
920                 s = HOP3c(t, 1, strend);
921                 goto restart;
922             }
923             else {
924                 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " at offset %ld...\n",
925                       (long)(s - i_strpos)));
926                 other_last = s; /* Fix this later. --Hugo */
927                 s = saved_s;
928                 if (t == strpos)
929                     goto try_at_start;
930                 goto try_at_offset;
931             }
932         }
933     }
934
935     
936     t= (char*)HOP3( s, -prog->check_offset_max, (prog->check_offset_max<0) ? strend : strpos);
937         
938     DEBUG_OPTIMISE_MORE_r(
939         PerlIO_printf(Perl_debug_log, 
940             "Check offset min:%"IVdf" max:%"IVdf" S:%"IVdf" t:%"IVdf" D:%"IVdf" end:%"IVdf"\n",
941             (IV)prog->check_offset_min,
942             (IV)prog->check_offset_max,
943             (IV)(s-strpos),
944             (IV)(t-strpos),
945             (IV)(t-s),
946             (IV)(strend-strpos)
947         )
948     );
949
950     if (s - strpos > prog->check_offset_max  /* signed-corrected t > strpos */
951         && (!utf8_target
952             || ((t = (char*)reghopmaybe3((U8*)s, -prog->check_offset_max, (U8*) ((prog->check_offset_max<0) ? strend : strpos)))
953                  && t > strpos))) 
954     {
955         /* Fixed substring is found far enough so that the match
956            cannot start at strpos. */
957       try_at_offset:
958         if (ml_anch && t[-1] != '\n') {
959             /* Eventually fbm_*() should handle this, but often
960                anchored_offset is not 0, so this check will not be wasted. */
961             /* XXXX In the code below we prefer to look for "^" even in
962                presence of anchored substrings.  And we search even
963                beyond the found float position.  These pessimizations
964                are historical artefacts only.  */
965           find_anchor:
966             while (t < strend - prog->minlen) {
967                 if (*t == '\n') {
968                     if (t < check_at - prog->check_offset_min) {
969                         if (utf8_target ? prog->anchored_utf8 : prog->anchored_substr) {
970                             /* Since we moved from the found position,
971                                we definitely contradict the found anchored
972                                substr.  Due to the above check we do not
973                                contradict "check" substr.
974                                Thus we can arrive here only if check substr
975                                is float.  Redo checking for "other"=="fixed".
976                              */
977                             strpos = t + 1;                     
978                             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Found /%s^%s/m at offset %ld, rescanning for anchored from offset %ld...\n",
979                                 PL_colors[0], PL_colors[1], (long)(strpos - i_strpos), (long)(strpos - i_strpos + prog->anchored_offset)));
980                             goto do_other_anchored;
981                         }
982                         /* We don't contradict the found floating substring. */
983                         /* XXXX Why not check for STCLASS? */
984                         s = t + 1;
985                         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Found /%s^%s/m at offset %ld...\n",
986                             PL_colors[0], PL_colors[1], (long)(s - i_strpos)));
987                         goto set_useful;
988                     }
989                     /* Position contradicts check-string */
990                     /* XXXX probably better to look for check-string
991                        than for "\n", so one should lower the limit for t? */
992                     DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Found /%s^%s/m, restarting lookup for check-string at offset %ld...\n",
993                         PL_colors[0], PL_colors[1], (long)(t + 1 - i_strpos)));
994                     other_last = strpos = s = t + 1;
995                     goto restart;
996                 }
997                 t++;
998             }
999             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Did not find /%s^%s/m...\n",
1000                         PL_colors[0], PL_colors[1]));
1001             goto fail_finish;
1002         }
1003         else {
1004             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Starting position does not contradict /%s^%s/m...\n",
1005                         PL_colors[0], PL_colors[1]));
1006         }
1007         s = t;
1008       set_useful:
1009         ++BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr);        /* hooray/5 */
1010     }
1011     else {
1012         /* The found string does not prohibit matching at strpos,
1013            - no optimization of calling REx engine can be performed,
1014            unless it was an MBOL and we are not after MBOL,
1015            or a future STCLASS check will fail this. */
1016       try_at_start:
1017         /* Even in this situation we may use MBOL flag if strpos is offset
1018            wrt the start of the string. */
1019         if (ml_anch && sv && !SvROK(sv) /* See prev comment on SvROK */
1020             && (strpos != strbeg) && strpos[-1] != '\n'
1021             /* May be due to an implicit anchor of m{.*foo}  */
1022             && !(prog->intflags & PREGf_IMPLICIT))
1023         {
1024             t = strpos;
1025             goto find_anchor;
1026         }
1027         DEBUG_EXECUTE_r( if (ml_anch)
1028             PerlIO_printf(Perl_debug_log, "Position at offset %ld does not contradict /%s^%s/m...\n",
1029                           (long)(strpos - i_strpos), PL_colors[0], PL_colors[1]);
1030         );
1031       success_at_start:
1032         if (!(prog->intflags & PREGf_NAUGHTY)   /* XXXX If strpos moved? */
1033             && (utf8_target ? (
1034                 prog->check_utf8                /* Could be deleted already */
1035                 && --BmUSEFUL(prog->check_utf8) < 0
1036                 && (prog->check_utf8 == prog->float_utf8)
1037             ) : (
1038                 prog->check_substr              /* Could be deleted already */
1039                 && --BmUSEFUL(prog->check_substr) < 0
1040                 && (prog->check_substr == prog->float_substr)
1041             )))
1042         {
1043             /* If flags & SOMETHING - do not do it many times on the same match */
1044             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "... Disabling check substring...\n"));
1045             /* XXX Does the destruction order has to change with utf8_target? */
1046             SvREFCNT_dec(utf8_target ? prog->check_utf8 : prog->check_substr);
1047             SvREFCNT_dec(utf8_target ? prog->check_substr : prog->check_utf8);
1048             prog->check_substr = prog->check_utf8 = NULL;       /* disable */
1049             prog->float_substr = prog->float_utf8 = NULL;       /* clear */
1050             check = NULL;                       /* abort */
1051             s = strpos;
1052             /* XXXX If the check string was an implicit check MBOL, then we need to unset the relevant flag
1053                     see http://bugs.activestate.com/show_bug.cgi?id=87173 */
1054             if (prog->intflags & PREGf_IMPLICIT)
1055                 prog->extflags &= ~RXf_ANCH_MBOL;
1056             /* XXXX This is a remnant of the old implementation.  It
1057                     looks wasteful, since now INTUIT can use many
1058                     other heuristics. */
1059             prog->extflags &= ~RXf_USE_INTUIT;
1060             /* XXXX What other flags might need to be cleared in this branch? */
1061         }
1062         else
1063             s = strpos;
1064     }
1065
1066     /* Last resort... */
1067     /* XXXX BmUSEFUL already changed, maybe multiple change is meaningful... */
1068     /* trie stclasses are too expensive to use here, we are better off to
1069        leave it to regmatch itself */
1070     if (progi->regstclass && PL_regkind[OP(progi->regstclass)]!=TRIE) {
1071         /* minlen == 0 is possible if regstclass is \b or \B,
1072            and the fixed substr is ''$.
1073            Since minlen is already taken into account, s+1 is before strend;
1074            accidentally, minlen >= 1 guaranties no false positives at s + 1
1075            even for \b or \B.  But (minlen? 1 : 0) below assumes that
1076            regstclass does not come from lookahead...  */
1077         /* If regstclass takes bytelength more than 1: If charlength==1, OK.
1078            This leaves EXACTF-ish only, which are dealt with in find_byclass().  */
1079         const U8* const str = (U8*)STRING(progi->regstclass);
1080         const int cl_l = (PL_regkind[OP(progi->regstclass)] == EXACT
1081                     ? CHR_DIST(str+STR_LEN(progi->regstclass), str)
1082                     : 1);
1083         char * endpos;
1084         if (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
1085             endpos= HOP3c(s, (prog->minlen ? cl_l : 0), strend);
1086         else if (prog->float_substr || prog->float_utf8)
1087             endpos= HOP3c(HOP3c(check_at, -start_shift, strbeg), cl_l, strend);
1088         else 
1089             endpos= strend;
1090                     
1091         if (checked_upto < s)
1092            checked_upto = s;
1093         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "start_shift: %"IVdf" check_at: %"IVdf" s: %"IVdf" endpos: %"IVdf" checked_upto: %"IVdf"\n",
1094                                       (IV)start_shift, (IV)(check_at - strbeg), (IV)(s - strbeg), (IV)(endpos - strbeg), (IV)(checked_upto- strbeg)));
1095
1096         t = s;
1097         s = find_byclass(prog, progi->regstclass, checked_upto, endpos, NULL);
1098         if (s) {
1099             checked_upto = s;
1100         } else {
1101 #ifdef DEBUGGING
1102             const char *what = NULL;
1103 #endif
1104             if (endpos == strend) {
1105                 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1106                                 "Could not match STCLASS...\n") );
1107                 goto fail;
1108             }
1109             DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1110                                    "This position contradicts STCLASS...\n") );
1111             if ((prog->extflags & RXf_ANCH) && !ml_anch)
1112                 goto fail;
1113             checked_upto = HOPBACKc(endpos, start_shift);
1114             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "start_shift: %"IVdf" check_at: %"IVdf" endpos: %"IVdf" checked_upto: %"IVdf"\n",
1115                                       (IV)start_shift, (IV)(check_at - strbeg), (IV)(endpos - strbeg), (IV)(checked_upto- strbeg)));
1116             /* Contradict one of substrings */
1117             if (prog->anchored_substr || prog->anchored_utf8) {
1118                 if ((utf8_target ? prog->anchored_utf8 : prog->anchored_substr) == check) {
1119                     DEBUG_EXECUTE_r( what = "anchored" );
1120                   hop_and_restart:
1121                     s = HOP3c(t, 1, strend);
1122                     if (s + start_shift + end_shift > strend) {
1123                         /* XXXX Should be taken into account earlier? */
1124                         DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1125                                                "Could not match STCLASS...\n") );
1126                         goto fail;
1127                     }
1128                     if (!check)
1129                         goto giveup;
1130                     DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1131                                 "Looking for %s substr starting at offset %ld...\n",
1132                                  what, (long)(s + start_shift - i_strpos)) );
1133                     goto restart;
1134                 }
1135                 /* Have both, check_string is floating */
1136                 if (t + start_shift >= check_at) /* Contradicts floating=check */
1137                     goto retry_floating_check;
1138                 /* Recheck anchored substring, but not floating... */
1139                 s = check_at;
1140                 if (!check)
1141                     goto giveup;
1142                 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1143                           "Looking for anchored substr starting at offset %ld...\n",
1144                           (long)(other_last - i_strpos)) );
1145                 goto do_other_anchored;
1146             }
1147             /* Another way we could have checked stclass at the
1148                current position only: */
1149             if (ml_anch) {
1150                 s = t = t + 1;
1151                 if (!check)
1152                     goto giveup;
1153                 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1154                           "Looking for /%s^%s/m starting at offset %ld...\n",
1155                           PL_colors[0], PL_colors[1], (long)(t - i_strpos)) );
1156                 goto try_at_offset;
1157             }
1158             if (!(utf8_target ? prog->float_utf8 : prog->float_substr)) /* Could have been deleted */
1159                 goto fail;
1160             /* Check is floating substring. */
1161           retry_floating_check:
1162             t = check_at - start_shift;
1163             DEBUG_EXECUTE_r( what = "floating" );
1164             goto hop_and_restart;
1165         }
1166         if (t != s) {
1167             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1168                         "By STCLASS: moving %ld --> %ld\n",
1169                                   (long)(t - i_strpos), (long)(s - i_strpos))
1170                    );
1171         }
1172         else {
1173             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1174                                   "Does not contradict STCLASS...\n"); 
1175                    );
1176         }
1177     }
1178   giveup:
1179     DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%s%s:%s match at offset %ld\n",
1180                           PL_colors[4], (check ? "Guessed" : "Giving up"),
1181                           PL_colors[5], (long)(s - i_strpos)) );
1182     return s;
1183
1184   fail_finish:                          /* Substring not found */
1185     if (prog->check_substr || prog->check_utf8)         /* could be removed already */
1186         BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
1187   fail:
1188     DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch rejected by optimizer%s\n",
1189                           PL_colors[4], PL_colors[5]));
1190     return NULL;
1191 }
1192
1193 #define DECL_TRIE_TYPE(scan) \
1194     const enum { trie_plain, trie_utf8, trie_utf8_fold, trie_latin_utf8_fold } \
1195                     trie_type = ((scan->flags == EXACT) \
1196                               ? (utf8_target ? trie_utf8 : trie_plain) \
1197                               : (utf8_target ? trie_utf8_fold : trie_latin_utf8_fold))
1198
1199 #define REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc, uscan, len,          \
1200 uvc, charid, foldlen, foldbuf, uniflags) STMT_START {                               \
1201     STRLEN skiplen;                                                                 \
1202     switch (trie_type) {                                                            \
1203     case trie_utf8_fold:                                                            \
1204         if ( foldlen>0 ) {                                                          \
1205             uvc = utf8n_to_uvuni( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1206             foldlen -= len;                                                         \
1207             uscan += len;                                                           \
1208             len=0;                                                                  \
1209         } else {                                                                    \
1210             uvc = to_utf8_fold( (const U8*) uc, foldbuf, &foldlen );                \
1211             len = UTF8SKIP(uc);                                                     \
1212             skiplen = UNISKIP( uvc );                                               \
1213             foldlen -= skiplen;                                                     \
1214             uscan = foldbuf + skiplen;                                              \
1215         }                                                                           \
1216         break;                                                                      \
1217     case trie_latin_utf8_fold:                                                      \
1218         if ( foldlen>0 ) {                                                          \
1219             uvc = utf8n_to_uvuni( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1220             foldlen -= len;                                                         \
1221             uscan += len;                                                           \
1222             len=0;                                                                  \
1223         } else {                                                                    \
1224             len = 1;                                                                \
1225             uvc = _to_fold_latin1( (U8) *uc, foldbuf, &foldlen, 1);                 \
1226             skiplen = UNISKIP( uvc );                                               \
1227             foldlen -= skiplen;                                                     \
1228             uscan = foldbuf + skiplen;                                              \
1229         }                                                                           \
1230         break;                                                                      \
1231     case trie_utf8:                                                                 \
1232         uvc = utf8n_to_uvuni( (const U8*) uc, UTF8_MAXLEN, &len, uniflags );        \
1233         break;                                                                      \
1234     case trie_plain:                                                                \
1235         uvc = (UV)*uc;                                                              \
1236         len = 1;                                                                    \
1237     }                                                                               \
1238     if (uvc < 256) {                                                                \
1239         charid = trie->charmap[ uvc ];                                              \
1240     }                                                                               \
1241     else {                                                                          \
1242         charid = 0;                                                                 \
1243         if (widecharmap) {                                                          \
1244             SV** const svpp = hv_fetch(widecharmap,                                 \
1245                         (char*)&uvc, sizeof(UV), 0);                                \
1246             if (svpp)                                                               \
1247                 charid = (U16)SvIV(*svpp);                                          \
1248         }                                                                           \
1249     }                                                                               \
1250 } STMT_END
1251
1252 #define REXEC_FBC_EXACTISH_SCAN(CoNd)                     \
1253 STMT_START {                                              \
1254     while (s <= e) {                                      \
1255         if ( (CoNd)                                       \
1256              && (ln == 1 || folder(s, pat_string, ln))    \
1257              && (!reginfo || regtry(reginfo, &s)) )       \
1258             goto got_it;                                  \
1259         s++;                                              \
1260     }                                                     \
1261 } STMT_END
1262
1263 #define REXEC_FBC_UTF8_SCAN(CoDe)                     \
1264 STMT_START {                                          \
1265     while (s + (uskip = UTF8SKIP(s)) <= strend) {     \
1266         CoDe                                          \
1267         s += uskip;                                   \
1268     }                                                 \
1269 } STMT_END
1270
1271 #define REXEC_FBC_SCAN(CoDe)                          \
1272 STMT_START {                                          \
1273     while (s < strend) {                              \
1274         CoDe                                          \
1275         s++;                                          \
1276     }                                                 \
1277 } STMT_END
1278
1279 #define REXEC_FBC_UTF8_CLASS_SCAN(CoNd)               \
1280 REXEC_FBC_UTF8_SCAN(                                  \
1281     if (CoNd) {                                       \
1282         if (tmp && (!reginfo || regtry(reginfo, &s)))  \
1283             goto got_it;                              \
1284         else                                          \
1285             tmp = doevery;                            \
1286     }                                                 \
1287     else                                              \
1288         tmp = 1;                                      \
1289 )
1290
1291 #define REXEC_FBC_CLASS_SCAN(CoNd)                    \
1292 REXEC_FBC_SCAN(                                       \
1293     if (CoNd) {                                       \
1294         if (tmp && (!reginfo || regtry(reginfo, &s)))  \
1295             goto got_it;                              \
1296         else                                          \
1297             tmp = doevery;                            \
1298     }                                                 \
1299     else                                              \
1300         tmp = 1;                                      \
1301 )
1302
1303 #define REXEC_FBC_TRYIT               \
1304 if ((!reginfo || regtry(reginfo, &s))) \
1305     goto got_it
1306
1307 #define REXEC_FBC_CSCAN(CoNdUtF8,CoNd)                         \
1308     if (utf8_target) {                                             \
1309         REXEC_FBC_UTF8_CLASS_SCAN(CoNdUtF8);                   \
1310     }                                                          \
1311     else {                                                     \
1312         REXEC_FBC_CLASS_SCAN(CoNd);                            \
1313     }
1314     
1315 #define REXEC_FBC_CSCAN_PRELOAD(UtFpReLoAd,CoNdUtF8,CoNd)      \
1316     if (utf8_target) {                                             \
1317         UtFpReLoAd;                                            \
1318         REXEC_FBC_UTF8_CLASS_SCAN(CoNdUtF8);                   \
1319     }                                                          \
1320     else {                                                     \
1321         REXEC_FBC_CLASS_SCAN(CoNd);                            \
1322     }
1323
1324 #define REXEC_FBC_CSCAN_TAINT(CoNdUtF8,CoNd)                   \
1325     PL_reg_flags |= RF_tainted;                                \
1326     if (utf8_target) {                                             \
1327         REXEC_FBC_UTF8_CLASS_SCAN(CoNdUtF8);                   \
1328     }                                                          \
1329     else {                                                     \
1330         REXEC_FBC_CLASS_SCAN(CoNd);                            \
1331     }
1332
1333 #define DUMP_EXEC_POS(li,s,doutf8) \
1334     dump_exec_pos(li,s,(PL_regeol),(PL_bostr),(PL_reg_starttry),doutf8)
1335
1336
1337 #define UTF8_NOLOAD(TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1338         tmp = (s != PL_bostr) ? UCHARAT(s - 1) : '\n';                         \
1339         tmp = TEST_NON_UTF8(tmp);                                              \
1340         REXEC_FBC_UTF8_SCAN(                                                   \
1341             if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1342                 tmp = !tmp;                                                    \
1343                 IF_SUCCESS;                                                    \
1344             }                                                                  \
1345             else {                                                             \
1346                 IF_FAIL;                                                       \
1347             }                                                                  \
1348         );                                                                     \
1349
1350 #define UTF8_LOAD(TeSt1_UtF8, TeSt2_UtF8, IF_SUCCESS, IF_FAIL) \
1351         if (s == PL_bostr) {                                                   \
1352             tmp = '\n';                                                        \
1353         }                                                                      \
1354         else {                                                                 \
1355             U8 * const r = reghop3((U8*)s, -1, (U8*)PL_bostr);                 \
1356             tmp = utf8n_to_uvchr(r, UTF8SKIP(r), 0, UTF8_ALLOW_DEFAULT);       \
1357         }                                                                      \
1358         tmp = TeSt1_UtF8;                                                      \
1359         LOAD_UTF8_CHARCLASS_ALNUM();                                                                \
1360         REXEC_FBC_UTF8_SCAN(                                                   \
1361             if (tmp == ! (TeSt2_UtF8)) { \
1362                 tmp = !tmp;                                                    \
1363                 IF_SUCCESS;                                                    \
1364             }                                                                  \
1365             else {                                                             \
1366                 IF_FAIL;                                                       \
1367             }                                                                  \
1368         );                                                                     \
1369
1370 /* The only difference between the BOUND and NBOUND cases is that
1371  * REXEC_FBC_TRYIT is called when matched in BOUND, and when non-matched in
1372  * NBOUND.  This is accomplished by passing it in either the if or else clause,
1373  * with the other one being empty */
1374 #define FBC_BOUND(TEST_NON_UTF8, TEST1_UTF8, TEST2_UTF8) \
1375     FBC_BOUND_COMMON(UTF8_LOAD(TEST1_UTF8, TEST2_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1376
1377 #define FBC_BOUND_NOLOAD(TEST_NON_UTF8, TEST1_UTF8, TEST2_UTF8) \
1378     FBC_BOUND_COMMON(UTF8_NOLOAD(TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1379
1380 #define FBC_NBOUND(TEST_NON_UTF8, TEST1_UTF8, TEST2_UTF8) \
1381     FBC_BOUND_COMMON(UTF8_LOAD(TEST1_UTF8, TEST2_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1382
1383 #define FBC_NBOUND_NOLOAD(TEST_NON_UTF8, TEST1_UTF8, TEST2_UTF8) \
1384     FBC_BOUND_COMMON(UTF8_NOLOAD(TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1385
1386
1387 /* Common to the BOUND and NBOUND cases.  Unfortunately the UTF8 tests need to
1388  * be passed in completely with the variable name being tested, which isn't
1389  * such a clean interface, but this is easier to read than it was before.  We
1390  * are looking for the boundary (or non-boundary between a word and non-word
1391  * character.  The utf8 and non-utf8 cases have the same logic, but the details
1392  * must be different.  Find the "wordness" of the character just prior to this
1393  * one, and compare it with the wordness of this one.  If they differ, we have
1394  * a boundary.  At the beginning of the string, pretend that the previous
1395  * character was a new-line */
1396 #define FBC_BOUND_COMMON(UTF8_CODE, TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1397     if (utf8_target) {                                                         \
1398                 UTF8_CODE \
1399     }                                                                          \
1400     else {  /* Not utf8 */                                                     \
1401         tmp = (s != PL_bostr) ? UCHARAT(s - 1) : '\n';                         \
1402         tmp = TEST_NON_UTF8(tmp);                                              \
1403         REXEC_FBC_SCAN(                                                        \
1404             if (tmp == ! TEST_NON_UTF8((U8) *s)) {                             \
1405                 tmp = !tmp;                                                    \
1406                 IF_SUCCESS;                                                    \
1407             }                                                                  \
1408             else {                                                             \
1409                 IF_FAIL;                                                       \
1410             }                                                                  \
1411         );                                                                     \
1412     }                                                                          \
1413     if ((!prog->minlen && tmp) && (!reginfo || regtry(reginfo, &s)))           \
1414         goto got_it;
1415
1416 /* We know what class REx starts with.  Try to find this position... */
1417 /* if reginfo is NULL, its a dryrun */
1418 /* annoyingly all the vars in this routine have different names from their counterparts
1419    in regmatch. /grrr */
1420
1421 STATIC char *
1422 S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s, 
1423     const char *strend, regmatch_info *reginfo)
1424 {
1425         dVAR;
1426         const I32 doevery = (prog->intflags & PREGf_SKIP) == 0;
1427         char *pat_string;   /* The pattern's exactish string */
1428         char *pat_end;      /* ptr to end char of pat_string */
1429         re_fold_t folder;       /* Function for computing non-utf8 folds */
1430         const U8 *fold_array;   /* array for folding ords < 256 */
1431         STRLEN ln;
1432         STRLEN lnc;
1433         STRLEN uskip;
1434         U8 c1;
1435         U8 c2;
1436         char *e;
1437         I32 tmp = 1;    /* Scratch variable? */
1438         const bool utf8_target = PL_reg_match_utf8;
1439         UV utf8_fold_flags = 0;
1440         RXi_GET_DECL(prog,progi);
1441
1442         PERL_ARGS_ASSERT_FIND_BYCLASS;
1443         
1444         /* We know what class it must start with. */
1445         switch (OP(c)) {
1446         case ANYOFV:
1447         case ANYOF:
1448             if (utf8_target || OP(c) == ANYOFV) {
1449                 STRLEN inclasslen = strend - s;
1450                 REXEC_FBC_UTF8_CLASS_SCAN(
1451                           reginclass(prog, c, (U8*)s, &inclasslen, utf8_target));
1452             }
1453             else {
1454                 REXEC_FBC_CLASS_SCAN(REGINCLASS(prog, c, (U8*)s));
1455             }
1456             break;
1457         case CANY:
1458             REXEC_FBC_SCAN(
1459                 if (tmp && (!reginfo || regtry(reginfo, &s)))
1460                     goto got_it;
1461                 else
1462                     tmp = doevery;
1463             );
1464             break;
1465
1466         case EXACTFA:
1467             if (UTF_PATTERN || utf8_target) {
1468                 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
1469                 goto do_exactf_utf8;
1470             }
1471             fold_array = PL_fold_latin1;    /* Latin1 folds are not affected by */
1472             folder = foldEQ_latin1;         /* /a, except the sharp s one which */
1473             goto do_exactf_non_utf8;        /* isn't dealt with by these */
1474
1475         case EXACTF:
1476             if (utf8_target) {
1477
1478                 /* regcomp.c already folded this if pattern is in UTF-8 */
1479                 utf8_fold_flags = 0;
1480                 goto do_exactf_utf8;
1481             }
1482             fold_array = PL_fold;
1483             folder = foldEQ;
1484             goto do_exactf_non_utf8;
1485
1486         case EXACTFL:
1487             if (UTF_PATTERN || utf8_target) {
1488                 utf8_fold_flags = FOLDEQ_UTF8_LOCALE;
1489                 goto do_exactf_utf8;
1490             }
1491             fold_array = PL_fold_locale;
1492             folder = foldEQ_locale;
1493             goto do_exactf_non_utf8;
1494
1495         case EXACTFU_SS:
1496             if (UTF_PATTERN) {
1497                 utf8_fold_flags = FOLDEQ_S2_ALREADY_FOLDED;
1498             }
1499             goto do_exactf_utf8;
1500
1501         case EXACTFU_TRICKYFOLD:
1502         case EXACTFU:
1503             if (UTF_PATTERN || utf8_target) {
1504                 utf8_fold_flags = (UTF_PATTERN) ? FOLDEQ_S2_ALREADY_FOLDED : 0;
1505                 goto do_exactf_utf8;
1506             }
1507
1508             /* Any 'ss' in the pattern should have been replaced by regcomp,
1509              * so we don't have to worry here about this single special case
1510              * in the Latin1 range */
1511             fold_array = PL_fold_latin1;
1512             folder = foldEQ_latin1;
1513
1514             /* FALL THROUGH */
1515
1516         do_exactf_non_utf8: /* Neither pattern nor string are UTF8, and there
1517                                are no glitches with fold-length differences
1518                                between the target string and pattern */
1519
1520             /* The idea in the non-utf8 EXACTF* cases is to first find the
1521              * first character of the EXACTF* node and then, if necessary,
1522              * case-insensitively compare the full text of the node.  c1 is the
1523              * first character.  c2 is its fold.  This logic will not work for
1524              * Unicode semantics and the german sharp ss, which hence should
1525              * not be compiled into a node that gets here. */
1526             pat_string = STRING(c);
1527             ln  = STR_LEN(c);   /* length to match in octets/bytes */
1528
1529             /* We know that we have to match at least 'ln' bytes (which is the
1530              * same as characters, since not utf8).  If we have to match 3
1531              * characters, and there are only 2 availabe, we know without
1532              * trying that it will fail; so don't start a match past the
1533              * required minimum number from the far end */
1534             e = HOP3c(strend, -((I32)ln), s);
1535
1536             if (!reginfo && e < s) {
1537                 e = s;                  /* Due to minlen logic of intuit() */
1538             }
1539
1540             c1 = *pat_string;
1541             c2 = fold_array[c1];
1542             if (c1 == c2) { /* If char and fold are the same */
1543                 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1);
1544             }
1545             else {
1546                 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1 || *(U8*)s == c2);
1547             }
1548             break;
1549
1550         do_exactf_utf8:
1551         {
1552             unsigned expansion;
1553
1554
1555             /* If one of the operands is in utf8, we can't use the simpler
1556              * folding above, due to the fact that many different characters
1557              * can have the same fold, or portion of a fold, or different-
1558              * length fold */
1559             pat_string = STRING(c);
1560             ln  = STR_LEN(c);   /* length to match in octets/bytes */
1561             pat_end = pat_string + ln;
1562             lnc = (UTF_PATTERN) /* length to match in characters */
1563                     ? utf8_length((U8 *) pat_string, (U8 *) pat_end)
1564                     : ln;
1565
1566             /* We have 'lnc' characters to match in the pattern, but because of
1567              * multi-character folding, each character in the target can match
1568              * up to 3 characters (Unicode guarantees it will never exceed
1569              * this) if it is utf8-encoded; and up to 2 if not (based on the
1570              * fact that the Latin 1 folds are already determined, and the
1571              * only multi-char fold in that range is the sharp-s folding to
1572              * 'ss'.  Thus, a pattern character can match as little as 1/3 of a
1573              * string character.  Adjust lnc accordingly, rounding up, so that
1574              * if we need to match at least 4+1/3 chars, that really is 5. */
1575             expansion = (utf8_target) ? UTF8_MAX_FOLD_CHAR_EXPAND : 2;
1576             lnc = (lnc + expansion - 1) / expansion;
1577
1578             /* As in the non-UTF8 case, if we have to match 3 characters, and
1579              * only 2 are left, it's guaranteed to fail, so don't start a
1580              * match that would require us to go beyond the end of the string
1581              */
1582             e = HOP3c(strend, -((I32)lnc), s);
1583
1584             if (!reginfo && e < s) {
1585                 e = s;                  /* Due to minlen logic of intuit() */
1586             }
1587
1588             /* XXX Note that we could recalculate e to stop the loop earlier,
1589              * as the worst case expansion above will rarely be met, and as we
1590              * go along we would usually find that e moves further to the left.
1591              * This would happen only after we reached the point in the loop
1592              * where if there were no expansion we should fail.  Unclear if
1593              * worth the expense */
1594
1595             while (s <= e) {
1596                 char *my_strend= (char *)strend;
1597                 if (foldEQ_utf8_flags(s, &my_strend, 0,  utf8_target,
1598                       pat_string, NULL, ln, cBOOL(UTF_PATTERN), utf8_fold_flags)
1599                     && (!reginfo || regtry(reginfo, &s)) )
1600                 {
1601                     goto got_it;
1602                 }
1603                 s += (utf8_target) ? UTF8SKIP(s) : 1;
1604             }
1605             break;
1606         }
1607         case BOUNDL:
1608             PL_reg_flags |= RF_tainted;
1609             FBC_BOUND(isALNUM_LC,
1610                       isALNUM_LC_uvchr(UNI_TO_NATIVE(tmp)),
1611                       isALNUM_LC_utf8((U8*)s));
1612             break;
1613         case NBOUNDL:
1614             PL_reg_flags |= RF_tainted;
1615             FBC_NBOUND(isALNUM_LC,
1616                        isALNUM_LC_uvchr(UNI_TO_NATIVE(tmp)),
1617                        isALNUM_LC_utf8((U8*)s));
1618             break;
1619         case BOUND:
1620             FBC_BOUND(isWORDCHAR,
1621                       isALNUM_uni(tmp),
1622                       cBOOL(swash_fetch(PL_utf8_alnum, (U8*)s, utf8_target)));
1623             break;
1624         case BOUNDA:
1625             FBC_BOUND_NOLOAD(isWORDCHAR_A,
1626                              isWORDCHAR_A(tmp),
1627                              isWORDCHAR_A((U8*)s));
1628             break;
1629         case NBOUND:
1630             FBC_NBOUND(isWORDCHAR,
1631                        isALNUM_uni(tmp),
1632                        cBOOL(swash_fetch(PL_utf8_alnum, (U8*)s, utf8_target)));
1633             break;
1634         case NBOUNDA:
1635             FBC_NBOUND_NOLOAD(isWORDCHAR_A,
1636                               isWORDCHAR_A(tmp),
1637                               isWORDCHAR_A((U8*)s));
1638             break;
1639         case BOUNDU:
1640             FBC_BOUND(isWORDCHAR_L1,
1641                       isALNUM_uni(tmp),
1642                       cBOOL(swash_fetch(PL_utf8_alnum, (U8*)s, utf8_target)));
1643             break;
1644         case NBOUNDU:
1645             FBC_NBOUND(isWORDCHAR_L1,
1646                        isALNUM_uni(tmp),
1647                        cBOOL(swash_fetch(PL_utf8_alnum, (U8*)s, utf8_target)));
1648             break;
1649         case ALNUML:
1650             REXEC_FBC_CSCAN_TAINT(
1651                 isALNUM_LC_utf8((U8*)s),
1652                 isALNUM_LC(*s)
1653             );
1654             break;
1655         case ALNUMU:
1656             REXEC_FBC_CSCAN_PRELOAD(
1657                 LOAD_UTF8_CHARCLASS_ALNUM(),
1658                 swash_fetch(PL_utf8_alnum,(U8*)s, utf8_target),
1659                 isWORDCHAR_L1((U8) *s)
1660             );
1661             break;
1662         case ALNUM:
1663             REXEC_FBC_CSCAN_PRELOAD(
1664                 LOAD_UTF8_CHARCLASS_ALNUM(),
1665                 swash_fetch(PL_utf8_alnum,(U8*)s, utf8_target),
1666                 isWORDCHAR((U8) *s)
1667             );
1668             break;
1669         case ALNUMA:
1670             /* Don't need to worry about utf8, as it can match only a single
1671              * byte invariant character */
1672             REXEC_FBC_CLASS_SCAN( isWORDCHAR_A(*s));
1673             break;
1674         case NALNUMU:
1675             REXEC_FBC_CSCAN_PRELOAD(
1676                 LOAD_UTF8_CHARCLASS_ALNUM(),
1677                 !swash_fetch(PL_utf8_alnum,(U8*)s, utf8_target),
1678                 ! isWORDCHAR_L1((U8) *s)
1679             );
1680             break;
1681         case NALNUM:
1682             REXEC_FBC_CSCAN_PRELOAD(
1683                 LOAD_UTF8_CHARCLASS_ALNUM(),
1684                 !swash_fetch(PL_utf8_alnum, (U8*)s, utf8_target),
1685                 ! isALNUM(*s)
1686             );
1687             break;
1688         case NALNUMA:
1689             REXEC_FBC_CSCAN(
1690                 !isWORDCHAR_A(*s),
1691                 !isWORDCHAR_A(*s)
1692             );
1693             break;
1694         case NALNUML:
1695             REXEC_FBC_CSCAN_TAINT(
1696                 !isALNUM_LC_utf8((U8*)s),
1697                 !isALNUM_LC(*s)
1698             );
1699             break;
1700         case SPACEU:
1701             REXEC_FBC_CSCAN_PRELOAD(
1702                 LOAD_UTF8_CHARCLASS_SPACE(),
1703                 *s == ' ' || swash_fetch(PL_utf8_space,(U8*)s, utf8_target),
1704                 isSPACE_L1((U8) *s)
1705             );
1706             break;
1707         case SPACE:
1708             REXEC_FBC_CSCAN_PRELOAD(
1709                 LOAD_UTF8_CHARCLASS_SPACE(),
1710                 *s == ' ' || swash_fetch(PL_utf8_space,(U8*)s, utf8_target),
1711                 isSPACE((U8) *s)
1712             );
1713             break;
1714         case SPACEA:
1715             /* Don't need to worry about utf8, as it can match only a single
1716              * byte invariant character */
1717             REXEC_FBC_CLASS_SCAN( isSPACE_A(*s));
1718             break;
1719         case SPACEL:
1720             REXEC_FBC_CSCAN_TAINT(
1721                 isSPACE_LC_utf8((U8*)s),
1722                 isSPACE_LC(*s)
1723             );
1724             break;
1725         case NSPACEU:
1726             REXEC_FBC_CSCAN_PRELOAD(
1727                 LOAD_UTF8_CHARCLASS_SPACE(),
1728                 !( *s == ' ' || swash_fetch(PL_utf8_space,(U8*)s, utf8_target)),
1729                 ! isSPACE_L1((U8) *s)
1730             );
1731             break;
1732         case NSPACE:
1733             REXEC_FBC_CSCAN_PRELOAD(
1734                 LOAD_UTF8_CHARCLASS_SPACE(),
1735                 !(*s == ' ' || swash_fetch(PL_utf8_space,(U8*)s, utf8_target)),
1736                 ! isSPACE((U8) *s)
1737             );
1738             break;
1739         case NSPACEA:
1740             REXEC_FBC_CSCAN(
1741                 !isSPACE_A(*s),
1742                 !isSPACE_A(*s)
1743             );
1744             break;
1745         case NSPACEL:
1746             REXEC_FBC_CSCAN_TAINT(
1747                 !isSPACE_LC_utf8((U8*)s),
1748                 !isSPACE_LC(*s)
1749             );
1750             break;
1751         case DIGIT:
1752             REXEC_FBC_CSCAN_PRELOAD(
1753                 LOAD_UTF8_CHARCLASS_DIGIT(),
1754                 swash_fetch(PL_utf8_digit,(U8*)s, utf8_target),
1755                 isDIGIT(*s)
1756             );
1757             break;
1758         case DIGITA:
1759             /* Don't need to worry about utf8, as it can match only a single
1760              * byte invariant character */
1761             REXEC_FBC_CLASS_SCAN( isDIGIT_A(*s));
1762             break;
1763         case DIGITL:
1764             REXEC_FBC_CSCAN_TAINT(
1765                 isDIGIT_LC_utf8((U8*)s),
1766                 isDIGIT_LC(*s)
1767             );
1768             break;
1769         case NDIGIT:
1770             REXEC_FBC_CSCAN_PRELOAD(
1771                 LOAD_UTF8_CHARCLASS_DIGIT(),
1772                 !swash_fetch(PL_utf8_digit,(U8*)s, utf8_target),
1773                 !isDIGIT(*s)
1774             );
1775             break;
1776         case NDIGITA:
1777             REXEC_FBC_CSCAN(
1778                 !isDIGIT_A(*s),
1779                 !isDIGIT_A(*s)
1780             );
1781             break;
1782         case NDIGITL:
1783             REXEC_FBC_CSCAN_TAINT(
1784                 !isDIGIT_LC_utf8((U8*)s),
1785                 !isDIGIT_LC(*s)
1786             );
1787             break;
1788         case LNBREAK:
1789             REXEC_FBC_CSCAN(
1790                 is_LNBREAK_utf8(s),
1791                 is_LNBREAK_latin1(s)
1792             );
1793             break;
1794         case VERTWS:
1795             REXEC_FBC_CSCAN(
1796                 is_VERTWS_utf8(s),
1797                 is_VERTWS_latin1(s)
1798             );
1799             break;
1800         case NVERTWS:
1801             REXEC_FBC_CSCAN(
1802                 !is_VERTWS_utf8(s),
1803                 !is_VERTWS_latin1(s)
1804             );
1805             break;
1806         case HORIZWS:
1807             REXEC_FBC_CSCAN(
1808                 is_HORIZWS_utf8(s),
1809                 is_HORIZWS_latin1(s)
1810             );
1811             break;
1812         case NHORIZWS:
1813             REXEC_FBC_CSCAN(
1814                 !is_HORIZWS_utf8(s),
1815                 !is_HORIZWS_latin1(s)
1816             );      
1817             break;
1818         case POSIXA:
1819             /* Don't need to worry about utf8, as it can match only a single
1820             * byte invariant character.  The flag in this node type is the
1821             * class number to pass to _generic_isCC() to build a mask for
1822             * searching in PL_charclass[] */
1823             REXEC_FBC_CLASS_SCAN( _generic_isCC_A(*s, FLAGS(c)));
1824             break;
1825         case NPOSIXA:
1826             REXEC_FBC_CSCAN(
1827                 !_generic_isCC_A(*s, FLAGS(c)),
1828                 !_generic_isCC_A(*s, FLAGS(c))
1829             );
1830             break;
1831
1832         case AHOCORASICKC:
1833         case AHOCORASICK: 
1834             {
1835                 DECL_TRIE_TYPE(c);
1836                 /* what trie are we using right now */
1837                 reg_ac_data *aho
1838                     = (reg_ac_data*)progi->data->data[ ARG( c ) ];
1839                 reg_trie_data *trie
1840                     = (reg_trie_data*)progi->data->data[ aho->trie ];
1841                 HV *widecharmap = MUTABLE_HV(progi->data->data[ aho->trie + 1 ]);
1842
1843                 const char *last_start = strend - trie->minlen;
1844 #ifdef DEBUGGING
1845                 const char *real_start = s;
1846 #endif
1847                 STRLEN maxlen = trie->maxlen;
1848                 SV *sv_points;
1849                 U8 **points; /* map of where we were in the input string
1850                                 when reading a given char. For ASCII this
1851                                 is unnecessary overhead as the relationship
1852                                 is always 1:1, but for Unicode, especially
1853                                 case folded Unicode this is not true. */
1854                 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1855                 U8 *bitmap=NULL;
1856
1857
1858                 GET_RE_DEBUG_FLAGS_DECL;
1859
1860                 /* We can't just allocate points here. We need to wrap it in
1861                  * an SV so it gets freed properly if there is a croak while
1862                  * running the match */
1863                 ENTER;
1864                 SAVETMPS;
1865                 sv_points=newSV(maxlen * sizeof(U8 *));
1866                 SvCUR_set(sv_points,
1867                     maxlen * sizeof(U8 *));
1868                 SvPOK_on(sv_points);
1869                 sv_2mortal(sv_points);
1870                 points=(U8**)SvPV_nolen(sv_points );
1871                 if ( trie_type != trie_utf8_fold 
1872                      && (trie->bitmap || OP(c)==AHOCORASICKC) ) 
1873                 {
1874                     if (trie->bitmap) 
1875                         bitmap=(U8*)trie->bitmap;
1876                     else
1877                         bitmap=(U8*)ANYOF_BITMAP(c);
1878                 }
1879                 /* this is the Aho-Corasick algorithm modified a touch
1880                    to include special handling for long "unknown char" 
1881                    sequences. The basic idea being that we use AC as long
1882                    as we are dealing with a possible matching char, when
1883                    we encounter an unknown char (and we have not encountered
1884                    an accepting state) we scan forward until we find a legal 
1885                    starting char. 
1886                    AC matching is basically that of trie matching, except
1887                    that when we encounter a failing transition, we fall back
1888                    to the current states "fail state", and try the current char 
1889                    again, a process we repeat until we reach the root state, 
1890                    state 1, or a legal transition. If we fail on the root state 
1891                    then we can either terminate if we have reached an accepting 
1892                    state previously, or restart the entire process from the beginning 
1893                    if we have not.
1894
1895                  */
1896                 while (s <= last_start) {
1897                     const U32 uniflags = UTF8_ALLOW_DEFAULT;
1898                     U8 *uc = (U8*)s;
1899                     U16 charid = 0;
1900                     U32 base = 1;
1901                     U32 state = 1;
1902                     UV uvc = 0;
1903                     STRLEN len = 0;
1904                     STRLEN foldlen = 0;
1905                     U8 *uscan = (U8*)NULL;
1906                     U8 *leftmost = NULL;
1907 #ifdef DEBUGGING                    
1908                     U32 accepted_word= 0;
1909 #endif
1910                     U32 pointpos = 0;
1911
1912                     while ( state && uc <= (U8*)strend ) {
1913                         int failed=0;
1914                         U32 word = aho->states[ state ].wordnum;
1915
1916                         if( state==1 ) {
1917                             if ( bitmap ) {
1918                                 DEBUG_TRIE_EXECUTE_r(
1919                                     if ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
1920                                         dump_exec_pos( (char *)uc, c, strend, real_start, 
1921                                             (char *)uc, utf8_target );
1922                                         PerlIO_printf( Perl_debug_log,
1923                                             " Scanning for legal start char...\n");
1924                                     }
1925                                 );
1926                                 if (utf8_target) {
1927                                     while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
1928                                         uc += UTF8SKIP(uc);
1929                                     }
1930                                 } else {
1931                                     while ( uc <= (U8*)last_start  && !BITMAP_TEST(bitmap,*uc) ) {
1932                                         uc++;
1933                                     }
1934                                 }
1935                                 s= (char *)uc;
1936                             }
1937                             if (uc >(U8*)last_start) break;
1938                         }
1939                                             
1940                         if ( word ) {
1941                             U8 *lpos= points[ (pointpos - trie->wordinfo[word].len) % maxlen ];
1942                             if (!leftmost || lpos < leftmost) {
1943                                 DEBUG_r(accepted_word=word);
1944                                 leftmost= lpos;
1945                             }
1946                             if (base==0) break;
1947                             
1948                         }
1949                         points[pointpos++ % maxlen]= uc;
1950                         REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
1951                                              uscan, len, uvc, charid, foldlen,
1952                                              foldbuf, uniflags);
1953                         DEBUG_TRIE_EXECUTE_r({
1954                             dump_exec_pos( (char *)uc, c, strend, real_start, 
1955                                 s,   utf8_target );
1956                             PerlIO_printf(Perl_debug_log,
1957                                 " Charid:%3u CP:%4"UVxf" ",
1958                                  charid, uvc);
1959                         });
1960
1961                         do {
1962 #ifdef DEBUGGING
1963                             word = aho->states[ state ].wordnum;
1964 #endif
1965                             base = aho->states[ state ].trans.base;
1966
1967                             DEBUG_TRIE_EXECUTE_r({
1968                                 if (failed) 
1969                                     dump_exec_pos( (char *)uc, c, strend, real_start, 
1970                                         s,   utf8_target );
1971                                 PerlIO_printf( Perl_debug_log,
1972                                     "%sState: %4"UVxf", word=%"UVxf,
1973                                     failed ? " Fail transition to " : "",
1974                                     (UV)state, (UV)word);
1975                             });
1976                             if ( base ) {
1977                                 U32 tmp;
1978                                 I32 offset;
1979                                 if (charid &&
1980                                      ( ((offset = base + charid
1981                                         - 1 - trie->uniquecharcount)) >= 0)
1982                                      && ((U32)offset < trie->lasttrans)
1983                                      && trie->trans[offset].check == state
1984                                      && (tmp=trie->trans[offset].next))
1985                                 {
1986                                     DEBUG_TRIE_EXECUTE_r(
1987                                         PerlIO_printf( Perl_debug_log," - legal\n"));
1988                                     state = tmp;
1989                                     break;
1990                                 }
1991                                 else {
1992                                     DEBUG_TRIE_EXECUTE_r(
1993                                         PerlIO_printf( Perl_debug_log," - fail\n"));
1994                                     failed = 1;
1995                                     state = aho->fail[state];
1996                                 }
1997                             }
1998                             else {
1999                                 /* we must be accepting here */
2000                                 DEBUG_TRIE_EXECUTE_r(
2001                                         PerlIO_printf( Perl_debug_log," - accepting\n"));
2002                                 failed = 1;
2003                                 break;
2004                             }
2005                         } while(state);
2006                         uc += len;
2007                         if (failed) {
2008                             if (leftmost)
2009                                 break;
2010                             if (!state) state = 1;
2011                         }
2012                     }
2013                     if ( aho->states[ state ].wordnum ) {
2014                         U8 *lpos = points[ (pointpos - trie->wordinfo[aho->states[ state ].wordnum].len) % maxlen ];
2015                         if (!leftmost || lpos < leftmost) {
2016                             DEBUG_r(accepted_word=aho->states[ state ].wordnum);
2017                             leftmost = lpos;
2018                         }
2019                     }
2020                     if (leftmost) {
2021                         s = (char*)leftmost;
2022                         DEBUG_TRIE_EXECUTE_r({
2023                             PerlIO_printf( 
2024                                 Perl_debug_log,"Matches word #%"UVxf" at position %"IVdf". Trying full pattern...\n",
2025                                 (UV)accepted_word, (IV)(s - real_start)
2026                             );
2027                         });
2028                         if (!reginfo || regtry(reginfo, &s)) {
2029                             FREETMPS;
2030                             LEAVE;
2031                             goto got_it;
2032                         }
2033                         s = HOPc(s,1);
2034                         DEBUG_TRIE_EXECUTE_r({
2035                             PerlIO_printf( Perl_debug_log,"Pattern failed. Looking for new start point...\n");
2036                         });
2037                     } else {
2038                         DEBUG_TRIE_EXECUTE_r(
2039                             PerlIO_printf( Perl_debug_log,"No match.\n"));
2040                         break;
2041                     }
2042                 }
2043                 FREETMPS;
2044                 LEAVE;
2045             }
2046             break;
2047         default:
2048             Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
2049             break;
2050         }
2051         return 0;
2052       got_it:
2053         return s;
2054 }
2055
2056
2057 /*
2058  - regexec_flags - match a regexp against a string
2059  */
2060 I32
2061 Perl_regexec_flags(pTHX_ REGEXP * const rx, char *stringarg, register char *strend,
2062               char *strbeg, I32 minend, SV *sv, void *data, U32 flags)
2063 /* strend: pointer to null at end of string */
2064 /* strbeg: real beginning of string */
2065 /* minend: end of match must be >=minend after stringarg. */
2066 /* data: May be used for some additional optimizations. 
2067          Currently its only used, with a U32 cast, for transmitting 
2068          the ganch offset when doing a /g match. This will change */
2069 /* nosave: For optimizations. */
2070 {
2071     dVAR;
2072     struct regexp *const prog = (struct regexp *)SvANY(rx);
2073     /*register*/ char *s;
2074     regnode *c;
2075     /*register*/ char *startpos = stringarg;
2076     I32 minlen;         /* must match at least this many chars */
2077     I32 dontbother = 0; /* how many characters not to try at end */
2078     I32 end_shift = 0;                  /* Same for the end. */         /* CC */
2079     I32 scream_pos = -1;                /* Internal iterator of scream. */
2080     char *scream_olds = NULL;
2081     const bool utf8_target = cBOOL(DO_UTF8(sv));
2082     I32 multiline;
2083     RXi_GET_DECL(prog,progi);
2084     regmatch_info reginfo;  /* create some info to pass to regtry etc */
2085     regexp_paren_pair *swap = NULL;
2086     GET_RE_DEBUG_FLAGS_DECL;
2087
2088     PERL_ARGS_ASSERT_REGEXEC_FLAGS;
2089     PERL_UNUSED_ARG(data);
2090
2091     /* Be paranoid... */
2092     if (prog == NULL || startpos == NULL) {
2093         Perl_croak(aTHX_ "NULL regexp parameter");
2094         return 0;
2095     }
2096
2097     multiline = prog->extflags & RXf_PMf_MULTILINE;
2098     reginfo.prog = rx;   /* Yes, sorry that this is confusing.  */
2099
2100     RX_MATCH_UTF8_set(rx, utf8_target);
2101     DEBUG_EXECUTE_r( 
2102         debug_start_match(rx, utf8_target, startpos, strend,
2103         "Matching");
2104     );
2105
2106     minlen = prog->minlen;
2107     
2108     if (strend - startpos < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
2109         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
2110                               "String too short [regexec_flags]...\n"));
2111         goto phooey;
2112     }
2113
2114     
2115     /* Check validity of program. */
2116     if (UCHARAT(progi->program) != REG_MAGIC) {
2117         Perl_croak(aTHX_ "corrupted regexp program");
2118     }
2119
2120     PL_reg_flags = 0;
2121     PL_reg_state.re_state_eval_setup_done = FALSE;
2122     PL_reg_maxiter = 0;
2123
2124     if (RX_UTF8(rx))
2125         PL_reg_flags |= RF_utf8;
2126
2127     /* Mark beginning of line for ^ and lookbehind. */
2128     reginfo.bol = startpos; /* XXX not used ??? */
2129     PL_bostr  = strbeg;
2130     reginfo.sv = sv;
2131
2132     /* Mark end of line for $ (and such) */
2133     PL_regeol = strend;
2134
2135     /* see how far we have to get to not match where we matched before */
2136     reginfo.till = startpos+minend;
2137
2138     /* If there is a "must appear" string, look for it. */
2139     s = startpos;
2140
2141     if (prog->extflags & RXf_GPOS_SEEN) { /* Need to set reginfo->ganch */
2142         MAGIC *mg;
2143         if (flags & REXEC_IGNOREPOS){   /* Means: check only at start */
2144             reginfo.ganch = startpos + prog->gofs;
2145             DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
2146               "GPOS IGNOREPOS: reginfo.ganch = startpos + %"UVxf"\n",(UV)prog->gofs));
2147         } else if (sv && SvTYPE(sv) >= SVt_PVMG
2148                   && SvMAGIC(sv)
2149                   && (mg = mg_find(sv, PERL_MAGIC_regex_global))
2150                   && mg->mg_len >= 0) {
2151             reginfo.ganch = strbeg + mg->mg_len;        /* Defined pos() */
2152             DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
2153                 "GPOS MAGIC: reginfo.ganch = strbeg + %"IVdf"\n",(IV)mg->mg_len));
2154
2155             if (prog->extflags & RXf_ANCH_GPOS) {
2156                 if (s > reginfo.ganch)
2157                     goto phooey;
2158                 s = reginfo.ganch - prog->gofs;
2159                 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
2160                      "GPOS ANCH_GPOS: s = ganch - %"UVxf"\n",(UV)prog->gofs));
2161                 if (s < strbeg)
2162                     goto phooey;
2163             }
2164         }
2165         else if (data) {
2166             reginfo.ganch = strbeg + PTR2UV(data);
2167             DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
2168                  "GPOS DATA: reginfo.ganch= strbeg + %"UVxf"\n",PTR2UV(data)));
2169
2170         } else {                                /* pos() not defined */
2171             reginfo.ganch = strbeg;
2172             DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
2173                  "GPOS: reginfo.ganch = strbeg\n"));
2174         }
2175     }
2176     if (PL_curpm && (PM_GETRE(PL_curpm) == rx)) {
2177         /* We have to be careful. If the previous successful match
2178            was from this regex we don't want a subsequent partially
2179            successful match to clobber the old results.
2180            So when we detect this possibility we add a swap buffer
2181            to the re, and switch the buffer each match. If we fail
2182            we switch it back, otherwise we leave it swapped.
2183         */
2184         swap = prog->offs;
2185         /* do we need a save destructor here for eval dies? */
2186         Newxz(prog->offs, (prog->nparens + 1), regexp_paren_pair);
2187         DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
2188             "rex=0x%"UVxf" saving  offs: orig=0x%"UVxf" new=0x%"UVxf"\n",
2189             PTR2UV(prog),
2190             PTR2UV(swap),
2191             PTR2UV(prog->offs)
2192         ));
2193     }
2194     if (!(flags & REXEC_CHECKED) && (prog->check_substr != NULL || prog->check_utf8 != NULL)) {
2195         re_scream_pos_data d;
2196
2197         d.scream_olds = &scream_olds;
2198         d.scream_pos = &scream_pos;
2199         s = re_intuit_start(rx, sv, s, strend, flags, &d);
2200         if (!s) {
2201             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Not present...\n"));
2202             goto phooey;        /* not present */
2203         }
2204     }
2205
2206
2207
2208     /* Simplest case:  anchored match need be tried only once. */
2209     /*  [unless only anchor is BOL and multiline is set] */
2210     if (prog->extflags & (RXf_ANCH & ~RXf_ANCH_GPOS)) {
2211         if (s == startpos && regtry(&reginfo, &startpos))
2212             goto got_it;
2213         else if (multiline || (prog->intflags & PREGf_IMPLICIT)
2214                  || (prog->extflags & RXf_ANCH_MBOL)) /* XXXX SBOL? */
2215         {
2216             char *end;
2217
2218             if (minlen)
2219                 dontbother = minlen - 1;
2220             end = HOP3c(strend, -dontbother, strbeg) - 1;
2221             /* for multiline we only have to try after newlines */
2222             if (prog->check_substr || prog->check_utf8) {
2223                 /* because of the goto we can not easily reuse the macros for bifurcating the
2224                    unicode/non-unicode match modes here like we do elsewhere - demerphq */
2225                 if (utf8_target) {
2226                     if (s == startpos)
2227                         goto after_try_utf8;
2228                     while (1) {
2229                         if (regtry(&reginfo, &s)) {
2230                             goto got_it;
2231                         }
2232                       after_try_utf8:
2233                         if (s > end) {
2234                             goto phooey;
2235                         }
2236                         if (prog->extflags & RXf_USE_INTUIT) {
2237                             s = re_intuit_start(rx, sv, s + UTF8SKIP(s), strend, flags, NULL);
2238                             if (!s) {
2239                                 goto phooey;
2240                             }
2241                         }
2242                         else {
2243                             s += UTF8SKIP(s);
2244                         }
2245                     }
2246                 } /* end search for check string in unicode */
2247                 else {
2248                     if (s == startpos) {
2249                         goto after_try_latin;
2250                     }
2251                     while (1) {
2252                         if (regtry(&reginfo, &s)) {
2253                             goto got_it;
2254                         }
2255                       after_try_latin:
2256                         if (s > end) {
2257                             goto phooey;
2258                         }
2259                         if (prog->extflags & RXf_USE_INTUIT) {
2260                             s = re_intuit_start(rx, sv, s + 1, strend, flags, NULL);
2261                             if (!s) {
2262                                 goto phooey;
2263                             }
2264                         }
2265                         else {
2266                             s++;
2267                         }
2268                     }
2269                 } /* end search for check string in latin*/
2270             } /* end search for check string */
2271             else { /* search for newline */
2272                 if (s > startpos) {
2273                     /*XXX: The s-- is almost definitely wrong here under unicode - demeprhq*/
2274                     s--;
2275                 }
2276                 /* We can use a more efficient search as newlines are the same in unicode as they are in latin */
2277                 while (s <= end) { /* note it could be possible to match at the end of the string */
2278                     if (*s++ == '\n') { /* don't need PL_utf8skip here */
2279                         if (regtry(&reginfo, &s))
2280                             goto got_it;
2281                     }
2282                 }
2283             } /* end search for newline */
2284         } /* end anchored/multiline check string search */
2285         goto phooey;
2286     } else if (RXf_GPOS_CHECK == (prog->extflags & RXf_GPOS_CHECK)) 
2287     {
2288         /* the warning about reginfo.ganch being used without initialization
2289            is bogus -- we set it above, when prog->extflags & RXf_GPOS_SEEN 
2290            and we only enter this block when the same bit is set. */
2291         char *tmp_s = reginfo.ganch - prog->gofs;
2292
2293         if (tmp_s >= strbeg && regtry(&reginfo, &tmp_s))
2294             goto got_it;
2295         goto phooey;
2296     }
2297
2298     /* Messy cases:  unanchored match. */
2299     if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
2300         /* we have /x+whatever/ */
2301         /* it must be a one character string (XXXX Except UTF_PATTERN?) */
2302         char ch;
2303 #ifdef DEBUGGING
2304         int did_match = 0;
2305 #endif
2306         if (!(utf8_target ? prog->anchored_utf8 : prog->anchored_substr))
2307             utf8_target ? to_utf8_substr(prog) : to_byte_substr(prog);
2308         ch = SvPVX_const(utf8_target ? prog->anchored_utf8 : prog->anchored_substr)[0];
2309
2310         if (utf8_target) {
2311             REXEC_FBC_SCAN(
2312                 if (*s == ch) {
2313                     DEBUG_EXECUTE_r( did_match = 1 );
2314                     if (regtry(&reginfo, &s)) goto got_it;
2315                     s += UTF8SKIP(s);
2316                     while (s < strend && *s == ch)
2317                         s += UTF8SKIP(s);
2318                 }
2319             );
2320         }
2321         else {
2322             REXEC_FBC_SCAN(
2323                 if (*s == ch) {
2324                     DEBUG_EXECUTE_r( did_match = 1 );
2325                     if (regtry(&reginfo, &s)) goto got_it;
2326                     s++;
2327                     while (s < strend && *s == ch)
2328                         s++;
2329                 }
2330             );
2331         }
2332         DEBUG_EXECUTE_r(if (!did_match)
2333                 PerlIO_printf(Perl_debug_log,
2334                                   "Did not find anchored character...\n")
2335                );
2336     }
2337     else if (prog->anchored_substr != NULL
2338               || prog->anchored_utf8 != NULL
2339               || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
2340                   && prog->float_max_offset < strend - s)) {
2341         SV *must;
2342         I32 back_max;
2343         I32 back_min;
2344         char *last;
2345         char *last1;            /* Last position checked before */
2346 #ifdef DEBUGGING
2347         int did_match = 0;
2348 #endif
2349         if (prog->anchored_substr || prog->anchored_utf8) {
2350             if (!(utf8_target ? prog->anchored_utf8 : prog->anchored_substr))
2351                 utf8_target ? to_utf8_substr(prog) : to_byte_substr(prog);
2352             must = utf8_target ? prog->anchored_utf8 : prog->anchored_substr;
2353             back_max = back_min = prog->anchored_offset;
2354         } else {
2355             if (!(utf8_target ? prog->float_utf8 : prog->float_substr))
2356                 utf8_target ? to_utf8_substr(prog) : to_byte_substr(prog);
2357             must = utf8_target ? prog->float_utf8 : prog->float_substr;
2358             back_max = prog->float_max_offset;
2359             back_min = prog->float_min_offset;
2360         }
2361         
2362             
2363         if (must == &PL_sv_undef)
2364             /* could not downgrade utf8 check substring, so must fail */
2365             goto phooey;
2366
2367         if (back_min<0) {
2368             last = strend;
2369         } else {
2370             last = HOP3c(strend,        /* Cannot start after this */
2371                   -(I32)(CHR_SVLEN(must)
2372                          - (SvTAIL(must) != 0) + back_min), strbeg);
2373         }
2374         if (s > PL_bostr)
2375             last1 = HOPc(s, -1);
2376         else
2377             last1 = s - 1;      /* bogus */
2378
2379         /* XXXX check_substr already used to find "s", can optimize if
2380            check_substr==must. */
2381         scream_pos = -1;
2382         dontbother = end_shift;
2383         strend = HOPc(strend, -dontbother);
2384         while ( (s <= last) &&
2385                 (s = fbm_instr((unsigned char*)HOP3(s, back_min, (back_min<0 ? strbeg : strend)),
2386                                   (unsigned char*)strend, must,
2387                                   multiline ? FBMrf_MULTILINE : 0)) ) {
2388             DEBUG_EXECUTE_r( did_match = 1 );
2389             if (HOPc(s, -back_max) > last1) {
2390                 last1 = HOPc(s, -back_min);
2391                 s = HOPc(s, -back_max);
2392             }
2393             else {
2394                 char * const t = (last1 >= PL_bostr) ? HOPc(last1, 1) : last1 + 1;
2395
2396                 last1 = HOPc(s, -back_min);
2397                 s = t;
2398             }
2399             if (utf8_target) {
2400                 while (s <= last1) {
2401                     if (regtry(&reginfo, &s))
2402                         goto got_it;
2403                     s += UTF8SKIP(s);
2404                 }
2405             }
2406             else {
2407                 while (s <= last1) {
2408                     if (regtry(&reginfo, &s))
2409                         goto got_it;
2410                     s++;
2411                 }
2412             }
2413         }
2414         DEBUG_EXECUTE_r(if (!did_match) {
2415             RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
2416                 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
2417             PerlIO_printf(Perl_debug_log, "Did not find %s substr %s%s...\n",
2418                               ((must == prog->anchored_substr || must == prog->anchored_utf8)
2419                                ? "anchored" : "floating"),
2420                 quoted, RE_SV_TAIL(must));
2421         });                 
2422         goto phooey;
2423     }
2424     else if ( (c = progi->regstclass) ) {
2425         if (minlen) {
2426             const OPCODE op = OP(progi->regstclass);
2427             /* don't bother with what can't match */
2428             if (PL_regkind[op] != EXACT && op != CANY && PL_regkind[op] != TRIE)
2429                 strend = HOPc(strend, -(minlen - 1));
2430         }
2431         DEBUG_EXECUTE_r({
2432             SV * const prop = sv_newmortal();
2433             regprop(prog, prop, c);
2434             {
2435                 RE_PV_QUOTED_DECL(quoted,utf8_target,PERL_DEBUG_PAD_ZERO(1),
2436                     s,strend-s,60);
2437                 PerlIO_printf(Perl_debug_log,
2438                     "Matching stclass %.*s against %s (%d bytes)\n",
2439                     (int)SvCUR(prop), SvPVX_const(prop),
2440                      quoted, (int)(strend - s));
2441             }
2442         });
2443         if (find_byclass(prog, c, s, strend, &reginfo))
2444             goto got_it;
2445         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Contradicts stclass... [regexec_flags]\n"));
2446     }
2447     else {
2448         dontbother = 0;
2449         if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
2450             /* Trim the end. */
2451             char *last= NULL;
2452             SV* float_real;
2453             STRLEN len;
2454             const char *little;
2455
2456             if (!(utf8_target ? prog->float_utf8 : prog->float_substr))
2457                 utf8_target ? to_utf8_substr(prog) : to_byte_substr(prog);
2458             float_real = utf8_target ? prog->float_utf8 : prog->float_substr;
2459
2460             little = SvPV_const(float_real, len);
2461             if (SvTAIL(float_real)) {
2462                     /* This means that float_real contains an artificial \n on the end
2463                      * due to the presence of something like this: /foo$/
2464                      * where we can match both "foo" and "foo\n" at the end of the string.
2465                      * So we have to compare the end of the string first against the float_real
2466                      * without the \n and then against the full float_real with the string.
2467                      * We have to watch out for cases where the string might be smaller
2468                      * than the float_real or the float_real without the \n.
2469                      */
2470                     char *checkpos= strend - len;
2471                     DEBUG_OPTIMISE_r(
2472                         PerlIO_printf(Perl_debug_log,
2473                             "%sChecking for float_real.%s\n",
2474                             PL_colors[4], PL_colors[5]));
2475                     if (checkpos + 1 < strbeg) {
2476                         /* can't match, even if we remove the trailing \n string is too short to match */
2477                         DEBUG_EXECUTE_r(
2478                             PerlIO_printf(Perl_debug_log,
2479                                 "%sString shorter than required trailing substring, cannot match.%s\n",
2480                                 PL_colors[4], PL_colors[5]));
2481                         goto phooey;
2482                     } else if (memEQ(checkpos + 1, little, len - 1)) {
2483                         /* can match, the end of the string matches without the "\n" */
2484                         last = checkpos + 1;
2485                     } else if (checkpos < strbeg) {
2486                         /* cant match, string is too short when the "\n" is included */
2487                         DEBUG_EXECUTE_r(
2488                             PerlIO_printf(Perl_debug_log,
2489                                 "%sString does not contain required trailing substring, cannot match.%s\n",
2490                                 PL_colors[4], PL_colors[5]));
2491                         goto phooey;
2492                     } else if (!multiline) {
2493                         /* non multiline match, so compare with the "\n" at the end of the string */
2494                         if (memEQ(checkpos, little, len)) {
2495                             last= checkpos;
2496                         } else {
2497                             DEBUG_EXECUTE_r(
2498                                 PerlIO_printf(Perl_debug_log,
2499                                     "%sString does not contain required trailing substring, cannot match.%s\n",
2500                                     PL_colors[4], PL_colors[5]));
2501                             goto phooey;
2502                         }
2503                     } else {
2504                         /* multiline match, so we have to search for a place where the full string is located */
2505                         goto find_last;
2506                     }
2507             } else {
2508                   find_last:
2509                     if (len)
2510                         last = rninstr(s, strend, little, little + len);
2511                     else
2512                         last = strend;  /* matching "$" */
2513             }
2514             if (!last) {
2515                 /* at one point this block contained a comment which was probably
2516                  * incorrect, which said that this was a "should not happen" case.
2517                  * Even if it was true when it was written I am pretty sure it is
2518                  * not anymore, so I have removed the comment and replaced it with
2519                  * this one. Yves */
2520                 DEBUG_EXECUTE_r(
2521                     PerlIO_printf(Perl_debug_log,
2522                         "String does not contain required substring, cannot match.\n"
2523                     ));
2524                 goto phooey;
2525             }
2526             dontbother = strend - last + prog->float_min_offset;
2527         }
2528         if (minlen && (dontbother < minlen))
2529             dontbother = minlen - 1;
2530         strend -= dontbother;              /* this one's always in bytes! */
2531         /* We don't know much -- general case. */
2532         if (utf8_target) {
2533             for (;;) {
2534                 if (regtry(&reginfo, &s))
2535                     goto got_it;
2536                 if (s >= strend)
2537                     break;
2538                 s += UTF8SKIP(s);
2539             };
2540         }
2541         else {
2542             do {
2543                 if (regtry(&reginfo, &s))
2544                     goto got_it;
2545             } while (s++ < strend);
2546         }
2547     }
2548
2549     /* Failure. */
2550     goto phooey;
2551
2552 got_it:
2553     DEBUG_BUFFERS_r(
2554         if (swap)
2555             PerlIO_printf(Perl_debug_log,
2556                 "rex=0x%"UVxf" freeing offs: 0x%"UVxf"\n",
2557                 PTR2UV(prog),
2558                 PTR2UV(swap)
2559             );
2560     );
2561     Safefree(swap);
2562     RX_MATCH_TAINTED_set(rx, PL_reg_flags & RF_tainted);
2563
2564     if (PL_reg_state.re_state_eval_setup_done)
2565         restore_pos(aTHX_ prog);
2566     if (RXp_PAREN_NAMES(prog)) 
2567         (void)hv_iterinit(RXp_PAREN_NAMES(prog));
2568
2569     /* make sure $`, $&, $', and $digit will work later */
2570     if ( !(flags & REXEC_NOT_FIRST) ) {
2571         RX_MATCH_COPY_FREE(rx);
2572         if (flags & REXEC_COPY_STR) {
2573             const I32 i = PL_regeol - startpos + (stringarg - strbeg);
2574 #ifdef PERL_OLD_COPY_ON_WRITE
2575             if ((SvIsCOW(sv)
2576                  || (SvFLAGS(sv) & CAN_COW_MASK) == CAN_COW_FLAGS)) {
2577                 if (DEBUG_C_TEST) {
2578                     PerlIO_printf(Perl_debug_log,
2579                                   "Copy on write: regexp capture, type %d\n",
2580                                   (int) SvTYPE(sv));
2581                 }
2582                 prog->saved_copy = sv_setsv_cow(prog->saved_copy, sv);
2583                 prog->subbeg = (char *)SvPVX_const(prog->saved_copy);
2584                 assert (SvPOKp(prog->saved_copy));
2585             } else
2586 #endif
2587             {
2588                 RX_MATCH_COPIED_on(rx);
2589                 s = savepvn(strbeg, i);
2590                 prog->subbeg = s;
2591             }
2592             prog->sublen = i;
2593         }
2594         else {
2595             prog->subbeg = strbeg;
2596             prog->sublen = PL_regeol - strbeg;  /* strend may have been modified */
2597         }
2598     }
2599
2600     return 1;
2601
2602 phooey:
2603     DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch failed%s\n",
2604                           PL_colors[4], PL_colors[5]));
2605     if (PL_reg_state.re_state_eval_setup_done)
2606         restore_pos(aTHX_ prog);
2607     if (swap) {
2608         /* we failed :-( roll it back */
2609         DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
2610             "rex=0x%"UVxf" rolling back offs: freeing=0x%"UVxf" restoring=0x%"UVxf"\n",
2611             PTR2UV(prog),
2612             PTR2UV(prog->offs),
2613             PTR2UV(swap)
2614         ));
2615         Safefree(prog->offs);
2616         prog->offs = swap;
2617     }
2618
2619     return 0;
2620 }
2621
2622
2623 /* Set which rex is pointed to by PL_reg_state, handling ref counting.
2624  * Do inc before dec, in case old and new rex are the same */
2625 #define SET_reg_curpm(Re2) \
2626     if (PL_reg_state.re_state_eval_setup_done) {    \
2627         (void)ReREFCNT_inc(Re2);                    \
2628         ReREFCNT_dec(PM_GETRE(PL_reg_curpm));       \
2629         PM_SETRE((PL_reg_curpm), (Re2));            \
2630     }
2631
2632
2633 /*
2634  - regtry - try match at specific point
2635  */
2636 STATIC I32                      /* 0 failure, 1 success */
2637 S_regtry(pTHX_ regmatch_info *reginfo, char **startpos)
2638 {
2639     dVAR;
2640     CHECKPOINT lastcp;
2641     REGEXP *const rx = reginfo->prog;
2642     regexp *const prog = (struct regexp *)SvANY(rx);
2643     RXi_GET_DECL(prog,progi);
2644     GET_RE_DEBUG_FLAGS_DECL;
2645
2646     PERL_ARGS_ASSERT_REGTRY;
2647
2648     reginfo->cutpoint=NULL;
2649
2650     if ((prog->extflags & RXf_EVAL_SEEN)
2651         && !PL_reg_state.re_state_eval_setup_done)
2652     {
2653         MAGIC *mg;
2654
2655         PL_reg_state.re_state_eval_setup_done = TRUE;
2656         if (reginfo->sv) {
2657             /* Make $_ available to executed code. */
2658             if (reginfo->sv != DEFSV) {
2659                 SAVE_DEFSV;
2660                 DEFSV_set(reginfo->sv);
2661             }
2662         
2663             if (!(SvTYPE(reginfo->sv) >= SVt_PVMG && SvMAGIC(reginfo->sv)
2664                   && (mg = mg_find(reginfo->sv, PERL_MAGIC_regex_global)))) {
2665                 /* prepare for quick setting of pos */
2666 #ifdef PERL_OLD_COPY_ON_WRITE
2667                 if (SvIsCOW(reginfo->sv))
2668                     sv_force_normal_flags(reginfo->sv, 0);
2669 #endif
2670                 mg = sv_magicext(reginfo->sv, NULL, PERL_MAGIC_regex_global,
2671                                  &PL_vtbl_mglob, NULL, 0);
2672                 mg->mg_len = -1;
2673             }
2674             PL_reg_magic    = mg;
2675             PL_reg_oldpos   = mg->mg_len;
2676             SAVEDESTRUCTOR_X(restore_pos, prog);
2677         }
2678         if (!PL_reg_curpm) {
2679             Newxz(PL_reg_curpm, 1, PMOP);
2680 #ifdef USE_ITHREADS
2681             {
2682                 SV* const repointer = &PL_sv_undef;
2683                 /* this regexp is also owned by the new PL_reg_curpm, which
2684                    will try to free it.  */
2685                 av_push(PL_regex_padav, repointer);
2686                 PL_reg_curpm->op_pmoffset = av_len(PL_regex_padav);
2687                 PL_regex_pad = AvARRAY(PL_regex_padav);
2688             }
2689 #endif      
2690         }
2691         SET_reg_curpm(rx);
2692         PL_reg_oldcurpm = PL_curpm;
2693         PL_curpm = PL_reg_curpm;
2694         if (RXp_MATCH_COPIED(prog)) {
2695             /*  Here is a serious problem: we cannot rewrite subbeg,
2696                 since it may be needed if this match fails.  Thus
2697                 $` inside (?{}) could fail... */
2698             PL_reg_oldsaved = prog->subbeg;
2699             PL_reg_oldsavedlen = prog->sublen;
2700 #ifdef PERL_OLD_COPY_ON_WRITE
2701             PL_nrs = prog->saved_copy;
2702 #endif
2703             RXp_MATCH_COPIED_off(prog);
2704         }
2705         else
2706             PL_reg_oldsaved = NULL;
2707         prog->subbeg = PL_bostr;
2708         prog->sublen = PL_regeol - PL_bostr; /* strend may have been modified */
2709     }
2710 #ifdef DEBUGGING
2711     PL_reg_starttry = *startpos;
2712 #endif
2713     prog->offs[0].start = *startpos - PL_bostr;
2714     PL_reginput = *startpos;
2715     prog->lastparen = 0;
2716     prog->lastcloseparen = 0;
2717     PL_regsize = 0;
2718
2719     /* XXXX What this code is doing here?!!!  There should be no need
2720        to do this again and again, prog->lastparen should take care of
2721        this!  --ilya*/
2722
2723     /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
2724      * Actually, the code in regcppop() (which Ilya may be meaning by
2725      * prog->lastparen), is not needed at all by the test suite
2726      * (op/regexp, op/pat, op/split), but that code is needed otherwise
2727      * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
2728      * Meanwhile, this code *is* needed for the
2729      * above-mentioned test suite tests to succeed.  The common theme
2730      * on those tests seems to be returning null fields from matches.
2731      * --jhi updated by dapm */
2732 #if 1
2733     if (prog->nparens) {
2734         regexp_paren_pair *pp = prog->offs;
2735         I32 i;
2736         for (i = prog->nparens; i > (I32)prog->lastparen; i--) {
2737             ++pp;
2738             pp->start = -1;
2739             pp->end = -1;
2740         }
2741     }
2742 #endif
2743     REGCP_SET(lastcp);
2744     if (regmatch(reginfo, progi->program + 1)) {
2745         prog->offs[0].end = PL_reginput - PL_bostr;
2746         return 1;
2747     }
2748     if (reginfo->cutpoint)
2749         *startpos= reginfo->cutpoint;
2750     REGCP_UNWIND(lastcp);
2751     return 0;
2752 }
2753
2754
2755 #define sayYES goto yes
2756 #define sayNO goto no
2757 #define sayNO_SILENT goto no_silent
2758
2759 /* we dont use STMT_START/END here because it leads to 
2760    "unreachable code" warnings, which are bogus, but distracting. */
2761 #define CACHEsayNO \
2762     if (ST.cache_mask) \
2763        PL_reg_poscache[ST.cache_offset] |= ST.cache_mask; \
2764     sayNO
2765
2766 /* this is used to determine how far from the left messages like
2767    'failed...' are printed. It should be set such that messages 
2768    are inline with the regop output that created them.
2769 */
2770 #define REPORT_CODE_OFF 32
2771
2772
2773 #define CHRTEST_UNINIT -1001 /* c1/c2 haven't been calculated yet */
2774 #define CHRTEST_VOID   -1000 /* the c1/c2 "next char" test should be skipped */
2775
2776 #define SLAB_FIRST(s) (&(s)->states[0])
2777 #define SLAB_LAST(s)  (&(s)->states[PERL_REGMATCH_SLAB_SLOTS-1])
2778
2779 /* grab a new slab and return the first slot in it */
2780
2781 STATIC regmatch_state *
2782 S_push_slab(pTHX)
2783 {
2784 #if PERL_VERSION < 9 && !defined(PERL_CORE)
2785     dMY_CXT;
2786 #endif
2787     regmatch_slab *s = PL_regmatch_slab->next;
2788     if (!s) {
2789         Newx(s, 1, regmatch_slab);
2790         s->prev = PL_regmatch_slab;
2791         s->next = NULL;
2792         PL_regmatch_slab->next = s;
2793     }
2794     PL_regmatch_slab = s;
2795     return SLAB_FIRST(s);
2796 }
2797
2798
2799 /* push a new state then goto it */
2800
2801 #define PUSH_STATE_GOTO(state, node) \
2802     scan = node; \
2803     st->resume_state = state; \
2804     goto push_state;
2805
2806 /* push a new state with success backtracking, then goto it */
2807
2808 #define PUSH_YES_STATE_GOTO(state, node) \
2809     scan = node; \
2810     st->resume_state = state; \
2811     goto push_yes_state;
2812
2813
2814
2815 /*
2816
2817 regmatch() - main matching routine
2818
2819 This is basically one big switch statement in a loop. We execute an op,
2820 set 'next' to point the next op, and continue. If we come to a point which
2821 we may need to backtrack to on failure such as (A|B|C), we push a
2822 backtrack state onto the backtrack stack. On failure, we pop the top
2823 state, and re-enter the loop at the state indicated. If there are no more
2824 states to pop, we return failure.
2825
2826 Sometimes we also need to backtrack on success; for example /A+/, where
2827 after successfully matching one A, we need to go back and try to
2828 match another one; similarly for lookahead assertions: if the assertion
2829 completes successfully, we backtrack to the state just before the assertion
2830 and then carry on.  In these cases, the pushed state is marked as
2831 'backtrack on success too'. This marking is in fact done by a chain of
2832 pointers, each pointing to the previous 'yes' state. On success, we pop to
2833 the nearest yes state, discarding any intermediate failure-only states.
2834 Sometimes a yes state is pushed just to force some cleanup code to be
2835 called at the end of a successful match or submatch; e.g. (??{$re}) uses
2836 it to free the inner regex.
2837
2838 Note that failure backtracking rewinds the cursor position, while
2839 success backtracking leaves it alone.
2840
2841 A pattern is complete when the END op is executed, while a subpattern
2842 such as (?=foo) is complete when the SUCCESS op is executed. Both of these
2843 ops trigger the "pop to last yes state if any, otherwise return true"
2844 behaviour.
2845
2846 A common convention in this function is to use A and B to refer to the two
2847 subpatterns (or to the first nodes thereof) in patterns like /A*B/: so A is
2848 the subpattern to be matched possibly multiple times, while B is the entire
2849 rest of the pattern. Variable and state names reflect this convention.
2850
2851 The states in the main switch are the union of ops and failure/success of
2852 substates associated with with that op.  For example, IFMATCH is the op
2853 that does lookahead assertions /(?=A)B/ and so the IFMATCH state means
2854 'execute IFMATCH'; while IFMATCH_A is a state saying that we have just
2855 successfully matched A and IFMATCH_A_fail is a state saying that we have
2856 just failed to match A. Resume states always come in pairs. The backtrack
2857 state we push is marked as 'IFMATCH_A', but when that is popped, we resume
2858 at IFMATCH_A or IFMATCH_A_fail, depending on whether we are backtracking
2859 on success or failure.
2860
2861 The struct that holds a backtracking state is actually a big union, with
2862 one variant for each major type of op. The variable st points to the
2863 top-most backtrack struct. To make the code clearer, within each
2864 block of code we #define ST to alias the relevant union.
2865
2866 Here's a concrete example of a (vastly oversimplified) IFMATCH
2867 implementation:
2868
2869     switch (state) {
2870     ....
2871
2872 #define ST st->u.ifmatch
2873
2874     case IFMATCH: // we are executing the IFMATCH op, (?=A)B
2875         ST.foo = ...; // some state we wish to save
2876         ...
2877         // push a yes backtrack state with a resume value of
2878         // IFMATCH_A/IFMATCH_A_fail, then continue execution at the
2879         // first node of A:
2880         PUSH_YES_STATE_GOTO(IFMATCH_A, A);
2881         // NOTREACHED
2882
2883     case IFMATCH_A: // we have successfully executed A; now continue with B
2884         next = B;
2885         bar = ST.foo; // do something with the preserved value
2886         break;
2887
2888     case IFMATCH_A_fail: // A failed, so the assertion failed
2889         ...;   // do some housekeeping, then ...
2890         sayNO; // propagate the failure
2891
2892 #undef ST
2893
2894     ...
2895     }
2896
2897 For any old-timers reading this who are familiar with the old recursive
2898 approach, the code above is equivalent to:
2899
2900     case IFMATCH: // we are executing the IFMATCH op, (?=A)B
2901     {
2902         int foo = ...
2903         ...
2904         if (regmatch(A)) {
2905             next = B;
2906             bar = foo;
2907             break;
2908         }
2909         ...;   // do some housekeeping, then ...
2910         sayNO; // propagate the failure
2911     }
2912
2913 The topmost backtrack state, pointed to by st, is usually free. If you
2914 want to claim it, populate any ST.foo fields in it with values you wish to
2915 save, then do one of
2916
2917         PUSH_STATE_GOTO(resume_state, node);
2918         PUSH_YES_STATE_GOTO(resume_state, node);
2919
2920 which sets that backtrack state's resume value to 'resume_state', pushes a
2921 new free entry to the top of the backtrack stack, then goes to 'node'.
2922 On backtracking, the free slot is popped, and the saved state becomes the
2923 new free state. An ST.foo field in this new top state can be temporarily
2924 accessed to retrieve values, but once the main loop is re-entered, it
2925 becomes available for reuse.
2926
2927 Note that the depth of the backtrack stack constantly increases during the
2928 left-to-right execution of the pattern, rather than going up and down with
2929 the pattern nesting. For example the stack is at its maximum at Z at the
2930 end of the pattern, rather than at X in the following:
2931
2932     /(((X)+)+)+....(Y)+....Z/
2933
2934 The only exceptions to this are lookahead/behind assertions and the cut,
2935 (?>A), which pop all the backtrack states associated with A before
2936 continuing.
2937  
2938 Backtrack state structs are allocated in slabs of about 4K in size.
2939 PL_regmatch_state and st always point to the currently active state,
2940 and PL_regmatch_slab points to the slab currently containing
2941 PL_regmatch_state.  The first time regmatch() is called, the first slab is
2942 allocated, and is never freed until interpreter destruction. When the slab
2943 is full, a new one is allocated and chained to the end. At exit from
2944 regmatch(), slabs allocated since entry are freed.
2945
2946 */
2947  
2948
2949 #define DEBUG_STATE_pp(pp)                                  \
2950     DEBUG_STATE_r({                                         \
2951         DUMP_EXEC_POS(locinput, scan, utf8_target);                 \
2952         PerlIO_printf(Perl_debug_log,                       \
2953             "    %*s"pp" %s%s%s%s%s\n",                     \
2954             depth*2, "",                                    \
2955             PL_reg_name[st->resume_state],                     \
2956             ((st==yes_state||st==mark_state) ? "[" : ""),   \
2957             ((st==yes_state) ? "Y" : ""),                   \
2958             ((st==mark_state) ? "M" : ""),                  \
2959             ((st==yes_state||st==mark_state) ? "]" : "")    \
2960         );                                                  \
2961     });
2962
2963
2964 #define REG_NODE_NUM(x) ((x) ? (int)((x)-prog) : -1)
2965
2966 #ifdef DEBUGGING
2967
2968 STATIC void
2969 S_debug_start_match(pTHX_ const REGEXP *prog, const bool utf8_target,
2970     const char *start, const char *end, const char *blurb)
2971 {
2972     const bool utf8_pat = RX_UTF8(prog) ? 1 : 0;
2973
2974     PERL_ARGS_ASSERT_DEBUG_START_MATCH;
2975
2976     if (!PL_colorset)   
2977             reginitcolors();    
2978     {
2979         RE_PV_QUOTED_DECL(s0, utf8_pat, PERL_DEBUG_PAD_ZERO(0), 
2980             RX_PRECOMP_const(prog), RX_PRELEN(prog), 60);   
2981         
2982         RE_PV_QUOTED_DECL(s1, utf8_target, PERL_DEBUG_PAD_ZERO(1),
2983             start, end - start, 60); 
2984         
2985         PerlIO_printf(Perl_debug_log, 
2986             "%s%s REx%s %s against %s\n", 
2987                        PL_colors[4], blurb, PL_colors[5], s0, s1); 
2988         
2989         if (utf8_target||utf8_pat)
2990             PerlIO_printf(Perl_debug_log, "UTF-8 %s%s%s...\n",
2991                 utf8_pat ? "pattern" : "",
2992                 utf8_pat && utf8_target ? " and " : "",
2993                 utf8_target ? "string" : ""
2994             ); 
2995     }
2996 }
2997
2998 STATIC void
2999 S_dump_exec_pos(pTHX_ const char *locinput, 
3000                       const regnode *scan, 
3001                       const char *loc_regeol, 
3002                       const char *loc_bostr, 
3003                       const char *loc_reg_starttry,
3004                       const bool utf8_target)
3005 {
3006     const int docolor = *PL_colors[0] || *PL_colors[2] || *PL_colors[4];
3007     const int taill = (docolor ? 10 : 7); /* 3 chars for "> <" */
3008     int l = (loc_regeol - locinput) > taill ? taill : (loc_regeol - locinput);
3009     /* The part of the string before starttry has one color
3010        (pref0_len chars), between starttry and current
3011        position another one (pref_len - pref0_len chars),
3012        after the current position the third one.
3013        We assume that pref0_len <= pref_len, otherwise we
3014        decrease pref0_len.  */
3015     int pref_len = (locinput - loc_bostr) > (5 + taill) - l
3016         ? (5 + taill) - l : locinput - loc_bostr;
3017     int pref0_len;
3018
3019     PERL_ARGS_ASSERT_DUMP_EXEC_POS;
3020
3021     while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput - pref_len)))
3022         pref_len++;
3023     pref0_len = pref_len  - (locinput - loc_reg_starttry);
3024     if (l + pref_len < (5 + taill) && l < loc_regeol - locinput)
3025         l = ( loc_regeol - locinput > (5 + taill) - pref_len
3026               ? (5 + taill) - pref_len : loc_regeol - locinput);
3027     while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput + l)))
3028         l--;
3029     if (pref0_len < 0)
3030         pref0_len = 0;
3031     if (pref0_len > pref_len)
3032         pref0_len = pref_len;
3033     {
3034         const int is_uni = (utf8_target && OP(scan) != CANY) ? 1 : 0;
3035
3036         RE_PV_COLOR_DECL(s0,len0,is_uni,PERL_DEBUG_PAD(0),
3037             (locinput - pref_len),pref0_len, 60, 4, 5);
3038         
3039         RE_PV_COLOR_DECL(s1,len1,is_uni,PERL_DEBUG_PAD(1),
3040                     (locinput - pref_len + pref0_len),
3041                     pref_len - pref0_len, 60, 2, 3);
3042         
3043         RE_PV_COLOR_DECL(s2,len2,is_uni,PERL_DEBUG_PAD(2),
3044                     locinput, loc_regeol - locinput, 10, 0, 1);
3045
3046         const STRLEN tlen=len0+len1+len2;
3047         PerlIO_printf(Perl_debug_log,
3048                     "%4"IVdf" <%.*s%.*s%s%.*s>%*s|",
3049                     (IV)(locinput - loc_bostr),
3050                     len0, s0,
3051                     len1, s1,
3052                     (docolor ? "" : "> <"),
3053                     len2, s2,
3054                     (int)(tlen > 19 ? 0 :  19 - tlen),
3055                     "");
3056     }
3057 }
3058
3059 #endif
3060
3061 /* reg_check_named_buff_matched()
3062  * Checks to see if a named buffer has matched. The data array of 
3063  * buffer numbers corresponding to the buffer is expected to reside
3064  * in the regexp->data->data array in the slot stored in the ARG() of
3065  * node involved. Note that this routine doesn't actually care about the
3066  * name, that information is not preserved from compilation to execution.
3067  * Returns the index of the leftmost defined buffer with the given name
3068  * or 0 if non of the buffers matched.
3069  */
3070 STATIC I32
3071 S_reg_check_named_buff_matched(pTHX_ const regexp *rex, const regnode *scan)
3072 {
3073     I32 n;
3074     RXi_GET_DECL(rex,rexi);
3075     SV *sv_dat= MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
3076     I32 *nums=(I32*)SvPVX(sv_dat);
3077
3078     PERL_ARGS_ASSERT_REG_CHECK_NAMED_BUFF_MATCHED;
3079
3080     for ( n=0; n<SvIVX(sv_dat); n++ ) {
3081         if ((I32)rex->lastparen >= nums[n] &&
3082             rex->offs[nums[n]].end != -1)
3083         {
3084             return nums[n];
3085         }
3086     }
3087     return 0;
3088 }
3089
3090
3091 /* free all slabs above current one  - called during LEAVE_SCOPE */
3092
3093 STATIC void
3094 S_clear_backtrack_stack(pTHX_ void *p)
3095 {
3096     regmatch_slab *s = PL_regmatch_slab->next;
3097     PERL_UNUSED_ARG(p);
3098
3099     if (!s)
3100         return;
3101     PL_regmatch_slab->next = NULL;
3102     while (s) {
3103         regmatch_slab * const osl = s;
3104         s = s->next;
3105         Safefree(osl);
3106     }
3107 }
3108
3109
3110 STATIC I32                      /* 0 failure, 1 success */
3111 S_regmatch(pTHX_ regmatch_info *reginfo, regnode *prog)
3112 {
3113 #if PERL_VERSION < 9 && !defined(PERL_CORE)
3114     dMY_CXT;
3115 #endif
3116     dVAR;
3117     const bool utf8_target = PL_reg_match_utf8;
3118     const U32 uniflags = UTF8_ALLOW_DEFAULT;
3119     REGEXP *rex_sv = reginfo->prog;
3120     regexp *rex = (struct regexp *)SvANY(rex_sv);
3121     RXi_GET_DECL(rex,rexi);
3122     I32 oldsave;
3123     /* the current state. This is a cached copy of PL_regmatch_state */
3124     regmatch_state *st;
3125     /* cache heavy used fields of st in registers */
3126     regnode *scan;
3127     regnode *next;
3128     U32 n = 0;  /* general value; init to avoid compiler warning */
3129     I32 ln = 0; /* len or last;  init to avoid compiler warning */
3130     char *locinput = PL_reginput;
3131     I32 nextchr;   /* is always set to UCHARAT(locinput) */
3132
3133     bool result = 0;        /* return value of S_regmatch */
3134     int depth = 0;          /* depth of backtrack stack */
3135     U32 nochange_depth = 0; /* depth of GOSUB recursion with nochange */
3136     const U32 max_nochange_depth =
3137         (3 * rex->nparens > MAX_RECURSE_EVAL_NOCHANGE_DEPTH) ?
3138         3 * rex->nparens : MAX_RECURSE_EVAL_NOCHANGE_DEPTH;
3139     regmatch_state *yes_state = NULL; /* state to pop to on success of
3140                                                             subpattern */
3141     /* mark_state piggy backs on the yes_state logic so that when we unwind 
3142        the stack on success we can update the mark_state as we go */
3143     regmatch_state *mark_state = NULL; /* last mark state we have seen */
3144     regmatch_state *cur_eval = NULL; /* most recent EVAL_AB state */
3145     struct regmatch_state  *cur_curlyx = NULL; /* most recent curlyx */
3146     U32 state_num;
3147     bool no_final = 0;      /* prevent failure from backtracking? */
3148     bool do_cutgroup = 0;   /* no_final only until next branch/trie entry */
3149     char *startpoint = PL_reginput;
3150     SV *popmark = NULL;     /* are we looking for a mark? */
3151     SV *sv_commit = NULL;   /* last mark name seen in failure */
3152     SV *sv_yes_mark = NULL; /* last mark name we have seen 
3153                                during a successful match */
3154     U32 lastopen = 0;       /* last open we saw */
3155     bool has_cutgroup = RX_HAS_CUTGROUP(rex) ? 1 : 0;   
3156     SV* const oreplsv = GvSV(PL_replgv);
3157     /* these three flags are set by various ops to signal information to
3158      * the very next op. They have a useful lifetime of exactly one loop
3159      * iteration, and are not preserved or restored by state pushes/pops
3160      */
3161     bool sw = 0;            /* the condition value in (?(cond)a|b) */
3162     bool minmod = 0;        /* the next "{n,m}" is a "{n,m}?" */
3163     int logical = 0;        /* the following EVAL is:
3164                                 0: (?{...})
3165                                 1: (?(?{...})X|Y)
3166                                 2: (??{...})
3167                                or the following IFMATCH/UNLESSM is:
3168                                 false: plain (?=foo)
3169                                 true:  used as a condition: (?(?=foo))
3170                             */
3171     PAD* last_pad = NULL;
3172     dMULTICALL;
3173     I32 gimme = G_SCALAR;
3174     CV *caller_cv = NULL;       /* who called us */
3175     CV *last_pushed_cv = NULL;  /* most recently called (?{}) CV */
3176     CHECKPOINT runops_cp;       /* savestack position before executing EVAL */
3177
3178 #ifdef DEBUGGING
3179     GET_RE_DEBUG_FLAGS_DECL;
3180 #endif
3181
3182     /* shut up 'may be used uninitialized' compiler warnings for dMULTICALL */
3183     multicall_oldcatch = 0;
3184     multicall_cv = NULL;
3185     cx = NULL;
3186     PERL_UNUSED_VAR(multicall_cop);
3187     PERL_UNUSED_VAR(newsp);
3188
3189
3190     PERL_ARGS_ASSERT_REGMATCH;
3191
3192     DEBUG_OPTIMISE_r( DEBUG_EXECUTE_r({
3193             PerlIO_printf(Perl_debug_log,"regmatch start\n");
3194     }));
3195     /* on first ever call to regmatch, allocate first slab */
3196     if (!PL_regmatch_slab) {
3197         Newx(PL_regmatch_slab, 1, regmatch_slab);
3198         PL_regmatch_slab->prev = NULL;
3199         PL_regmatch_slab->next = NULL;
3200         PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
3201     }
3202
3203     oldsave = PL_savestack_ix;
3204     SAVEDESTRUCTOR_X(S_clear_backtrack_stack, NULL);
3205     SAVEVPTR(PL_regmatch_slab);
3206     SAVEVPTR(PL_regmatch_state);
3207
3208     /* grab next free state slot */
3209     st = ++PL_regmatch_state;
3210     if (st >  SLAB_LAST(PL_regmatch_slab))
3211         st = PL_regmatch_state = S_push_slab(aTHX);
3212
3213     /* Note that nextchr is a byte even in UTF */
3214     nextchr = UCHARAT(locinput);
3215     scan = prog;
3216     while (scan != NULL) {
3217
3218         DEBUG_EXECUTE_r( {
3219             SV * const prop = sv_newmortal();
3220             regnode *rnext=regnext(scan);
3221             DUMP_EXEC_POS( locinput, scan, utf8_target );
3222             regprop(rex, prop, scan);
3223             
3224             PerlIO_printf(Perl_debug_log,
3225                     "%3"IVdf":%*s%s(%"IVdf")\n",
3226                     (IV)(scan - rexi->program), depth*2, "",
3227                     SvPVX_const(prop),
3228                     (PL_regkind[OP(scan)] == END || !rnext) ? 
3229                         0 : (IV)(rnext - rexi->program));
3230         });
3231
3232         next = scan + NEXT_OFF(scan);
3233         if (next == scan)
3234             next = NULL;
3235         state_num = OP(scan);
3236
3237         REH_CALL_EXEC_NODE_HOOK(rex, scan, reginfo, st);
3238       reenter_switch:
3239
3240         switch (state_num) {
3241         case BOL:
3242             if (locinput == PL_bostr)
3243             {
3244                 /* reginfo->till = reginfo->bol; */
3245                 break;
3246             }
3247             sayNO;
3248         case MBOL:
3249             if (locinput == PL_bostr ||
3250                 ((nextchr || locinput < PL_regeol) && locinput[-1] == '\n'))
3251             {
3252                 break;
3253             }
3254             sayNO;
3255         case SBOL:
3256             if (locinput == PL_bostr)
3257                 break;
3258             sayNO;
3259         case GPOS:
3260             if (locinput == reginfo->ganch)
3261                 break;
3262             sayNO;
3263
3264         case KEEPS:
3265             /* update the startpoint */
3266             st->u.keeper.val = rex->offs[0].start;
3267             PL_reginput = locinput;
3268             rex->offs[0].start = locinput - PL_bostr;
3269             PUSH_STATE_GOTO(KEEPS_next, next);
3270             /*NOT-REACHED*/
3271         case KEEPS_next_fail:
3272             /* rollback the start point change */
3273             rex->offs[0].start = st->u.keeper.val;
3274             sayNO_SILENT;
3275             /*NOT-REACHED*/
3276         case EOL:
3277                 goto seol;
3278         case MEOL:
3279             if ((nextchr || locinput < PL_regeol) && nextchr != '\n')
3280                 sayNO;
3281             break;
3282         case SEOL:
3283           seol:
3284             if ((nextchr || locinput < PL_regeol) && nextchr != '\n')
3285                 sayNO;
3286             if (PL_regeol - locinput > 1)
3287                 sayNO;
3288             break;
3289         case EOS:
3290             if (PL_regeol != locinput)
3291                 sayNO;
3292             break;
3293         case SANY:
3294             if (!nextchr && locinput >= PL_regeol)
3295                 sayNO;
3296             if (utf8_target) {
3297                 locinput += PL_utf8skip[nextchr];
3298                 if (locinput > PL_regeol)
3299                     sayNO;
3300                 nextchr = UCHARAT(locinput);
3301             }
3302             else
3303                 nextchr = UCHARAT(++locinput);
3304             break;
3305         case CANY:
3306             if (!nextchr && locinput >= PL_regeol)
3307                 sayNO;
3308             nextchr = UCHARAT(++locinput);
3309             break;
3310         case REG_ANY:
3311             if ((!nextchr && locinput >= PL_regeol) || nextchr == '\n')
3312                 sayNO;
3313             if (utf8_target) {
3314                 locinput += PL_utf8skip[nextchr];
3315                 if (locinput > PL_regeol)
3316                     sayNO;
3317                 nextchr = UCHARAT(locinput);
3318             }
3319             else
3320                 nextchr = UCHARAT(++locinput);
3321             break;
3322
3323 #undef  ST
3324 #define ST st->u.trie
3325         case TRIEC:
3326             /* In this case the charclass data is available inline so
3327                we can fail fast without a lot of extra overhead. 
3328              */
3329             if(!ANYOF_BITMAP_TEST(scan, *locinput)) {
3330                 DEBUG_EXECUTE_r(
3331                     PerlIO_printf(Perl_debug_log,
3332                               "%*s  %sfailed to match trie start class...%s\n",
3333                               REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
3334                 );
3335                 sayNO_SILENT;
3336                 assert(0); /* NOTREACHED */
3337             }
3338             /* FALL THROUGH */
3339         case TRIE:
3340             /* the basic plan of execution of the trie is:
3341              * At the beginning, run though all the states, and
3342              * find the longest-matching word. Also remember the position
3343              * of the shortest matching word. For example, this pattern:
3344              *    1  2 3 4    5
3345              *    ab|a|x|abcd|abc
3346              * when matched against the string "abcde", will generate
3347              * accept states for all words except 3, with the longest
3348              * matching word being 4, and the shortest being 1 (with
3349              * the position being after char 1 of the string).
3350              *
3351              * Then for each matching word, in word order (i.e. 1,2,4,5),
3352              * we run the remainder of the pattern; on each try setting
3353              * the current position to the character following the word,
3354              * returning to try the next word on failure.
3355              *
3356              * We avoid having to build a list of words at runtime by
3357              * using a compile-time structure, wordinfo[].prev, which
3358              * gives, for each word, the previous accepting word (if any).
3359              * In the case above it would contain the mappings 1->2, 2->0,
3360              * 3->0, 4->5, 5->1.  We can use this table to generate, from
3361              * the longest word (4 above), a list of all words, by
3362              * following the list of prev pointers; this gives us the
3363              * unordered list 4,5,1,2. Then given the current word we have
3364              * just tried, we can go through the list and find the
3365              * next-biggest word to try (so if we just failed on word 2,
3366              * the next in the list is 4).
3367              *
3368              * Since at runtime we don't record the matching position in
3369              * the string for each word, we have to work that out for
3370              * each word we're about to process. The wordinfo table holds
3371              * the character length of each word; given that we recorded
3372              * at the start: the position of the shortest word and its
3373              * length in chars, we just need to move the pointer the
3374              * difference between the two char lengths. Depending on
3375              * Unicode status and folding, that's cheap or expensive.
3376              *
3377              * This algorithm is optimised for the case where are only a
3378              * small number of accept states, i.e. 0,1, or maybe 2.
3379              * With lots of accepts states, and having to try all of them,
3380              * it becomes quadratic on number of accept states to find all
3381              * the next words.
3382              */
3383
3384             {
3385                 /* what type of TRIE am I? (utf8 makes this contextual) */
3386                 DECL_TRIE_TYPE(scan);
3387
3388                 /* what trie are we using right now */
3389                 reg_trie_data * const trie
3390                     = (reg_trie_data*)rexi->data->data[ ARG( scan ) ];
3391                 HV * widecharmap = MUTABLE_HV(rexi->data->data[ ARG( scan ) + 1 ]);
3392                 U32 state = trie->startstate;
3393
3394                 if (trie->bitmap && !TRIE_BITMAP_TEST(trie,*locinput) ) {
3395                     if (trie->states[ state ].wordnum) {
3396                          DEBUG_EXECUTE_r(
3397                             PerlIO_printf(Perl_debug_log,
3398                                           "%*s  %smatched empty string...%s\n",
3399                                           REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
3400                         );
3401                         if (!trie->jump)
3402                             break;
3403                     } else {
3404                         DEBUG_EXECUTE_r(
3405                             PerlIO_printf(Perl_debug_log,
3406                                           "%*s  %sfailed to match trie start class...%s\n",
3407                                           REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
3408                         );
3409                         sayNO_SILENT;
3410                    }
3411                 }
3412
3413             { 
3414                 U8 *uc = ( U8* )locinput;
3415
3416                 STRLEN len = 0;
3417                 STRLEN foldlen = 0;
3418                 U8 *uscan = (U8*)NULL;
3419                 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
3420                 U32 charcount = 0; /* how many input chars we have matched */
3421                 U32 accepted = 0; /* have we seen any accepting states? */
3422
3423                 ST.jump = trie->jump;
3424                 ST.me = scan;
3425                 ST.firstpos = NULL;
3426                 ST.longfold = FALSE; /* char longer if folded => it's harder */
3427                 ST.nextword = 0;
3428
3429                 /* fully traverse the TRIE; note the position of the
3430                    shortest accept state and the wordnum of the longest
3431                    accept state */
3432
3433                 while ( state && uc <= (U8*)PL_regeol ) {
3434                     U32 base = trie->states[ state ].trans.base;
3435                     UV uvc = 0;
3436                     U16 charid = 0;
3437                     U16 wordnum;
3438                     wordnum = trie->states[ state ].wordnum;
3439
3440                     if (wordnum) { /* it's an accept state */
3441                         if (!accepted) {
3442                             accepted = 1;
3443                             /* record first match position */
3444                             if (ST.longfold) {
3445                                 ST.firstpos = (U8*)locinput;
3446                                 ST.firstchars = 0;
3447                             }
3448                             else {
3449                                 ST.firstpos = uc;
3450                                 ST.firstchars = charcount;
3451                             }
3452                         }
3453                         if (!ST.nextword || wordnum < ST.nextword)
3454                             ST.nextword = wordnum;
3455                         ST.topword = wordnum;
3456                     }
3457
3458                     DEBUG_TRIE_EXECUTE_r({
3459                                 DUMP_EXEC_POS( (char *)uc, scan, utf8_target );
3460                                 PerlIO_printf( Perl_debug_log,
3461                                     "%*s  %sState: %4"UVxf" Accepted: %c ",
3462                                     2+depth * 2, "", PL_colors[4],
3463                                     (UV)state, (accepted ? 'Y' : 'N'));
3464                     });
3465
3466                     /* read a char and goto next state */
3467                     if ( base ) {
3468                         I32 offset;
3469                         REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
3470                                              uscan, len, uvc, charid, foldlen,
3471                                              foldbuf, uniflags);
3472                         charcount++;
3473                         if (foldlen>0)
3474                             ST.longfold = TRUE;
3475                         if (charid &&
3476                              ( ((offset =
3477                               base + charid - 1 - trie->uniquecharcount)) >= 0)
3478
3479                              && ((U32)offset < trie->lasttrans)
3480                              && trie->trans[offset].check == state)
3481                         {
3482                             state = trie->trans[offset].next;
3483                         }
3484                         else {
3485                             state = 0;
3486                         }
3487                         uc += len;
3488
3489                     }
3490                     else {
3491                         state = 0;
3492                     }
3493                     DEBUG_TRIE_EXECUTE_r(
3494                         PerlIO_printf( Perl_debug_log,
3495                             "Charid:%3x CP:%4"UVxf" After State: %4"UVxf"%s\n",
3496                             charid, uvc, (UV)state, PL_colors[5] );
3497                     );
3498                 }
3499                 if (!accepted)
3500                    sayNO;
3501
3502                 /* calculate total number of accept states */
3503                 {
3504                     U16 w = ST.topword;
3505                     accepted = 0;
3506                     while (w) {
3507                         w = trie->wordinfo[w].prev;
3508                         accepted++;
3509                     }
3510                     ST.accepted = accepted;
3511                 }
3512
3513                 DEBUG_EXECUTE_r(
3514                     PerlIO_printf( Perl_debug_log,
3515                         "%*s  %sgot %"IVdf" possible matches%s\n",
3516                         REPORT_CODE_OFF + depth * 2, "",
3517                         PL_colors[4], (IV)ST.accepted, PL_colors[5] );
3518                 );
3519                 goto trie_first_try; /* jump into the fail handler */
3520             }}
3521             assert(0); /* NOTREACHED */
3522
3523         case TRIE_next_fail: /* we failed - try next alternative */
3524             if ( ST.jump) {
3525                 REGCP_UNWIND(ST.cp);
3526                 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
3527             }
3528             if (!--ST.accepted) {
3529                 DEBUG_EXECUTE_r({
3530                     PerlIO_printf( Perl_debug_log,
3531                         "%*s  %sTRIE failed...%s\n",
3532                         REPORT_CODE_OFF+depth*2, "", 
3533                         PL_colors[4],
3534                         PL_colors[5] );
3535                 });
3536                 sayNO_SILENT;
3537             }
3538             {
3539                 /* Find next-highest word to process.  Note that this code
3540                  * is O(N^2) per trie run (O(N) per branch), so keep tight */
3541                 U16 min = 0;
3542                 U16 word;
3543                 U16 const nextword = ST.nextword;
3544                 reg_trie_wordinfo * const wordinfo
3545                     = ((reg_trie_data*)rexi->data->data[ARG(ST.me)])->wordinfo;
3546                 for (word=ST.topword; word; word=wordinfo[word].prev) {
3547                     if (word > nextword && (!min || word < min))
3548                         min = word;
3549                 }
3550                 ST.nextword = min;
3551             }
3552
3553           trie_first_try:
3554             if (do_cutgroup) {
3555                 do_cutgroup = 0;
3556                 no_final = 0;
3557             }
3558
3559             if ( ST.jump) {
3560                 ST.lastparen = rex->lastparen;
3561                 ST.lastcloseparen = rex->lastcloseparen;
3562                 REGCP_SET(ST.cp);
3563             }
3564
3565             /* find start char of end of current word */
3566             {
3567                 U32 chars; /* how many chars to skip */
3568                 U8 *uc = ST.firstpos;
3569                 reg_trie_data * const trie
3570                     = (reg_trie_data*)rexi->data->data[ARG(ST.me)];
3571
3572                 assert((trie->wordinfo[ST.nextword].len - trie->prefixlen)
3573                             >=  ST.firstchars);
3574                 chars = (trie->wordinfo[ST.nextword].len - trie->prefixlen)
3575                             - ST.firstchars;
3576
3577                 if (ST.longfold) {
3578                     /* the hard option - fold each char in turn and find
3579                      * its folded length (which may be different */
3580                     U8 foldbuf[UTF8_MAXBYTES_CASE + 1];
3581                     STRLEN foldlen;
3582                     STRLEN len;
3583                     UV uvc;
3584                     U8 *uscan;
3585
3586                     while (chars) {
3587                         if (utf8_target) {
3588                             uvc = utf8n_to_uvuni((U8*)uc, UTF8_MAXLEN, &len,
3589                                                     uniflags);
3590                             uc += len;
3591                         }
3592                         else {
3593                             uvc = *uc;
3594                             uc++;
3595                         }
3596                         uvc = to_uni_fold(uvc, foldbuf, &foldlen);
3597                         uscan = foldbuf;
3598                         while (foldlen) {
3599                             if (!--chars)
3600                                 break;
3601                             uvc = utf8n_to_uvuni(uscan, UTF8_MAXLEN, &len,
3602                                             uniflags);
3603                             uscan += len;
3604                             foldlen -= len;
3605                         }
3606                     }
3607                 }
3608                 else {
3609                     if (utf8_target)
3610                         while (chars--)
3611                             uc += UTF8SKIP(uc);
3612                     else
3613                         uc += chars;
3614                 }
3615                 PL_reginput = (char *)uc;
3616             }
3617
3618             scan = ST.me + ((ST.jump && ST.jump[ST.nextword])
3619                             ? ST.jump[ST.nextword]
3620                             : NEXT_OFF(ST.me));
3621
3622             DEBUG_EXECUTE_r({
3623                 PerlIO_printf( Perl_debug_log,
3624                     "%*s  %sTRIE matched word #%d, continuing%s\n",
3625                     REPORT_CODE_OFF+depth*2, "", 
3626                     PL_colors[4],
3627                     ST.nextword,
3628                     PL_colors[5]
3629                     );
3630             });
3631
3632             if (ST.accepted > 1 || has_cutgroup) {
3633                 PUSH_STATE_GOTO(TRIE_next, scan);
3634                 assert(0); /* NOTREACHED */
3635             }
3636             /* only one choice left - just continue */
3637             DEBUG_EXECUTE_r({
3638                 AV *const trie_words
3639                     = MUTABLE_AV(rexi->data->data[ARG(ST.me)+TRIE_WORDS_OFFSET]);
3640                 SV ** const tmp = av_fetch( trie_words,
3641                     ST.nextword-1, 0 );
3642                 SV *sv= tmp ? sv_newmortal() : NULL;
3643
3644                 PerlIO_printf( Perl_debug_log,
3645                     "%*s  %sonly one match left, short-circuiting: #%d <%s>%s\n",
3646                     REPORT_CODE_OFF+depth*2, "", PL_colors[4],
3647                     ST.nextword,
3648                     tmp ? pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 0,
3649                             PL_colors[0], PL_colors[1],
3650                             (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)|PERL_PV_ESCAPE_NONASCII
3651                         ) 
3652                     : "not compiled under -Dr",
3653                     PL_colors[5] );
3654             });
3655
3656             locinput = PL_reginput;
3657             nextchr = UCHARAT(locinput);
3658             continue; /* execute rest of RE */
3659             assert(0); /* NOTREACHED */
3660 #undef  ST
3661
3662         case EXACT: {
3663             char *s = STRING(scan);
3664             ln = STR_LEN(scan);
3665             if (utf8_target != UTF_PATTERN) {
3666                 /* The target and the pattern have differing utf8ness. */
3667                 char *l = locinput;
3668                 const char * const e = s + ln;
3669
3670                 if (utf8_target) {
3671                     /* The target is utf8, the pattern is not utf8. */
3672                     while (s < e) {
3673                         STRLEN ulen;
3674                         if (l >= PL_regeol)
3675                              sayNO;
3676                         if (NATIVE_TO_UNI(*(U8*)s) !=
3677                             utf8n_to_uvuni((U8*)l, UTF8_MAXBYTES, &ulen,
3678                                             uniflags))
3679                              sayNO;
3680                         l += ulen;
3681                         s ++;
3682                     }
3683                 }
3684                 else {
3685                     /* The target is not utf8, the pattern is utf8. */
3686                     while (s < e) {
3687                         STRLEN ulen;
3688                         if (l >= PL_regeol)
3689                             sayNO;
3690                         if (NATIVE_TO_UNI(*((U8*)l)) !=
3691                             utf8n_to_uvuni((U8*)s, UTF8_MAXBYTES, &ulen,
3692                                            uniflags))
3693                             sayNO;
3694                         s += ulen;
3695                         l ++;
3696                     }
3697                 }
3698                 locinput = l;
3699                 nextchr = UCHARAT(locinput);
3700                 break;
3701             }
3702             /* The target and the pattern have the same utf8ness. */
3703             /* Inline the first character, for speed. */
3704             if (UCHARAT(s) != nextchr)
3705                 sayNO;
3706             if (PL_regeol - locinput < ln)
3707                 sayNO;
3708             if (ln > 1 && memNE(s, locinput, ln))
3709                 sayNO;
3710             locinput += ln;
3711             nextchr = UCHARAT(locinput);
3712             break;
3713             }
3714         case EXACTFL: {
3715             re_fold_t folder;
3716             const U8 * fold_array;
3717             const char * s;
3718             U32 fold_utf8_flags;
3719
3720             PL_reg_flags |= RF_tainted;
3721             folder = foldEQ_locale;
3722             fold_array = PL_fold_locale;
3723             fold_utf8_flags = FOLDEQ_UTF8_LOCALE;
3724             goto do_exactf;
3725
3726         case EXACTFU_SS:
3727         case EXACTFU_TRICKYFOLD:
3728         case EXACTFU:
3729             folder = foldEQ_latin1;
3730             fold_array = PL_fold_latin1;
3731             fold_utf8_flags = (UTF_PATTERN) ? FOLDEQ_S1_ALREADY_FOLDED : 0;
3732             goto do_exactf;
3733
3734         case EXACTFA:
3735             folder = foldEQ_latin1;
3736             fold_array = PL_fold_latin1;
3737             fold_utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
3738             goto do_exactf;
3739
3740         case EXACTF:
3741             folder = foldEQ;
3742             fold_array = PL_fold;
3743             fold_utf8_flags = 0;
3744
3745           do_exactf:
3746             s = STRING(scan);
3747             ln = STR_LEN(scan);
3748
3749             if (utf8_target || UTF_PATTERN || state_num == EXACTFU_SS) {
3750               /* Either target or the pattern are utf8, or has the issue where
3751                * the fold lengths may differ. */
3752                 const char * const l = locinput;
3753                 char *e = PL_regeol;
3754
3755                 if (! foldEQ_utf8_flags(s, 0,  ln, cBOOL(UTF_PATTERN),
3756                                         l, &e, 0,  utf8_target, fold_utf8_flags))
3757                 {
3758                     sayNO;
3759                 }
3760                 locinput = e;
3761                 nextchr = UCHARAT(locinput);
3762                 break;
3763             }
3764
3765             /* Neither the target nor the pattern are utf8 */
3766             if (UCHARAT(s) != nextchr &&
3767                 UCHARAT(s) != fold_array[nextchr])
3768             {
3769                 sayNO;
3770             }
3771             if (PL_regeol - locinput < ln)
3772                 sayNO;
3773             if (ln > 1 && ! folder(s, locinput, ln))
3774                 sayNO;
3775             locinput += ln;
3776             nextchr = UCHARAT(locinput);
3777             break;
3778         }
3779
3780         /* XXX Could improve efficiency by separating these all out using a
3781          * macro or in-line function.  At that point regcomp.c would no longer
3782          * have to set the FLAGS fields of these */
3783         case BOUNDL:
3784         case NBOUNDL:
3785             PL_reg_flags |= RF_tainted;
3786             /* FALL THROUGH */
3787         case BOUND:
3788         case BOUNDU:
3789         case BOUNDA:
3790         case NBOUND:
3791         case NBOUNDU:
3792         case NBOUNDA:
3793             /* was last char in word? */
3794             if (utf8_target
3795                 && FLAGS(scan) != REGEX_ASCII_RESTRICTED_CHARSET
3796                 && FLAGS(scan) != REGEX_ASCII_MORE_RESTRICTED_CHARSET)
3797             {
3798                 if (locinput == PL_bostr)
3799                     ln = '\n';
3800                 else {
3801                     const U8 * const r = reghop3((U8*)locinput, -1, (U8*)PL_bostr);
3802
3803                     ln = utf8n_to_uvchr(r, UTF8SKIP(r), 0, uniflags);
3804                 }
3805                 if (FLAGS(scan) != REGEX_LOCALE_CHARSET) {
3806                     ln = isALNUM_uni(ln);
3807                     LOAD_UTF8_CHARCLASS_ALNUM();
3808                     n = swash_fetch(PL_utf8_alnum, (U8*)locinput, utf8_target);
3809                 }
3810                 else {
3811                     ln = isALNUM_LC_uvchr(UNI_TO_NATIVE(ln));
3812                     n = isALNUM_LC_utf8((U8*)locinput);
3813                 }
3814             }
3815             else {
3816
3817                 /* Here the string isn't utf8, or is utf8 and only ascii
3818                  * characters are to match \w.  In the latter case looking at
3819                  * the byte just prior to the current one may be just the final
3820                  * byte of a multi-byte character.  This is ok.  There are two
3821                  * cases:
3822                  * 1) it is a single byte character, and then the test is doing
3823                  *      just what it's supposed to.
3824                  * 2) it is a multi-byte character, in which case the final
3825                  *      byte is never mistakable for ASCII, and so the test
3826                  *      will say it is not a word character, which is the
3827                  *      correct answer. */
3828                 ln = (locinput != PL_bostr) ?
3829                     UCHARAT(locinput - 1) : '\n';
3830                 switch (FLAGS(scan)) {
3831                     case REGEX_UNICODE_CHARSET:
3832                         ln = isWORDCHAR_L1(ln);
3833                         n = isWORDCHAR_L1(nextchr);
3834                         break;
3835                     case REGEX_LOCALE_CHARSET:
3836                         ln = isALNUM_LC(ln);
3837                         n = isALNUM_LC(nextchr);
3838                         break;
3839                     case REGEX_DEPENDS_CHARSET:
3840                         ln = isALNUM(ln);
3841                         n = isALNUM(nextchr);
3842                         break;
3843                     case REGEX_ASCII_RESTRICTED_CHARSET:
3844                     case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
3845                         ln = isWORDCHAR_A(ln);
3846                         n = isWORDCHAR_A(nextchr);
3847                         break;
3848                     default:
3849                         Perl_croak(aTHX_ "panic: Unexpected FLAGS %u in op %u", FLAGS(scan), OP(scan));
3850                         break;
3851                 }
3852             }
3853             /* Note requires that all BOUNDs be lower than all NBOUNDs in
3854              * regcomp.sym */
3855             if (((!ln) == (!n)) == (OP(scan) < NBOUND))
3856                     sayNO;
3857             break;
3858         case ANYOFV:
3859         case ANYOF:
3860             if (utf8_target || state_num == ANYOFV) {
3861                 STRLEN inclasslen = PL_regeol - locinput;
3862                 if (locinput >= PL_regeol)
3863                     sayNO;
3864
3865                 if (!reginclass(rex, scan, (U8*)locinput, &inclasslen, utf8_target))
3866                     sayNO;
3867                 locinput += inclasslen;
3868                 nextchr = UCHARAT(locinput);
3869                 break;
3870             }
3871             else {
3872                 if (nextchr < 0)
3873                     nextchr = UCHARAT(locinput);
3874                 if (!nextchr && locinput >= PL_regeol)
3875                     sayNO;
3876                 if (!REGINCLASS(rex, scan, (U8*)locinput))
3877                     sayNO;
3878                 nextchr = UCHARAT(++locinput);
3879                 break;
3880             }
3881             break;
3882         /* Special char classes - The defines start on line 129 or so */
3883         CCC_TRY_U(ALNUM,  NALNUM,  isWORDCHAR,
3884                   ALNUML, NALNUML, isALNUM_LC, isALNUM_LC_utf8,
3885                   ALNUMU, NALNUMU, isWORDCHAR_L1,
3886                   ALNUMA, NALNUMA, isWORDCHAR_A,
3887                   alnum, "a");
3888
3889         CCC_TRY_U(SPACE,  NSPACE,  isSPACE,
3890                   SPACEL, NSPACEL, isSPACE_LC, isSPACE_LC_utf8,
3891                   SPACEU, NSPACEU, isSPACE_L1,
3892                   SPACEA, NSPACEA, isSPACE_A,
3893                   space, " ");
3894
3895         CCC_TRY(DIGIT,  NDIGIT,  isDIGIT,
3896                 DIGITL, NDIGITL, isDIGIT_LC, isDIGIT_LC_utf8,
3897                 DIGITA, NDIGITA, isDIGIT_A,
3898                 digit, "0");
3899
3900         case POSIXA:
3901             if (locinput >= PL_regeol || ! _generic_isCC_A(nextchr, FLAGS(scan))) {
3902                 sayNO;
3903             }
3904             /* Matched a utf8-invariant, so don't have to worry about utf8 */
3905             nextchr = UCHARAT(++locinput);
3906             break;
3907         case NPOSIXA:
3908             if (locinput >= PL_regeol || _generic_isCC_A(nextchr, FLAGS(scan))) {
3909                 sayNO;
3910             }
3911             if (utf8_target) {
3912                 locinput += PL_utf8skip[nextchr];
3913                 nextchr = UCHARAT(locinput);
3914             }
3915             else {
3916                 nextchr = UCHARAT(++locinput);
3917             }
3918             break;
3919
3920         case CLUMP: /* Match \X: logical Unicode character.  This is defined as
3921                        a Unicode extended Grapheme Cluster */
3922             /* From http://www.unicode.org/reports/tr29 (5.2 version).  An
3923               extended Grapheme Cluster is:
3924
3925                CR LF
3926                | Prepend* Begin Extend*
3927                | .
3928
3929                Begin is (Hangul-syllable | ! Control)
3930                Extend is (Grapheme_Extend | Spacing_Mark)
3931                Control is [ GCB_Control CR LF ]
3932
3933                The discussion below shows how the code for CLUMP is derived
3934                from this regex.  Note that most of these concepts are from
3935                property values of the Grapheme Cluster Boundary (GCB) property.
3936                No code point can have multiple property values for a given
3937                property.  Thus a code point in Prepend can't be in Control, but
3938                it must be in !Control.  This is why Control above includes
3939                GCB_Control plus CR plus LF.  The latter two are used in the GCB
3940                property separately, and so can't be in GCB_Control, even though
3941                they logically are controls.  Control is not the same as gc=cc,
3942                but includes format and other characters as well.
3943
3944                The Unicode definition of Hangul-syllable is:
3945                    L+
3946                    | (L* ( ( V | LV ) V* | LVT ) T*)
3947                    | T+ 
3948                   )
3949                Each of these is a value for the GCB property, and hence must be
3950                disjoint, so the order they are tested is immaterial, so the
3951                above can safely be changed to
3952                    T+
3953                    | L+
3954                    | (L* ( LVT | ( V | LV ) V*) T*)
3955
3956                The last two terms can be combined like this:
3957                    L* ( L
3958                         | (( LVT | ( V | LV ) V*) T*))
3959
3960                And refactored into this:
3961                    L* (L | LVT T* | V  V* T* | LV  V* T*)
3962
3963                That means that if we have seen any L's at all we can quit
3964                there, but if the next character is an LVT, a V, or an LV we
3965                should keep going.
3966
3967                There is a subtlety with Prepend* which showed up in testing.
3968                Note that the Begin, and only the Begin is required in:
3969                 | Prepend* Begin Extend*
3970                Also, Begin contains '! Control'.  A Prepend must be a
3971                '!  Control', which means it must also be a Begin.  What it
3972                comes down to is that if we match Prepend* and then find no
3973                suitable Begin afterwards, that if we backtrack the last
3974                Prepend, that one will be a suitable Begin.
3975             */
3976
3977             if (locinput >= PL_regeol)
3978                 sayNO;
3979             if  (! utf8_target) {
3980
3981                 /* Match either CR LF  or '.', as all the other possibilities
3982                  * require utf8 */
3983                 locinput++;         /* Match the . or CR */
3984                 if (nextchr == '\r' /* And if it was CR, and the next is LF,
3985                                        match the LF */
3986                     && locinput < PL_regeol
3987                     && UCHARAT(locinput) == '\n') locinput++;
3988             }
3989             else {
3990
3991                 /* Utf8: See if is ( CR LF ); already know that locinput <
3992                  * PL_regeol, so locinput+1 is in bounds */
3993                 if (nextchr == '\r' && UCHARAT(locinput + 1) == '\n') {
3994                     locinput += 2;
3995                 }
3996                 else {
3997                     /* In case have to backtrack to beginning, then match '.' */
3998                     char *starting = locinput;
3999
4000                     /* In case have to backtrack the last prepend */
4001                     char *previous_prepend = 0;
4002
4003                     LOAD_UTF8_CHARCLASS_GCB();
4004
4005                     /* Match (prepend)* */
4006                     while (locinput < PL_regeol
4007                            && swash_fetch(PL_utf8_X_prepend,
4008                                           (U8*)locinput, utf8_target))
4009                     {
4010                         previous_prepend = locinput;
4011                         locinput += UTF8SKIP(locinput);
4012                     }
4013
4014                     /* As noted above, if we matched a prepend character, but
4015                      * the next thing won't match, back off the last prepend we
4016                      * matched, as it is guaranteed to match the begin */
4017                     if (previous_prepend
4018                         && (locinput >=  PL_regeol
4019                             || ! swash_fetch(PL_utf8_X_begin,
4020                                              (U8*)locinput, utf8_target)))
4021                     {
4022                         locinput = previous_prepend;
4023                     }
4024
4025                     /* Note that here we know PL_regeol > locinput, as we
4026                      * tested that upon input to this switch case, and if we
4027                      * moved locinput forward, we tested the result just above
4028                      * and it either passed, or we backed off so that it will
4029                      * now pass */
4030                     if (! swash_fetch(PL_utf8_X_begin, (U8*)locinput, utf8_target)) {
4031
4032                         /* Here did not match the required 'Begin' in the
4033                          * second term.  So just match the very first
4034                          * character, the '.' of the final term of the regex */
4035                         locinput = starting + UTF8SKIP(starting);
4036                     } else {
4037
4038                         /* Here is the beginning of a character that can have
4039                          * an extender.  It is either a hangul syllable, or a
4040                          * non-control */
4041                         if (swash_fetch(PL_utf8_X_non_hangul,
4042                                         (U8*)locinput, utf8_target))
4043                         {
4044
4045                             /* Here not a Hangul syllable, must be a
4046                              * ('!  * Control') */
4047                             locinput += UTF8SKIP(locinput);
4048                         } else {
4049
4050                             /* Here is a Hangul syllable.  It can be composed
4051                              * of several individual characters.  One
4052                              * possibility is T+ */
4053                             if (swash_fetch(PL_utf8_X_T,
4054                                             (U8*)locinput, utf8_target))
4055                             {
4056                                 while (locinput < PL_regeol
4057                                         && swash_fetch(PL_utf8_X_T,
4058                                                         (U8*)locinput, utf8_target))
4059                                 {
4060                                     locinput += UTF8SKIP(locinput);
4061                                 }
4062                             } else {
4063
4064                                 /* Here, not T+, but is a Hangul.  That means
4065                                  * it is one of the others: L, LV, LVT or V,
4066                                  * and matches:
4067                                  * L* (L | LVT T* | V  V* T* | LV  V* T*) */
4068
4069                                 /* Match L*           */
4070                                 while (locinput < PL_regeol
4071                                         && swash_fetch(PL_utf8_X_L,
4072                                                         (U8*)locinput, utf8_target))
4073                                 {
4074                                     locinput += UTF8SKIP(locinput);
4075                                 }
4076
4077                                 /* Here, have exhausted L*.  If the next
4078                                  * character is not an LV, LVT nor V, it means
4079                                  * we had to have at least one L, so matches L+
4080                                  * in the original equation, we have a complete
4081                                  * hangul syllable.  Are done. */
4082
4083                                 if (locinput < PL_regeol
4084                                     && swash_fetch(PL_utf8_X_LV_LVT_V,
4085                                                     (U8*)locinput, utf8_target))
4086                                 {
4087
4088                                     /* Otherwise keep going.  Must be LV, LVT
4089                                      * or V.  See if LVT */
4090                                     if (swash_fetch(PL_utf8_X_LVT,
4091                                                     (U8*)locinput, utf8_target))
4092                                     {
4093                                         locinput += UTF8SKIP(locinput);
4094                                     } else {
4095
4096                                         /* Must be  V or LV.  Take it, then
4097                                          * match V*     */
4098                                         locinput += UTF8SKIP(locinput);
4099                                         while (locinput < PL_regeol
4100                                                 && swash_fetch(PL_utf8_X_V,
4101                                                          (U8*)locinput, utf8_target))
4102                                         {
4103                                             locinput += UTF8SKIP(locinput);
4104                                         }
4105                                     }
4106
4107                                     /* And any of LV, LVT, or V can be followed
4108                                      * by T*            */
4109                                     while (locinput < PL_regeol
4110                                            && swash_fetch(PL_utf8_X_T,
4111                                                            (U8*)locinput,
4112                                                            utf8_target))
4113                                     {
4114                                         locinput += UTF8SKIP(locinput);
4115                                     }
4116                                 }
4117                             }
4118                         }
4119
4120                         /* Match any extender */
4121                         while (locinput < PL_regeol
4122                                 && swash_fetch(PL_utf8_X_extend,
4123                                                 (U8*)locinput, utf8_target))
4124                         {
4125                             locinput += UTF8SKIP(locinput);
4126                         }
4127                     }
4128                 }
4129                 if (locinput > PL_regeol) sayNO;
4130             }
4131             nextchr = UCHARAT(locinput);
4132             break;
4133             
4134         case NREFFL:
4135         {   /* The capture buffer cases.  The ones beginning with N for the
4136                named buffers just convert to the equivalent numbered and
4137                pretend they were called as the corresponding numbered buffer
4138                op.  */
4139             /* don't initialize these in the declaration, it makes C++
4140                unhappy */
4141             char *s;
4142             char type;
4143             re_fold_t folder;
4144             const U8 *fold_array;
4145             UV utf8_fold_flags;
4146
4147             PL_reg_flags |= RF_tainted;
4148             folder = foldEQ_locale;
4149             fold_array = PL_fold_locale;
4150             type = REFFL;
4151             utf8_fold_flags = FOLDEQ_UTF8_LOCALE;
4152             goto do_nref;
4153
4154         case NREFFA:
4155             folder = foldEQ_latin1;
4156             fold_array = PL_fold_latin1;
4157             type = REFFA;
4158             utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
4159             goto do_nref;
4160
4161         case NREFFU:
4162             folder = foldEQ_latin1;
4163             fold_array = PL_fold_latin1;
4164             type = REFFU;
4165             utf8_fold_flags = 0;
4166             goto do_nref;
4167
4168         case NREFF:
4169             folder = foldEQ;
4170             fold_array = PL_fold;
4171             type = REFF;
4172             utf8_fold_flags = 0;
4173             goto do_nref;
4174
4175         case NREF:
4176             type = REF;
4177             folder = NULL;
4178             fold_array = NULL;
4179             utf8_fold_flags = 0;
4180           do_nref:
4181
4182             /* For the named back references, find the corresponding buffer
4183              * number */
4184             n = reg_check_named_buff_matched(rex,scan);
4185
4186             if ( ! n ) {
4187                 sayNO;
4188             }
4189             goto do_nref_ref_common;
4190
4191         case REFFL:
4192             PL_reg_flags |= RF_tainted;
4193             folder = foldEQ_locale;
4194             fold_array = PL_fold_locale;
4195             utf8_fold_flags = FOLDEQ_UTF8_LOCALE;
4196             goto do_ref;
4197
4198         case REFFA:
4199             folder = foldEQ_latin1;
4200             fold_array = PL_fold_latin1;
4201             utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
4202             goto do_ref;
4203
4204         case REFFU:
4205             folder = foldEQ_latin1;
4206             fold_array = PL_fold_latin1;
4207             utf8_fold_flags = 0;
4208             goto do_ref;
4209
4210         case REFF:
4211             folder = foldEQ;
4212             fold_array = PL_fold;
4213             utf8_fold_flags = 0;
4214             goto do_ref;
4215
4216         case REF:
4217             folder = NULL;
4218             fold_array = NULL;
4219             utf8_fold_flags = 0;
4220
4221           do_ref:
4222             type = OP(scan);
4223             n = ARG(scan);  /* which paren pair */
4224
4225           do_nref_ref_common:
4226             ln = rex->offs[n].start;
4227             PL_reg_leftiter = PL_reg_maxiter;           /* Void cache */
4228             if (rex->lastparen < n || ln == -1)
4229                 sayNO;                  /* Do not match unless seen CLOSEn. */
4230             if (ln == rex->offs[n].end)
4231                 break;
4232
4233             s = PL_bostr + ln;
4234             if (type != REF     /* REF can do byte comparison */
4235                 && (utf8_target || type == REFFU))
4236             { /* XXX handle REFFL better */
4237                 char * limit = PL_regeol;
4238
4239                 /* This call case insensitively compares the entire buffer
4240                     * at s, with the current input starting at locinput, but
4241                     * not going off the end given by PL_regeol, and returns in
4242                     * limit upon success, how much of the current input was
4243                     * matched */
4244                 if (! foldEQ_utf8_flags(s, NULL, rex->offs[n].end - ln, utf8_target,
4245                                     locinput, &limit, 0, utf8_target, utf8_fold_flags))
4246                 {
4247                     sayNO;
4248                 }
4249                 locinput = limit;
4250                 nextchr = UCHARAT(locinput);
4251                 break;
4252             }
4253
4254             /* Not utf8:  Inline the first character, for speed. */
4255             if (UCHARAT(s) != nextchr &&
4256                 (type == REF ||
4257                  UCHARAT(s) != fold_array[nextchr]))
4258                 sayNO;
4259             ln = rex->offs[n].end - ln;
4260             if (locinput + ln > PL_regeol)
4261                 sayNO;
4262             if (ln > 1 && (type == REF
4263                            ? memNE(s, locinput, ln)
4264                            : ! folder(s, locinput, ln)))
4265                 sayNO;
4266             locinput += ln;
4267             nextchr = UCHARAT(locinput);
4268             break;
4269         }
4270         case NOTHING:
4271         case TAIL:
4272             break;
4273         case BACK:
4274             break;
4275
4276 #undef  ST
4277 #define ST st->u.eval
4278         {
4279             SV *ret;
4280             REGEXP *re_sv;
4281             regexp *re;
4282             regexp_internal *rei;
4283             regnode *startpoint;
4284
4285         case GOSTART:
4286         case GOSUB: /*    /(...(?1))/   /(...(?&foo))/   */
4287             if (cur_eval && cur_eval->locinput==locinput) {
4288                 if (cur_eval->u.eval.close_paren == (U32)ARG(scan)) 
4289                     Perl_croak(aTHX_ "Infinite recursion in regex");
4290                 if ( ++nochange_depth > max_nochange_depth )
4291                     Perl_croak(aTHX_ 
4292                         "Pattern subroutine nesting without pos change"
4293                         " exceeded limit in regex");
4294             } else {
4295                 nochange_depth = 0;
4296             }
4297             re_sv = rex_sv;
4298             re = rex;
4299             rei = rexi;
4300             if (OP(scan)==GOSUB) {
4301                 startpoint = scan + ARG2L(scan);
4302                 ST.close_paren = ARG(scan);
4303             } else {
4304                 startpoint = rei->program+1;
4305                 ST.close_paren = 0;
4306             }
4307             goto eval_recurse_doit;
4308             assert(0); /* NOTREACHED */
4309         case EVAL:  /*   /(?{A})B/   /(??{A})B/  and /(?(?{A})X|Y)B/   */        
4310             if (cur_eval && cur_eval->locinput==locinput) {
4311                 if ( ++nochange_depth > max_nochange_depth )
4312                     Perl_croak(aTHX_ "EVAL without pos change exceeded limit in regex");
4313             } else {
4314                 nochange_depth = 0;
4315             }    
4316             {
4317                 /* execute the code in the {...} */
4318
4319                 dSP;
4320                 SV ** before;
4321                 OP * const oop = PL_op;
4322                 COP * const ocurcop = PL_curcop;
4323                 OP *nop;
4324                 char *saved_regeol = PL_regeol;
4325                 struct re_save_state saved_state;
4326                 CV *newcv;
4327
4328                 /* save *all* paren positions */
4329                 regcppush(rex, 0);
4330                 REGCP_SET(runops_cp);
4331
4332                 /* To not corrupt the existing regex state while executing the
4333                  * eval we would normally put it on the save stack, like with
4334                  * save_re_context. However, re-evals have a weird scoping so we
4335                  * can't just add ENTER/LEAVE here. With that, things like
4336                  *
4337                  *    (?{$a=2})(a(?{local$a=$a+1}))*aak*c(?{$b=$a})
4338                  *
4339                  * would break, as they expect the localisation to be unwound
4340                  * only when the re-engine backtracks through the bit that
4341                  * localised it.
4342                  *
4343                  * What we do instead is just saving the state in a local c
4344                  * variable.
4345                  */
4346                 Copy(&PL_reg_state, &saved_state, 1, struct re_save_state);
4347
4348                 PL_reg_state.re_reparsing = FALSE;
4349
4350                 if (!caller_cv)
4351                     caller_cv = find_runcv(NULL);
4352
4353                 n = ARG(scan);
4354
4355                 if (rexi->data->what[n] == 'r') { /* code from an external qr */
4356                     newcv = ((struct regexp *)SvANY(
4357                                                 (REGEXP*)(rexi->data->data[n])
4358                                             ))->qr_anoncv
4359                                         ;
4360                     nop = (OP*)rexi->data->data[n+1];
4361                 }
4362                 else if (rexi->data->what[n] == 'l') { /* literal code */
4363                     newcv = caller_cv;
4364                     nop = (OP*)rexi->data->data[n];
4365                     assert(CvDEPTH(newcv));
4366                 }
4367                 else {
4368                     /* literal with own CV */
4369                     assert(rexi->data->what[n] == 'L');
4370                     newcv = rex->qr_anoncv;
4371                     nop = (OP*)rexi->data->data[n];
4372                 }
4373
4374                 /* normally if we're about to execute code from the same
4375                  * CV that we used previously, we just use the existing
4376                  * CX stack entry. However, its possible that in the
4377                  * meantime we may have backtracked, popped from the save
4378                  * stack, and undone the SAVECOMPPAD(s) associated with
4379                  * PUSH_MULTICALL; in which case PL_comppad no longer
4380                  * points to newcv's pad. */
4381                 if (newcv != last_pushed_cv || PL_comppad != last_pad)
4382                 {
4383                     I32 depth = (newcv == caller_cv) ? 0 : 1;
4384                     if (last_pushed_cv) {
4385                         CHANGE_MULTICALL_WITHDEPTH(newcv, depth);
4386                     }
4387                     else {
4388                         PUSH_MULTICALL_WITHDEPTH(newcv, depth);
4389                     }
4390                     last_pushed_cv = newcv;
4391                 }
4392                 last_pad = PL_comppad;
4393
4394                 /* the initial nextstate you would normally execute
4395                  * at the start of an eval (which would cause error
4396                  * messages to come from the eval), may be optimised
4397                  * away from the execution path in the regex code blocks;
4398                  * so manually set PL_curcop to it initially */
4399                 {
4400                     OP *o = cUNOPx(nop)->op_first;
4401                     assert(o->op_type == OP_NULL);
4402                     if (o->op_targ == OP_SCOPE) {
4403                         o = cUNOPo->op_first;
4404                     }
4405                     else {
4406                         assert(o->op_targ == OP_LEAVE);
4407                         o = cUNOPo->op_first;
4408                         assert(o->op_type == OP_ENTER);
4409                         o = o->op_sibling;
4410                     }
4411
4412                     if (o->op_type != OP_STUB) {
4413                         assert(    o->op_type == OP_NEXTSTATE
4414                                 || o->op_type == OP_DBSTATE
4415                                 || (o->op_type == OP_NULL
4416                                     &&  (  o->op_targ == OP_NEXTSTATE
4417                                         || o->op_targ == OP_DBSTATE
4418                                         )
4419                                     )
4420                         );
4421                         PL_curcop = (COP*)o;
4422                     }
4423                 }
4424                 nop = nop->op_next;
4425
4426                 DEBUG_STATE_r( PerlIO_printf(Perl_debug_log, 
4427                     "  re EVAL PL_op=0x%"UVxf"\n", PTR2UV(nop)) );
4428
4429                 rex->offs[0].end = PL_reg_magic->mg_len = locinput - PL_bostr;
4430
4431                 if (sv_yes_mark) {
4432                     SV *sv_mrk = get_sv("REGMARK", 1);
4433                     sv_setsv(sv_mrk, sv_yes_mark);
4434                 }
4435
4436                 /* we don't use MULTICALL here as we want to call the
4437                  * first op of the block of interest, rather than the
4438                  * first op of the sub */
4439                 before = SP;
4440                 PL_op = nop;
4441                 CALLRUNOPS(aTHX);                       /* Scalar context. */
4442                 SPAGAIN;
4443                 if (SP == before)
4444                     ret = &PL_sv_undef;   /* protect against empty (?{}) blocks. */
4445                 else {
4446                     ret = POPs;
4447                     PUTBACK;
4448                 }
4449
4450                 /* before restoring everything, evaluate the returned
4451                  * value, so that 'uninit' warnings don't use the wrong
4452                  * PL_op or pad. Also need to process any magic vars
4453                  * (e.g. $1) *before* parentheses are restored */
4454
4455                 PL_op = NULL;
4456
4457                 re_sv = NULL;
4458                 if (logical == 0)        /*   (?{})/   */
4459                     sv_setsv(save_scalar(PL_replgv), ret); /* $^R */
4460                 else if (logical == 1) { /*   /(?(?{...})X|Y)/    */
4461                     sw = cBOOL(SvTRUE(ret));
4462                     logical = 0;
4463                 }
4464                 else {                   /*  /(??{})  */
4465                     /*  if its overloaded, let the regex compiler handle
4466                      *  it; otherwise extract regex, or stringify  */
4467                     if (!SvAMAGIC(ret)) {
4468                         SV *sv = ret;
4469                         if (SvROK(sv))
4470                             sv = SvRV(sv);
4471                         if (SvTYPE(sv) == SVt_REGEXP)
4472                             re_sv = (REGEXP*) sv;
4473                         else if (SvSMAGICAL(sv)) {
4474                             MAGIC *mg = mg_find(sv, PERL_MAGIC_qr);
4475                             if (mg)
4476                                 re_sv = (REGEXP *) mg->mg_obj;
4477                         }
4478
4479                         /* force any magic, undef warnings here */
4480                         if (!re_sv) {
4481                             ret = sv_mortalcopy(ret);
4482                             (void) SvPV_force_nolen(ret);
4483                         }
4484                     }
4485
4486                 }
4487
4488                 Copy(&saved_state, &PL_reg_state, 1, struct re_save_state);
4489
4490                 /* *** Note that at this point we don't restore
4491                  * PL_comppad, (or pop the CxSUB) on the assumption it may
4492                  * be used again soon. This is safe as long as nothing
4493                  * in the regexp code uses the pad ! */
4494                 PL_op = oop;
4495                 PL_curcop = ocurcop;
4496                 PL_regeol = saved_regeol;
4497                 S_regcp_restore(aTHX_ rex, runops_cp);
4498
4499                 if (logical != 2)
4500                     break;
4501             }
4502
4503                 /* only /(??{})/  from now on */
4504                 logical = 0;
4505                 {
4506                     /* extract RE object from returned value; compiling if
4507                      * necessary */
4508
4509                     if (re_sv) {
4510                         re_sv = reg_temp_copy(NULL, re_sv);
4511                     }
4512                     else {
4513                         U32 pm_flags = 0;
4514                         const I32 osize = PL_regsize;
4515
4516                         if (SvUTF8(ret) && IN_BYTES) {
4517                             /* In use 'bytes': make a copy of the octet
4518                              * sequence, but without the flag on */
4519                             STRLEN len;
4520                             const char *const p = SvPV(ret, len);
4521                             ret = newSVpvn_flags(p, len, SVs_TEMP);
4522                         }
4523                         if (rex->intflags & PREGf_USE_RE_EVAL)
4524                             pm_flags |= PMf_USE_RE_EVAL;
4525
4526                         /* if we got here, it should be an engine which
4527                          * supports compiling code blocks and stuff */
4528                         assert(rex->engine && rex->engine->op_comp);
4529                         assert(!(scan->flags & ~RXf_PMf_COMPILETIME));
4530                         re_sv = rex->engine->op_comp(aTHX_ &ret, 1, NULL,
4531                                     rex->engine, NULL, NULL,
4532                                     /* copy /msix etc to inner pattern */
4533                                     scan->flags,
4534                                     pm_flags);
4535
4536                         if (!(SvFLAGS(ret)
4537                               & (SVs_TEMP | SVs_PADTMP | SVf_READONLY
4538                                  | SVs_GMG))) {
4539                             /* This isn't a first class regexp. Instead, it's
4540                                caching a regexp onto an existing, Perl visible
4541                                scalar.  */
4542                             sv_magic(ret, MUTABLE_SV(re_sv), PERL_MAGIC_qr, 0, 0);
4543                         }
4544                         PL_regsize = osize;
4545                         /* safe to do now that any $1 etc has been
4546                          * interpolated into the new pattern string and
4547                          * compiled */
4548                         S_regcp_restore(aTHX_ rex, runops_cp);
4549                     }
4550                     re = (struct regexp *)SvANY(re_sv);
4551                 }
4552                 RXp_MATCH_COPIED_off(re);
4553                 re->subbeg = rex->subbeg;
4554                 re->sublen = rex->sublen;
4555                 rei = RXi_GET(re);
4556                 DEBUG_EXECUTE_r(
4557                     debug_start_match(re_sv, utf8_target, locinput, PL_regeol,
4558                         "Matching embedded");
4559                 );              
4560                 startpoint = rei->program + 1;
4561                 ST.close_paren = 0; /* only used for GOSUB */
4562
4563         eval_recurse_doit: /* Share code with GOSUB below this line */                          
4564                 /* run the pattern returned from (??{...}) */
4565                 ST.cp = regcppush(rex, 0);      /* Save *all* the positions. */
4566                 REGCP_SET(ST.lastcp);
4567                 
4568                 re->lastparen = 0;
4569                 re->lastcloseparen = 0;
4570
4571                 PL_reginput = locinput;
4572                 PL_regsize = 0;
4573
4574                 /* XXXX This is too dramatic a measure... */
4575                 PL_reg_maxiter = 0;
4576
4577                 ST.toggle_reg_flags = PL_reg_flags;
4578                 if (RX_UTF8(re_sv))
4579                     PL_reg_flags |= RF_utf8;
4580                 else
4581                     PL_reg_flags &= ~RF_utf8;
4582                 ST.toggle_reg_flags ^= PL_reg_flags; /* diff of old and new */
4583
4584                 ST.prev_rex = rex_sv;
4585                 ST.prev_curlyx = cur_curlyx;
4586                 rex_sv = re_sv;
4587                 SET_reg_curpm(rex_sv);
4588                 rex = re;
4589                 rexi = rei;
4590                 cur_curlyx = NULL;
4591                 ST.B = next;
4592                 ST.prev_eval = cur_eval;
4593                 cur_eval = st;
4594                 /* now continue from first node in postoned RE */
4595                 PUSH_YES_STATE_GOTO(EVAL_AB, startpoint);
4596                 assert(0); /* NOTREACHED */
4597         }
4598
4599         case EVAL_AB: /* cleanup after a successful (??{A})B */
4600             /* note: this is called twice; first after popping B, then A */
4601             PL_reg_flags ^= ST.toggle_reg_flags; 
4602             rex_sv = ST.prev_rex;
4603             SET_reg_curpm(rex_sv);
4604             rex = (struct regexp *)SvANY(rex_sv);
4605             rexi = RXi_GET(rex);
4606             regcpblow(ST.cp);
4607             cur_eval = ST.prev_eval;
4608             cur_curlyx = ST.prev_curlyx;
4609
4610             /* XXXX This is too dramatic a measure... */
4611             PL_reg_maxiter = 0;
4612             if ( nochange_depth )
4613                 nochange_depth--;
4614             sayYES;
4615
4616
4617         case EVAL_AB_fail: /* unsuccessfully ran A or B in (??{A})B */
4618             /* note: this is called twice; first after popping B, then A */
4619             PL_reg_flags ^= ST.toggle_reg_flags; 
4620             rex_sv = ST.prev_rex;
4621             SET_reg_curpm(rex_sv);
4622             rex = (struct regexp *)SvANY(rex_sv);
4623             rexi = RXi_GET(rex); 
4624
4625             PL_reginput = locinput;
4626             REGCP_UNWIND(ST.lastcp);
4627             regcppop(rex);
4628             cur_eval = ST.prev_eval;
4629             cur_curlyx = ST.prev_curlyx;
4630             /* XXXX This is too dramatic a measure... */
4631             PL_reg_maxiter = 0;
4632             if ( nochange_depth )
4633                 nochange_depth--;
4634             sayNO_SILENT;
4635 #undef ST
4636
4637         case OPEN:
4638             n = ARG(scan);  /* which paren pair */
4639             rex->offs[n].start_tmp = locinput - PL_bostr;
4640             if (n > PL_regsize)
4641                 PL_regsize = n;
4642             DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
4643                 "rex=0x%"UVxf" offs=0x%"UVxf": \\%"UVuf": set %"IVdf" tmp; regsize=%"UVuf"\n",
4644                 PTR2UV(rex),
4645                 PTR2UV(rex->offs),
4646                 (UV)n,
4647                 (IV)rex->offs[n].start_tmp,
4648                 (UV)PL_regsize
4649             ));
4650             lastopen = n;
4651             break;
4652
4653 /* XXX really need to log other places start/end are set too */
4654 #define CLOSE_CAPTURE \
4655     rex->offs[n].start = rex->offs[n].start_tmp; \
4656     rex->offs[n].end = locinput - PL_bostr; \
4657     DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log, \
4658         "rex=0x%"UVxf" offs=0x%"UVxf": \\%"UVuf": set %"IVdf"..%"IVdf"\n", \
4659         PTR2UV(rex), \
4660         PTR2UV(rex->offs), \
4661         (UV)n, \
4662         (IV)rex->offs[n].start, \
4663         (IV)rex->offs[n].end \
4664     ))
4665
4666         case CLOSE:
4667             n = ARG(scan);  /* which paren pair */
4668             CLOSE_CAPTURE;
4669             /*if (n > PL_regsize)
4670                 PL_regsize = n;*/
4671             if (n > rex->lastparen)
4672                 rex->lastparen = n;
4673             rex->lastcloseparen = n;
4674             if (cur_eval && cur_eval->u.eval.close_paren == n) {
4675                 goto fake_end;
4676             }    
4677             break;
4678         case ACCEPT:
4679             if (ARG(scan)){
4680                 regnode *cursor;
4681                 for (cursor=scan;
4682                      cursor && OP(cursor)!=END; 
4683                      cursor=regnext(cursor)) 
4684                 {
4685                     if ( OP(cursor)==CLOSE ){
4686                         n = ARG(cursor);
4687                         if ( n <= lastopen ) {
4688                             CLOSE_CAPTURE;
4689                             /*if (n > PL_regsize)
4690                             PL_regsize = n;*/
4691                             if (n > rex->lastparen)
4692                                 rex->lastparen = n;
4693                             rex->lastcloseparen = n;
4694                             if ( n == ARG(scan) || (cur_eval &&
4695                                 cur_eval->u.eval.close_paren == n))
4696                                 break;
4697                         }
4698                     }
4699                 }
4700             }
4701             goto fake_end;
4702             /*NOTREACHED*/          
4703         case GROUPP:
4704             n = ARG(scan);  /* which paren pair */
4705             sw = cBOOL(rex->lastparen >= n && rex->offs[n].end != -1);
4706             break;
4707         case NGROUPP:
4708             /* reg_check_named_buff_matched returns 0 for no match */
4709             sw = cBOOL(0 < reg_check_named_buff_matched(rex,scan));
4710             break;
4711         case INSUBP:
4712             n = ARG(scan);
4713             sw = (cur_eval && (!n || cur_eval->u.eval.close_paren == n));
4714             break;
4715         case DEFINEP:
4716             sw = 0;
4717             break;
4718         case IFTHEN:
4719             PL_reg_leftiter = PL_reg_maxiter;           /* Void cache */
4720             if (sw)
4721                 next = NEXTOPER(NEXTOPER(scan));
4722             else {
4723                 next = scan + ARG(scan);
4724                 if (OP(next) == IFTHEN) /* Fake one. */
4725                     next = NEXTOPER(NEXTOPER(next));
4726             }
4727             break;
4728         case LOGICAL:
4729             logical = scan->flags;
4730             break;
4731
4732 /*******************************************************************
4733
4734 The CURLYX/WHILEM pair of ops handle the most generic case of the /A*B/
4735 pattern, where A and B are subpatterns. (For simple A, CURLYM or
4736 STAR/PLUS/CURLY/CURLYN are used instead.)
4737
4738 A*B is compiled as <CURLYX><A><WHILEM><B>
4739
4740 On entry to the subpattern, CURLYX is called. This pushes a CURLYX
4741 state, which contains the current count, initialised to -1. It also sets
4742 cur_curlyx to point to this state, with any previous value saved in the
4743 state block.
4744
4745 CURLYX then jumps straight to the WHILEM op, rather than executing A,
4746 since the pattern may possibly match zero times (i.e. it's a while {} loop
4747 rather than a do {} while loop).
4748
4749 Each entry to WHILEM represents a successful match of A. The count in the
4750 CURLYX block is incremented, another WHILEM state is pushed, and execution
4751 passes to A or B depending on greediness and the current count.
4752
4753 For example, if matching against the string a1a2a3b (where the aN are
4754 substrings that match /A/), then the match progresses as follows: (the
4755 pushed states are interspersed with the bits of strings matched so far):
4756
4757     <CURLYX cnt=-1>
4758     <CURLYX cnt=0><WHILEM>
4759     <CURLYX cnt=1><WHILEM> a1 <WHILEM>
4760     <CURLYX cnt=2><WHILEM> a1 <WHILEM> a2 <WHILEM>
4761     <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM>
4762     <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM> b
4763
4764 (Contrast this with something like CURLYM, which maintains only a single
4765 backtrack state:
4766
4767     <CURLYM cnt=0> a1
4768     a1 <CURLYM cnt=1> a2
4769     a1 a2 <CURLYM cnt=2> a3
4770     a1 a2 a3 <CURLYM cnt=3> b
4771 )
4772
4773 Each WHILEM state block marks a point to backtrack to upon partial failure
4774 of A or B, and also contains some minor state data related to that
4775 iteration.  The CURLYX block, pointed to by cur_curlyx, contains the
4776 overall state, such as the count, and pointers to the A and B ops.
4777
4778 This is complicated slightly by nested CURLYX/WHILEM's. Since cur_curlyx
4779 must always point to the *current* CURLYX block, the rules are:
4780
4781 When executing CURLYX, save the old cur_curlyx in the CURLYX state block,
4782 and set cur_curlyx to point the new block.
4783
4784 When popping the CURLYX block after a successful or unsuccessful match,
4785 restore the previous cur_curlyx.
4786
4787 When WHILEM is about to execute B, save the current cur_curlyx, and set it
4788 to the outer one saved in the CURLYX block.
4789
4790 When popping the WHILEM block after a successful or unsuccessful B match,
4791 restore the previous cur_curlyx.
4792
4793 Here's an example for the pattern (AI* BI)*BO
4794 I and O refer to inner and outer, C and W refer to CURLYX and WHILEM:
4795
4796 cur_
4797 curlyx backtrack stack
4798 ------ ---------------
4799 NULL   
4800 CO     <CO prev=NULL> <WO>
4801 CI     <CO prev=NULL> <WO> <CI prev=CO> <WI> ai 
4802 CO     <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi 
4803 NULL   <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi <WO prev=CO> bo
4804
4805 At this point the pattern succeeds, and we work back down the stack to
4806 clean up, restoring as we go:
4807
4808 CO     <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi 
4809 CI     <CO prev=NULL> <WO> <CI prev=CO> <WI> ai 
4810 CO     <CO prev=NULL> <WO>
4811 NULL   
4812
4813 *******************************************************************/
4814
4815 #define ST st->u.curlyx
4816
4817         case CURLYX:    /* start of /A*B/  (for complex A) */
4818         {
4819             /* No need to save/restore up to this paren */
4820             I32 parenfloor = scan->flags;
4821             
4822             assert(next); /* keep Coverity happy */
4823             if (OP(PREVOPER(next)) == NOTHING) /* LONGJMP */
4824                 next += ARG(next);
4825
4826             /* XXXX Probably it is better to teach regpush to support
4827                parenfloor > PL_regsize... */
4828             if (parenfloor > (I32)rex->lastparen)
4829                 parenfloor = rex->lastparen; /* Pessimization... */
4830
4831             ST.prev_curlyx= cur_curlyx;
4832             cur_curlyx = st;
4833             ST.cp = PL_savestack_ix;
4834
4835             /* these fields contain the state of the current curly.
4836              * they are accessed by subsequent WHILEMs */
4837             ST.parenfloor = parenfloor;
4838             ST.me = scan;
4839             ST.B = next;
4840             ST.minmod = minmod;
4841             minmod = 0;
4842             ST.count = -1;      /* this will be updated by WHILEM */
4843             ST.lastloc = NULL;  /* this will be updated by WHILEM */
4844
4845             PL_reginput = locinput;
4846             PUSH_YES_STATE_GOTO(CURLYX_end, PREVOPER(next));
4847             assert(0); /* NOTREACHED */
4848         }
4849
4850         case CURLYX_end: /* just finished matching all of A*B */
4851             cur_curlyx = ST.prev_curlyx;
4852             sayYES;
4853             assert(0); /* NOTREACHED */
4854
4855         case CURLYX_end_fail: /* just failed to match all of A*B */
4856             regcpblow(ST.cp);
4857             cur_curlyx = ST.prev_curlyx;
4858             sayNO;
4859             assert(0); /* NOTREACHED */
4860
4861
4862 #undef ST
4863 #define ST st->u.whilem
4864
4865         case WHILEM:     /* just matched an A in /A*B/  (for complex A) */
4866         {
4867             /* see the discussion above about CURLYX/WHILEM */
4868             I32 n;
4869             int min = ARG1(cur_curlyx->u.curlyx.me);
4870             int max = ARG2(cur_curlyx->u.curlyx.me);
4871             regnode *A = NEXTOPER(cur_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS;
4872
4873             assert(cur_curlyx); /* keep Coverity happy */
4874             n = ++cur_curlyx->u.curlyx.count; /* how many A's matched */
4875             ST.save_lastloc = cur_curlyx->u.curlyx.lastloc;
4876             ST.cache_offset = 0;
4877             ST.cache_mask = 0;
4878             
4879             PL_reginput = locinput;
4880
4881             DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
4882                   "%*s  whilem: matched %ld out of %d..%d\n",
4883                   REPORT_CODE_OFF+depth*2, "", (long)n, min, max)
4884             );
4885
4886             /* First just match a string of min A's. */
4887
4888             if (n < min) {
4889                 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor);
4890                 cur_curlyx->u.curlyx.lastloc = locinput;
4891                 REGCP_SET(ST.lastcp);
4892
4893                 PUSH_STATE_GOTO(WHILEM_A_pre, A);
4894                 assert(0); /* NOTREACHED */
4895             }
4896
4897             /* If degenerate A matches "", assume A done. */
4898
4899             if (locinput == cur_curlyx->u.curlyx.lastloc) {
4900                 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
4901                    "%*s  whilem: empty match detected, trying continuation...\n",
4902                    REPORT_CODE_OFF+depth*2, "")
4903                 );
4904                 goto do_whilem_B_max;
4905             }
4906
4907             /* super-linear cache processing */
4908
4909             if (scan->flags) {
4910
4911                 if (!PL_reg_maxiter) {
4912                     /* start the countdown: Postpone detection until we
4913                      * know the match is not *that* much linear. */
4914                     PL_reg_maxiter = (PL_regeol - PL_bostr + 1) * (scan->flags>>4);
4915                     /* possible overflow for long strings and many CURLYX's */
4916                     if (PL_reg_maxiter < 0)
4917                         PL_reg_maxiter = I32_MAX;
4918                     PL_reg_leftiter = PL_reg_maxiter;
4919                 }
4920
4921                 if (PL_reg_leftiter-- == 0) {
4922                     /* initialise cache */
4923                     const I32 size = (PL_reg_maxiter + 7)/8;
4924                     if (PL_reg_poscache) {
4925                         if ((I32)PL_reg_poscache_size < size) {
4926                             Renew(PL_reg_poscache, size, char);
4927                             PL_reg_poscache_size = size;
4928                         }
4929                         Zero(PL_reg_poscache, size, char);
4930                     }
4931                     else {
4932                         PL_reg_poscache_size = size;
4933                         Newxz(PL_reg_poscache, size, char);
4934                     }
4935                     DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
4936       "%swhilem: Detected a super-linear match, switching on caching%s...\n",
4937                               PL_colors[4], PL_colors[5])
4938                     );
4939                 }
4940
4941                 if (PL_reg_leftiter < 0) {
4942                     /* have we already failed at this position? */
4943                     I32 offset, mask;
4944                     offset  = (scan->flags & 0xf) - 1
4945                                 + (locinput - PL_bostr)  * (scan->flags>>4);
4946                     mask    = 1 << (offset % 8);
4947                     offset /= 8;
4948                     if (PL_reg_poscache[offset] & mask) {
4949                         DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
4950                             "%*s  whilem: (cache) already tried at this position...\n",
4951                             REPORT_CODE_OFF+depth*2, "")
4952                         );
4953                         sayNO; /* cache records failure */
4954                     }
4955                     ST.cache_offset = offset;
4956                     ST.cache_mask   = mask;
4957                 }
4958             }
4959
4960             /* Prefer B over A for minimal matching. */
4961
4962             if (cur_curlyx->u.curlyx.minmod) {
4963                 ST.save_curlyx = cur_curlyx;
4964                 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
4965                 ST.cp = regcppush(rex, ST.save_curlyx->u.curlyx.parenfloor);
4966                 REGCP_SET(ST.lastcp);
4967                 PUSH_YES_STATE_GOTO(WHILEM_B_min, ST.save_curlyx->u.curlyx.B);
4968                 assert(0); /* NOTREACHED */
4969             }
4970
4971             /* Prefer A over B for maximal matching. */
4972
4973             if (n < max) { /* More greed allowed? */
4974                 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor);
4975                 cur_curlyx->u.curlyx.lastloc = locinput;
4976                 REGCP_SET(ST.lastcp);
4977                 PUSH_STATE_GOTO(WHILEM_A_max, A);
4978                 assert(0); /* NOTREACHED */
4979             }
4980             goto do_whilem_B_max;
4981         }
4982         assert(0); /* NOTREACHED */
4983
4984         case WHILEM_B_min: /* just matched B in a minimal match */
4985         case WHILEM_B_max: /* just matched B in a maximal match */
4986             cur_curlyx = ST.save_curlyx;
4987             sayYES;
4988             assert(0); /* NOTREACHED */
4989
4990         case WHILEM_B_max_fail: /* just failed to match B in a maximal match */
4991             cur_curlyx = ST.save_curlyx;
4992             cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
4993             cur_curlyx->u.curlyx.count--;
4994             CACHEsayNO;
4995             assert(0); /* NOTREACHED */
4996
4997         case WHILEM_A_min_fail: /* just failed to match A in a minimal match */
4998             /* FALL THROUGH */
4999         case WHILEM_A_pre_fail: /* just failed to match even minimal A */
5000             REGCP_UNWIND(ST.lastcp);
5001             regcppop(rex);
5002             cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
5003             cur_curlyx->u.curlyx.count--;
5004             CACHEsayNO;
5005             assert(0); /* NOTREACHED */
5006
5007         case WHILEM_A_max_fail: /* just failed to match A in a maximal match */
5008             REGCP_UNWIND(ST.lastcp);
5009             regcppop(rex);      /* Restore some previous $<digit>s? */
5010             PL_reginput = locinput;
5011             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
5012                 "%*s  whilem: failed, trying continuation...\n",
5013                 REPORT_CODE_OFF+depth*2, "")
5014             );
5015           do_whilem_B_max:
5016             if (cur_curlyx->u.curlyx.count >= REG_INFTY
5017                 && ckWARN(WARN_REGEXP)
5018                 && !(PL_reg_flags & RF_warned))
5019             {
5020                 PL_reg_flags |= RF_warned;
5021                 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
5022                      "Complex regular subexpression recursion limit (%d) "
5023                      "exceeded",
5024                      REG_INFTY - 1);
5025             }
5026
5027             /* now try B */
5028             ST.save_curlyx = cur_curlyx;
5029             cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
5030             PUSH_YES_STATE_GOTO(WHILEM_B_max, ST.save_curlyx->u.curlyx.B);
5031             assert(0); /* NOTREACHED */
5032
5033         case WHILEM_B_min_fail: /* just failed to match B in a minimal match */
5034             cur_curlyx = ST.save_curlyx;
5035             REGCP_UNWIND(ST.lastcp);
5036             regcppop(rex);
5037
5038             if (cur_curlyx->u.curlyx.count >= /*max*/ARG2(cur_curlyx->u.curlyx.me)) {
5039                 /* Maximum greed exceeded */
5040                 if (cur_curlyx->u.curlyx.count >= REG_INFTY
5041                     && ckWARN(WARN_REGEXP)
5042                     && !(PL_reg_flags & RF_warned))
5043                 {
5044                     PL_reg_flags |= RF_warned;
5045                     Perl_warner(aTHX_ packWARN(WARN_REGEXP),
5046                         "Complex regular subexpression recursion "
5047                         "limit (%d) exceeded",
5048                         REG_INFTY - 1);
5049                 }
5050                 cur_curlyx->u.curlyx.count--;
5051                 CACHEsayNO;
5052             }
5053
5054             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
5055                 "%*s  trying longer...\n", REPORT_CODE_OFF+depth*2, "")
5056             );
5057             /* Try grabbing another A and see if it helps. */
5058             PL_reginput = locinput;
5059             cur_curlyx->u.curlyx.lastloc = locinput;
5060             ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor);
5061             REGCP_SET(ST.lastcp);
5062             PUSH_STATE_GOTO(WHILEM_A_min,
5063                 /*A*/ NEXTOPER(ST.save_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS);
5064             assert(0); /* NOTREACHED */
5065
5066 #undef  ST
5067 #define ST st->u.branch
5068
5069         case BRANCHJ:       /*  /(...|A|...)/ with long next pointer */
5070             next = scan + ARG(scan);
5071             if (next == scan)
5072                 next = NULL;
5073             scan = NEXTOPER(scan);
5074             /* FALL THROUGH */
5075
5076         case BRANCH:        /*  /(...|A|...)/ */
5077             scan = NEXTOPER(scan); /* scan now points to inner node */
5078             ST.lastparen = rex->lastparen;
5079             ST.lastcloseparen = rex->lastcloseparen;
5080             ST.next_branch = next;
5081             REGCP_SET(ST.cp);
5082             PL_reginput = locinput;
5083
5084             /* Now go into the branch */
5085             if (has_cutgroup) {
5086                 PUSH_YES_STATE_GOTO(BRANCH_next, scan);    
5087             } else {
5088                 PUSH_STATE_GOTO(BRANCH_next, scan);
5089             }
5090             assert(0); /* NOTREACHED */
5091         case CUTGROUP:
5092             PL_reginput = locinput;
5093             sv_yes_mark = st->u.mark.mark_name = scan->flags ? NULL :
5094                 MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
5095             PUSH_STATE_GOTO(CUTGROUP_next,next);
5096             assert(0); /* NOTREACHED */
5097         case CUTGROUP_next_fail:
5098             do_cutgroup = 1;
5099             no_final = 1;
5100             if (st->u.mark.mark_name)
5101                 sv_commit = st->u.mark.mark_name;
5102             sayNO;          
5103             assert(0); /* NOTREACHED */
5104         case BRANCH_next:
5105             sayYES;
5106             assert(0); /* NOTREACHED */
5107         case BRANCH_next_fail: /* that branch failed; try the next, if any */
5108             if (do_cutgroup) {
5109                 do_cutgroup = 0;
5110                 no_final = 0;
5111             }
5112             REGCP_UNWIND(ST.cp);
5113             UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
5114             scan = ST.next_branch;
5115             /* no more branches? */
5116             if (!scan || (OP(scan) != BRANCH && OP(scan) != BRANCHJ)) {
5117                 DEBUG_EXECUTE_r({
5118                     PerlIO_printf( Perl_debug_log,
5119                         "%*s  %sBRANCH failed...%s\n",
5120                         REPORT_CODE_OFF+depth*2, "", 
5121                         PL_colors[4],
5122                         PL_colors[5] );
5123                 });
5124                 sayNO_SILENT;
5125             }
5126             continue; /* execute next BRANCH[J] op */
5127             assert(0); /* NOTREACHED */
5128     
5129         case MINMOD:
5130             minmod = 1;
5131             break;
5132
5133 #undef  ST
5134 #define ST st->u.curlym
5135
5136         case CURLYM:    /* /A{m,n}B/ where A is fixed-length */
5137
5138             /* This is an optimisation of CURLYX that enables us to push
5139              * only a single backtracking state, no matter how many matches
5140              * there are in {m,n}. It relies on the pattern being constant
5141              * length, with no parens to influence future backrefs
5142              */
5143
5144             ST.me = scan;
5145             scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
5146
5147             ST.lastparen      = rex->lastparen;
5148             ST.lastcloseparen = rex->lastcloseparen;
5149
5150             /* if paren positive, emulate an OPEN/CLOSE around A */
5151             if (ST.me->flags) {
5152                 U32 paren = ST.me->flags;
5153                 if (paren > PL_regsize)
5154                     PL_regsize = paren;
5155                 scan += NEXT_OFF(scan); /* Skip former OPEN. */
5156             }
5157             ST.A = scan;
5158             ST.B = next;
5159             ST.alen = 0;
5160             ST.count = 0;
5161             ST.minmod = minmod;
5162             minmod = 0;
5163             ST.c1 = CHRTEST_UNINIT;
5164             REGCP_SET(ST.cp);
5165
5166             if (!(ST.minmod ? ARG1(ST.me) : ARG2(ST.me))) /* min/max */
5167                 goto curlym_do_B;
5168
5169           curlym_do_A: /* execute the A in /A{m,n}B/  */
5170             PL_reginput = locinput;
5171             PUSH_YES_STATE_GOTO(CURLYM_A, ST.A); /* match A */
5172             assert(0); /* NOTREACHED */
5173
5174         case CURLYM_A: /* we've just matched an A */
5175             locinput = st->locinput;
5176             nextchr = UCHARAT(locinput);
5177
5178             ST.count++;
5179             /* after first match, determine A's length: u.curlym.alen */
5180             if (ST.count == 1) {
5181                 if (PL_reg_match_utf8) {
5182                     char *s = locinput;
5183                     while (s < PL_reginput) {
5184                         ST.alen++;
5185                         s += UTF8SKIP(s);
5186                     }
5187                 }
5188                 else {
5189                     ST.alen = PL_reginput - locinput;
5190                 }
5191                 if (ST.alen == 0)
5192                     ST.count = ST.minmod ? ARG1(ST.me) : ARG2(ST.me);
5193             }
5194             DEBUG_EXECUTE_r(
5195                 PerlIO_printf(Perl_debug_log,
5196                           "%*s  CURLYM now matched %"IVdf" times, len=%"IVdf"...\n",
5197                           (int)(REPORT_CODE_OFF+(depth*2)), "",
5198                           (IV) ST.count, (IV)ST.alen)
5199             );
5200
5201             locinput = PL_reginput;
5202                         
5203             if (cur_eval && cur_eval->u.eval.close_paren && 
5204                 cur_eval->u.eval.close_paren == (U32)ST.me->flags) 
5205                 goto fake_end;
5206                 
5207             {
5208                 I32 max = (ST.minmod ? ARG1(ST.me) : ARG2(ST.me));
5209                 if ( max == REG_INFTY || ST.count < max )
5210                     goto curlym_do_A; /* try to match another A */
5211             }
5212             goto curlym_do_B; /* try to match B */
5213
5214         case CURLYM_A_fail: /* just failed to match an A */
5215             REGCP_UNWIND(ST.cp);
5216
5217             if (ST.minmod || ST.count < ARG1(ST.me) /* min*/ 
5218                 || (cur_eval && cur_eval->u.eval.close_paren &&
5219                     cur_eval->u.eval.close_paren == (U32)ST.me->flags))
5220                 sayNO;
5221
5222           curlym_do_B: /* execute the B in /A{m,n}B/  */
5223             PL_reginput = locinput;
5224             if (ST.c1 == CHRTEST_UNINIT) {
5225                 /* calculate c1 and c2 for possible match of 1st char
5226                  * following curly */
5227                 ST.c1 = ST.c2 = CHRTEST_VOID;
5228                 if (HAS_TEXT(ST.B) || JUMPABLE(ST.B)) {
5229                     regnode *text_node = ST.B;
5230                     if (! HAS_TEXT(text_node))
5231                         FIND_NEXT_IMPT(text_node);
5232                     /* this used to be 
5233                         
5234                         (HAS_TEXT(text_node) && PL_regkind[OP(text_node)] == EXACT)
5235                         
5236                         But the former is redundant in light of the latter.
5237                         
5238                         if this changes back then the macro for 
5239                         IS_TEXT and friends need to change.
5240                      */
5241                     if (PL_regkind[OP(text_node)] == EXACT)
5242                     {
5243                         
5244                         ST.c1 = (U8)*STRING(text_node);
5245                         switch (OP(text_node)) {
5246                             case EXACTF: ST.c2 = PL_fold[ST.c1]; break;
5247                             case EXACTFA:
5248                             case EXACTFU_SS:
5249                             case EXACTFU_TRICKYFOLD:
5250                             case EXACTFU: ST.c2 = PL_fold_latin1[ST.c1]; break;
5251                             case EXACTFL: ST.c2 = PL_fold_locale[ST.c1]; break;
5252                             default: ST.c2 = ST.c1;
5253                         }
5254                     }
5255                 }
5256             }
5257
5258             DEBUG_EXECUTE_r(
5259                 PerlIO_printf(Perl_debug_log,
5260                     "%*s  CURLYM trying tail with matches=%"IVdf"...\n",
5261                     (int)(REPORT_CODE_OFF+(depth*2)),
5262                     "", (IV)ST.count)
5263                 );
5264             if (ST.c1 != CHRTEST_VOID
5265                     && UCHARAT(PL_reginput) != ST.c1
5266                     && UCHARAT(PL_reginput) != ST.c2)
5267             {
5268                 /* simulate B failing */
5269                 DEBUG_OPTIMISE_r(
5270                     PerlIO_printf(Perl_debug_log,
5271                         "%*s  CURLYM Fast bail c1=%"IVdf" c2=%"IVdf"\n",
5272                         (int)(REPORT_CODE_OFF+(depth*2)),"",
5273                         (IV)ST.c1,(IV)ST.c2
5274                 ));
5275                 state_num = CURLYM_B_fail;
5276                 goto reenter_switch;
5277             }
5278
5279             if (ST.me->flags) {
5280                 /* emulate CLOSE: mark current A as captured */
5281                 I32 paren = ST.me->flags;
5282                 if (ST.count) {
5283                     rex->offs[paren].start
5284                         = HOPc(PL_reginput, -ST.alen) - PL_bostr;
5285                     rex->offs[paren].end = PL_reginput - PL_bostr;
5286                     if ((U32)paren > rex->lastparen)
5287                         rex->lastparen = paren;
5288                     rex->lastcloseparen = paren;
5289                 }
5290                 else
5291                     rex->offs[paren].end = -1;
5292                 if (cur_eval && cur_eval->u.eval.close_paren &&
5293                     cur_eval->u.eval.close_paren == (U32)ST.me->flags) 
5294                 {
5295                     if (ST.count) 
5296                         goto fake_end;
5297                     else
5298                         sayNO;
5299                 }
5300             }
5301             
5302             PUSH_STATE_GOTO(CURLYM_B, ST.B); /* match B */
5303             assert(0); /* NOTREACHED */
5304
5305         case CURLYM_B_fail: /* just failed to match a B */
5306             REGCP_UNWIND(ST.cp);
5307             UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
5308             if (ST.minmod) {
5309                 I32 max = ARG2(ST.me);
5310                 if (max != REG_INFTY && ST.count == max)
5311                     sayNO;
5312                 goto curlym_do_A; /* try to match a further A */
5313             }
5314             /* backtrack one A */
5315             if (ST.count == ARG1(ST.me) /* min */)
5316                 sayNO;
5317             ST.count--;
5318             locinput = HOPc(locinput, -ST.alen);
5319             goto curlym_do_B; /* try to match B */
5320
5321 #undef ST
5322 #define ST st->u.curly
5323
5324 #define CURLY_SETPAREN(paren, success) \
5325     if (paren) { \
5326         if (success) { \
5327             rex->offs[paren].start = HOPc(locinput, -1) - PL_bostr; \
5328             rex->offs[paren].end = locinput - PL_bostr; \
5329             if (paren > rex->lastparen) \
5330                 rex->lastparen = paren; \
5331             rex->lastcloseparen = paren; \
5332         } \
5333         else { \
5334             rex->offs[paren].end = -1; \
5335             rex->lastparen      = ST.lastparen; \
5336             rex->lastcloseparen = ST.lastcloseparen; \
5337         } \
5338     }
5339
5340         case STAR:              /*  /A*B/ where A is width 1 */
5341             ST.paren = 0;
5342             ST.min = 0;
5343             ST.max = REG_INFTY;
5344             scan = NEXTOPER(scan);
5345             goto repeat;
5346         case PLUS:              /*  /A+B/ where A is width 1 */
5347             ST.paren = 0;
5348             ST.min = 1;
5349             ST.max = REG_INFTY;
5350             scan = NEXTOPER(scan);
5351             goto repeat;
5352         case CURLYN:            /*  /(A){m,n}B/ where A is width 1 */
5353             ST.paren = scan->flags;     /* Which paren to set */
5354             ST.lastparen      = rex->lastparen;
5355             ST.lastcloseparen = rex->lastcloseparen;
5356             if (ST.paren > PL_regsize)
5357                 PL_regsize = ST.paren;
5358             ST.min = ARG1(scan);  /* min to match */
5359             ST.max = ARG2(scan);  /* max to match */
5360             if (cur_eval && cur_eval->u.eval.close_paren &&
5361                 cur_eval->u.eval.close_paren == (U32)ST.paren) {
5362                 ST.min=1;
5363                 ST.max=1;
5364             }
5365             scan = regnext(NEXTOPER(scan) + NODE_STEP_REGNODE);
5366             goto repeat;
5367         case CURLY:             /*  /A{m,n}B/ where A is width 1 */
5368             ST.paren = 0;
5369             ST.min = ARG1(scan);  /* min to match */
5370             ST.max = ARG2(scan);  /* max to match */
5371             scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
5372           repeat:
5373             /*
5374             * Lookahead to avoid useless match attempts
5375             * when we know what character comes next.
5376             *
5377             * Used to only do .*x and .*?x, but now it allows
5378             * for )'s, ('s and (?{ ... })'s to be in the way
5379             * of the quantifier and the EXACT-like node.  -- japhy
5380             */
5381
5382             if (ST.min > ST.max) /* XXX make this a compile-time check? */
5383                 sayNO;
5384             if (HAS_TEXT(next) || JUMPABLE(next)) {
5385                 U8 *s;
5386                 regnode *text_node = next;
5387
5388                 if (! HAS_TEXT(text_node)) 
5389                     FIND_NEXT_IMPT(text_node);
5390
5391                 if (! HAS_TEXT(text_node))
5392                     ST.c1 = ST.c2 = CHRTEST_VOID;
5393                 else {
5394                     if ( PL_regkind[OP(text_node)] != EXACT ) {
5395                         ST.c1 = ST.c2 = CHRTEST_VOID;
5396                         goto assume_ok_easy;
5397                     }
5398                     else
5399                         s = (U8*)STRING(text_node);
5400                     
5401                     /*  Currently we only get here when 
5402                         
5403                         PL_rekind[OP(text_node)] == EXACT
5404                     
5405                         if this changes back then the macro for IS_TEXT and 
5406                         friends need to change. */
5407                     if (!UTF_PATTERN) {
5408                         ST.c1 = *s;
5409                         switch (OP(text_node)) {
5410                             case EXACTF: ST.c2 = PL_fold[ST.c1]; break;
5411                             case EXACTFA:
5412                             case EXACTFU_SS:
5413                             case EXACTFU_TRICKYFOLD:
5414                             case EXACTFU: ST.c2 = PL_fold_latin1[ST.c1]; break;
5415                             case EXACTFL: ST.c2 = PL_fold_locale[ST.c1]; break;
5416                             default: ST.c2 = ST.c1; break;
5417                         }
5418                     }
5419                     else { /* UTF_PATTERN */
5420                         if (IS_TEXTFU(text_node) || IS_TEXTF(text_node)) {
5421                              STRLEN ulen;
5422                              U8 tmpbuf[UTF8_MAXBYTES_CASE+1];
5423
5424                              to_utf8_fold((U8*)s, tmpbuf, &ulen);
5425                              ST.c1 = ST.c2 = utf8n_to_uvchr(tmpbuf, UTF8_MAXLEN, 0,
5426                                                     uniflags);
5427                         }
5428                         else {
5429                             ST.c2 = ST.c1 = utf8n_to_uvchr(s, UTF8_MAXBYTES, 0,
5430                                                      uniflags);
5431                         }
5432                     }
5433                 }
5434             }
5435             else
5436                 ST.c1 = ST.c2 = CHRTEST_VOID;
5437         assume_ok_easy:
5438
5439             ST.A = scan;
5440             ST.B = next;
5441             PL_reginput = locinput;
5442             if (minmod) {
5443                 minmod = 0;
5444                 if (ST.min && regrepeat(rex, ST.A, ST.min, depth) < ST.min)
5445                     sayNO;
5446                 ST.count = ST.min;
5447                 locinput = PL_reginput;
5448                 REGCP_SET(ST.cp);
5449                 if (ST.c1 == CHRTEST_VOID)
5450                     goto curly_try_B_min;
5451
5452                 ST.oldloc = locinput;
5453
5454                 /* set ST.maxpos to the furthest point along the
5455                  * string that could possibly match */
5456                 if  (ST.max == REG_INFTY) {
5457                     ST.maxpos = PL_regeol - 1;
5458                     if (utf8_target)
5459                         while (UTF8_IS_CONTINUATION(*(U8*)ST.maxpos))
5460                             ST.maxpos--;
5461                 }
5462                 else if (utf8_target) {
5463                     int m = ST.max - ST.min;
5464                     for (ST.maxpos = locinput;
5465                          m >0 && ST.maxpos + UTF8SKIP(ST.maxpos) <= PL_regeol; m--)
5466                         ST.maxpos += UTF8SKIP(ST.maxpos);
5467                 }
5468                 else {
5469                     ST.maxpos = locinput + ST.max - ST.min;
5470                     if (ST.maxpos >= PL_regeol)
5471                         ST.maxpos = PL_regeol - 1;
5472                 }
5473                 goto curly_try_B_min_known;
5474
5475             }
5476             else {
5477                 ST.count = regrepeat(rex, ST.A, ST.max, depth);
5478                 locinput = PL_reginput;
5479                 if (ST.count < ST.min)
5480                     sayNO;
5481                 if ((ST.count > ST.min)
5482                     && (PL_regkind[OP(ST.B)] == EOL) && (OP(ST.B) != MEOL))
5483                 {
5484                     /* A{m,n} must come at the end of the string, there's
5485                      * no point in backing off ... */
5486                     ST.min = ST.count;
5487                     /* ...except that $ and \Z can match before *and* after
5488                        newline at the end.  Consider "\n\n" =~ /\n+\Z\n/.
5489                        We may back off by one in this case. */
5490                     if (UCHARAT(PL_reginput - 1) == '\n' && OP(ST.B) != EOS)
5491                         ST.min--;
5492                 }
5493                 REGCP_SET(ST.cp);
5494                 goto curly_try_B_max;
5495             }
5496             assert(0); /* NOTREACHED */
5497
5498
5499         case CURLY_B_min_known_fail:
5500             /* failed to find B in a non-greedy match where c1,c2 valid */
5501
5502             PL_reginput = locinput;     /* Could be reset... */
5503             REGCP_UNWIND(ST.cp);
5504             if (ST.paren) {
5505                 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
5506             }
5507             /* Couldn't or didn't -- move forward. */
5508             ST.oldloc = locinput;
5509             if (utf8_target)
5510                 locinput += UTF8SKIP(locinput);
5511             else
5512                 locinput++;
5513             ST.count++;
5514           curly_try_B_min_known:
5515              /* find the next place where 'B' could work, then call B */
5516             {
5517                 int n;
5518                 if (utf8_target) {
5519                     n = (ST.oldloc == locinput) ? 0 : 1;
5520                     if (ST.c1 == ST.c2) {
5521                         STRLEN len;
5522                         /* set n to utf8_distance(oldloc, locinput) */
5523                         while (locinput <= ST.maxpos &&
5524                                utf8n_to_uvchr((U8*)locinput,
5525                                               UTF8_MAXBYTES, &len,
5526                                               uniflags) != (UV)ST.c1) {
5527                             locinput += len;
5528                             n++;
5529                         }
5530                     }
5531                     else {
5532                         /* set n to utf8_distance(oldloc, locinput) */
5533                         while (locinput <= ST.maxpos) {
5534                             STRLEN len;
5535                             const UV c = utf8n_to_uvchr((U8*)locinput,
5536                                                   UTF8_MAXBYTES, &len,
5537                                                   uniflags);
5538                             if (c == (UV)ST.c1 || c == (UV)ST.c2)
5539                                 break;
5540                             locinput += len;
5541                             n++;
5542                         }
5543                     }
5544                 }
5545                 else {
5546                     if (ST.c1 == ST.c2) {
5547                         while (locinput <= ST.maxpos &&
5548                                UCHARAT(locinput) != ST.c1)
5549                             locinput++;
5550                     }
5551                     else {
5552                         while (locinput <= ST.maxpos
5553                                && UCHARAT(locinput) != ST.c1
5554                                && UCHARAT(locinput) != ST.c2)
5555                             locinput++;
5556                     }
5557                     n = locinput - ST.oldloc;
5558                 }
5559                 if (locinput > ST.maxpos)
5560                     sayNO;
5561                 /* PL_reginput == oldloc now */
5562                 if (n) {
5563                     ST.count += n;
5564                     if (regrepeat(rex, ST.A, n, depth) < n)
5565                         sayNO;
5566                 }
5567                 PL_reginput = locinput;
5568                 CURLY_SETPAREN(ST.paren, ST.count);
5569                 if (cur_eval && cur_eval->u.eval.close_paren && 
5570                     cur_eval->u.eval.close_paren == (U32)ST.paren) {
5571                     goto fake_end;
5572                 }
5573                 PUSH_STATE_GOTO(CURLY_B_min_known, ST.B);
5574             }
5575             assert(0); /* NOTREACHED */
5576
5577
5578         case CURLY_B_min_fail:
5579             /* failed to find B in a non-greedy match where c1,c2 invalid */
5580
5581             REGCP_UNWIND(ST.cp);
5582             if (ST.paren) {
5583                 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
5584             }
5585             /* failed -- move forward one */
5586             PL_reginput = locinput;
5587             if (regrepeat(rex, ST.A, 1, depth)) {
5588                 ST.count++;
5589                 locinput = PL_reginput;
5590                 if (ST.count <= ST.max || (ST.max == REG_INFTY &&
5591                         ST.count > 0)) /* count overflow ? */
5592                 {
5593                   curly_try_B_min:
5594                     CURLY_SETPAREN(ST.paren, ST.count);
5595                     if (cur_eval && cur_eval->u.eval.close_paren &&
5596                         cur_eval->u.eval.close_paren == (U32)ST.paren) {
5597                         goto fake_end;
5598                     }
5599                     PUSH_STATE_GOTO(CURLY_B_min, ST.B);
5600                 }
5601             }
5602             sayNO;
5603             assert(0); /* NOTREACHED */
5604
5605
5606         curly_try_B_max:
5607             /* a successful greedy match: now try to match B */
5608             if (cur_eval && cur_eval->u.eval.close_paren &&
5609                 cur_eval->u.eval.close_paren == (U32)ST.paren) {
5610                 goto fake_end;
5611             }
5612             {
5613                 UV c = 0;
5614                 if (ST.c1 != CHRTEST_VOID)
5615                     c = utf8_target ? utf8n_to_uvchr((U8*)PL_reginput,
5616                                            UTF8_MAXBYTES, 0, uniflags)
5617                                 : (UV) UCHARAT(PL_reginput);
5618                 /* If it could work, try it. */
5619                 if (ST.c1 == CHRTEST_VOID || c == (UV)ST.c1 || c == (UV)ST.c2) {
5620                     CURLY_SETPAREN(ST.paren, ST.count);
5621                     PUSH_STATE_GOTO(CURLY_B_max, ST.B);
5622                     assert(0); /* NOTREACHED */
5623                 }
5624             }
5625             /* FALL THROUGH */
5626         case CURLY_B_max_fail:
5627             /* failed to find B in a greedy match */
5628
5629             REGCP_UNWIND(ST.cp);
5630             if (ST.paren) {
5631                 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
5632             }
5633             /*  back up. */
5634             if (--ST.count < ST.min)
5635                 sayNO;
5636             PL_reginput = locinput = HOPc(locinput, -1);
5637             goto curly_try_B_max;
5638
5639 #undef ST
5640
5641         case END:
5642             fake_end:
5643             if (cur_eval) {
5644                 /* we've just finished A in /(??{A})B/; now continue with B */
5645                 st->u.eval.toggle_reg_flags
5646                             = cur_eval->u.eval.toggle_reg_flags;
5647                 PL_reg_flags ^= st->u.eval.toggle_reg_flags; 
5648
5649                 st->u.eval.prev_rex = rex_sv;           /* inner */
5650                 st->u.eval.cp = regcppush(rex, 0); /* Save *all* the positions. */
5651                 rex_sv = cur_eval->u.eval.prev_rex;
5652                 SET_reg_curpm(rex_sv);
5653                 rex = (struct regexp *)SvANY(rex_sv);
5654                 rexi = RXi_GET(rex);
5655                 cur_curlyx = cur_eval->u.eval.prev_curlyx;
5656
5657                 REGCP_SET(st->u.eval.lastcp);
5658                 PL_reginput = locinput;
5659
5660                 /* Restore parens of the outer rex without popping the
5661                  * savestack */
5662                 S_regcp_restore(aTHX_ rex, cur_eval->u.eval.lastcp);
5663
5664                 st->u.eval.prev_eval = cur_eval;
5665                 cur_eval = cur_eval->u.eval.prev_eval;
5666                 DEBUG_EXECUTE_r(
5667                     PerlIO_printf(Perl_debug_log, "%*s  EVAL trying tail ... %"UVxf"\n",
5668                                       REPORT_CODE_OFF+depth*2, "",PTR2UV(cur_eval)););
5669                 if ( nochange_depth )
5670                     nochange_depth--;
5671
5672                 PUSH_YES_STATE_GOTO(EVAL_AB,
5673                         st->u.eval.prev_eval->u.eval.B); /* match B */
5674             }
5675
5676             if (locinput < reginfo->till) {
5677                 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
5678                                       "%sMatch possible, but length=%ld is smaller than requested=%ld, failing!%s\n",
5679                                       PL_colors[4],
5680                                       (long)(locinput - PL_reg_starttry),
5681                                       (long)(reginfo->till - PL_reg_starttry),
5682                                       PL_colors[5]));
5683                                               
5684                 sayNO_SILENT;           /* Cannot match: too short. */
5685             }
5686             PL_reginput = locinput;     /* put where regtry can find it */
5687             sayYES;                     /* Success! */
5688
5689         case SUCCEED: /* successful SUSPEND/UNLESSM/IFMATCH/CURLYM */
5690             DEBUG_EXECUTE_r(
5691             PerlIO_printf(Perl_debug_log,
5692                 "%*s  %ssubpattern success...%s\n",
5693                 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5]));
5694             PL_reginput = locinput;     /* put where regtry can find it */
5695             sayYES;                     /* Success! */
5696
5697 #undef  ST
5698 #define ST st->u.ifmatch
5699
5700         case SUSPEND:   /* (?>A) */
5701             ST.wanted = 1;
5702             PL_reginput = locinput;
5703             goto do_ifmatch;    
5704
5705         case UNLESSM:   /* -ve lookaround: (?!A), or with flags, (?<!A) */
5706             ST.wanted = 0;
5707             goto ifmatch_trivial_fail_test;
5708
5709         case IFMATCH:   /* +ve lookaround: (?=A), or with flags, (?<=A) */
5710             ST.wanted = 1;
5711           ifmatch_trivial_fail_test:
5712             if (scan->flags) {
5713                 char * const s = HOPBACKc(locinput, scan->flags);
5714                 if (!s) {
5715                     /* trivial fail */
5716                     if (logical) {
5717                         logical = 0;
5718                         sw = 1 - cBOOL(ST.wanted);
5719                     }
5720                     else if (ST.wanted)
5721                         sayNO;
5722                     next = scan + ARG(scan);
5723                     if (next == scan)
5724                         next = NULL;
5725                     break;
5726                 }
5727                 PL_reginput = s;
5728             }
5729             else
5730                 PL_reginput = locinput;
5731
5732           do_ifmatch:
5733             ST.me = scan;
5734             ST.logical = logical;
5735             logical = 0; /* XXX: reset state of logical once it has been saved into ST */
5736             
5737             /* execute body of (?...A) */
5738             PUSH_YES_STATE_GOTO(IFMATCH_A, NEXTOPER(NEXTOPER(scan)));
5739             assert(0); /* NOTREACHED */
5740
5741         case IFMATCH_A_fail: /* body of (?...A) failed */
5742             ST.wanted = !ST.wanted;
5743             /* FALL THROUGH */
5744
5745         case IFMATCH_A: /* body of (?...A) succeeded */
5746             if (ST.logical) {
5747                 sw = cBOOL(ST.wanted);
5748             }
5749             else if (!ST.wanted)
5750                 sayNO;
5751
5752             if (OP(ST.me) == SUSPEND)
5753                 locinput = PL_reginput;
5754             else {
5755                 locinput = PL_reginput = st->locinput;
5756                 nextchr = UCHARAT(locinput);
5757             }
5758             scan = ST.me + ARG(ST.me);
5759             if (scan == ST.me)
5760                 scan = NULL;
5761             continue; /* execute B */
5762
5763 #undef ST
5764
5765         case LONGJMP:
5766             next = scan + ARG(scan);
5767             if (next == scan)
5768                 next = NULL;
5769             break;
5770         case COMMIT:
5771             reginfo->cutpoint = PL_regeol;
5772             /* FALLTHROUGH */
5773         case PRUNE:
5774             PL_reginput = locinput;
5775             if (!scan->flags)
5776                 sv_yes_mark = sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
5777             PUSH_STATE_GOTO(COMMIT_next,next);
5778             assert(0); /* NOTREACHED */
5779         case COMMIT_next_fail:
5780             no_final = 1;    
5781             /* FALLTHROUGH */       
5782         case OPFAIL:
5783             sayNO;
5784             assert(0); /* NOTREACHED */
5785
5786 #define ST st->u.mark
5787         case MARKPOINT:
5788             ST.prev_mark = mark_state;
5789             ST.mark_name = sv_commit = sv_yes_mark 
5790                 = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
5791             mark_state = st;
5792             ST.mark_loc = PL_reginput = locinput;
5793             PUSH_YES_STATE_GOTO(MARKPOINT_next,next);
5794             assert(0); /* NOTREACHED */
5795         case MARKPOINT_next:
5796             mark_state = ST.prev_mark;
5797             sayYES;
5798             assert(0); /* NOTREACHED */
5799         case MARKPOINT_next_fail:
5800             if (popmark && sv_eq(ST.mark_name,popmark)) 
5801             {
5802                 if (ST.mark_loc > startpoint)
5803                     reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
5804                 popmark = NULL; /* we found our mark */
5805                 sv_commit = ST.mark_name;
5806
5807                 DEBUG_EXECUTE_r({
5808                         PerlIO_printf(Perl_debug_log,
5809                             "%*s  %ssetting cutpoint to mark:%"SVf"...%s\n",
5810                             REPORT_CODE_OFF+depth*2, "", 
5811                             PL_colors[4], SVfARG(sv_commit), PL_colors[5]);
5812                 });
5813             }
5814             mark_state = ST.prev_mark;
5815             sv_yes_mark = mark_state ? 
5816                 mark_state->u.mark.mark_name : NULL;
5817             sayNO;
5818             assert(0); /* NOTREACHED */
5819         case SKIP:
5820             PL_reginput = locinput;
5821             if (scan->flags) {
5822                 /* (*SKIP) : if we fail we cut here*/
5823                 ST.mark_name = NULL;
5824                 ST.mark_loc = locinput;
5825                 PUSH_STATE_GOTO(SKIP_next,next);    
5826             } else {
5827                 /* (*SKIP:NAME) : if there is a (*MARK:NAME) fail where it was, 
5828                    otherwise do nothing.  Meaning we need to scan 
5829                  */
5830                 regmatch_state *cur = mark_state;
5831                 SV *find = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
5832                 
5833                 while (cur) {
5834                     if ( sv_eq( cur->u.mark.mark_name, 
5835                                 find ) ) 
5836                     {
5837                         ST.mark_name = find;
5838                         PUSH_STATE_GOTO( SKIP_next, next );
5839                     }
5840                     cur = cur->u.mark.prev_mark;
5841                 }
5842             }    
5843             /* Didn't find our (*MARK:NAME) so ignore this (*SKIP:NAME) */
5844             break;    
5845         case SKIP_next_fail:
5846             if (ST.mark_name) {
5847                 /* (*CUT:NAME) - Set up to search for the name as we 
5848                    collapse the stack*/
5849                 popmark = ST.mark_name;    
5850             } else {
5851                 /* (*CUT) - No name, we cut here.*/
5852                 if (ST.mark_loc > startpoint)
5853                     reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
5854                 /* but we set sv_commit to latest mark_name if there
5855                    is one so they can test to see how things lead to this
5856                    cut */    
5857                 if (mark_state) 
5858                     sv_commit=mark_state->u.mark.mark_name;                 
5859             } 
5860             no_final = 1; 
5861             sayNO;
5862             assert(0); /* NOTREACHED */
5863 #undef ST
5864         case LNBREAK:
5865             if ((n=is_LNBREAK(locinput,utf8_target))) {
5866                 locinput += n;
5867                 nextchr = UCHARAT(locinput);
5868             } else
5869                 sayNO;
5870             break;
5871
5872 #define CASE_CLASS(nAmE)                              \
5873         case nAmE:                                    \
5874             if (locinput >= PL_regeol)                \
5875                 sayNO;                                \
5876             if ((n=is_##nAmE(locinput,utf8_target))) {    \
5877                 locinput += n;                        \
5878                 nextchr = UCHARAT(locinput);          \
5879             } else                                    \
5880                 sayNO;                                \
5881             break;                                    \
5882         case N##nAmE:                                 \
5883             if (locinput >= PL_regeol)                \
5884                 sayNO;                                \
5885             if ((n=is_##nAmE(locinput,utf8_target))) {    \
5886                 sayNO;                                \
5887             } else {                                  \
5888                 locinput += UTF8SKIP(locinput);       \
5889                 nextchr = UCHARAT(locinput);          \
5890             }                                         \
5891             break
5892
5893         CASE_CLASS(VERTWS);
5894         CASE_CLASS(HORIZWS);
5895 #undef CASE_CLASS
5896
5897         default:
5898             PerlIO_printf(Perl_error_log, "%"UVxf" %d\n",
5899                           PTR2UV(scan), OP(scan));
5900             Perl_croak(aTHX_ "regexp memory corruption");
5901             
5902         } /* end switch */ 
5903
5904         /* switch break jumps here */
5905         scan = next; /* prepare to execute the next op and ... */
5906         continue;    /* ... jump back to the top, reusing st */
5907         assert(0); /* NOTREACHED */
5908
5909       push_yes_state:
5910         /* push a state that backtracks on success */
5911         st->u.yes.prev_yes_state = yes_state;
5912         yes_state = st;
5913         /* FALL THROUGH */
5914       push_state:
5915         /* push a new regex state, then continue at scan  */
5916         {
5917             regmatch_state *newst;
5918
5919             DEBUG_STACK_r({
5920                 regmatch_state *cur = st;
5921                 regmatch_state *curyes = yes_state;
5922                 int curd = depth;
5923                 regmatch_slab *slab = PL_regmatch_slab;
5924                 for (;curd > -1;cur--,curd--) {
5925                     if (cur < SLAB_FIRST(slab)) {
5926                         slab = slab->prev;
5927                         cur = SLAB_LAST(slab);
5928                     }
5929                     PerlIO_printf(Perl_error_log, "%*s#%-3d %-10s %s\n",
5930                         REPORT_CODE_OFF + 2 + depth * 2,"",
5931                         curd, PL_reg_name[cur->resume_state],
5932                         (curyes == cur) ? "yes" : ""
5933                     );
5934                     if (curyes == cur)
5935                         curyes = cur->u.yes.prev_yes_state;
5936                 }
5937             } else 
5938                 DEBUG_STATE_pp("push")
5939             );
5940             depth++;
5941             st->locinput = locinput;
5942             newst = st+1; 
5943             if (newst >  SLAB_LAST(PL_regmatch_slab))
5944                 newst = S_push_slab(aTHX);
5945             PL_regmatch_state = newst;
5946
5947             locinput = PL_reginput;
5948             nextchr = UCHARAT(locinput);
5949             st = newst;
5950             continue;
5951             assert(0); /* NOTREACHED */
5952         }
5953     }
5954
5955     /*
5956     * We get here only if there's trouble -- normally "case END" is
5957     * the terminating point.
5958     */
5959     Perl_croak(aTHX_ "corrupted regexp pointers");
5960     /*NOTREACHED*/
5961     sayNO;
5962
5963 yes:
5964     if (yes_state) {
5965         /* we have successfully completed a subexpression, but we must now
5966          * pop to the state marked by yes_state and continue from there */
5967         assert(st != yes_state);
5968 #ifdef DEBUGGING
5969         while (st != yes_state) {
5970             st--;
5971             if (st < SLAB_FIRST(PL_regmatch_slab)) {
5972                 PL_regmatch_slab = PL_regmatch_slab->prev;
5973                 st = SLAB_LAST(PL_regmatch_slab);
5974             }
5975             DEBUG_STATE_r({
5976                 if (no_final) {
5977                     DEBUG_STATE_pp("pop (no final)");        
5978                 } else {
5979                     DEBUG_STATE_pp("pop (yes)");
5980                 }
5981             });
5982             depth--;
5983         }
5984 #else
5985         while (yes_state < SLAB_FIRST(PL_regmatch_slab)
5986             || yes_state > SLAB_LAST(PL_regmatch_slab))
5987         {
5988             /* not in this slab, pop slab */
5989             depth -= (st - SLAB_FIRST(PL_regmatch_slab) + 1);
5990             PL_regmatch_slab = PL_regmatch_slab->prev;
5991             st = SLAB_LAST(PL_regmatch_slab);
5992         }
5993         depth -= (st - yes_state);
5994 #endif
5995         st = yes_state;
5996         yes_state = st->u.yes.prev_yes_state;
5997         PL_regmatch_state = st;
5998         
5999         if (no_final) {
6000             locinput= st->locinput;
6001             nextchr = UCHARAT(locinput);
6002         }
6003         state_num = st->resume_state + no_final;
6004         goto reenter_switch;
6005     }
6006
6007     DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch successful!%s\n",
6008                           PL_colors[4], PL_colors[5]));
6009
6010     if (PL_reg_state.re_state_eval_setup_done) {
6011         /* each successfully executed (?{...}) block does the equivalent of
6012          *   local $^R = do {...}
6013          * When popping the save stack, all these locals would be undone;
6014          * bypass this by setting the outermost saved $^R to the latest
6015          * value */
6016         if (oreplsv != GvSV(PL_replgv))
6017             sv_setsv(oreplsv, GvSV(PL_replgv));
6018     }
6019     result = 1;
6020     goto final_exit;
6021
6022 no:
6023     DEBUG_EXECUTE_r(
6024         PerlIO_printf(Perl_debug_log,
6025             "%*s  %sfailed...%s\n",
6026             REPORT_CODE_OFF+depth*2, "", 
6027             PL_colors[4], PL_colors[5])
6028         );
6029
6030 no_silent:
6031     if (no_final) {
6032         if (yes_state) {
6033             goto yes;
6034         } else {
6035             goto final_exit;
6036         }
6037     }    
6038     if (depth) {
6039         /* there's a previous state to backtrack to */
6040         st--;
6041         if (st < SLAB_FIRST(PL_regmatch_slab)) {
6042             PL_regmatch_slab = PL_regmatch_slab->prev;
6043             st = SLAB_LAST(PL_regmatch_slab);
6044         }
6045         PL_regmatch_state = st;
6046         locinput= st->locinput;
6047         nextchr = UCHARAT(locinput);
6048
6049         DEBUG_STATE_pp("pop");
6050         depth--;
6051         if (yes_state == st)
6052             yes_state = st->u.yes.prev_yes_state;
6053
6054         state_num = st->resume_state + 1; /* failure = success + 1 */
6055         goto reenter_switch;
6056     }
6057     result = 0;
6058
6059   final_exit:
6060     if (rex->intflags & PREGf_VERBARG_SEEN) {
6061         SV *sv_err = get_sv("REGERROR", 1);
6062         SV *sv_mrk = get_sv("REGMARK", 1);
6063         if (result) {
6064             sv_commit = &PL_sv_no;
6065             if (!sv_yes_mark) 
6066                 sv_yes_mark = &PL_sv_yes;
6067         } else {
6068             if (!sv_commit) 
6069                 sv_commit = &PL_sv_yes;
6070             sv_yes_mark = &PL_sv_no;
6071         }
6072         sv_setsv(sv_err, sv_commit);
6073         sv_setsv(sv_mrk, sv_yes_mark);
6074     }
6075
6076
6077     if (last_pushed_cv) {
6078         dSP;
6079         POP_MULTICALL;
6080         PERL_UNUSED_VAR(SP);
6081     }
6082
6083     /* clean up; in particular, free all slabs above current one */
6084     LEAVE_SCOPE(oldsave);
6085
6086     return result;
6087 }
6088
6089 /*
6090  - regrepeat - repeatedly match something simple, report how many
6091  */
6092 /*
6093  * [This routine now assumes that it will only match on things of length 1.
6094  * That was true before, but now we assume scan - reginput is the count,
6095  * rather than incrementing count on every character.  [Er, except utf8.]]
6096  */
6097 STATIC I32
6098 S_regrepeat(pTHX_ const regexp *prog, const regnode *p, I32 max, int depth)
6099 {
6100     dVAR;
6101     char *scan;
6102     I32 c;
6103     char *loceol = PL_regeol;
6104     I32 hardcount = 0;
6105     bool utf8_target = PL_reg_match_utf8;
6106     UV utf8_flags;
6107 #ifndef DEBUGGING
6108     PERL_UNUSED_ARG(depth);
6109 #endif
6110
6111     PERL_ARGS_ASSERT_REGREPEAT;
6112
6113     scan = PL_reginput;
6114     if (max == REG_INFTY)
6115         max = I32_MAX;
6116     else if (max < loceol - scan)
6117         loceol = scan + max;
6118     switch (OP(p)) {
6119     case REG_ANY:
6120         if (utf8_target) {
6121             loceol = PL_regeol;
6122             while (scan < loceol && hardcount < max && *scan != '\n') {
6123                 scan += UTF8SKIP(scan);
6124                 hardcount++;
6125             }
6126         } else {
6127             while (scan < loceol && *scan != '\n')
6128                 scan++;
6129         }
6130         break;
6131     case SANY:
6132         if (utf8_target) {
6133             loceol = PL_regeol;
6134             while (scan < loceol && hardcount < max) {
6135                 scan += UTF8SKIP(scan);
6136                 hardcount++;
6137             }
6138         }
6139         else
6140             scan = loceol;
6141         break;
6142     case CANY:
6143         scan = loceol;
6144         break;
6145     case EXACT:
6146         /* To get here, EXACTish nodes must have *byte* length == 1.  That
6147          * means they match only characters in the string that can be expressed
6148          * as a single byte.  For non-utf8 strings, that means a simple match.
6149          * For utf8 strings, the character matched must be an invariant, or
6150          * downgradable to a single byte.  The pattern's utf8ness is
6151          * irrelevant, as since it's a single byte, it either isn't utf8, or if
6152          * it is, it's an invariant */
6153
6154         c = (U8)*STRING(p);
6155         assert(! UTF_PATTERN || UNI_IS_INVARIANT(c));
6156
6157         if (! utf8_target || UNI_IS_INVARIANT(c)) {
6158             while (scan < loceol && UCHARAT(scan) == c) {
6159                 scan++;
6160             }
6161         }
6162         else {
6163
6164             /* Here, the string is utf8, and the pattern char is different
6165              * in utf8 than not, so can't compare them directly.  Outside the
6166              * loop, find the two utf8 bytes that represent c, and then
6167              * look for those in sequence in the utf8 string */
6168             U8 high = UTF8_TWO_BYTE_HI(c);
6169             U8 low = UTF8_TWO_BYTE_LO(c);
6170             loceol = PL_regeol;
6171
6172             while (hardcount < max
6173                     && scan + 1 < loceol
6174                     && UCHARAT(scan) == high
6175                     && UCHARAT(scan + 1) == low)
6176             {
6177                 scan += 2;
6178                 hardcount++;
6179             }
6180         }
6181         break;
6182     case EXACTFA:
6183         utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
6184         goto do_exactf;
6185
6186     case EXACTFL:
6187         PL_reg_flags |= RF_tainted;
6188         utf8_flags = FOLDEQ_UTF8_LOCALE;
6189         goto do_exactf;
6190
6191     case EXACTF:
6192             utf8_flags = 0;
6193             goto do_exactf;
6194
6195     case EXACTFU_SS:
6196     case EXACTFU_TRICKYFOLD:
6197     case EXACTFU:
6198         utf8_flags = (UTF_PATTERN) ? FOLDEQ_S2_ALREADY_FOLDED : 0;
6199
6200         /* The comments for the EXACT case above apply as well to these fold
6201          * ones */
6202
6203     do_exactf:
6204         c = (U8)*STRING(p);
6205         assert(! UTF_PATTERN || UNI_IS_INVARIANT(c));
6206
6207         if (utf8_target || OP(p) == EXACTFU_SS) { /* Use full Unicode fold matching */
6208             char *tmpeol = loceol;
6209             while (hardcount < max
6210                     && foldEQ_utf8_flags(scan, &tmpeol, 0, utf8_target,
6211                                    STRING(p), NULL, 1, cBOOL(UTF_PATTERN), utf8_flags))
6212             {
6213                 scan = tmpeol;
6214                 tmpeol = loceol;
6215                 hardcount++;
6216             }
6217
6218             /* XXX Note that the above handles properly the German sharp s in
6219              * the pattern matching ss in the string.  But it doesn't handle
6220              * properly cases where the string contains say 'LIGATURE ff' and
6221              * the pattern is 'f+'.  This would require, say, a new function or
6222              * revised interface to foldEQ_utf8(), in which the maximum number
6223              * of characters to match could be passed and it would return how
6224              * many actually did.  This is just one of many cases where
6225              * multi-char folds don't work properly, and so the fix is being
6226              * deferred */
6227         }
6228         else {
6229             U8 folded;
6230
6231             /* Here, the string isn't utf8 and c is a single byte; and either
6232              * the pattern isn't utf8 or c is an invariant, so its utf8ness
6233              * doesn't affect c.  Can just do simple comparisons for exact or
6234              * fold matching. */
6235             switch (OP(p)) {
6236                 case EXACTF: folded = PL_fold[c]; break;
6237                 case EXACTFA:
6238                 case EXACTFU_TRICKYFOLD:
6239                 case EXACTFU: folded = PL_fold_latin1[c]; break;
6240                 case EXACTFL: folded = PL_fold_locale[c]; break;
6241                 default: Perl_croak(aTHX_ "panic: Unexpected op %u", OP(p));
6242             }
6243             while (scan < loceol &&
6244                    (UCHARAT(scan) == c || UCHARAT(scan) == folded))
6245             {
6246                 scan++;
6247             }
6248         }
6249         break;
6250     case ANYOFV:
6251     case ANYOF:
6252         if (utf8_target || OP(p) == ANYOFV) {
6253             STRLEN inclasslen;
6254             loceol = PL_regeol;
6255             inclasslen = loceol - scan;
6256             while (hardcount < max
6257                    && ((inclasslen = loceol - scan) > 0)
6258                    && reginclass(prog, p, (U8*)scan, &inclasslen, utf8_target))
6259             {
6260                 scan += inclasslen;
6261                 hardcount++;
6262             }
6263         } else {
6264             while (scan < loceol && REGINCLASS(prog, p, (U8*)scan))
6265                 scan++;
6266         }
6267         break;
6268     case ALNUMU:
6269         if (utf8_target) {
6270     utf8_wordchar:
6271             loceol = PL_regeol;
6272             LOAD_UTF8_CHARCLASS_ALNUM();
6273             while (hardcount < max && scan < loceol &&
6274                    swash_fetch(PL_utf8_alnum, (U8*)scan, utf8_target))
6275             {
6276                 scan += UTF8SKIP(scan);
6277                 hardcount++;
6278             }
6279         } else {
6280             while (scan < loceol && isWORDCHAR_L1((U8) *scan)) {
6281                 scan++;
6282             }
6283         }
6284         break;
6285     case ALNUM:
6286         if (utf8_target)
6287             goto utf8_wordchar;
6288         while (scan < loceol && isALNUM((U8) *scan)) {
6289             scan++;
6290         }
6291         break;
6292     case ALNUMA:
6293         while (scan < loceol && isWORDCHAR_A((U8) *scan)) {
6294             scan++;
6295         }
6296         break;
6297     case ALNUML:
6298         PL_reg_flags |= RF_tainted;
6299         if (utf8_target) {
6300             loceol = PL_regeol;
6301             while (hardcount < max && scan < loceol &&
6302                    isALNUM_LC_utf8((U8*)scan)) {
6303                 scan += UTF8SKIP(scan);
6304                 hardcount++;
6305             }
6306         } else {
6307             while (scan < loceol && isALNUM_LC(*scan))
6308                 scan++;
6309         }
6310         break;
6311     case NALNUMU:
6312         if (utf8_target) {
6313
6314     utf8_Nwordchar:
6315
6316             loceol = PL_regeol;
6317             LOAD_UTF8_CHARCLASS_ALNUM();
6318             while (hardcount < max && scan < loceol &&
6319                    ! swash_fetch(PL_utf8_alnum, (U8*)scan, utf8_target))
6320             {
6321                 scan += UTF8SKIP(scan);
6322                 hardcount++;
6323             }
6324         } else {
6325             while (scan < loceol && ! isWORDCHAR_L1((U8) *scan)) {
6326                 scan++;
6327             }
6328         }
6329         break;
6330     case NALNUM:
6331         if (utf8_target)
6332             goto utf8_Nwordchar;
6333         while (scan < loceol && ! isALNUM((U8) *scan)) {
6334             scan++;
6335         }
6336         break;
6337
6338     case POSIXA:
6339        while (scan < loceol && _generic_isCC_A((U8) *scan, FLAGS(p))) {
6340             scan++;
6341         }
6342         break;
6343     case NPOSIXA:
6344         if (utf8_target) {
6345             while (scan < loceol && ! _generic_isCC_A((U8) *scan, FLAGS(p))) {
6346                 scan += UTF8SKIP(scan);
6347             }
6348         }
6349         else {
6350             while (scan < loceol && ! _generic_isCC_A((U8) *scan, FLAGS(p))) {
6351                 scan++;
6352             }
6353         }
6354         break;
6355     case NALNUMA:
6356         if (utf8_target) {
6357             while (scan < loceol && ! isWORDCHAR_A((U8) *scan)) {
6358                 scan += UTF8SKIP(scan);
6359             }
6360         }
6361         else {
6362             while (scan < loceol && ! isWORDCHAR_A((U8) *scan)) {
6363                 scan++;
6364             }
6365         }
6366         break;
6367     case NALNUML:
6368         PL_reg_flags |= RF_tainted;
6369         if (utf8_target) {
6370             loceol = PL_regeol;
6371             while (hardcount < max && scan < loceol &&
6372                    !isALNUM_LC_utf8((U8*)scan)) {
6373                 scan += UTF8SKIP(scan);
6374                 hardcount++;
6375             }
6376         } else {
6377             while (scan < loceol && !isALNUM_LC(*scan))
6378                 scan++;
6379         }
6380         break;
6381     case SPACEU:
6382         if (utf8_target) {
6383
6384     utf8_space:
6385
6386             loceol = PL_regeol;
6387             LOAD_UTF8_CHARCLASS_SPACE();
6388             while (hardcount < max && scan < loceol &&
6389                    (*scan == ' ' ||
6390                     swash_fetch(PL_utf8_space,(U8*)scan, utf8_target)))
6391             {
6392                 scan += UTF8SKIP(scan);
6393                 hardcount++;
6394             }
6395             break;
6396         }
6397         else {
6398             while (scan < loceol && isSPACE_L1((U8) *scan)) {
6399                 scan++;
6400             }
6401             break;
6402         }
6403     case SPACE:
6404         if (utf8_target)
6405             goto utf8_space;
6406
6407         while (scan < loceol && isSPACE((U8) *scan)) {
6408             scan++;
6409         }
6410         break;
6411     case SPACEA:
6412         while (scan < loceol && isSPACE_A((U8) *scan)) {
6413             scan++;
6414         }
6415         break;
6416     case SPACEL:
6417         PL_reg_flags |= RF_tainted;
6418         if (utf8_target) {
6419             loceol = PL_regeol;
6420             while (hardcount < max && scan < loceol &&
6421                    isSPACE_LC_utf8((U8*)scan)) {
6422                 scan += UTF8SKIP(scan);
6423                 hardcount++;
6424             }
6425         } else {
6426             while (scan < loceol && isSPACE_LC(*scan))
6427                 scan++;
6428         }
6429         break;
6430     case NSPACEU:
6431         if (utf8_target) {
6432
6433     utf8_Nspace:
6434
6435             loceol = PL_regeol;
6436             LOAD_UTF8_CHARCLASS_SPACE();
6437             while (hardcount < max && scan < loceol &&
6438                    ! (*scan == ' ' ||
6439                       swash_fetch(PL_utf8_space,(U8*)scan, utf8_target)))
6440             {
6441                 scan += UTF8SKIP(scan);
6442                 hardcount++;
6443             }
6444             break;
6445         }
6446         else {
6447             while (scan < loceol && ! isSPACE_L1((U8) *scan)) {
6448                 scan++;
6449             }
6450         }
6451         break;
6452     case NSPACE:
6453         if (utf8_target)
6454             goto utf8_Nspace;
6455
6456         while (scan < loceol && ! isSPACE((U8) *scan)) {
6457             scan++;
6458         }
6459         break;
6460     case NSPACEA:
6461         if (utf8_target) {
6462             while (scan < loceol && ! isSPACE_A((U8) *scan)) {
6463                 scan += UTF8SKIP(scan);
6464             }
6465         }
6466         else {
6467             while (scan < loceol && ! isSPACE_A((U8) *scan)) {
6468                 scan++;
6469             }
6470         }
6471         break;
6472     case NSPACEL:
6473         PL_reg_flags |= RF_tainted;
6474         if (utf8_target) {
6475             loceol = PL_regeol;
6476             while (hardcount < max && scan < loceol &&
6477                    !isSPACE_LC_utf8((U8*)scan)) {
6478                 scan += UTF8SKIP(scan);
6479                 hardcount++;
6480             }
6481         } else {
6482             while (scan < loceol && !isSPACE_LC(*scan))
6483                 scan++;
6484         }
6485         break;
6486     case DIGIT:
6487         if (utf8_target) {
6488             loceol = PL_regeol;
6489             LOAD_UTF8_CHARCLASS_DIGIT();
6490             while (hardcount < max && scan < loceol &&
6491                    swash_fetch(PL_utf8_digit, (U8*)scan, utf8_target)) {
6492                 scan += UTF8SKIP(scan);
6493                 hardcount++;
6494             }
6495         } else {
6496             while (scan < loceol && isDIGIT(*scan))
6497                 scan++;
6498         }
6499         break;
6500     case DIGITA:
6501         while (scan < loceol && isDIGIT_A((U8) *scan)) {
6502             scan++;
6503         }
6504         break;
6505     case DIGITL:
6506         PL_reg_flags |= RF_tainted;
6507         if (utf8_target) {
6508             loceol = PL_regeol;
6509             while (hardcount < max && scan < loceol &&
6510                    isDIGIT_LC_utf8((U8*)scan)) {
6511                 scan += UTF8SKIP(scan);
6512                 hardcount++;
6513             }
6514         } else {
6515             while (scan < loceol && isDIGIT_LC(*scan))
6516                 scan++;
6517         }
6518         break;
6519     case NDIGIT:
6520         if (utf8_target) {
6521             loceol = PL_regeol;
6522             LOAD_UTF8_CHARCLASS_DIGIT();
6523             while (hardcount < max && scan < loceol &&
6524                    !swash_fetch(PL_utf8_digit, (U8*)scan, utf8_target)) {
6525                 scan += UTF8SKIP(scan);
6526                 hardcount++;
6527             }
6528         } else {
6529             while (scan < loceol && !isDIGIT(*scan))
6530                 scan++;
6531         }
6532         break;
6533     case NDIGITA:
6534         if (utf8_target) {
6535             while (scan < loceol && ! isDIGIT_A((U8) *scan)) {
6536                 scan += UTF8SKIP(scan);
6537             }
6538         }
6539         else {
6540             while (scan < loceol && ! isDIGIT_A((U8) *scan)) {
6541                 scan++;
6542             }
6543         }
6544         break;
6545     case NDIGITL:
6546         PL_reg_flags |= RF_tainted;
6547         if (utf8_target) {
6548             loceol = PL_regeol;
6549             while (hardcount < max && scan < loceol &&
6550                    !isDIGIT_LC_utf8((U8*)scan)) {
6551                 scan += UTF8SKIP(scan);
6552                 hardcount++;
6553             }
6554         } else {
6555             while (scan < loceol && !isDIGIT_LC(*scan))
6556                 scan++;
6557         }
6558         break;
6559     case LNBREAK:
6560         if (utf8_target) {
6561             loceol = PL_regeol;
6562             while (hardcount < max && scan < loceol && (c=is_LNBREAK_utf8(scan))) {
6563                 scan += c;
6564                 hardcount++;
6565             }
6566         } else {
6567             /*
6568               LNBREAK can match two latin chars, which is ok,
6569               because we have a null terminated string, but we
6570               have to use hardcount in this situation
6571             */
6572             while (scan < loceol && (c=is_LNBREAK_latin1(scan)))  {
6573                 scan+=c;
6574                 hardcount++;
6575             }
6576         }       
6577         break;
6578     case HORIZWS:
6579         if (utf8_target) {
6580             loceol = PL_regeol;
6581             while (hardcount < max && scan < loceol && (c=is_HORIZWS_utf8(scan))) {
6582                 scan += c;
6583                 hardcount++;
6584             }
6585         } else {
6586             while (scan < loceol && is_HORIZWS_latin1(scan)) 
6587                 scan++;         
6588         }       
6589         break;
6590     case NHORIZWS:
6591         if (utf8_target) {
6592             loceol = PL_regeol;
6593             while (hardcount < max && scan < loceol && !is_HORIZWS_utf8(scan)) {
6594                 scan += UTF8SKIP(scan);
6595                 hardcount++;
6596             }
6597         } else {
6598             while (scan < loceol && !is_HORIZWS_latin1(scan))
6599                 scan++;
6600
6601         }       
6602         break;
6603     case VERTWS:
6604         if (utf8_target) {
6605             loceol = PL_regeol;
6606             while (hardcount < max && scan < loceol && (c=is_VERTWS_utf8(scan))) {
6607                 scan += c;
6608                 hardcount++;
6609             }
6610         } else {
6611             while (scan < loceol && is_VERTWS_latin1(scan)) 
6612                 scan++;
6613
6614         }       
6615         break;
6616     case NVERTWS:
6617         if (utf8_target) {
6618             loceol = PL_regeol;
6619             while (hardcount < max && scan < loceol && !is_VERTWS_utf8(scan)) {
6620                 scan += UTF8SKIP(scan);
6621                 hardcount++;
6622             }
6623         } else {
6624             while (scan < loceol && !is_VERTWS_latin1(scan)) 
6625                 scan++;
6626           
6627         }       
6628         break;
6629
6630     default:            /* Called on something of 0 width. */
6631         break;          /* So match right here or not at all. */
6632     }
6633
6634     if (hardcount)
6635         c = hardcount;
6636     else
6637         c = scan - PL_reginput;
6638     PL_reginput = scan;
6639
6640     DEBUG_r({
6641         GET_RE_DEBUG_FLAGS_DECL;
6642         DEBUG_EXECUTE_r({
6643             SV * const prop = sv_newmortal();
6644             regprop(prog, prop, p);
6645             PerlIO_printf(Perl_debug_log,
6646                         "%*s  %s can match %"IVdf" times out of %"IVdf"...\n",
6647                         REPORT_CODE_OFF + depth*2, "", SvPVX_const(prop),(IV)c,(IV)max);
6648         });
6649     });
6650
6651     return(c);
6652 }
6653
6654
6655 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
6656 /*
6657 - regclass_swash - prepare the utf8 swash.  Wraps the shared core version to
6658 create a copy so that changes the caller makes won't change the shared one
6659  */
6660 SV *
6661 Perl_regclass_swash(pTHX_ const regexp *prog, register const regnode* node, bool doinit, SV** listsvp, SV **altsvp)
6662 {
6663     PERL_ARGS_ASSERT_REGCLASS_SWASH;
6664     return newSVsv(core_regclass_swash(prog, node, doinit, listsvp, altsvp));
6665 }
6666 #endif
6667
6668 STATIC SV *
6669 S_core_regclass_swash(pTHX_ const regexp *prog, register const regnode* node, bool doinit, SV** listsvp, SV **altsvp)
6670 {
6671     /* Returns the swash for the input 'node' in the regex 'prog'.
6672      * If <doinit> is true, will attempt to create the swash if not already
6673      *    done.
6674      * If <listsvp> is non-null, will return the swash initialization string in
6675      *    it.
6676      * If <altsvp> is non-null, will return the alternates to the regular swash
6677      *    in it
6678      * Tied intimately to how regcomp.c sets up the data structure */
6679
6680     dVAR;
6681     SV *sw  = NULL;
6682     SV *si  = NULL;
6683     SV *alt = NULL;
6684     SV*  invlist = NULL;
6685
6686     RXi_GET_DECL(prog,progi);
6687     const struct reg_data * const data = prog ? progi->data : NULL;
6688
6689     PERL_ARGS_ASSERT_CORE_REGCLASS_SWASH;
6690
6691     assert(ANYOF_NONBITMAP(node));
6692
6693     if (data && data->count) {
6694         const U32 n = ARG(node);
6695
6696         if (data->what[n] == 's') {
6697             SV * const rv = MUTABLE_SV(data->data[n]);
6698             AV * const av = MUTABLE_AV(SvRV(rv));
6699             SV **const ary = AvARRAY(av);
6700             bool invlist_has_user_defined_property;
6701         
6702             si = *ary;  /* ary[0] = the string to initialize the swash with */
6703
6704             /* Elements 3 and 4 are either both present or both absent. [3] is
6705              * any inversion list generated at compile time; [4] indicates if
6706              * that inversion list has any user-defined properties in it. */
6707             if (av_len(av) >= 3) {
6708                 invlist = ary[3];
6709                 invlist_has_user_defined_property = cBOOL(SvUV(ary[4]));
6710             }
6711             else {
6712                 invlist = NULL;
6713                 invlist_has_user_defined_property = FALSE;
6714             }
6715
6716             /* Element [1] is reserved for the set-up swash.  If already there,
6717              * return it; if not, create it and store it there */
6718             if (SvROK(ary[1])) {
6719                 sw = ary[1];
6720             }
6721             else if (si && doinit) {
6722
6723                 sw = _core_swash_init("utf8", /* the utf8 package */
6724                                       "", /* nameless */
6725                                       si,
6726                                       1, /* binary */
6727                                       0, /* not from tr/// */
6728                                       FALSE, /* is error if can't find
6729                                                 property */
6730                                       invlist,
6731                                       invlist_has_user_defined_property);
6732                 (void)av_store(av, 1, sw);
6733             }
6734
6735             /* Element [2] is for any multi-char folds.  Note that is a
6736              * fundamentally flawed design, because can't backtrack and try
6737              * again.  See [perl #89774] */
6738             if (SvTYPE(ary[2]) == SVt_PVAV) {
6739                 alt = ary[2];
6740             }
6741         }
6742     }
6743         
6744     if (listsvp) {
6745         SV* matches_string = newSVpvn("", 0);
6746         SV** invlistsvp;
6747
6748         /* Use the swash, if any, which has to have incorporated into it all
6749          * possibilities */
6750         if (   sw
6751             && SvROK(sw)
6752             && SvTYPE(SvRV(sw)) == SVt_PVHV
6753             && (invlistsvp = hv_fetchs(MUTABLE_HV(SvRV(sw)), "INVLIST", FALSE)))
6754         {
6755             invlist = *invlistsvp;
6756         }
6757         else if (si && si != &PL_sv_undef) {
6758
6759             /* If no swash, use the input nitialization string, if available */
6760             sv_catsv(matches_string, si);
6761         }
6762
6763         /* Add the inversion list to whatever we have.  This may have come from
6764          * the swash, or from an input parameter */
6765         if (invlist) {
6766             sv_catsv(matches_string, _invlist_contents(invlist));
6767         }
6768         *listsvp = matches_string;
6769     }
6770
6771     if (altsvp)
6772         *altsvp  = alt;
6773
6774     return sw;
6775 }
6776
6777 /*
6778  - reginclass - determine if a character falls into a character class
6779  
6780   n is the ANYOF regnode
6781   p is the target string
6782   lenp is pointer to the maximum number of bytes of how far to go in p
6783     (This is assumed wthout checking to always be at least the current
6784     character's size)
6785   utf8_target tells whether p is in UTF-8.
6786
6787   Returns true if matched; false otherwise.  If lenp is not NULL, on return
6788   from a successful match, the value it points to will be updated to how many
6789   bytes in p were matched.  If there was no match, the value is undefined,
6790   possibly changed from the input.
6791
6792   Note that this can be a synthetic start class, a combination of various
6793   nodes, so things you think might be mutually exclusive, such as locale,
6794   aren't.  It can match both locale and non-locale
6795
6796  */
6797
6798 STATIC bool
6799 S_reginclass(pTHX_ const regexp * const prog, register const regnode * const n, register const U8* const p, STRLEN* lenp, register const bool utf8_target)
6800 {
6801     dVAR;
6802     const char flags = ANYOF_FLAGS(n);
6803     bool match = FALSE;
6804     UV c = *p;
6805     STRLEN c_len = 0;
6806     STRLEN maxlen;
6807
6808     PERL_ARGS_ASSERT_REGINCLASS;
6809
6810     /* If c is not already the code point, get it */
6811     if (utf8_target && !UTF8_IS_INVARIANT(c)) {
6812         c = utf8n_to_uvchr(p, UTF8_MAXBYTES, &c_len,
6813                 (UTF8_ALLOW_DEFAULT & UTF8_ALLOW_ANYUV)
6814                 | UTF8_ALLOW_FFFF | UTF8_CHECK_ONLY);
6815                 /* see [perl #37836] for UTF8_ALLOW_ANYUV; [perl #38293] for
6816                  * UTF8_ALLOW_FFFF */
6817         if (c_len == (STRLEN)-1)
6818             Perl_croak(aTHX_ "Malformed UTF-8 character (fatal)");
6819     }
6820     else {
6821         c_len = 1;
6822     }
6823
6824     /* Use passed in max length, or one character if none passed in or less
6825      * than one character.  And assume will match just one character.  This is
6826      * overwritten later if matched more. */
6827     if (lenp) {
6828         maxlen = (*lenp > c_len) ? *lenp : c_len;
6829         *lenp = c_len;
6830
6831     }
6832     else {
6833         maxlen = c_len;
6834     }
6835
6836     /* If this character is potentially in the bitmap, check it */
6837     if (c < 256) {
6838         if (ANYOF_BITMAP_TEST(n, c))
6839             match = TRUE;
6840         else if (flags & ANYOF_NON_UTF8_LATIN1_ALL
6841                 && ! utf8_target
6842                 && ! isASCII(c))
6843         {
6844             match = TRUE;
6845         }
6846
6847         else if (flags & ANYOF_LOCALE) {
6848             PL_reg_flags |= RF_tainted;
6849
6850             if ((flags & ANYOF_LOC_NONBITMAP_FOLD)
6851                  && ANYOF_BITMAP_TEST(n, PL_fold_locale[c]))
6852             {
6853                 match = TRUE;
6854             }
6855             else if (ANYOF_CLASS_TEST_ANY_SET(n) &&
6856                      ((ANYOF_CLASS_TEST(n, ANYOF_ALNUM)   &&  isALNUM_LC(c))  ||
6857                       (ANYOF_CLASS_TEST(n, ANYOF_NALNUM)  && !isALNUM_LC(c))  ||
6858                       (ANYOF_CLASS_TEST(n, ANYOF_SPACE)   &&  isSPACE_LC(c))  ||
6859                       (ANYOF_CLASS_TEST(n, ANYOF_NSPACE)  && !isSPACE_LC(c))  ||
6860                       (ANYOF_CLASS_TEST(n, ANYOF_DIGIT)   &&  isDIGIT_LC(c))  ||
6861                       (ANYOF_CLASS_TEST(n, ANYOF_NDIGIT)  && !isDIGIT_LC(c))  ||
6862                       (ANYOF_CLASS_TEST(n, ANYOF_ALNUMC)  &&  isALNUMC_LC(c)) ||
6863                       (ANYOF_CLASS_TEST(n, ANYOF_NALNUMC) && !isALNUMC_LC(c)) ||
6864                       (ANYOF_CLASS_TEST(n, ANYOF_ALPHA)   &&  isALPHA_LC(c))  ||
6865                       (ANYOF_CLASS_TEST(n, ANYOF_NALPHA)  && !isALPHA_LC(c))  ||
6866                       (ANYOF_CLASS_TEST(n, ANYOF_ASCII)   &&  isASCII_LC(c))  ||
6867                       (ANYOF_CLASS_TEST(n, ANYOF_NASCII)  && !isASCII_LC(c))  ||
6868                       (ANYOF_CLASS_TEST(n, ANYOF_CNTRL)   &&  isCNTRL_LC(c))  ||
6869                       (ANYOF_CLASS_TEST(n, ANYOF_NCNTRL)  && !isCNTRL_LC(c))  ||
6870                       (ANYOF_CLASS_TEST(n, ANYOF_GRAPH)   &&  isGRAPH_LC(c))  ||
6871                       (ANYOF_CLASS_TEST(n, ANYOF_NGRAPH)  && !isGRAPH_LC(c))  ||
6872                       (ANYOF_CLASS_TEST(n, ANYOF_LOWER)   &&  isLOWER_LC(c))  ||
6873                       (ANYOF_CLASS_TEST(n, ANYOF_NLOWER)  && !isLOWER_LC(c))  ||
6874                       (ANYOF_CLASS_TEST(n, ANYOF_PRINT)   &&  isPRINT_LC(c))  ||
6875                       (ANYOF_CLASS_TEST(n, ANYOF_NPRINT)  && !isPRINT_LC(c))  ||
6876                       (ANYOF_CLASS_TEST(n, ANYOF_PUNCT)   &&  isPUNCT_LC(c))  ||
6877                       (ANYOF_CLASS_TEST(n, ANYOF_NPUNCT)  && !isPUNCT_LC(c))  ||
6878                       (ANYOF_CLASS_TEST(n, ANYOF_UPPER)   &&  isUPPER_LC(c))  ||
6879                       (ANYOF_CLASS_TEST(n, ANYOF_NUPPER)  && !isUPPER_LC(c))  ||
6880                       (ANYOF_CLASS_TEST(n, ANYOF_XDIGIT)  &&  isXDIGIT(c))    ||
6881                       (ANYOF_CLASS_TEST(n, ANYOF_NXDIGIT) && !isXDIGIT(c))    ||
6882                       (ANYOF_CLASS_TEST(n, ANYOF_PSXSPC)  &&  isPSXSPC(c))    ||
6883                       (ANYOF_CLASS_TEST(n, ANYOF_NPSXSPC) && !isPSXSPC(c))    ||
6884                       (ANYOF_CLASS_TEST(n, ANYOF_BLANK)   &&  isBLANK_LC(c))  ||
6885                       (ANYOF_CLASS_TEST(n, ANYOF_NBLANK)  && !isBLANK_LC(c))
6886                      ) /* How's that for a conditional? */
6887             ) {
6888                 match = TRUE;
6889             }
6890         }
6891     }
6892
6893     /* If the bitmap didn't (or couldn't) match, and something outside the
6894      * bitmap could match, try that.  Locale nodes specifiy completely the
6895      * behavior of code points in the bit map (otherwise, a utf8 target would
6896      * cause them to be treated as Unicode and not locale), except in
6897      * the very unlikely event when this node is a synthetic start class, which
6898      * could be a combination of locale and non-locale nodes.  So allow locale
6899      * to match for the synthetic start class, which will give a false
6900      * positive that will be resolved when the match is done again as not part
6901      * of the synthetic start class */
6902     if (!match) {
6903         if (utf8_target && (flags & ANYOF_UNICODE_ALL) && c >= 256) {
6904             match = TRUE;       /* Everything above 255 matches */
6905         }
6906         else if (ANYOF_NONBITMAP(n)
6907                  && ((flags & ANYOF_NONBITMAP_NON_UTF8)
6908                      || (utf8_target
6909                          && (c >=256
6910                              || (! (flags & ANYOF_LOCALE))
6911                              || (flags & ANYOF_IS_SYNTHETIC)))))
6912         {
6913             AV *av;
6914             SV * const sw = core_regclass_swash(prog, n, TRUE, 0, (SV**)&av);
6915
6916             if (sw) {
6917                 U8 * utf8_p;
6918                 if (utf8_target) {
6919                     utf8_p = (U8 *) p;
6920                 } else {
6921
6922                     /* Not utf8.  Convert as much of the string as available up
6923                      * to the limit of how far the (single) character in the
6924                      * pattern can possibly match (no need to go further).  If
6925                      * the node is a straight ANYOF or not folding, it can't
6926                      * match more than one.  Otherwise, It can match up to how
6927                      * far a single char can fold to.  Since not utf8, each
6928                      * character is a single byte, so the max it can be in
6929                      * bytes is the same as the max it can be in characters */
6930                     STRLEN len = (OP(n) == ANYOF
6931                                   || ! (flags & ANYOF_LOC_NONBITMAP_FOLD))
6932                                   ? 1
6933                                   : (maxlen < UTF8_MAX_FOLD_CHAR_EXPAND)
6934                                     ? maxlen
6935                                     : UTF8_MAX_FOLD_CHAR_EXPAND;
6936                     utf8_p = bytes_to_utf8(p, &len);
6937                 }
6938
6939                 if (swash_fetch(sw, utf8_p, TRUE))
6940                     match = TRUE;
6941                 else if (flags & ANYOF_LOC_NONBITMAP_FOLD) {
6942
6943                     /* Here, we need to test if the fold of the target string
6944                      * matches.  The non-multi char folds have all been moved to
6945                      * the compilation phase, and the multi-char folds have
6946                      * been stored by regcomp into 'av'; we linearly check to
6947                      * see if any match the target string (folded).   We know
6948                      * that the originals were each one character, but we don't
6949                      * currently know how many characters/bytes each folded to,
6950                      * except we do know that there are small limits imposed by
6951                      * Unicode.  XXX A performance enhancement would be to have
6952                      * regcomp.c store the max number of chars/bytes that are
6953                      * in an av entry, as, say the 0th element.  Even better
6954                      * would be to have a hash of the few characters that can
6955                      * start a multi-char fold to the max number of chars of
6956                      * those folds.
6957                      *
6958                      * If there is a match, we will need to advance (if lenp is
6959                      * specified) the match pointer in the target string.  But
6960                      * what we are comparing here isn't that string directly,
6961                      * but its fold, whose length may differ from the original.
6962                      * As we go along in constructing the fold, therefore, we
6963                      * create a map so that we know how many bytes in the
6964                      * source to advance given that we have matched a certain
6965                      * number of bytes in the fold.  This map is stored in
6966                      * 'map_fold_len_back'.  Let n mean the number of bytes in
6967                      * the fold of the first character that we are folding.
6968                      * Then map_fold_len_back[n] is set to the number of bytes
6969                      * in that first character.  Similarly let m be the
6970                      * corresponding number for the second character to be
6971                      * folded.  Then map_fold_len_back[n+m] is set to the
6972                      * number of bytes occupied by the first two source
6973                      * characters. ... */
6974                     U8 map_fold_len_back[UTF8_MAXBYTES_CASE+1] = { 0 };
6975                     U8 folded[UTF8_MAXBYTES_CASE+1];
6976                     STRLEN foldlen = 0; /* num bytes in fold of 1st char */
6977                     STRLEN total_foldlen = 0; /* num bytes in fold of all
6978                                                   chars */
6979
6980                     if (OP(n) == ANYOF || maxlen == 1 || ! lenp || ! av) {
6981
6982                         /* Here, only need to fold the first char of the target
6983                          * string.  It the source wasn't utf8, is 1 byte long */
6984                         to_utf8_fold(utf8_p, folded, &foldlen);
6985                         total_foldlen = foldlen;
6986                         map_fold_len_back[foldlen] = (utf8_target)
6987                                                      ? UTF8SKIP(utf8_p)
6988                                                      : 1;
6989                     }
6990                     else {
6991
6992                         /* Here, need to fold more than the first char.  Do so
6993                          * up to the limits */
6994                         U8* source_ptr = utf8_p;    /* The source for the fold
6995                                                        is the regex target
6996                                                        string */
6997                         U8* folded_ptr = folded;
6998                         U8* e = utf8_p + maxlen;    /* Can't go beyond last
6999                                                        available byte in the
7000                                                        target string */
7001                         U8 i;
7002                         for (i = 0;
7003                              i < UTF8_MAX_FOLD_CHAR_EXPAND && source_ptr < e;
7004                              i++)
7005                         {
7006
7007                             /* Fold the next character */
7008                             U8 this_char_folded[UTF8_MAXBYTES_CASE+1];
7009                             STRLEN this_char_foldlen;
7010                             to_utf8_fold(source_ptr,
7011                                          this_char_folded,
7012                                          &this_char_foldlen);
7013
7014                             /* Bail if it would exceed the byte limit for
7015                              * folding a single char. */
7016                             if (this_char_foldlen + folded_ptr - folded >
7017                                                             UTF8_MAXBYTES_CASE)
7018                             {
7019                                 break;
7020                             }
7021
7022                             /* Add the fold of this character */
7023                             Copy(this_char_folded,
7024                                  folded_ptr,
7025                                  this_char_foldlen,
7026                                  U8);
7027                             source_ptr += UTF8SKIP(source_ptr);
7028                             folded_ptr += this_char_foldlen;
7029                             total_foldlen = folded_ptr - folded;
7030
7031                             /* Create map from the number of bytes in the fold
7032                              * back to the number of bytes in the source.  If
7033                              * the source isn't utf8, the byte count is just
7034                              * the number of characters so far */
7035                             map_fold_len_back[total_foldlen]
7036                                                       = (utf8_target)
7037                                                         ? source_ptr - utf8_p
7038                                                         : i + 1;
7039                         }
7040                         *folded_ptr = '\0';
7041                     }
7042
7043
7044                     /* Do the linear search to see if the fold is in the list
7045                      * of multi-char folds. */
7046                     if (av) {
7047                         I32 i;
7048                         for (i = 0; i <= av_len(av); i++) {
7049                             SV* const sv = *av_fetch(av, i, FALSE);
7050                             STRLEN len;
7051                             const char * const s = SvPV_const(sv, len);
7052
7053                             if (len <= total_foldlen
7054                                 && memEQ(s, (char*)folded, len)
7055
7056                                    /* If 0, means matched a partial char. See
7057                                     * [perl #90536] */
7058                                 && map_fold_len_back[len])
7059                             {
7060
7061                                 /* Advance the target string ptr to account for
7062                                  * this fold, but have to translate from the
7063                                  * folded length to the corresponding source
7064                                  * length. */
7065                                 if (lenp) {
7066                                     *lenp = map_fold_len_back[len];
7067                                 }
7068                                 match = TRUE;
7069                                 break;
7070                             }
7071                         }
7072                     }
7073                 }
7074
7075                 /* If we allocated a string above, free it */
7076                 if (! utf8_target) Safefree(utf8_p);
7077             }
7078         }
7079
7080         if (UNICODE_IS_SUPER(c)
7081             && (flags & ANYOF_WARN_SUPER)
7082             && ckWARN_d(WARN_NON_UNICODE))
7083         {
7084             Perl_warner(aTHX_ packWARN(WARN_NON_UNICODE),
7085                 "Code point 0x%04"UVXf" is not Unicode, all \\p{} matches fail; all \\P{} matches succeed", c);
7086         }
7087     }
7088
7089     return (flags & ANYOF_INVERT) ? !match : match;
7090 }
7091
7092 STATIC U8 *
7093 S_reghop3(U8 *s, I32 off, const U8* lim)
7094 {
7095     /* return the position 'off' UTF-8 characters away from 's', forward if
7096      * 'off' >= 0, backwards if negative.  But don't go outside of position
7097      * 'lim', which better be < s  if off < 0 */
7098
7099     dVAR;
7100
7101     PERL_ARGS_ASSERT_REGHOP3;
7102
7103     if (off >= 0) {
7104         while (off-- && s < lim) {
7105             /* XXX could check well-formedness here */
7106             s += UTF8SKIP(s);
7107         }
7108     }
7109     else {
7110         while (off++ && s > lim) {
7111             s--;
7112             if (UTF8_IS_CONTINUED(*s)) {
7113                 while (s > lim && UTF8_IS_CONTINUATION(*s))
7114                     s--;
7115             }
7116             /* XXX could check well-formedness here */
7117         }
7118     }
7119     return s;
7120 }
7121
7122 #ifdef XXX_dmq
7123 /* there are a bunch of places where we use two reghop3's that should
7124    be replaced with this routine. but since thats not done yet 
7125    we ifdef it out - dmq
7126 */
7127 STATIC U8 *
7128 S_reghop4(U8 *s, I32 off, const U8* llim, const U8* rlim)
7129 {
7130     dVAR;
7131
7132     PERL_ARGS_ASSERT_REGHOP4;
7133
7134     if (off >= 0) {
7135         while (off-- && s < rlim) {
7136             /* XXX could check well-formedness here */
7137             s += UTF8SKIP(s);
7138         }
7139     }
7140     else {
7141         while (off++ && s > llim) {
7142             s--;
7143             if (UTF8_IS_CONTINUED(*s)) {
7144                 while (s > llim && UTF8_IS_CONTINUATION(*s))
7145                     s--;
7146             }
7147             /* XXX could check well-formedness here */
7148         }
7149     }
7150     return s;
7151 }
7152 #endif
7153
7154 STATIC U8 *
7155 S_reghopmaybe3(U8* s, I32 off, const U8* lim)
7156 {
7157     dVAR;
7158
7159     PERL_ARGS_ASSERT_REGHOPMAYBE3;
7160
7161     if (off >= 0) {
7162         while (off-- && s < lim) {
7163             /* XXX could check well-formedness here */
7164             s += UTF8SKIP(s);
7165         }
7166         if (off >= 0)
7167             return NULL;
7168     }
7169     else {
7170         while (off++ && s > lim) {
7171             s--;
7172             if (UTF8_IS_CONTINUED(*s)) {
7173                 while (s > lim && UTF8_IS_CONTINUATION(*s))
7174                     s--;
7175             }
7176             /* XXX could check well-formedness here */
7177         }
7178         if (off <= 0)
7179             return NULL;
7180     }
7181     return s;
7182 }
7183
7184 static void
7185 restore_pos(pTHX_ void *arg)
7186 {
7187     dVAR;
7188     regexp * const rex = (regexp *)arg;
7189     if (PL_reg_state.re_state_eval_setup_done) {
7190         if (PL_reg_oldsaved) {
7191             rex->subbeg = PL_reg_oldsaved;
7192             rex->sublen = PL_reg_oldsavedlen;
7193 #ifdef PERL_OLD_COPY_ON_WRITE
7194             rex->saved_copy = PL_nrs;
7195 #endif
7196             RXp_MATCH_COPIED_on(rex);
7197         }
7198         PL_reg_magic->mg_len = PL_reg_oldpos;
7199         PL_reg_state.re_state_eval_setup_done = FALSE;
7200         PL_curpm = PL_reg_oldcurpm;
7201     }   
7202 }
7203
7204 STATIC void
7205 S_to_utf8_substr(pTHX_ register regexp *prog)
7206 {
7207     int i = 1;
7208
7209     PERL_ARGS_ASSERT_TO_UTF8_SUBSTR;
7210
7211     do {
7212         if (prog->substrs->data[i].substr
7213             && !prog->substrs->data[i].utf8_substr) {
7214             SV* const sv = newSVsv(prog->substrs->data[i].substr);
7215             prog->substrs->data[i].utf8_substr = sv;
7216             sv_utf8_upgrade(sv);
7217             if (SvVALID(prog->substrs->data[i].substr)) {
7218                 if (SvTAIL(prog->substrs->data[i].substr)) {
7219                     /* Trim the trailing \n that fbm_compile added last
7220                        time.  */
7221                     SvCUR_set(sv, SvCUR(sv) - 1);
7222                     /* Whilst this makes the SV technically "invalid" (as its
7223                        buffer is no longer followed by "\0") when fbm_compile()
7224                        adds the "\n" back, a "\0" is restored.  */
7225                     fbm_compile(sv, FBMcf_TAIL);
7226                 } else
7227                     fbm_compile(sv, 0);
7228             }
7229             if (prog->substrs->data[i].substr == prog->check_substr)
7230                 prog->check_utf8 = sv;
7231         }
7232     } while (i--);
7233 }
7234
7235 STATIC void
7236 S_to_byte_substr(pTHX_ register regexp *prog)
7237 {
7238     dVAR;
7239     int i = 1;
7240
7241     PERL_ARGS_ASSERT_TO_BYTE_SUBSTR;
7242
7243     do {
7244         if (prog->substrs->data[i].utf8_substr
7245             && !prog->substrs->data[i].substr) {
7246             SV* sv = newSVsv(prog->substrs->data[i].utf8_substr);
7247             if (sv_utf8_downgrade(sv, TRUE)) {
7248                 if (SvVALID(prog->substrs->data[i].utf8_substr)) {
7249                     if (SvTAIL(prog->substrs->data[i].utf8_substr)) {
7250                         /* Trim the trailing \n that fbm_compile added last
7251                            time.  */
7252                         SvCUR_set(sv, SvCUR(sv) - 1);
7253                         fbm_compile(sv, FBMcf_TAIL);
7254                     } else
7255                         fbm_compile(sv, 0);
7256                 }
7257             } else {
7258                 SvREFCNT_dec(sv);
7259                 sv = &PL_sv_undef;
7260             }
7261             prog->substrs->data[i].substr = sv;
7262             if (prog->substrs->data[i].utf8_substr == prog->check_utf8)
7263                 prog->check_substr = sv;
7264         }
7265     } while (i--);
7266 }
7267
7268 /*
7269  * Local variables:
7270  * c-indentation-style: bsd
7271  * c-basic-offset: 4
7272  * indent-tabs-mode: nil
7273  * End:
7274  *
7275  * ex: set ts=8 sts=4 sw=4 et:
7276  */