This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
[perl #124387] TODO test for AUTOLOAD on DESTROY
[perl5.git] / 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
77 #ifdef PERL_IN_XSUB_RE
78 #  include "re_comp.h"
79 #else
80 #  include "regcomp.h"
81 #endif
82
83 #include "invlist_inline.h"
84 #include "unicode_constants.h"
85
86 #define B_ON_NON_UTF8_LOCALE_IS_WRONG            \
87  "Use of \\b{} or \\B{} for non-UTF-8 locale is wrong.  Assuming a UTF-8 locale"
88
89 static const char utf8_locale_required[] =
90       "Use of (?[ ]) for non-UTF-8 locale is wrong.  Assuming a UTF-8 locale";
91
92 #ifdef DEBUGGING
93 /* At least one required character in the target string is expressible only in
94  * UTF-8. */
95 static const char* const non_utf8_target_but_utf8_required
96                 = "Can't match, because target string needs to be in UTF-8\n";
97 #endif
98
99 #define NON_UTF8_TARGET_BUT_UTF8_REQUIRED(target) STMT_START { \
100     DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%s", non_utf8_target_but_utf8_required));\
101     goto target; \
102 } STMT_END
103
104 #define HAS_NONLATIN1_FOLD_CLOSURE(i) _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
105
106 #ifndef STATIC
107 #define STATIC  static
108 #endif
109
110 /* Valid only for non-utf8 strings: avoids the reginclass
111  * call if there are no complications: i.e., if everything matchable is
112  * straight forward in the bitmap */
113 #define REGINCLASS(prog,p,c)  (ANYOF_FLAGS(p) ? reginclass(prog,p,c,c+1,0)   \
114                                               : ANYOF_BITMAP_TEST(p,*(c)))
115
116 /*
117  * Forwards.
118  */
119
120 #define CHR_SVLEN(sv) (utf8_target ? sv_len_utf8(sv) : SvCUR(sv))
121 #define CHR_DIST(a,b) (reginfo->is_utf8_target ? utf8_distance(a,b) : a - b)
122
123 #define HOPc(pos,off) \
124         (char *)(reginfo->is_utf8_target \
125             ? reghop3((U8*)pos, off, \
126                     (U8*)(off >= 0 ? reginfo->strend : reginfo->strbeg)) \
127             : (U8*)(pos + off))
128
129 #define HOPBACKc(pos, off) \
130         (char*)(reginfo->is_utf8_target \
131             ? reghopmaybe3((U8*)pos, -off, (U8*)(reginfo->strbeg)) \
132             : (pos - off >= reginfo->strbeg)    \
133                 ? (U8*)pos - off                \
134                 : NULL)
135
136 #define HOP3(pos,off,lim) (reginfo->is_utf8_target  ? reghop3((U8*)(pos), off, (U8*)(lim)) : (U8*)(pos + off))
137 #define HOP3c(pos,off,lim) ((char*)HOP3(pos,off,lim))
138
139 /* lim must be +ve. Returns NULL on overshoot */
140 #define HOPMAYBE3(pos,off,lim) \
141         (reginfo->is_utf8_target                        \
142             ? reghopmaybe3((U8*)pos, off, (U8*)(lim))   \
143             : ((U8*)pos + off <= lim)                   \
144                 ? (U8*)pos + off                        \
145                 : NULL)
146
147 /* like HOP3, but limits the result to <= lim even for the non-utf8 case.
148  * off must be >=0; args should be vars rather than expressions */
149 #define HOP3lim(pos,off,lim) (reginfo->is_utf8_target \
150     ? reghop3((U8*)(pos), off, (U8*)(lim)) \
151     : (U8*)((pos + off) > lim ? lim : (pos + off)))
152
153 #define HOP4(pos,off,llim, rlim) (reginfo->is_utf8_target \
154     ? reghop4((U8*)(pos), off, (U8*)(llim), (U8*)(rlim)) \
155     : (U8*)(pos + off))
156 #define HOP4c(pos,off,llim, rlim) ((char*)HOP4(pos,off,llim, rlim))
157
158 #define NEXTCHR_EOS -10 /* nextchr has fallen off the end */
159 #define NEXTCHR_IS_EOS (nextchr < 0)
160
161 #define SET_nextchr \
162     nextchr = ((locinput < reginfo->strend) ? UCHARAT(locinput) : NEXTCHR_EOS)
163
164 #define SET_locinput(p) \
165     locinput = (p);  \
166     SET_nextchr
167
168
169 #define LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist) STMT_START {   \
170         if (!swash_ptr) {                                                     \
171             U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;                       \
172             swash_ptr = _core_swash_init("utf8", property_name, &PL_sv_undef, \
173                                          1, 0, invlist, &flags);              \
174             assert(swash_ptr);                                                \
175         }                                                                     \
176     } STMT_END
177
178 /* If in debug mode, we test that a known character properly matches */
179 #ifdef DEBUGGING
180 #   define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr,                          \
181                                           property_name,                      \
182                                           invlist,                            \
183                                           utf8_char_in_property)              \
184         LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist);               \
185         assert(swash_fetch(swash_ptr, (U8 *) utf8_char_in_property, TRUE));
186 #else
187 #   define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr,                          \
188                                           property_name,                      \
189                                           invlist,                            \
190                                           utf8_char_in_property)              \
191         LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist)
192 #endif
193
194 #define LOAD_UTF8_CHARCLASS_ALNUM() LOAD_UTF8_CHARCLASS_DEBUG_TEST(           \
195                                         PL_utf8_swash_ptrs[_CC_WORDCHAR],     \
196                                         "",                                   \
197                                         PL_XPosix_ptrs[_CC_WORDCHAR],         \
198                                         LATIN_SMALL_LIGATURE_LONG_S_T_UTF8);
199
200 #define PLACEHOLDER     /* Something for the preprocessor to grab onto */
201 /* TODO: Combine JUMPABLE and HAS_TEXT to cache OP(rn) */
202
203 /* for use after a quantifier and before an EXACT-like node -- japhy */
204 /* it would be nice to rework regcomp.sym to generate this stuff. sigh
205  *
206  * NOTE that *nothing* that affects backtracking should be in here, specifically
207  * VERBS must NOT be included. JUMPABLE is used to determine  if we can ignore a
208  * node that is in between two EXACT like nodes when ascertaining what the required
209  * "follow" character is. This should probably be moved to regex compile time
210  * although it may be done at run time beause of the REF possibility - more
211  * investigation required. -- demerphq
212 */
213 #define JUMPABLE(rn) (                                                             \
214     OP(rn) == OPEN ||                                                              \
215     (OP(rn) == CLOSE && (!cur_eval || cur_eval->u.eval.close_paren != ARG(rn))) || \
216     OP(rn) == EVAL ||                                                              \
217     OP(rn) == SUSPEND || OP(rn) == IFMATCH ||                                      \
218     OP(rn) == PLUS || OP(rn) == MINMOD ||                                          \
219     OP(rn) == KEEPS ||                                                             \
220     (PL_regkind[OP(rn)] == CURLY && ARG1(rn) > 0)                                  \
221 )
222 #define IS_EXACT(rn) (PL_regkind[OP(rn)] == EXACT)
223
224 #define HAS_TEXT(rn) ( IS_EXACT(rn) || PL_regkind[OP(rn)] == REF )
225
226 #if 0 
227 /* Currently these are only used when PL_regkind[OP(rn)] == EXACT so
228    we don't need this definition.  XXX These are now out-of-sync*/
229 #define IS_TEXT(rn)   ( OP(rn)==EXACT   || OP(rn)==REF   || OP(rn)==NREF   )
230 #define IS_TEXTF(rn)  ( OP(rn)==EXACTFU || OP(rn)==EXACTFU_SS || OP(rn)==EXACTFA || OP(rn)==EXACTFA_NO_TRIE || OP(rn)==EXACTF || OP(rn)==REFF  || OP(rn)==NREFF )
231 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL || OP(rn)==REFFL || OP(rn)==NREFFL )
232
233 #else
234 /* ... so we use this as its faster. */
235 #define IS_TEXT(rn)   ( OP(rn)==EXACT || OP(rn)==EXACTL )
236 #define IS_TEXTFU(rn)  ( OP(rn)==EXACTFU || OP(rn)==EXACTFLU8 || OP(rn)==EXACTFU_SS || OP(rn) == EXACTFA || OP(rn) == EXACTFA_NO_TRIE)
237 #define IS_TEXTF(rn)  ( OP(rn)==EXACTF  )
238 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL )
239
240 #endif
241
242 /*
243   Search for mandatory following text node; for lookahead, the text must
244   follow but for lookbehind (rn->flags != 0) we skip to the next step.
245 */
246 #define FIND_NEXT_IMPT(rn) STMT_START {                                   \
247     while (JUMPABLE(rn)) { \
248         const OPCODE type = OP(rn); \
249         if (type == SUSPEND || PL_regkind[type] == CURLY) \
250             rn = NEXTOPER(NEXTOPER(rn)); \
251         else if (type == PLUS) \
252             rn = NEXTOPER(rn); \
253         else if (type == IFMATCH) \
254             rn = (rn->flags == 0) ? NEXTOPER(NEXTOPER(rn)) : rn + ARG(rn); \
255         else rn += NEXT_OFF(rn); \
256     } \
257 } STMT_END 
258
259 #define SLAB_FIRST(s) (&(s)->states[0])
260 #define SLAB_LAST(s)  (&(s)->states[PERL_REGMATCH_SLAB_SLOTS-1])
261
262 static void S_setup_eval_state(pTHX_ regmatch_info *const reginfo);
263 static void S_cleanup_regmatch_info_aux(pTHX_ void *arg);
264 static regmatch_state * S_push_slab(pTHX);
265
266 #define REGCP_PAREN_ELEMS 3
267 #define REGCP_OTHER_ELEMS 3
268 #define REGCP_FRAME_ELEMS 1
269 /* REGCP_FRAME_ELEMS are not part of the REGCP_OTHER_ELEMS and
270  * are needed for the regexp context stack bookkeeping. */
271
272 STATIC CHECKPOINT
273 S_regcppush(pTHX_ const regexp *rex, I32 parenfloor, U32 maxopenparen)
274 {
275     const int retval = PL_savestack_ix;
276     const int paren_elems_to_push =
277                 (maxopenparen - parenfloor) * REGCP_PAREN_ELEMS;
278     const UV total_elems = paren_elems_to_push + REGCP_OTHER_ELEMS;
279     const UV elems_shifted = total_elems << SAVE_TIGHT_SHIFT;
280     I32 p;
281     GET_RE_DEBUG_FLAGS_DECL;
282
283     PERL_ARGS_ASSERT_REGCPPUSH;
284
285     if (paren_elems_to_push < 0)
286         Perl_croak(aTHX_ "panic: paren_elems_to_push, %i < 0, maxopenparen: %i parenfloor: %i REGCP_PAREN_ELEMS: %u",
287                    (int)paren_elems_to_push, (int)maxopenparen,
288                    (int)parenfloor, (unsigned)REGCP_PAREN_ELEMS);
289
290     if ((elems_shifted >> SAVE_TIGHT_SHIFT) != total_elems)
291         Perl_croak(aTHX_ "panic: paren_elems_to_push offset %"UVuf
292                    " out of range (%lu-%ld)",
293                    total_elems,
294                    (unsigned long)maxopenparen,
295                    (long)parenfloor);
296
297     SSGROW(total_elems + REGCP_FRAME_ELEMS);
298     
299     DEBUG_BUFFERS_r(
300         if ((int)maxopenparen > (int)parenfloor)
301             PerlIO_printf(Perl_debug_log,
302                 "rex=0x%"UVxf" offs=0x%"UVxf": saving capture indices:\n",
303                 PTR2UV(rex),
304                 PTR2UV(rex->offs)
305             );
306     );
307     for (p = parenfloor+1; p <= (I32)maxopenparen;  p++) {
308 /* REGCP_PARENS_ELEMS are pushed per pairs of parentheses. */
309         SSPUSHIV(rex->offs[p].end);
310         SSPUSHIV(rex->offs[p].start);
311         SSPUSHINT(rex->offs[p].start_tmp);
312         DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
313             "    \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"\n",
314             (UV)p,
315             (IV)rex->offs[p].start,
316             (IV)rex->offs[p].start_tmp,
317             (IV)rex->offs[p].end
318         ));
319     }
320 /* REGCP_OTHER_ELEMS are pushed in any case, parentheses or no. */
321     SSPUSHINT(maxopenparen);
322     SSPUSHINT(rex->lastparen);
323     SSPUSHINT(rex->lastcloseparen);
324     SSPUSHUV(SAVEt_REGCONTEXT | elems_shifted); /* Magic cookie. */
325
326     return retval;
327 }
328
329 /* These are needed since we do not localize EVAL nodes: */
330 #define REGCP_SET(cp)                                           \
331     DEBUG_STATE_r(                                              \
332             PerlIO_printf(Perl_debug_log,                       \
333                 "  Setting an EVAL scope, savestack=%"IVdf"\n", \
334                 (IV)PL_savestack_ix));                          \
335     cp = PL_savestack_ix
336
337 #define REGCP_UNWIND(cp)                                        \
338     DEBUG_STATE_r(                                              \
339         if (cp != PL_savestack_ix)                              \
340             PerlIO_printf(Perl_debug_log,                       \
341                 "  Clearing an EVAL scope, savestack=%"IVdf"..%"IVdf"\n", \
342                 (IV)(cp), (IV)PL_savestack_ix));                \
343     regcpblow(cp)
344
345 #define UNWIND_PAREN(lp, lcp)               \
346     for (n = rex->lastparen; n > lp; n--)   \
347         rex->offs[n].end = -1;              \
348     rex->lastparen = n;                     \
349     rex->lastcloseparen = lcp;
350
351
352 STATIC void
353 S_regcppop(pTHX_ regexp *rex, U32 *maxopenparen_p)
354 {
355     UV i;
356     U32 paren;
357     GET_RE_DEBUG_FLAGS_DECL;
358
359     PERL_ARGS_ASSERT_REGCPPOP;
360
361     /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
362     i = SSPOPUV;
363     assert((i & SAVE_MASK) == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
364     i >>= SAVE_TIGHT_SHIFT; /* Parentheses elements to pop. */
365     rex->lastcloseparen = SSPOPINT;
366     rex->lastparen = SSPOPINT;
367     *maxopenparen_p = SSPOPINT;
368
369     i -= REGCP_OTHER_ELEMS;
370     /* Now restore the parentheses context. */
371     DEBUG_BUFFERS_r(
372         if (i || rex->lastparen + 1 <= rex->nparens)
373             PerlIO_printf(Perl_debug_log,
374                 "rex=0x%"UVxf" offs=0x%"UVxf": restoring capture indices to:\n",
375                 PTR2UV(rex),
376                 PTR2UV(rex->offs)
377             );
378     );
379     paren = *maxopenparen_p;
380     for ( ; i > 0; i -= REGCP_PAREN_ELEMS) {
381         SSize_t tmps;
382         rex->offs[paren].start_tmp = SSPOPINT;
383         rex->offs[paren].start = SSPOPIV;
384         tmps = SSPOPIV;
385         if (paren <= rex->lastparen)
386             rex->offs[paren].end = tmps;
387         DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
388             "    \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"%s\n",
389             (UV)paren,
390             (IV)rex->offs[paren].start,
391             (IV)rex->offs[paren].start_tmp,
392             (IV)rex->offs[paren].end,
393             (paren > rex->lastparen ? "(skipped)" : ""));
394         );
395         paren--;
396     }
397 #if 1
398     /* It would seem that the similar code in regtry()
399      * already takes care of this, and in fact it is in
400      * a better location to since this code can #if 0-ed out
401      * but the code in regtry() is needed or otherwise tests
402      * requiring null fields (pat.t#187 and split.t#{13,14}
403      * (as of patchlevel 7877)  will fail.  Then again,
404      * this code seems to be necessary or otherwise
405      * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
406      * --jhi updated by dapm */
407     for (i = rex->lastparen + 1; i <= rex->nparens; i++) {
408         if (i > *maxopenparen_p)
409             rex->offs[i].start = -1;
410         rex->offs[i].end = -1;
411         DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
412             "    \\%"UVuf": %s   ..-1 undeffing\n",
413             (UV)i,
414             (i > *maxopenparen_p) ? "-1" : "  "
415         ));
416     }
417 #endif
418 }
419
420 /* restore the parens and associated vars at savestack position ix,
421  * but without popping the stack */
422
423 STATIC void
424 S_regcp_restore(pTHX_ regexp *rex, I32 ix, U32 *maxopenparen_p)
425 {
426     I32 tmpix = PL_savestack_ix;
427     PL_savestack_ix = ix;
428     regcppop(rex, maxopenparen_p);
429     PL_savestack_ix = tmpix;
430 }
431
432 #define regcpblow(cp) LEAVE_SCOPE(cp)   /* Ignores regcppush()ed data. */
433
434 STATIC bool
435 S_isFOO_lc(pTHX_ const U8 classnum, const U8 character)
436 {
437     /* Returns a boolean as to whether or not 'character' is a member of the
438      * Posix character class given by 'classnum' that should be equivalent to a
439      * value in the typedef '_char_class_number'.
440      *
441      * Ideally this could be replaced by a just an array of function pointers
442      * to the C library functions that implement the macros this calls.
443      * However, to compile, the precise function signatures are required, and
444      * these may vary from platform to to platform.  To avoid having to figure
445      * out what those all are on each platform, I (khw) am using this method,
446      * which adds an extra layer of function call overhead (unless the C
447      * optimizer strips it away).  But we don't particularly care about
448      * performance with locales anyway. */
449
450     switch ((_char_class_number) classnum) {
451         case _CC_ENUM_ALPHANUMERIC: return isALPHANUMERIC_LC(character);
452         case _CC_ENUM_ALPHA:     return isALPHA_LC(character);
453         case _CC_ENUM_ASCII:     return isASCII_LC(character);
454         case _CC_ENUM_BLANK:     return isBLANK_LC(character);
455         case _CC_ENUM_CASED:     return isLOWER_LC(character)
456                                         || isUPPER_LC(character);
457         case _CC_ENUM_CNTRL:     return isCNTRL_LC(character);
458         case _CC_ENUM_DIGIT:     return isDIGIT_LC(character);
459         case _CC_ENUM_GRAPH:     return isGRAPH_LC(character);
460         case _CC_ENUM_LOWER:     return isLOWER_LC(character);
461         case _CC_ENUM_PRINT:     return isPRINT_LC(character);
462         case _CC_ENUM_PUNCT:     return isPUNCT_LC(character);
463         case _CC_ENUM_SPACE:     return isSPACE_LC(character);
464         case _CC_ENUM_UPPER:     return isUPPER_LC(character);
465         case _CC_ENUM_WORDCHAR:  return isWORDCHAR_LC(character);
466         case _CC_ENUM_XDIGIT:    return isXDIGIT_LC(character);
467         default:    /* VERTSPACE should never occur in locales */
468             Perl_croak(aTHX_ "panic: isFOO_lc() has an unexpected character class '%d'", classnum);
469     }
470
471     NOT_REACHED; /* NOTREACHED */
472     return FALSE;
473 }
474
475 STATIC bool
476 S_isFOO_utf8_lc(pTHX_ const U8 classnum, const U8* character)
477 {
478     /* Returns a boolean as to whether or not the (well-formed) UTF-8-encoded
479      * 'character' is a member of the Posix character class given by 'classnum'
480      * that should be equivalent to a value in the typedef
481      * '_char_class_number'.
482      *
483      * This just calls isFOO_lc on the code point for the character if it is in
484      * the range 0-255.  Outside that range, all characters use Unicode
485      * rules, ignoring any locale.  So use the Unicode function if this class
486      * requires a swash, and use the Unicode macro otherwise. */
487
488     PERL_ARGS_ASSERT_ISFOO_UTF8_LC;
489
490     if (UTF8_IS_INVARIANT(*character)) {
491         return isFOO_lc(classnum, *character);
492     }
493     else if (UTF8_IS_DOWNGRADEABLE_START(*character)) {
494         return isFOO_lc(classnum,
495                         EIGHT_BIT_UTF8_TO_NATIVE(*character, *(character + 1)));
496     }
497
498     _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(character, character + UTF8SKIP(character));
499
500     if (classnum < _FIRST_NON_SWASH_CC) {
501
502         /* Initialize the swash unless done already */
503         if (! PL_utf8_swash_ptrs[classnum]) {
504             U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
505             PL_utf8_swash_ptrs[classnum] =
506                     _core_swash_init("utf8",
507                                      "",
508                                      &PL_sv_undef, 1, 0,
509                                      PL_XPosix_ptrs[classnum], &flags);
510         }
511
512         return cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum], (U8 *)
513                                  character,
514                                  TRUE /* is UTF */ ));
515     }
516
517     switch ((_char_class_number) classnum) {
518         case _CC_ENUM_SPACE:     return is_XPERLSPACE_high(character);
519         case _CC_ENUM_BLANK:     return is_HORIZWS_high(character);
520         case _CC_ENUM_XDIGIT:    return is_XDIGIT_high(character);
521         case _CC_ENUM_VERTSPACE: return is_VERTWS_high(character);
522         default:                 break;
523     }
524
525     return FALSE; /* Things like CNTRL are always below 256 */
526 }
527
528 /*
529  * pregexec and friends
530  */
531
532 #ifndef PERL_IN_XSUB_RE
533 /*
534  - pregexec - match a regexp against a string
535  */
536 I32
537 Perl_pregexec(pTHX_ REGEXP * const prog, char* stringarg, char *strend,
538          char *strbeg, SSize_t minend, SV *screamer, U32 nosave)
539 /* stringarg: the point in the string at which to begin matching */
540 /* strend:    pointer to null at end of string */
541 /* strbeg:    real beginning of string */
542 /* minend:    end of match must be >= minend bytes after stringarg. */
543 /* screamer:  SV being matched: only used for utf8 flag, pos() etc; string
544  *            itself is accessed via the pointers above */
545 /* nosave:    For optimizations. */
546 {
547     PERL_ARGS_ASSERT_PREGEXEC;
548
549     return
550         regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
551                       nosave ? 0 : REXEC_COPY_STR);
552 }
553 #endif
554
555
556
557 /* re_intuit_start():
558  *
559  * Based on some optimiser hints, try to find the earliest position in the
560  * string where the regex could match.
561  *
562  *   rx:     the regex to match against
563  *   sv:     the SV being matched: only used for utf8 flag; the string
564  *           itself is accessed via the pointers below. Note that on
565  *           something like an overloaded SV, SvPOK(sv) may be false
566  *           and the string pointers may point to something unrelated to
567  *           the SV itself.
568  *   strbeg: real beginning of string
569  *   strpos: the point in the string at which to begin matching
570  *   strend: pointer to the byte following the last char of the string
571  *   flags   currently unused; set to 0
572  *   data:   currently unused; set to NULL
573  *
574  * The basic idea of re_intuit_start() is to use some known information
575  * about the pattern, namely:
576  *
577  *   a) the longest known anchored substring (i.e. one that's at a
578  *      constant offset from the beginning of the pattern; but not
579  *      necessarily at a fixed offset from the beginning of the
580  *      string);
581  *   b) the longest floating substring (i.e. one that's not at a constant
582  *      offset from the beginning of the pattern);
583  *   c) Whether the pattern is anchored to the string; either
584  *      an absolute anchor: /^../, or anchored to \n: /^.../m,
585  *      or anchored to pos(): /\G/;
586  *   d) A start class: a real or synthetic character class which
587  *      represents which characters are legal at the start of the pattern;
588  *
589  * to either quickly reject the match, or to find the earliest position
590  * within the string at which the pattern might match, thus avoiding
591  * running the full NFA engine at those earlier locations, only to
592  * eventually fail and retry further along.
593  *
594  * Returns NULL if the pattern can't match, or returns the address within
595  * the string which is the earliest place the match could occur.
596  *
597  * The longest of the anchored and floating substrings is called 'check'
598  * and is checked first. The other is called 'other' and is checked
599  * second. The 'other' substring may not be present.  For example,
600  *
601  *    /(abc|xyz)ABC\d{0,3}DEFG/
602  *
603  * will have
604  *
605  *   check substr (float)    = "DEFG", offset 6..9 chars
606  *   other substr (anchored) = "ABC",  offset 3..3 chars
607  *   stclass = [ax]
608  *
609  * Be aware that during the course of this function, sometimes 'anchored'
610  * refers to a substring being anchored relative to the start of the
611  * pattern, and sometimes to the pattern itself being anchored relative to
612  * the string. For example:
613  *
614  *   /\dabc/:   "abc" is anchored to the pattern;
615  *   /^\dabc/:  "abc" is anchored to the pattern and the string;
616  *   /\d+abc/:  "abc" is anchored to neither the pattern nor the string;
617  *   /^\d+abc/: "abc" is anchored to neither the pattern nor the string,
618  *                    but the pattern is anchored to the string.
619  */
620
621 char *
622 Perl_re_intuit_start(pTHX_
623                     REGEXP * const rx,
624                     SV *sv,
625                     const char * const strbeg,
626                     char *strpos,
627                     char *strend,
628                     const U32 flags,
629                     re_scream_pos_data *data)
630 {
631     struct regexp *const prog = ReANY(rx);
632     SSize_t start_shift = prog->check_offset_min;
633     /* Should be nonnegative! */
634     SSize_t end_shift   = 0;
635     /* current lowest pos in string where the regex can start matching */
636     char *rx_origin = strpos;
637     SV *check;
638     const bool utf8_target = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
639     U8   other_ix = 1 - prog->substrs->check_ix;
640     bool ml_anch = 0;
641     char *other_last = strpos;/* latest pos 'other' substr already checked to */
642     char *check_at = NULL;              /* check substr found at this pos */
643     const I32 multiline = prog->extflags & RXf_PMf_MULTILINE;
644     RXi_GET_DECL(prog,progi);
645     regmatch_info reginfo_buf;  /* create some info to pass to find_byclass */
646     regmatch_info *const reginfo = &reginfo_buf;
647     GET_RE_DEBUG_FLAGS_DECL;
648
649     PERL_ARGS_ASSERT_RE_INTUIT_START;
650     PERL_UNUSED_ARG(flags);
651     PERL_UNUSED_ARG(data);
652
653     DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
654                 "Intuit: trying to determine minimum start position...\n"));
655
656     /* for now, assume that all substr offsets are positive. If at some point
657      * in the future someone wants to do clever things with lookbehind and
658      * -ve offsets, they'll need to fix up any code in this function
659      * which uses these offsets. See the thread beginning
660      * <20140113145929.GF27210@iabyn.com>
661      */
662     assert(prog->substrs->data[0].min_offset >= 0);
663     assert(prog->substrs->data[0].max_offset >= 0);
664     assert(prog->substrs->data[1].min_offset >= 0);
665     assert(prog->substrs->data[1].max_offset >= 0);
666     assert(prog->substrs->data[2].min_offset >= 0);
667     assert(prog->substrs->data[2].max_offset >= 0);
668
669     /* for now, assume that if both present, that the floating substring
670      * doesn't start before the anchored substring.
671      * If you break this assumption (e.g. doing better optimisations
672      * with lookahead/behind), then you'll need to audit the code in this
673      * function carefully first
674      */
675     assert(
676             ! (  (prog->anchored_utf8 || prog->anchored_substr)
677               && (prog->float_utf8    || prog->float_substr))
678            || (prog->float_min_offset >= prog->anchored_offset));
679
680     /* byte rather than char calculation for efficiency. It fails
681      * to quickly reject some cases that can't match, but will reject
682      * them later after doing full char arithmetic */
683     if (prog->minlen > strend - strpos) {
684         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
685                               "  String too short...\n"));
686         goto fail;
687     }
688
689     RX_MATCH_UTF8_set(rx,utf8_target);
690     reginfo->is_utf8_target = cBOOL(utf8_target);
691     reginfo->info_aux = NULL;
692     reginfo->strbeg = strbeg;
693     reginfo->strend = strend;
694     reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
695     reginfo->intuit = 1;
696     /* not actually used within intuit, but zero for safety anyway */
697     reginfo->poscache_maxiter = 0;
698
699     if (utf8_target) {
700         if (!prog->check_utf8 && prog->check_substr)
701             to_utf8_substr(prog);
702         check = prog->check_utf8;
703     } else {
704         if (!prog->check_substr && prog->check_utf8) {
705             if (! to_byte_substr(prog)) {
706                 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(fail);
707             }
708         }
709         check = prog->check_substr;
710     }
711
712     /* dump the various substring data */
713     DEBUG_OPTIMISE_MORE_r({
714         int i;
715         for (i=0; i<=2; i++) {
716             SV *sv = (utf8_target ? prog->substrs->data[i].utf8_substr
717                                   : prog->substrs->data[i].substr);
718             if (!sv)
719                 continue;
720
721             PerlIO_printf(Perl_debug_log,
722                 "  substrs[%d]: min=%"IVdf" max=%"IVdf" end shift=%"IVdf
723                 " useful=%"IVdf" utf8=%d [%s]\n",
724                 i,
725                 (IV)prog->substrs->data[i].min_offset,
726                 (IV)prog->substrs->data[i].max_offset,
727                 (IV)prog->substrs->data[i].end_shift,
728                 BmUSEFUL(sv),
729                 utf8_target ? 1 : 0,
730                 SvPEEK(sv));
731         }
732     });
733
734     if (prog->intflags & PREGf_ANCH) { /* Match at \G, beg-of-str or after \n */
735
736         /* ml_anch: check after \n?
737          *
738          * A note about PREGf_IMPLICIT: on an un-anchored pattern beginning
739          * with /.*.../, these flags will have been added by the
740          * compiler:
741          *   /.*abc/, /.*abc/m:  PREGf_IMPLICIT | PREGf_ANCH_MBOL
742          *   /.*abc/s:           PREGf_IMPLICIT | PREGf_ANCH_SBOL
743          */
744         ml_anch =      (prog->intflags & PREGf_ANCH_MBOL)
745                    && !(prog->intflags & PREGf_IMPLICIT);
746
747         if (!ml_anch && !(prog->intflags & PREGf_IMPLICIT)) {
748             /* we are only allowed to match at BOS or \G */
749
750             /* trivially reject if there's a BOS anchor and we're not at BOS.
751              *
752              * Note that we don't try to do a similar quick reject for
753              * \G, since generally the caller will have calculated strpos
754              * based on pos() and gofs, so the string is already correctly
755              * anchored by definition; and handling the exceptions would
756              * be too fiddly (e.g. REXEC_IGNOREPOS).
757              */
758             if (   strpos != strbeg
759                 && (prog->intflags & PREGf_ANCH_SBOL))
760             {
761                 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
762                                 "  Not at start...\n"));
763                 goto fail;
764             }
765
766             /* in the presence of an anchor, the anchored (relative to the
767              * start of the regex) substr must also be anchored relative
768              * to strpos. So quickly reject if substr isn't found there.
769              * This works for \G too, because the caller will already have
770              * subtracted gofs from pos, and gofs is the offset from the
771              * \G to the start of the regex. For example, in /.abc\Gdef/,
772              * where substr="abcdef", pos()=3, gofs=4, offset_min=1:
773              * caller will have set strpos=pos()-4; we look for the substr
774              * at position pos()-4+1, which lines up with the "a" */
775
776             if (prog->check_offset_min == prog->check_offset_max) {
777                 /* Substring at constant offset from beg-of-str... */
778                 SSize_t slen = SvCUR(check);
779                 char *s = HOP3c(strpos, prog->check_offset_min, strend);
780             
781                 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
782                     "  Looking for check substr at fixed offset %"IVdf"...\n",
783                     (IV)prog->check_offset_min));
784
785                 if (SvTAIL(check)) {
786                     /* In this case, the regex is anchored at the end too.
787                      * Unless it's a multiline match, the lengths must match
788                      * exactly, give or take a \n.  NB: slen >= 1 since
789                      * the last char of check is \n */
790                     if (!multiline
791                         && (   strend - s > slen
792                             || strend - s < slen - 1
793                             || (strend - s == slen && strend[-1] != '\n')))
794                     {
795                         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
796                                             "  String too long...\n"));
797                         goto fail_finish;
798                     }
799                     /* Now should match s[0..slen-2] */
800                     slen--;
801                 }
802                 if (slen && (*SvPVX_const(check) != *s
803                     || (slen > 1 && memNE(SvPVX_const(check), s, slen))))
804                 {
805                     DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
806                                     "  String not equal...\n"));
807                     goto fail_finish;
808                 }
809
810                 check_at = s;
811                 goto success_at_start;
812             }
813         }
814     }
815
816     end_shift = prog->check_end_shift;
817
818 #ifdef DEBUGGING        /* 7/99: reports of failure (with the older version) */
819     if (end_shift < 0)
820         Perl_croak(aTHX_ "panic: end_shift: %"IVdf" pattern:\n%s\n ",
821                    (IV)end_shift, RX_PRECOMP(prog));
822 #endif
823
824   restart:
825     
826     /* This is the (re)entry point of the main loop in this function.
827      * The goal of this loop is to:
828      * 1) find the "check" substring in the region rx_origin..strend
829      *    (adjusted by start_shift / end_shift). If not found, reject
830      *    immediately.
831      * 2) If it exists, look for the "other" substr too if defined; for
832      *    example, if the check substr maps to the anchored substr, then
833      *    check the floating substr, and vice-versa. If not found, go
834      *    back to (1) with rx_origin suitably incremented.
835      * 3) If we find an rx_origin position that doesn't contradict
836      *    either of the substrings, then check the possible additional
837      *    constraints on rx_origin of /^.../m or a known start class.
838      *    If these fail, then depending on which constraints fail, jump
839      *    back to here, or to various other re-entry points further along
840      *    that skip some of the first steps.
841      * 4) If we pass all those tests, update the BmUSEFUL() count on the
842      *    substring. If the start position was determined to be at the
843      *    beginning of the string  - so, not rejected, but not optimised,
844      *    since we have to run regmatch from position 0 - decrement the
845      *    BmUSEFUL() count. Otherwise increment it.
846      */
847
848
849     /* first, look for the 'check' substring */
850
851     {
852         U8* start_point;
853         U8* end_point;
854
855         DEBUG_OPTIMISE_MORE_r({
856             PerlIO_printf(Perl_debug_log,
857                 "  At restart: rx_origin=%"IVdf" Check offset min: %"IVdf
858                 " Start shift: %"IVdf" End shift %"IVdf
859                 " Real end Shift: %"IVdf"\n",
860                 (IV)(rx_origin - strbeg),
861                 (IV)prog->check_offset_min,
862                 (IV)start_shift,
863                 (IV)end_shift,
864                 (IV)prog->check_end_shift);
865         });
866         
867         end_point = HOP3(strend, -end_shift, strbeg);
868         start_point = HOPMAYBE3(rx_origin, start_shift, end_point);
869         if (!start_point)
870             goto fail_finish;
871
872
873         /* If the regex is absolutely anchored to either the start of the
874          * string (SBOL) or to pos() (ANCH_GPOS), then
875          * check_offset_max represents an upper bound on the string where
876          * the substr could start. For the ANCH_GPOS case, we assume that
877          * the caller of intuit will have already set strpos to
878          * pos()-gofs, so in this case strpos + offset_max will still be
879          * an upper bound on the substr.
880          */
881         if (!ml_anch
882             && prog->intflags & PREGf_ANCH
883             && prog->check_offset_max != SSize_t_MAX)
884         {
885             SSize_t len = SvCUR(check) - !!SvTAIL(check);
886             const char * const anchor =
887                         (prog->intflags & PREGf_ANCH_GPOS ? strpos : strbeg);
888
889             /* do a bytes rather than chars comparison. It's conservative;
890              * so it skips doing the HOP if the result can't possibly end
891              * up earlier than the old value of end_point.
892              */
893             if ((char*)end_point - anchor > prog->check_offset_max) {
894                 end_point = HOP3lim((U8*)anchor,
895                                 prog->check_offset_max,
896                                 end_point -len)
897                             + len;
898             }
899         }
900
901         check_at = fbm_instr( start_point, end_point,
902                       check, multiline ? FBMrf_MULTILINE : 0);
903
904         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
905             "  doing 'check' fbm scan, [%"IVdf"..%"IVdf"] gave %"IVdf"\n",
906             (IV)((char*)start_point - strbeg),
907             (IV)((char*)end_point   - strbeg),
908             (IV)(check_at ? check_at - strbeg : -1)
909         ));
910
911         /* Update the count-of-usability, remove useless subpatterns,
912             unshift s.  */
913
914         DEBUG_EXECUTE_r({
915             RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
916                 SvPVX_const(check), RE_SV_DUMPLEN(check), 30);
917             PerlIO_printf(Perl_debug_log, "  %s %s substr %s%s%s",
918                               (check_at ? "Found" : "Did not find"),
919                 (check == (utf8_target ? prog->anchored_utf8 : prog->anchored_substr)
920                     ? "anchored" : "floating"),
921                 quoted,
922                 RE_SV_TAIL(check),
923                 (check_at ? " at offset " : "...\n") );
924         });
925
926         if (!check_at)
927             goto fail_finish;
928         /* set rx_origin to the minimum position where the regex could start
929          * matching, given the constraint of the just-matched check substring.
930          * But don't set it lower than previously.
931          */
932
933         if (check_at - rx_origin > prog->check_offset_max)
934             rx_origin = HOP3c(check_at, -prog->check_offset_max, rx_origin);
935         /* Finish the diagnostic message */
936         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
937             "%ld (rx_origin now %"IVdf")...\n",
938             (long)(check_at - strbeg),
939             (IV)(rx_origin - strbeg)
940         ));
941     }
942
943
944     /* now look for the 'other' substring if defined */
945
946     if (utf8_target ? prog->substrs->data[other_ix].utf8_substr
947                     : prog->substrs->data[other_ix].substr)
948     {
949         /* Take into account the "other" substring. */
950         char *last, *last1;
951         char *s;
952         SV* must;
953         struct reg_substr_datum *other;
954
955       do_other_substr:
956         other = &prog->substrs->data[other_ix];
957
958         /* if "other" is anchored:
959          * we've previously found a floating substr starting at check_at.
960          * This means that the regex origin must lie somewhere
961          * between min (rx_origin): HOP3(check_at, -check_offset_max)
962          * and max:                 HOP3(check_at, -check_offset_min)
963          * (except that min will be >= strpos)
964          * So the fixed  substr must lie somewhere between
965          *  HOP3(min, anchored_offset)
966          *  HOP3(max, anchored_offset) + SvCUR(substr)
967          */
968
969         /* if "other" is floating
970          * Calculate last1, the absolute latest point where the
971          * floating substr could start in the string, ignoring any
972          * constraints from the earlier fixed match. It is calculated
973          * as follows:
974          *
975          * strend - prog->minlen (in chars) is the absolute latest
976          * position within the string where the origin of the regex
977          * could appear. The latest start point for the floating
978          * substr is float_min_offset(*) on from the start of the
979          * regex.  last1 simply combines thee two offsets.
980          *
981          * (*) You might think the latest start point should be
982          * float_max_offset from the regex origin, and technically
983          * you'd be correct. However, consider
984          *    /a\d{2,4}bcd\w/
985          * Here, float min, max are 3,5 and minlen is 7.
986          * This can match either
987          *    /a\d\dbcd\w/
988          *    /a\d\d\dbcd\w/
989          *    /a\d\d\d\dbcd\w/
990          * In the first case, the regex matches minlen chars; in the
991          * second, minlen+1, in the third, minlen+2.
992          * In the first case, the floating offset is 3 (which equals
993          * float_min), in the second, 4, and in the third, 5 (which
994          * equals float_max). In all cases, the floating string bcd
995          * can never start more than 4 chars from the end of the
996          * string, which equals minlen - float_min. As the substring
997          * starts to match more than float_min from the start of the
998          * regex, it makes the regex match more than minlen chars,
999          * and the two cancel each other out. So we can always use
1000          * float_min - minlen, rather than float_max - minlen for the
1001          * latest position in the string.
1002          *
1003          * Note that -minlen + float_min_offset is equivalent (AFAIKT)
1004          * to CHR_SVLEN(must) - !!SvTAIL(must) + prog->float_end_shift
1005          */
1006
1007         assert(prog->minlen >= other->min_offset);
1008         last1 = HOP3c(strend,
1009                         other->min_offset - prog->minlen, strbeg);
1010
1011         if (other_ix) {/* i.e. if (other-is-float) */
1012             /* last is the latest point where the floating substr could
1013              * start, *given* any constraints from the earlier fixed
1014              * match. This constraint is that the floating string starts
1015              * <= float_max_offset chars from the regex origin (rx_origin).
1016              * If this value is less than last1, use it instead.
1017              */
1018             assert(rx_origin <= last1);
1019             last =
1020                 /* this condition handles the offset==infinity case, and
1021                  * is a short-cut otherwise. Although it's comparing a
1022                  * byte offset to a char length, it does so in a safe way,
1023                  * since 1 char always occupies 1 or more bytes,
1024                  * so if a string range is  (last1 - rx_origin) bytes,
1025                  * it will be less than or equal to  (last1 - rx_origin)
1026                  * chars; meaning it errs towards doing the accurate HOP3
1027                  * rather than just using last1 as a short-cut */
1028                 (last1 - rx_origin) < other->max_offset
1029                     ? last1
1030                     : (char*)HOP3lim(rx_origin, other->max_offset, last1);
1031         }
1032         else {
1033             assert(strpos + start_shift <= check_at);
1034             last = HOP4c(check_at, other->min_offset - start_shift,
1035                         strbeg, strend);
1036         }
1037
1038         s = HOP3c(rx_origin, other->min_offset, strend);
1039         if (s < other_last)     /* These positions already checked */
1040             s = other_last;
1041
1042         must = utf8_target ? other->utf8_substr : other->substr;
1043         assert(SvPOK(must));
1044         {
1045             char *from = s;
1046             char *to   = last + SvCUR(must) - (SvTAIL(must)!=0);
1047
1048             if (from > to) {
1049                 s = NULL;
1050                 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1051                     "  skipping 'other' fbm scan: %"IVdf" > %"IVdf"\n",
1052                     (IV)(from - strbeg),
1053                     (IV)(to   - strbeg)
1054                 ));
1055             }
1056             else {
1057                 s = fbm_instr(
1058                     (unsigned char*)from,
1059                     (unsigned char*)to,
1060                     must,
1061                     multiline ? FBMrf_MULTILINE : 0
1062                 );
1063                 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1064                     "  doing 'other' fbm scan, [%"IVdf"..%"IVdf"] gave %"IVdf"\n",
1065                     (IV)(from - strbeg),
1066                     (IV)(to   - strbeg),
1067                     (IV)(s ? s - strbeg : -1)
1068                 ));
1069             }
1070         }
1071
1072         DEBUG_EXECUTE_r({
1073             RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
1074                 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
1075             PerlIO_printf(Perl_debug_log, "  %s %s substr %s%s",
1076                 s ? "Found" : "Contradicts",
1077                 other_ix ? "floating" : "anchored",
1078                 quoted, RE_SV_TAIL(must));
1079         });
1080
1081
1082         if (!s) {
1083             /* last1 is latest possible substr location. If we didn't
1084              * find it before there, we never will */
1085             if (last >= last1) {
1086                 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1087                                         "; giving up...\n"));
1088                 goto fail_finish;
1089             }
1090
1091             /* try to find the check substr again at a later
1092              * position. Maybe next time we'll find the "other" substr
1093              * in range too */
1094             other_last = HOP3c(last, 1, strend) /* highest failure */;
1095             rx_origin =
1096                 other_ix /* i.e. if other-is-float */
1097                     ? HOP3c(rx_origin, 1, strend)
1098                     : HOP4c(last, 1 - other->min_offset, strbeg, strend);
1099             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1100                 "; about to retry %s at offset %ld (rx_origin now %"IVdf")...\n",
1101                 (other_ix ? "floating" : "anchored"),
1102                 (long)(HOP3c(check_at, 1, strend) - strbeg),
1103                 (IV)(rx_origin - strbeg)
1104             ));
1105             goto restart;
1106         }
1107         else {
1108             if (other_ix) { /* if (other-is-float) */
1109                 /* other_last is set to s, not s+1, since its possible for
1110                  * a floating substr to fail first time, then succeed
1111                  * second time at the same floating position; e.g.:
1112                  *     "-AB--AABZ" =~ /\wAB\d*Z/
1113                  * The first time round, anchored and float match at
1114                  * "-(AB)--AAB(Z)" then fail on the initial \w character
1115                  * class. Second time round, they match at "-AB--A(AB)(Z)".
1116                  */
1117                 other_last = s;
1118             }
1119             else {
1120                 rx_origin = HOP3c(s, -other->min_offset, strbeg);
1121                 other_last = HOP3c(s, 1, strend);
1122             }
1123             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1124                 " at offset %ld (rx_origin now %"IVdf")...\n",
1125                   (long)(s - strbeg),
1126                 (IV)(rx_origin - strbeg)
1127               ));
1128
1129         }
1130     }
1131     else {
1132         DEBUG_OPTIMISE_MORE_r(
1133             PerlIO_printf(Perl_debug_log,
1134                 "  Check-only match: offset min:%"IVdf" max:%"IVdf
1135                 " check_at:%"IVdf" rx_origin:%"IVdf" rx_origin-check_at:%"IVdf
1136                 " strend:%"IVdf"\n",
1137                 (IV)prog->check_offset_min,
1138                 (IV)prog->check_offset_max,
1139                 (IV)(check_at-strbeg),
1140                 (IV)(rx_origin-strbeg),
1141                 (IV)(rx_origin-check_at),
1142                 (IV)(strend-strbeg)
1143             )
1144         );
1145     }
1146
1147   postprocess_substr_matches:
1148
1149     /* handle the extra constraint of /^.../m if present */
1150
1151     if (ml_anch && rx_origin != strbeg && rx_origin[-1] != '\n') {
1152         char *s;
1153
1154         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1155                         "  looking for /^/m anchor"));
1156
1157         /* we have failed the constraint of a \n before rx_origin.
1158          * Find the next \n, if any, even if it's beyond the current
1159          * anchored and/or floating substrings. Whether we should be
1160          * scanning ahead for the next \n or the next substr is debatable.
1161          * On the one hand you'd expect rare substrings to appear less
1162          * often than \n's. On the other hand, searching for \n means
1163          * we're effectively flipping between check_substr and "\n" on each
1164          * iteration as the current "rarest" string candidate, which
1165          * means for example that we'll quickly reject the whole string if
1166          * hasn't got a \n, rather than trying every substr position
1167          * first
1168          */
1169
1170         s = HOP3c(strend, - prog->minlen, strpos);
1171         if (s <= rx_origin ||
1172             ! ( rx_origin = (char *)memchr(rx_origin, '\n', s - rx_origin)))
1173         {
1174             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1175                             "  Did not find /%s^%s/m...\n",
1176                             PL_colors[0], PL_colors[1]));
1177             goto fail_finish;
1178         }
1179
1180         /* earliest possible origin is 1 char after the \n.
1181          * (since *rx_origin == '\n', it's safe to ++ here rather than
1182          * HOP(rx_origin, 1)) */
1183         rx_origin++;
1184
1185         if (prog->substrs->check_ix == 0  /* check is anchored */
1186             || rx_origin >= HOP3c(check_at,  - prog->check_offset_min, strpos))
1187         {
1188             /* Position contradicts check-string; either because
1189              * check was anchored (and thus has no wiggle room),
1190              * or check was float and rx_origin is above the float range */
1191             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1192                 "  Found /%s^%s/m, about to restart lookup for check-string with rx_origin %ld...\n",
1193                 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1194             goto restart;
1195         }
1196
1197         /* if we get here, the check substr must have been float,
1198          * is in range, and we may or may not have had an anchored
1199          * "other" substr which still contradicts */
1200         assert(prog->substrs->check_ix); /* check is float */
1201
1202         if (utf8_target ? prog->anchored_utf8 : prog->anchored_substr) {
1203             /* whoops, the anchored "other" substr exists, so we still
1204              * contradict. On the other hand, the float "check" substr
1205              * didn't contradict, so just retry the anchored "other"
1206              * substr */
1207             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1208                 "  Found /%s^%s/m, rescanning for anchored from offset %"IVdf" (rx_origin now %"IVdf")...\n",
1209                 PL_colors[0], PL_colors[1],
1210                 (IV)(rx_origin - strbeg + prog->anchored_offset),
1211                 (IV)(rx_origin - strbeg)
1212             ));
1213             goto do_other_substr;
1214         }
1215
1216         /* success: we don't contradict the found floating substring
1217          * (and there's no anchored substr). */
1218         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1219             "  Found /%s^%s/m with rx_origin %ld...\n",
1220             PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1221     }
1222     else {
1223         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1224             "  (multiline anchor test skipped)\n"));
1225     }
1226
1227   success_at_start:
1228
1229
1230     /* if we have a starting character class, then test that extra constraint.
1231      * (trie stclasses are too expensive to use here, we are better off to
1232      * leave it to regmatch itself) */
1233
1234     if (progi->regstclass && PL_regkind[OP(progi->regstclass)]!=TRIE) {
1235         const U8* const str = (U8*)STRING(progi->regstclass);
1236
1237         /* XXX this value could be pre-computed */
1238         const int cl_l = (PL_regkind[OP(progi->regstclass)] == EXACT
1239                     ?  (reginfo->is_utf8_pat
1240                         ? utf8_distance(str + STR_LEN(progi->regstclass), str)
1241                         : STR_LEN(progi->regstclass))
1242                     : 1);
1243         char * endpos;
1244         char *s;
1245         /* latest pos that a matching float substr constrains rx start to */
1246         char *rx_max_float = NULL;
1247
1248         /* if the current rx_origin is anchored, either by satisfying an
1249          * anchored substring constraint, or a /^.../m constraint, then we
1250          * can reject the current origin if the start class isn't found
1251          * at the current position. If we have a float-only match, then
1252          * rx_origin is constrained to a range; so look for the start class
1253          * in that range. if neither, then look for the start class in the
1254          * whole rest of the string */
1255
1256         /* XXX DAPM it's not clear what the minlen test is for, and why
1257          * it's not used in the floating case. Nothing in the test suite
1258          * causes minlen == 0 here. See <20140313134639.GS12844@iabyn.com>.
1259          * Here are some old comments, which may or may not be correct:
1260          *
1261          *   minlen == 0 is possible if regstclass is \b or \B,
1262          *   and the fixed substr is ''$.
1263          *   Since minlen is already taken into account, rx_origin+1 is
1264          *   before strend; accidentally, minlen >= 1 guaranties no false
1265          *   positives at rx_origin + 1 even for \b or \B.  But (minlen? 1 :
1266          *   0) below assumes that regstclass does not come from lookahead...
1267          *   If regstclass takes bytelength more than 1: If charlength==1, OK.
1268          *   This leaves EXACTF-ish only, which are dealt with in
1269          *   find_byclass().
1270          */
1271
1272         if (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
1273             endpos= HOP3c(rx_origin, (prog->minlen ? cl_l : 0), strend);
1274         else if (prog->float_substr || prog->float_utf8) {
1275             rx_max_float = HOP3c(check_at, -start_shift, strbeg);
1276             endpos= HOP3c(rx_max_float, cl_l, strend);
1277         }
1278         else 
1279             endpos= strend;
1280                     
1281         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1282             "  looking for class: start_shift: %"IVdf" check_at: %"IVdf
1283             " rx_origin: %"IVdf" endpos: %"IVdf"\n",
1284               (IV)start_shift, (IV)(check_at - strbeg),
1285               (IV)(rx_origin - strbeg), (IV)(endpos - strbeg)));
1286
1287         s = find_byclass(prog, progi->regstclass, rx_origin, endpos,
1288                             reginfo);
1289         if (!s) {
1290             if (endpos == strend) {
1291                 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1292                                 "  Could not match STCLASS...\n") );
1293                 goto fail;
1294             }
1295             DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1296                                "  This position contradicts STCLASS...\n") );
1297             if ((prog->intflags & PREGf_ANCH) && !ml_anch
1298                         && !(prog->intflags & PREGf_IMPLICIT))
1299                 goto fail;
1300
1301             /* Contradict one of substrings */
1302             if (prog->anchored_substr || prog->anchored_utf8) {
1303                 if (prog->substrs->check_ix == 1) { /* check is float */
1304                     /* Have both, check_string is floating */
1305                     assert(rx_origin + start_shift <= check_at);
1306                     if (rx_origin + start_shift != check_at) {
1307                         /* not at latest position float substr could match:
1308                          * Recheck anchored substring, but not floating.
1309                          * The condition above is in bytes rather than
1310                          * chars for efficiency. It's conservative, in
1311                          * that it errs on the side of doing 'goto
1312                          * do_other_substr'. In this case, at worst,
1313                          * an extra anchored search may get done, but in
1314                          * practice the extra fbm_instr() is likely to
1315                          * get skipped anyway. */
1316                         DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1317                             "  about to retry anchored at offset %ld (rx_origin now %"IVdf")...\n",
1318                             (long)(other_last - strbeg),
1319                             (IV)(rx_origin - strbeg)
1320                         ));
1321                         goto do_other_substr;
1322                     }
1323                 }
1324             }
1325             else {
1326                 /* float-only */
1327
1328                 if (ml_anch) {
1329                     /* In the presence of ml_anch, we might be able to
1330                      * find another \n without breaking the current float
1331                      * constraint. */
1332
1333                     /* strictly speaking this should be HOP3c(..., 1, ...),
1334                      * but since we goto a block of code that's going to
1335                      * search for the next \n if any, its safe here */
1336                     rx_origin++;
1337                     DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1338                               "  about to look for /%s^%s/m starting at rx_origin %ld...\n",
1339                               PL_colors[0], PL_colors[1],
1340                               (long)(rx_origin - strbeg)) );
1341                     goto postprocess_substr_matches;
1342                 }
1343
1344                 /* strictly speaking this can never be true; but might
1345                  * be if we ever allow intuit without substrings */
1346                 if (!(utf8_target ? prog->float_utf8 : prog->float_substr))
1347                     goto fail;
1348
1349                 rx_origin = rx_max_float;
1350             }
1351
1352             /* at this point, any matching substrings have been
1353              * contradicted. Start again... */
1354
1355             rx_origin = HOP3c(rx_origin, 1, strend);
1356
1357             /* uses bytes rather than char calculations for efficiency.
1358              * It's conservative: it errs on the side of doing 'goto restart',
1359              * where there is code that does a proper char-based test */
1360             if (rx_origin + start_shift + end_shift > strend) {
1361                 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1362                                        "  Could not match STCLASS...\n") );
1363                 goto fail;
1364             }
1365             DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1366                 "  about to look for %s substr starting at offset %ld (rx_origin now %"IVdf")...\n",
1367                 (prog->substrs->check_ix ? "floating" : "anchored"),
1368                 (long)(rx_origin + start_shift - strbeg),
1369                 (IV)(rx_origin - strbeg)
1370             ));
1371             goto restart;
1372         }
1373
1374         /* Success !!! */
1375
1376         if (rx_origin != s) {
1377             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1378                         "  By STCLASS: moving %ld --> %ld\n",
1379                                   (long)(rx_origin - strbeg), (long)(s - strbeg))
1380                    );
1381         }
1382         else {
1383             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1384                                   "  Does not contradict STCLASS...\n");
1385                    );
1386         }
1387     }
1388
1389     /* Decide whether using the substrings helped */
1390
1391     if (rx_origin != strpos) {
1392         /* Fixed substring is found far enough so that the match
1393            cannot start at strpos. */
1394
1395         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "  try at offset...\n"));
1396         ++BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr);        /* hooray/5 */
1397     }
1398     else {
1399         /* The found rx_origin position does not prohibit matching at
1400          * strpos, so calling intuit didn't gain us anything. Decrement
1401          * the BmUSEFUL() count on the check substring, and if we reach
1402          * zero, free it.  */
1403         if (!(prog->intflags & PREGf_NAUGHTY)
1404             && (utf8_target ? (
1405                 prog->check_utf8                /* Could be deleted already */
1406                 && --BmUSEFUL(prog->check_utf8) < 0
1407                 && (prog->check_utf8 == prog->float_utf8)
1408             ) : (
1409                 prog->check_substr              /* Could be deleted already */
1410                 && --BmUSEFUL(prog->check_substr) < 0
1411                 && (prog->check_substr == prog->float_substr)
1412             )))
1413         {
1414             /* If flags & SOMETHING - do not do it many times on the same match */
1415             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "  ... Disabling check substring...\n"));
1416             /* XXX Does the destruction order has to change with utf8_target? */
1417             SvREFCNT_dec(utf8_target ? prog->check_utf8 : prog->check_substr);
1418             SvREFCNT_dec(utf8_target ? prog->check_substr : prog->check_utf8);
1419             prog->check_substr = prog->check_utf8 = NULL;       /* disable */
1420             prog->float_substr = prog->float_utf8 = NULL;       /* clear */
1421             check = NULL;                       /* abort */
1422             /* XXXX This is a remnant of the old implementation.  It
1423                     looks wasteful, since now INTUIT can use many
1424                     other heuristics. */
1425             prog->extflags &= ~RXf_USE_INTUIT;
1426         }
1427     }
1428
1429     DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1430             "Intuit: %sSuccessfully guessed:%s match at offset %ld\n",
1431              PL_colors[4], PL_colors[5], (long)(rx_origin - strbeg)) );
1432
1433     return rx_origin;
1434
1435   fail_finish:                          /* Substring not found */
1436     if (prog->check_substr || prog->check_utf8)         /* could be removed already */
1437         BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
1438   fail:
1439     DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch rejected by optimizer%s\n",
1440                           PL_colors[4], PL_colors[5]));
1441     return NULL;
1442 }
1443
1444
1445 #define DECL_TRIE_TYPE(scan) \
1446     const enum { trie_plain, trie_utf8, trie_utf8_fold, trie_latin_utf8_fold,       \
1447                  trie_utf8_exactfa_fold, trie_latin_utf8_exactfa_fold,              \
1448                  trie_utf8l, trie_flu8 }                                            \
1449                     trie_type = ((scan->flags == EXACT)                             \
1450                                  ? (utf8_target ? trie_utf8 : trie_plain)           \
1451                                  : (scan->flags == EXACTL)                          \
1452                                     ? (utf8_target ? trie_utf8l : trie_plain)       \
1453                                     : (scan->flags == EXACTFA)                      \
1454                                       ? (utf8_target                                \
1455                                          ? trie_utf8_exactfa_fold                   \
1456                                          : trie_latin_utf8_exactfa_fold)            \
1457                                       : (scan->flags == EXACTFLU8                   \
1458                                          ? trie_flu8                                \
1459                                          : (utf8_target                             \
1460                                            ? trie_utf8_fold                         \
1461                                            :   trie_latin_utf8_fold)))
1462
1463 #define REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc, uscan, len, uvc, charid, foldlen, foldbuf, uniflags) \
1464 STMT_START {                                                                        \
1465     STRLEN skiplen;                                                                 \
1466     U8 flags = FOLD_FLAGS_FULL;                                                     \
1467     switch (trie_type) {                                                            \
1468     case trie_flu8:                                                                 \
1469         _CHECK_AND_WARN_PROBLEMATIC_LOCALE;                                         \
1470         if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) {                             \
1471             _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc));          \
1472         }                                                                           \
1473         goto do_trie_utf8_fold;                                                     \
1474     case trie_utf8_exactfa_fold:                                                    \
1475         flags |= FOLD_FLAGS_NOMIX_ASCII;                                            \
1476         /* FALLTHROUGH */                                                           \
1477     case trie_utf8_fold:                                                            \
1478       do_trie_utf8_fold:                                                            \
1479         if ( foldlen>0 ) {                                                          \
1480             uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1481             foldlen -= len;                                                         \
1482             uscan += len;                                                           \
1483             len=0;                                                                  \
1484         } else {                                                                    \
1485             uvc = _to_utf8_fold_flags( (const U8*) uc, foldbuf, &foldlen, flags);   \
1486             len = UTF8SKIP(uc);                                                     \
1487             skiplen = UVCHR_SKIP( uvc );                                            \
1488             foldlen -= skiplen;                                                     \
1489             uscan = foldbuf + skiplen;                                              \
1490         }                                                                           \
1491         break;                                                                      \
1492     case trie_latin_utf8_exactfa_fold:                                              \
1493         flags |= FOLD_FLAGS_NOMIX_ASCII;                                            \
1494         /* FALLTHROUGH */                                                           \
1495     case trie_latin_utf8_fold:                                                      \
1496         if ( foldlen>0 ) {                                                          \
1497             uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1498             foldlen -= len;                                                         \
1499             uscan += len;                                                           \
1500             len=0;                                                                  \
1501         } else {                                                                    \
1502             len = 1;                                                                \
1503             uvc = _to_fold_latin1( (U8) *uc, foldbuf, &foldlen, flags);             \
1504             skiplen = UVCHR_SKIP( uvc );                                            \
1505             foldlen -= skiplen;                                                     \
1506             uscan = foldbuf + skiplen;                                              \
1507         }                                                                           \
1508         break;                                                                      \
1509     case trie_utf8l:                                                                \
1510         _CHECK_AND_WARN_PROBLEMATIC_LOCALE;                                         \
1511         if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) {                             \
1512             _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc));          \
1513         }                                                                           \
1514         /* FALLTHROUGH */                                                           \
1515     case trie_utf8:                                                                 \
1516         uvc = utf8n_to_uvchr( (const U8*) uc, UTF8_MAXLEN, &len, uniflags );        \
1517         break;                                                                      \
1518     case trie_plain:                                                                \
1519         uvc = (UV)*uc;                                                              \
1520         len = 1;                                                                    \
1521     }                                                                               \
1522     if (uvc < 256) {                                                                \
1523         charid = trie->charmap[ uvc ];                                              \
1524     }                                                                               \
1525     else {                                                                          \
1526         charid = 0;                                                                 \
1527         if (widecharmap) {                                                          \
1528             SV** const svpp = hv_fetch(widecharmap,                                 \
1529                         (char*)&uvc, sizeof(UV), 0);                                \
1530             if (svpp)                                                               \
1531                 charid = (U16)SvIV(*svpp);                                          \
1532         }                                                                           \
1533     }                                                                               \
1534 } STMT_END
1535
1536 #define DUMP_EXEC_POS(li,s,doutf8)                          \
1537     dump_exec_pos(li,s,(reginfo->strend),(reginfo->strbeg), \
1538                 startpos, doutf8)
1539
1540 #define REXEC_FBC_EXACTISH_SCAN(COND)                     \
1541 STMT_START {                                              \
1542     while (s <= e) {                                      \
1543         if ( (COND)                                       \
1544              && (ln == 1 || folder(s, pat_string, ln))    \
1545              && (reginfo->intuit || regtry(reginfo, &s)) )\
1546             goto got_it;                                  \
1547         s++;                                              \
1548     }                                                     \
1549 } STMT_END
1550
1551 #define REXEC_FBC_UTF8_SCAN(CODE)                     \
1552 STMT_START {                                          \
1553     while (s < strend) {                              \
1554         CODE                                          \
1555         s += UTF8SKIP(s);                             \
1556     }                                                 \
1557 } STMT_END
1558
1559 #define REXEC_FBC_SCAN(CODE)                          \
1560 STMT_START {                                          \
1561     while (s < strend) {                              \
1562         CODE                                          \
1563         s++;                                          \
1564     }                                                 \
1565 } STMT_END
1566
1567 #define REXEC_FBC_UTF8_CLASS_SCAN(COND)                        \
1568 REXEC_FBC_UTF8_SCAN( /* Loops while (s < strend) */            \
1569     if (COND) {                                                \
1570         if (tmp && (reginfo->intuit || regtry(reginfo, &s)))   \
1571             goto got_it;                                       \
1572         else                                                   \
1573             tmp = doevery;                                     \
1574     }                                                          \
1575     else                                                       \
1576         tmp = 1;                                               \
1577 )
1578
1579 #define REXEC_FBC_CLASS_SCAN(COND)                             \
1580 REXEC_FBC_SCAN( /* Loops while (s < strend) */                 \
1581     if (COND) {                                                \
1582         if (tmp && (reginfo->intuit || regtry(reginfo, &s)))   \
1583             goto got_it;                                       \
1584         else                                                   \
1585             tmp = doevery;                                     \
1586     }                                                          \
1587     else                                                       \
1588         tmp = 1;                                               \
1589 )
1590
1591 #define REXEC_FBC_CSCAN(CONDUTF8,COND)                         \
1592     if (utf8_target) {                                         \
1593         REXEC_FBC_UTF8_CLASS_SCAN(CONDUTF8);                   \
1594     }                                                          \
1595     else {                                                     \
1596         REXEC_FBC_CLASS_SCAN(COND);                            \
1597     }
1598
1599 /* The three macros below are slightly different versions of the same logic.
1600  *
1601  * The first is for /a and /aa when the target string is UTF-8.  This can only
1602  * match ascii, but it must advance based on UTF-8.   The other two handle the
1603  * non-UTF-8 and the more generic UTF-8 cases.   In all three, we are looking
1604  * for the boundary (or non-boundary) between a word and non-word character.
1605  * The utf8 and non-utf8 cases have the same logic, but the details must be
1606  * different.  Find the "wordness" of the character just prior to this one, and
1607  * compare it with the wordness of this one.  If they differ, we have a
1608  * boundary.  At the beginning of the string, pretend that the previous
1609  * character was a new-line.
1610  *
1611  * All these macros uncleanly have side-effects with each other and outside
1612  * variables.  So far it's been too much trouble to clean-up
1613  *
1614  * TEST_NON_UTF8 is the macro or function to call to test if its byte input is
1615  *               a word character or not.
1616  * IF_SUCCESS    is code to do if it finds that we are at a boundary between
1617  *               word/non-word
1618  * IF_FAIL       is code to do if we aren't at a boundary between word/non-word
1619  *
1620  * Exactly one of the two IF_FOO parameters is a no-op, depending on whether we
1621  * are looking for a boundary or for a non-boundary.  If we are looking for a
1622  * boundary, we want IF_FAIL to be the no-op, and for IF_SUCCESS to go out and
1623  * see if this tentative match actually works, and if so, to quit the loop
1624  * here.  And vice-versa if we are looking for a non-boundary.
1625  *
1626  * 'tmp' below in the next three macros in the REXEC_FBC_SCAN and
1627  * REXEC_FBC_UTF8_SCAN loops is a loop invariant, a bool giving the return of
1628  * TEST_NON_UTF8(s-1).  To see this, note that that's what it is defined to be
1629  * at entry to the loop, and to get to the IF_FAIL branch, tmp must equal
1630  * TEST_NON_UTF8(s), and in the opposite branch, IF_SUCCESS, tmp is that
1631  * complement.  But in that branch we complement tmp, meaning that at the
1632  * bottom of the loop tmp is always going to be equal to TEST_NON_UTF8(s),
1633  * which means at the top of the loop in the next iteration, it is
1634  * TEST_NON_UTF8(s-1) */
1635 #define FBC_UTF8_A(TEST_NON_UTF8, IF_SUCCESS, IF_FAIL)                         \
1636     tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n';                      \
1637     tmp = TEST_NON_UTF8(tmp);                                                  \
1638     REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */                     \
1639         if (tmp == ! TEST_NON_UTF8((U8) *s)) {                                 \
1640             tmp = !tmp;                                                        \
1641             IF_SUCCESS; /* Is a boundary if values for s-1 and s differ */     \
1642         }                                                                      \
1643         else {                                                                 \
1644             IF_FAIL;                                                           \
1645         }                                                                      \
1646     );                                                                         \
1647
1648 /* Like FBC_UTF8_A, but TEST_UV is a macro which takes a UV as its input, and
1649  * TEST_UTF8 is a macro that for the same input code points returns identically
1650  * to TEST_UV, but takes a pointer to a UTF-8 encoded string instead */
1651 #define FBC_UTF8(TEST_UV, TEST_UTF8, IF_SUCCESS, IF_FAIL)                      \
1652     if (s == reginfo->strbeg) {                                                \
1653         tmp = '\n';                                                            \
1654     }                                                                          \
1655     else { /* Back-up to the start of the previous character */                \
1656         U8 * const r = reghop3((U8*)s, -1, (U8*)reginfo->strbeg);              \
1657         tmp = utf8n_to_uvchr(r, (U8*) reginfo->strend - r,                     \
1658                                                        0, UTF8_ALLOW_DEFAULT); \
1659     }                                                                          \
1660     tmp = TEST_UV(tmp);                                                        \
1661     LOAD_UTF8_CHARCLASS_ALNUM();                                               \
1662     REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */                     \
1663         if (tmp == ! (TEST_UTF8((U8 *) s))) {                                  \
1664             tmp = !tmp;                                                        \
1665             IF_SUCCESS;                                                        \
1666         }                                                                      \
1667         else {                                                                 \
1668             IF_FAIL;                                                           \
1669         }                                                                      \
1670     );
1671
1672 /* Like the above two macros.  UTF8_CODE is the complete code for handling
1673  * UTF-8.  Common to the BOUND and NBOUND cases, set-up by the FBC_BOUND, etc
1674  * macros below */
1675 #define FBC_BOUND_COMMON(UTF8_CODE, TEST_NON_UTF8, IF_SUCCESS, IF_FAIL)        \
1676     if (utf8_target) {                                                         \
1677         UTF8_CODE                                                              \
1678     }                                                                          \
1679     else {  /* Not utf8 */                                                     \
1680         tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n';                  \
1681         tmp = TEST_NON_UTF8(tmp);                                              \
1682         REXEC_FBC_SCAN( /* advances s while s < strend */                      \
1683             if (tmp == ! TEST_NON_UTF8((U8) *s)) {                             \
1684                 IF_SUCCESS;                                                    \
1685                 tmp = !tmp;                                                    \
1686             }                                                                  \
1687             else {                                                             \
1688                 IF_FAIL;                                                       \
1689             }                                                                  \
1690         );                                                                     \
1691     }                                                                          \
1692     /* Here, things have been set up by the previous code so that tmp is the   \
1693      * return of TEST_NON_UTF(s-1) or TEST_UTF8(s-1) (depending on the         \
1694      * utf8ness of the target).  We also have to check if this matches against \
1695      * the EOS, which we treat as a \n (which is the same value in both UTF-8  \
1696      * or non-UTF8, so can use the non-utf8 test condition even for a UTF-8    \
1697      * string */                                                               \
1698     if (tmp == ! TEST_NON_UTF8('\n')) {                                        \
1699         IF_SUCCESS;                                                            \
1700     }                                                                          \
1701     else {                                                                     \
1702         IF_FAIL;                                                               \
1703     }
1704
1705 /* This is the macro to use when we want to see if something that looks like it
1706  * could match, actually does, and if so exits the loop */
1707 #define REXEC_FBC_TRYIT                            \
1708     if ((reginfo->intuit || regtry(reginfo, &s)))  \
1709         goto got_it
1710
1711 /* The only difference between the BOUND and NBOUND cases is that
1712  * REXEC_FBC_TRYIT is called when matched in BOUND, and when non-matched in
1713  * NBOUND.  This is accomplished by passing it as either the if or else clause,
1714  * with the other one being empty (PLACEHOLDER is defined as empty).
1715  *
1716  * The TEST_FOO parameters are for operating on different forms of input, but
1717  * all should be ones that return identically for the same underlying code
1718  * points */
1719 #define FBC_BOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8)                           \
1720     FBC_BOUND_COMMON(                                                          \
1721           FBC_UTF8(TEST_UV, TEST_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER),          \
1722           TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1723
1724 #define FBC_BOUND_A(TEST_NON_UTF8)                                             \
1725     FBC_BOUND_COMMON(                                                          \
1726             FBC_UTF8_A(TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER),           \
1727             TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1728
1729 #define FBC_NBOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8)                          \
1730     FBC_BOUND_COMMON(                                                          \
1731           FBC_UTF8(TEST_UV, TEST_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT),          \
1732           TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1733
1734 #define FBC_NBOUND_A(TEST_NON_UTF8)                                            \
1735     FBC_BOUND_COMMON(                                                          \
1736             FBC_UTF8_A(TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT),           \
1737             TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1738
1739 #ifdef DEBUGGING
1740 static IV
1741 S_get_break_val_cp_checked(SV* const invlist, const UV cp_in) {
1742   IV cp_out = Perl__invlist_search(invlist, cp_in);
1743   assert(cp_out >= 0);
1744   return cp_out;
1745 }
1746 #  define _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp) \
1747         invmap[S_get_break_val_cp_checked(invlist, cp)]
1748 #else
1749 #  define _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp) \
1750         invmap[_invlist_search(invlist, cp)]
1751 #endif
1752
1753 /* Takes a pointer to an inversion list, a pointer to its corresponding
1754  * inversion map, and a code point, and returns the code point's value
1755  * according to the two arrays.  It assumes that all code points have a value.
1756  * This is used as the base macro for macros for particular properties */
1757 #define _generic_GET_BREAK_VAL_CP(invlist, invmap, cp)              \
1758         _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp)
1759
1760 /* Same as above, but takes begin, end ptrs to a UTF-8 encoded string instead
1761  * of a code point, returning the value for the first code point in the string.
1762  * And it takes the particular macro name that finds the desired value given a
1763  * code point.  Merely convert the UTF-8 to code point and call the cp macro */
1764 #define _generic_GET_BREAK_VAL_UTF8(cp_macro, pos, strend)                     \
1765              (__ASSERT_(pos < strend)                                          \
1766                  /* Note assumes is valid UTF-8 */                             \
1767              (cp_macro(utf8_to_uvchr_buf((pos), (strend), NULL))))
1768
1769 /* Returns the GCB value for the input code point */
1770 #define getGCB_VAL_CP(cp)                                                      \
1771           _generic_GET_BREAK_VAL_CP(                                           \
1772                                     PL_GCB_invlist,                            \
1773                                     _Perl_GCB_invmap,                          \
1774                                     (cp))
1775
1776 /* Returns the GCB value for the first code point in the UTF-8 encoded string
1777  * bounded by pos and strend */
1778 #define getGCB_VAL_UTF8(pos, strend)                                           \
1779     _generic_GET_BREAK_VAL_UTF8(getGCB_VAL_CP, pos, strend)
1780
1781 /* Returns the LB value for the input code point */
1782 #define getLB_VAL_CP(cp)                                                       \
1783           _generic_GET_BREAK_VAL_CP(                                           \
1784                                     PL_LB_invlist,                             \
1785                                     _Perl_LB_invmap,                           \
1786                                     (cp))
1787
1788 /* Returns the LB value for the first code point in the UTF-8 encoded string
1789  * bounded by pos and strend */
1790 #define getLB_VAL_UTF8(pos, strend)                                            \
1791     _generic_GET_BREAK_VAL_UTF8(getLB_VAL_CP, pos, strend)
1792
1793
1794 /* Returns the SB value for the input code point */
1795 #define getSB_VAL_CP(cp)                                                       \
1796           _generic_GET_BREAK_VAL_CP(                                           \
1797                                     PL_SB_invlist,                             \
1798                                     _Perl_SB_invmap,                     \
1799                                     (cp))
1800
1801 /* Returns the SB value for the first code point in the UTF-8 encoded string
1802  * bounded by pos and strend */
1803 #define getSB_VAL_UTF8(pos, strend)                                            \
1804     _generic_GET_BREAK_VAL_UTF8(getSB_VAL_CP, pos, strend)
1805
1806 /* Returns the WB value for the input code point */
1807 #define getWB_VAL_CP(cp)                                                       \
1808           _generic_GET_BREAK_VAL_CP(                                           \
1809                                     PL_WB_invlist,                             \
1810                                     _Perl_WB_invmap,                         \
1811                                     (cp))
1812
1813 /* Returns the WB value for the first code point in the UTF-8 encoded string
1814  * bounded by pos and strend */
1815 #define getWB_VAL_UTF8(pos, strend)                                            \
1816     _generic_GET_BREAK_VAL_UTF8(getWB_VAL_CP, pos, strend)
1817
1818 /* We know what class REx starts with.  Try to find this position... */
1819 /* if reginfo->intuit, its a dryrun */
1820 /* annoyingly all the vars in this routine have different names from their counterparts
1821    in regmatch. /grrr */
1822 STATIC char *
1823 S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s, 
1824     const char *strend, regmatch_info *reginfo)
1825 {
1826     dVAR;
1827     const I32 doevery = (prog->intflags & PREGf_SKIP) == 0;
1828     char *pat_string;   /* The pattern's exactish string */
1829     char *pat_end;          /* ptr to end char of pat_string */
1830     re_fold_t folder;   /* Function for computing non-utf8 folds */
1831     const U8 *fold_array;   /* array for folding ords < 256 */
1832     STRLEN ln;
1833     STRLEN lnc;
1834     U8 c1;
1835     U8 c2;
1836     char *e;
1837     I32 tmp = 1;        /* Scratch variable? */
1838     const bool utf8_target = reginfo->is_utf8_target;
1839     UV utf8_fold_flags = 0;
1840     const bool is_utf8_pat = reginfo->is_utf8_pat;
1841     bool to_complement = FALSE; /* Invert the result?  Taking the xor of this
1842                                    with a result inverts that result, as 0^1 =
1843                                    1 and 1^1 = 0 */
1844     _char_class_number classnum;
1845
1846     RXi_GET_DECL(prog,progi);
1847
1848     PERL_ARGS_ASSERT_FIND_BYCLASS;
1849
1850     /* We know what class it must start with. */
1851     switch (OP(c)) {
1852     case ANYOFL:
1853         _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1854
1855         if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(c)) && ! IN_UTF8_CTYPE_LOCALE) {
1856             Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
1857         }
1858
1859         /* FALLTHROUGH */
1860     case ANYOFD:
1861     case ANYOF:
1862         if (utf8_target) {
1863             REXEC_FBC_UTF8_CLASS_SCAN(
1864                       reginclass(prog, c, (U8*)s, (U8*) strend, utf8_target));
1865         }
1866         else {
1867             REXEC_FBC_CLASS_SCAN(REGINCLASS(prog, c, (U8*)s));
1868         }
1869         break;
1870
1871     case EXACTFA_NO_TRIE:   /* This node only generated for non-utf8 patterns */
1872         assert(! is_utf8_pat);
1873         /* FALLTHROUGH */
1874     case EXACTFA:
1875         if (is_utf8_pat || utf8_target) {
1876             utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
1877             goto do_exactf_utf8;
1878         }
1879         fold_array = PL_fold_latin1;    /* Latin1 folds are not affected by */
1880         folder = foldEQ_latin1;         /* /a, except the sharp s one which */
1881         goto do_exactf_non_utf8;        /* isn't dealt with by these */
1882
1883     case EXACTF:   /* This node only generated for non-utf8 patterns */
1884         assert(! is_utf8_pat);
1885         if (utf8_target) {
1886             utf8_fold_flags = 0;
1887             goto do_exactf_utf8;
1888         }
1889         fold_array = PL_fold;
1890         folder = foldEQ;
1891         goto do_exactf_non_utf8;
1892
1893     case EXACTFL:
1894         _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1895         if (is_utf8_pat || utf8_target || IN_UTF8_CTYPE_LOCALE) {
1896             utf8_fold_flags = FOLDEQ_LOCALE;
1897             goto do_exactf_utf8;
1898         }
1899         fold_array = PL_fold_locale;
1900         folder = foldEQ_locale;
1901         goto do_exactf_non_utf8;
1902
1903     case EXACTFU_SS:
1904         if (is_utf8_pat) {
1905             utf8_fold_flags = FOLDEQ_S2_ALREADY_FOLDED;
1906         }
1907         goto do_exactf_utf8;
1908
1909     case EXACTFLU8:
1910             if (! utf8_target) {    /* All code points in this node require
1911                                        UTF-8 to express.  */
1912                 break;
1913             }
1914             utf8_fold_flags =  FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
1915                                              | FOLDEQ_S2_FOLDS_SANE;
1916             goto do_exactf_utf8;
1917
1918     case EXACTFU:
1919         if (is_utf8_pat || utf8_target) {
1920             utf8_fold_flags = is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
1921             goto do_exactf_utf8;
1922         }
1923
1924         /* Any 'ss' in the pattern should have been replaced by regcomp,
1925          * so we don't have to worry here about this single special case
1926          * in the Latin1 range */
1927         fold_array = PL_fold_latin1;
1928         folder = foldEQ_latin1;
1929
1930         /* FALLTHROUGH */
1931
1932       do_exactf_non_utf8: /* Neither pattern nor string are UTF8, and there
1933                            are no glitches with fold-length differences
1934                            between the target string and pattern */
1935
1936         /* The idea in the non-utf8 EXACTF* cases is to first find the
1937          * first character of the EXACTF* node and then, if necessary,
1938          * case-insensitively compare the full text of the node.  c1 is the
1939          * first character.  c2 is its fold.  This logic will not work for
1940          * Unicode semantics and the german sharp ss, which hence should
1941          * not be compiled into a node that gets here. */
1942         pat_string = STRING(c);
1943         ln  = STR_LEN(c);       /* length to match in octets/bytes */
1944
1945         /* We know that we have to match at least 'ln' bytes (which is the
1946          * same as characters, since not utf8).  If we have to match 3
1947          * characters, and there are only 2 availabe, we know without
1948          * trying that it will fail; so don't start a match past the
1949          * required minimum number from the far end */
1950         e = HOP3c(strend, -((SSize_t)ln), s);
1951
1952         if (reginfo->intuit && e < s) {
1953             e = s;                      /* Due to minlen logic of intuit() */
1954         }
1955
1956         c1 = *pat_string;
1957         c2 = fold_array[c1];
1958         if (c1 == c2) { /* If char and fold are the same */
1959             REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1);
1960         }
1961         else {
1962             REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1 || *(U8*)s == c2);
1963         }
1964         break;
1965
1966       do_exactf_utf8:
1967       {
1968         unsigned expansion;
1969
1970         /* If one of the operands is in utf8, we can't use the simpler folding
1971          * above, due to the fact that many different characters can have the
1972          * same fold, or portion of a fold, or different- length fold */
1973         pat_string = STRING(c);
1974         ln  = STR_LEN(c);       /* length to match in octets/bytes */
1975         pat_end = pat_string + ln;
1976         lnc = is_utf8_pat       /* length to match in characters */
1977                 ? utf8_length((U8 *) pat_string, (U8 *) pat_end)
1978                 : ln;
1979
1980         /* We have 'lnc' characters to match in the pattern, but because of
1981          * multi-character folding, each character in the target can match
1982          * up to 3 characters (Unicode guarantees it will never exceed
1983          * this) if it is utf8-encoded; and up to 2 if not (based on the
1984          * fact that the Latin 1 folds are already determined, and the
1985          * only multi-char fold in that range is the sharp-s folding to
1986          * 'ss'.  Thus, a pattern character can match as little as 1/3 of a
1987          * string character.  Adjust lnc accordingly, rounding up, so that
1988          * if we need to match at least 4+1/3 chars, that really is 5. */
1989         expansion = (utf8_target) ? UTF8_MAX_FOLD_CHAR_EXPAND : 2;
1990         lnc = (lnc + expansion - 1) / expansion;
1991
1992         /* As in the non-UTF8 case, if we have to match 3 characters, and
1993          * only 2 are left, it's guaranteed to fail, so don't start a
1994          * match that would require us to go beyond the end of the string
1995          */
1996         e = HOP3c(strend, -((SSize_t)lnc), s);
1997
1998         if (reginfo->intuit && e < s) {
1999             e = s;                      /* Due to minlen logic of intuit() */
2000         }
2001
2002         /* XXX Note that we could recalculate e to stop the loop earlier,
2003          * as the worst case expansion above will rarely be met, and as we
2004          * go along we would usually find that e moves further to the left.
2005          * This would happen only after we reached the point in the loop
2006          * where if there were no expansion we should fail.  Unclear if
2007          * worth the expense */
2008
2009         while (s <= e) {
2010             char *my_strend= (char *)strend;
2011             if (foldEQ_utf8_flags(s, &my_strend, 0,  utf8_target,
2012                   pat_string, NULL, ln, is_utf8_pat, utf8_fold_flags)
2013                 && (reginfo->intuit || regtry(reginfo, &s)) )
2014             {
2015                 goto got_it;
2016             }
2017             s += (utf8_target) ? UTF8SKIP(s) : 1;
2018         }
2019         break;
2020     }
2021
2022     case BOUNDL:
2023         _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2024         if (FLAGS(c) != TRADITIONAL_BOUND) {
2025             if (! IN_UTF8_CTYPE_LOCALE) {
2026                 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2027                                                 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2028             }
2029             goto do_boundu;
2030         }
2031
2032         FBC_BOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8);
2033         break;
2034
2035     case NBOUNDL:
2036         _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2037         if (FLAGS(c) != TRADITIONAL_BOUND) {
2038             if (! IN_UTF8_CTYPE_LOCALE) {
2039                 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2040                                                 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2041             }
2042             goto do_nboundu;
2043         }
2044
2045         FBC_NBOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8);
2046         break;
2047
2048     case BOUND: /* regcomp.c makes sure that this only has the traditional \b
2049                    meaning */
2050         assert(FLAGS(c) == TRADITIONAL_BOUND);
2051
2052         FBC_BOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8);
2053         break;
2054
2055     case BOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2056                    meaning */
2057         assert(FLAGS(c) == TRADITIONAL_BOUND);
2058
2059         FBC_BOUND_A(isWORDCHAR_A);
2060         break;
2061
2062     case NBOUND: /* regcomp.c makes sure that this only has the traditional \b
2063                    meaning */
2064         assert(FLAGS(c) == TRADITIONAL_BOUND);
2065
2066         FBC_NBOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8);
2067         break;
2068
2069     case NBOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2070                    meaning */
2071         assert(FLAGS(c) == TRADITIONAL_BOUND);
2072
2073         FBC_NBOUND_A(isWORDCHAR_A);
2074         break;
2075
2076     case NBOUNDU:
2077         if ((bound_type) FLAGS(c) == TRADITIONAL_BOUND) {
2078             FBC_NBOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8);
2079             break;
2080         }
2081
2082       do_nboundu:
2083
2084         to_complement = 1;
2085         /* FALLTHROUGH */
2086
2087     case BOUNDU:
2088       do_boundu:
2089         switch((bound_type) FLAGS(c)) {
2090             case TRADITIONAL_BOUND:
2091                 FBC_BOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8);
2092                 break;
2093             case GCB_BOUND:
2094                 if (s == reginfo->strbeg) {
2095                     if (reginfo->intuit || regtry(reginfo, &s))
2096                     {
2097                         goto got_it;
2098                     }
2099
2100                     /* Didn't match.  Try at the next position (if there is one) */
2101                     s += (utf8_target) ? UTF8SKIP(s) : 1;
2102                     if (UNLIKELY(s >= reginfo->strend)) {
2103                         break;
2104                     }
2105                 }
2106
2107                 if (utf8_target) {
2108                     GCB_enum before = getGCB_VAL_UTF8(
2109                                                reghop3((U8*)s, -1,
2110                                                        (U8*)(reginfo->strbeg)),
2111                                                (U8*) reginfo->strend);
2112                     while (s < strend) {
2113                         GCB_enum after = getGCB_VAL_UTF8((U8*) s,
2114                                                         (U8*) reginfo->strend);
2115                         if (   (to_complement ^ isGCB(before, after))
2116                             && (reginfo->intuit || regtry(reginfo, &s)))
2117                         {
2118                             goto got_it;
2119                         }
2120                         before = after;
2121                         s += UTF8SKIP(s);
2122                     }
2123                 }
2124                 else {  /* Not utf8.  Everything is a GCB except between CR and
2125                            LF */
2126                     while (s < strend) {
2127                         if ((to_complement ^ (   UCHARAT(s - 1) != '\r'
2128                                               || UCHARAT(s) != '\n'))
2129                             && (reginfo->intuit || regtry(reginfo, &s)))
2130                         {
2131                             goto got_it;
2132                         }
2133                         s++;
2134                     }
2135                 }
2136
2137                 /* And, since this is a bound, it can match after the final
2138                  * character in the string */
2139                 if ((reginfo->intuit || regtry(reginfo, &s))) {
2140                     goto got_it;
2141                 }
2142                 break;
2143
2144             case LB_BOUND:
2145                 if (s == reginfo->strbeg) {
2146                     if (reginfo->intuit || regtry(reginfo, &s)) {
2147                         goto got_it;
2148                     }
2149                     s += (utf8_target) ? UTF8SKIP(s) : 1;
2150                     if (UNLIKELY(s >= reginfo->strend)) {
2151                         break;
2152                     }
2153                 }
2154
2155                 if (utf8_target) {
2156                     LB_enum before = getLB_VAL_UTF8(reghop3((U8*)s,
2157                                                                -1,
2158                                                                (U8*)(reginfo->strbeg)),
2159                                                        (U8*) reginfo->strend);
2160                     while (s < strend) {
2161                         LB_enum after = getLB_VAL_UTF8((U8*) s, (U8*) reginfo->strend);
2162                         if (to_complement ^ isLB(before,
2163                                                  after,
2164                                                  (U8*) reginfo->strbeg,
2165                                                  (U8*) s,
2166                                                  (U8*) reginfo->strend,
2167                                                  utf8_target)
2168                             && (reginfo->intuit || regtry(reginfo, &s)))
2169                         {
2170                             goto got_it;
2171                         }
2172                         before = after;
2173                         s += UTF8SKIP(s);
2174                     }
2175                 }
2176                 else {  /* Not utf8. */
2177                     LB_enum before = getLB_VAL_CP((U8) *(s -1));
2178                     while (s < strend) {
2179                         LB_enum after = getLB_VAL_CP((U8) *s);
2180                         if (to_complement ^ isLB(before,
2181                                                  after,
2182                                                  (U8*) reginfo->strbeg,
2183                                                  (U8*) s,
2184                                                  (U8*) reginfo->strend,
2185                                                  utf8_target)
2186                             && (reginfo->intuit || regtry(reginfo, &s)))
2187                         {
2188                             goto got_it;
2189                         }
2190                         before = after;
2191                         s++;
2192                     }
2193                 }
2194
2195                 if (reginfo->intuit || regtry(reginfo, &s)) {
2196                     goto got_it;
2197                 }
2198
2199                 break;
2200
2201             case SB_BOUND:
2202                 if (s == reginfo->strbeg) {
2203                     if (reginfo->intuit || regtry(reginfo, &s)) {
2204                         goto got_it;
2205                     }
2206                     s += (utf8_target) ? UTF8SKIP(s) : 1;
2207                     if (UNLIKELY(s >= reginfo->strend)) {
2208                         break;
2209                     }
2210                 }
2211
2212                 if (utf8_target) {
2213                     SB_enum before = getSB_VAL_UTF8(reghop3((U8*)s,
2214                                                         -1,
2215                                                         (U8*)(reginfo->strbeg)),
2216                                                       (U8*) reginfo->strend);
2217                     while (s < strend) {
2218                         SB_enum after = getSB_VAL_UTF8((U8*) s,
2219                                                          (U8*) reginfo->strend);
2220                         if ((to_complement ^ isSB(before,
2221                                                   after,
2222                                                   (U8*) reginfo->strbeg,
2223                                                   (U8*) s,
2224                                                   (U8*) reginfo->strend,
2225                                                   utf8_target))
2226                             && (reginfo->intuit || regtry(reginfo, &s)))
2227                         {
2228                             goto got_it;
2229                         }
2230                         before = after;
2231                         s += UTF8SKIP(s);
2232                     }
2233                 }
2234                 else {  /* Not utf8. */
2235                     SB_enum before = getSB_VAL_CP((U8) *(s -1));
2236                     while (s < strend) {
2237                         SB_enum after = getSB_VAL_CP((U8) *s);
2238                         if ((to_complement ^ isSB(before,
2239                                                   after,
2240                                                   (U8*) reginfo->strbeg,
2241                                                   (U8*) s,
2242                                                   (U8*) reginfo->strend,
2243                                                   utf8_target))
2244                             && (reginfo->intuit || regtry(reginfo, &s)))
2245                         {
2246                             goto got_it;
2247                         }
2248                         before = after;
2249                         s++;
2250                     }
2251                 }
2252
2253                 /* Here are at the final position in the target string.  The SB
2254                  * value is always true here, so matches, depending on other
2255                  * constraints */
2256                 if (reginfo->intuit || regtry(reginfo, &s)) {
2257                     goto got_it;
2258                 }
2259
2260                 break;
2261
2262             case WB_BOUND:
2263                 if (s == reginfo->strbeg) {
2264                     if (reginfo->intuit || regtry(reginfo, &s)) {
2265                         goto got_it;
2266                     }
2267                     s += (utf8_target) ? UTF8SKIP(s) : 1;
2268                     if (UNLIKELY(s >= reginfo->strend)) {
2269                         break;
2270                     }
2271                 }
2272
2273                 if (utf8_target) {
2274                     /* We are at a boundary between char_sub_0 and char_sub_1.
2275                      * We also keep track of the value for char_sub_-1 as we
2276                      * loop through the line.   Context may be needed to make a
2277                      * determination, and if so, this can save having to
2278                      * recalculate it */
2279                     WB_enum previous = WB_UNKNOWN;
2280                     WB_enum before = getWB_VAL_UTF8(
2281                                               reghop3((U8*)s,
2282                                                       -1,
2283                                                       (U8*)(reginfo->strbeg)),
2284                                               (U8*) reginfo->strend);
2285                     while (s < strend) {
2286                         WB_enum after = getWB_VAL_UTF8((U8*) s,
2287                                                         (U8*) reginfo->strend);
2288                         if ((to_complement ^ isWB(previous,
2289                                                   before,
2290                                                   after,
2291                                                   (U8*) reginfo->strbeg,
2292                                                   (U8*) s,
2293                                                   (U8*) reginfo->strend,
2294                                                   utf8_target))
2295                             && (reginfo->intuit || regtry(reginfo, &s)))
2296                         {
2297                             goto got_it;
2298                         }
2299                         previous = before;
2300                         before = after;
2301                         s += UTF8SKIP(s);
2302                     }
2303                 }
2304                 else {  /* Not utf8. */
2305                     WB_enum previous = WB_UNKNOWN;
2306                     WB_enum before = getWB_VAL_CP((U8) *(s -1));
2307                     while (s < strend) {
2308                         WB_enum after = getWB_VAL_CP((U8) *s);
2309                         if ((to_complement ^ isWB(previous,
2310                                                   before,
2311                                                   after,
2312                                                   (U8*) reginfo->strbeg,
2313                                                   (U8*) s,
2314                                                   (U8*) reginfo->strend,
2315                                                   utf8_target))
2316                             && (reginfo->intuit || regtry(reginfo, &s)))
2317                         {
2318                             goto got_it;
2319                         }
2320                         previous = before;
2321                         before = after;
2322                         s++;
2323                     }
2324                 }
2325
2326                 if (reginfo->intuit || regtry(reginfo, &s)) {
2327                     goto got_it;
2328                 }
2329         }
2330         break;
2331
2332     case LNBREAK:
2333         REXEC_FBC_CSCAN(is_LNBREAK_utf8_safe(s, strend),
2334                         is_LNBREAK_latin1_safe(s, strend)
2335         );
2336         break;
2337
2338     /* The argument to all the POSIX node types is the class number to pass to
2339      * _generic_isCC() to build a mask for searching in PL_charclass[] */
2340
2341     case NPOSIXL:
2342         to_complement = 1;
2343         /* FALLTHROUGH */
2344
2345     case POSIXL:
2346         _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2347         REXEC_FBC_CSCAN(to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(c), (U8 *) s)),
2348                         to_complement ^ cBOOL(isFOO_lc(FLAGS(c), *s)));
2349         break;
2350
2351     case NPOSIXD:
2352         to_complement = 1;
2353         /* FALLTHROUGH */
2354
2355     case POSIXD:
2356         if (utf8_target) {
2357             goto posix_utf8;
2358         }
2359         goto posixa;
2360
2361     case NPOSIXA:
2362         if (utf8_target) {
2363             /* The complement of something that matches only ASCII matches all
2364              * non-ASCII, plus everything in ASCII that isn't in the class. */
2365             REXEC_FBC_UTF8_CLASS_SCAN(! isASCII_utf8(s)
2366                                       || ! _generic_isCC_A(*s, FLAGS(c)));
2367             break;
2368         }
2369
2370         to_complement = 1;
2371         /* FALLTHROUGH */
2372
2373     case POSIXA:
2374       posixa:
2375         /* Don't need to worry about utf8, as it can match only a single
2376          * byte invariant character. */
2377         REXEC_FBC_CLASS_SCAN(
2378                         to_complement ^ cBOOL(_generic_isCC_A(*s, FLAGS(c))));
2379         break;
2380
2381     case NPOSIXU:
2382         to_complement = 1;
2383         /* FALLTHROUGH */
2384
2385     case POSIXU:
2386         if (! utf8_target) {
2387             REXEC_FBC_CLASS_SCAN(to_complement ^ cBOOL(_generic_isCC(*s,
2388                                                                     FLAGS(c))));
2389         }
2390         else {
2391
2392           posix_utf8:
2393             classnum = (_char_class_number) FLAGS(c);
2394             if (classnum < _FIRST_NON_SWASH_CC) {
2395                 while (s < strend) {
2396
2397                     /* We avoid loading in the swash as long as possible, but
2398                      * should we have to, we jump to a separate loop.  This
2399                      * extra 'if' statement is what keeps this code from being
2400                      * just a call to REXEC_FBC_UTF8_CLASS_SCAN() */
2401                     if (UTF8_IS_ABOVE_LATIN1(*s)) {
2402                         goto found_above_latin1;
2403                     }
2404                     if ((UTF8_IS_INVARIANT(*s)
2405                          && to_complement ^ cBOOL(_generic_isCC((U8) *s,
2406                                                                 classnum)))
2407                         || (UTF8_IS_DOWNGRADEABLE_START(*s)
2408                             && to_complement ^ cBOOL(
2409                                 _generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(*s,
2410                                                                       *(s + 1)),
2411                                               classnum))))
2412                     {
2413                         if (tmp && (reginfo->intuit || regtry(reginfo, &s)))
2414                             goto got_it;
2415                         else {
2416                             tmp = doevery;
2417                         }
2418                     }
2419                     else {
2420                         tmp = 1;
2421                     }
2422                     s += UTF8SKIP(s);
2423                 }
2424             }
2425             else switch (classnum) {    /* These classes are implemented as
2426                                            macros */
2427                 case _CC_ENUM_SPACE:
2428                     REXEC_FBC_UTF8_CLASS_SCAN(
2429                                         to_complement ^ cBOOL(isSPACE_utf8(s)));
2430                     break;
2431
2432                 case _CC_ENUM_BLANK:
2433                     REXEC_FBC_UTF8_CLASS_SCAN(
2434                                         to_complement ^ cBOOL(isBLANK_utf8(s)));
2435                     break;
2436
2437                 case _CC_ENUM_XDIGIT:
2438                     REXEC_FBC_UTF8_CLASS_SCAN(
2439                                        to_complement ^ cBOOL(isXDIGIT_utf8(s)));
2440                     break;
2441
2442                 case _CC_ENUM_VERTSPACE:
2443                     REXEC_FBC_UTF8_CLASS_SCAN(
2444                                        to_complement ^ cBOOL(isVERTWS_utf8(s)));
2445                     break;
2446
2447                 case _CC_ENUM_CNTRL:
2448                     REXEC_FBC_UTF8_CLASS_SCAN(
2449                                         to_complement ^ cBOOL(isCNTRL_utf8(s)));
2450                     break;
2451
2452                 default:
2453                     Perl_croak(aTHX_ "panic: find_byclass() node %d='%s' has an unexpected character class '%d'", OP(c), PL_reg_name[OP(c)], classnum);
2454                     NOT_REACHED; /* NOTREACHED */
2455             }
2456         }
2457         break;
2458
2459       found_above_latin1:   /* Here we have to load a swash to get the result
2460                                for the current code point */
2461         if (! PL_utf8_swash_ptrs[classnum]) {
2462             U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
2463             PL_utf8_swash_ptrs[classnum] =
2464                     _core_swash_init("utf8",
2465                                      "",
2466                                      &PL_sv_undef, 1, 0,
2467                                      PL_XPosix_ptrs[classnum], &flags);
2468         }
2469
2470         /* This is a copy of the loop above for swash classes, though using the
2471          * FBC macro instead of being expanded out.  Since we've loaded the
2472          * swash, we don't have to check for that each time through the loop */
2473         REXEC_FBC_UTF8_CLASS_SCAN(
2474                 to_complement ^ cBOOL(_generic_utf8(
2475                                       classnum,
2476                                       s,
2477                                       swash_fetch(PL_utf8_swash_ptrs[classnum],
2478                                                   (U8 *) s, TRUE))));
2479         break;
2480
2481     case AHOCORASICKC:
2482     case AHOCORASICK:
2483         {
2484             DECL_TRIE_TYPE(c);
2485             /* what trie are we using right now */
2486             reg_ac_data *aho = (reg_ac_data*)progi->data->data[ ARG( c ) ];
2487             reg_trie_data *trie = (reg_trie_data*)progi->data->data[ aho->trie ];
2488             HV *widecharmap = MUTABLE_HV(progi->data->data[ aho->trie + 1 ]);
2489
2490             const char *last_start = strend - trie->minlen;
2491 #ifdef DEBUGGING
2492             const char *real_start = s;
2493 #endif
2494             STRLEN maxlen = trie->maxlen;
2495             SV *sv_points;
2496             U8 **points; /* map of where we were in the input string
2497                             when reading a given char. For ASCII this
2498                             is unnecessary overhead as the relationship
2499                             is always 1:1, but for Unicode, especially
2500                             case folded Unicode this is not true. */
2501             U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
2502             U8 *bitmap=NULL;
2503
2504
2505             GET_RE_DEBUG_FLAGS_DECL;
2506
2507             /* We can't just allocate points here. We need to wrap it in
2508              * an SV so it gets freed properly if there is a croak while
2509              * running the match */
2510             ENTER;
2511             SAVETMPS;
2512             sv_points=newSV(maxlen * sizeof(U8 *));
2513             SvCUR_set(sv_points,
2514                 maxlen * sizeof(U8 *));
2515             SvPOK_on(sv_points);
2516             sv_2mortal(sv_points);
2517             points=(U8**)SvPV_nolen(sv_points );
2518             if ( trie_type != trie_utf8_fold
2519                  && (trie->bitmap || OP(c)==AHOCORASICKC) )
2520             {
2521                 if (trie->bitmap)
2522                     bitmap=(U8*)trie->bitmap;
2523                 else
2524                     bitmap=(U8*)ANYOF_BITMAP(c);
2525             }
2526             /* this is the Aho-Corasick algorithm modified a touch
2527                to include special handling for long "unknown char" sequences.
2528                The basic idea being that we use AC as long as we are dealing
2529                with a possible matching char, when we encounter an unknown char
2530                (and we have not encountered an accepting state) we scan forward
2531                until we find a legal starting char.
2532                AC matching is basically that of trie matching, except that when
2533                we encounter a failing transition, we fall back to the current
2534                states "fail state", and try the current char again, a process
2535                we repeat until we reach the root state, state 1, or a legal
2536                transition. If we fail on the root state then we can either
2537                terminate if we have reached an accepting state previously, or
2538                restart the entire process from the beginning if we have not.
2539
2540              */
2541             while (s <= last_start) {
2542                 const U32 uniflags = UTF8_ALLOW_DEFAULT;
2543                 U8 *uc = (U8*)s;
2544                 U16 charid = 0;
2545                 U32 base = 1;
2546                 U32 state = 1;
2547                 UV uvc = 0;
2548                 STRLEN len = 0;
2549                 STRLEN foldlen = 0;
2550                 U8 *uscan = (U8*)NULL;
2551                 U8 *leftmost = NULL;
2552 #ifdef DEBUGGING
2553                 U32 accepted_word= 0;
2554 #endif
2555                 U32 pointpos = 0;
2556
2557                 while ( state && uc <= (U8*)strend ) {
2558                     int failed=0;
2559                     U32 word = aho->states[ state ].wordnum;
2560
2561                     if( state==1 ) {
2562                         if ( bitmap ) {
2563                             DEBUG_TRIE_EXECUTE_r(
2564                                 if ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2565                                     dump_exec_pos( (char *)uc, c, strend, real_start,
2566                                         (char *)uc, utf8_target );
2567                                     PerlIO_printf( Perl_debug_log,
2568                                         " Scanning for legal start char...\n");
2569                                 }
2570                             );
2571                             if (utf8_target) {
2572                                 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2573                                     uc += UTF8SKIP(uc);
2574                                 }
2575                             } else {
2576                                 while ( uc <= (U8*)last_start  && !BITMAP_TEST(bitmap,*uc) ) {
2577                                     uc++;
2578                                 }
2579                             }
2580                             s= (char *)uc;
2581                         }
2582                         if (uc >(U8*)last_start) break;
2583                     }
2584
2585                     if ( word ) {
2586                         U8 *lpos= points[ (pointpos - trie->wordinfo[word].len) % maxlen ];
2587                         if (!leftmost || lpos < leftmost) {
2588                             DEBUG_r(accepted_word=word);
2589                             leftmost= lpos;
2590                         }
2591                         if (base==0) break;
2592
2593                     }
2594                     points[pointpos++ % maxlen]= uc;
2595                     if (foldlen || uc < (U8*)strend) {
2596                         REXEC_TRIE_READ_CHAR(trie_type, trie,
2597                                          widecharmap, uc,
2598                                          uscan, len, uvc, charid, foldlen,
2599                                          foldbuf, uniflags);
2600                         DEBUG_TRIE_EXECUTE_r({
2601                             dump_exec_pos( (char *)uc, c, strend,
2602                                         real_start, s, utf8_target);
2603                             PerlIO_printf(Perl_debug_log,
2604                                 " Charid:%3u CP:%4"UVxf" ",
2605                                  charid, uvc);
2606                         });
2607                     }
2608                     else {
2609                         len = 0;
2610                         charid = 0;
2611                     }
2612
2613
2614                     do {
2615 #ifdef DEBUGGING
2616                         word = aho->states[ state ].wordnum;
2617 #endif
2618                         base = aho->states[ state ].trans.base;
2619
2620                         DEBUG_TRIE_EXECUTE_r({
2621                             if (failed)
2622                                 dump_exec_pos( (char *)uc, c, strend, real_start,
2623                                     s,   utf8_target );
2624                             PerlIO_printf( Perl_debug_log,
2625                                 "%sState: %4"UVxf", word=%"UVxf,
2626                                 failed ? " Fail transition to " : "",
2627                                 (UV)state, (UV)word);
2628                         });
2629                         if ( base ) {
2630                             U32 tmp;
2631                             I32 offset;
2632                             if (charid &&
2633                                  ( ((offset = base + charid
2634                                     - 1 - trie->uniquecharcount)) >= 0)
2635                                  && ((U32)offset < trie->lasttrans)
2636                                  && trie->trans[offset].check == state
2637                                  && (tmp=trie->trans[offset].next))
2638                             {
2639                                 DEBUG_TRIE_EXECUTE_r(
2640                                     PerlIO_printf( Perl_debug_log," - legal\n"));
2641                                 state = tmp;
2642                                 break;
2643                             }
2644                             else {
2645                                 DEBUG_TRIE_EXECUTE_r(
2646                                     PerlIO_printf( Perl_debug_log," - fail\n"));
2647                                 failed = 1;
2648                                 state = aho->fail[state];
2649                             }
2650                         }
2651                         else {
2652                             /* we must be accepting here */
2653                             DEBUG_TRIE_EXECUTE_r(
2654                                     PerlIO_printf( Perl_debug_log," - accepting\n"));
2655                             failed = 1;
2656                             break;
2657                         }
2658                     } while(state);
2659                     uc += len;
2660                     if (failed) {
2661                         if (leftmost)
2662                             break;
2663                         if (!state) state = 1;
2664                     }
2665                 }
2666                 if ( aho->states[ state ].wordnum ) {
2667                     U8 *lpos = points[ (pointpos - trie->wordinfo[aho->states[ state ].wordnum].len) % maxlen ];
2668                     if (!leftmost || lpos < leftmost) {
2669                         DEBUG_r(accepted_word=aho->states[ state ].wordnum);
2670                         leftmost = lpos;
2671                     }
2672                 }
2673                 if (leftmost) {
2674                     s = (char*)leftmost;
2675                     DEBUG_TRIE_EXECUTE_r({
2676                         PerlIO_printf(
2677                             Perl_debug_log,"Matches word #%"UVxf" at position %"IVdf". Trying full pattern...\n",
2678                             (UV)accepted_word, (IV)(s - real_start)
2679                         );
2680                     });
2681                     if (reginfo->intuit || regtry(reginfo, &s)) {
2682                         FREETMPS;
2683                         LEAVE;
2684                         goto got_it;
2685                     }
2686                     s = HOPc(s,1);
2687                     DEBUG_TRIE_EXECUTE_r({
2688                         PerlIO_printf( Perl_debug_log,"Pattern failed. Looking for new start point...\n");
2689                     });
2690                 } else {
2691                     DEBUG_TRIE_EXECUTE_r(
2692                         PerlIO_printf( Perl_debug_log,"No match.\n"));
2693                     break;
2694                 }
2695             }
2696             FREETMPS;
2697             LEAVE;
2698         }
2699         break;
2700     default:
2701         Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
2702     }
2703     return 0;
2704   got_it:
2705     return s;
2706 }
2707
2708 /* set RX_SAVED_COPY, RX_SUBBEG etc.
2709  * flags have same meanings as with regexec_flags() */
2710
2711 static void
2712 S_reg_set_capture_string(pTHX_ REGEXP * const rx,
2713                             char *strbeg,
2714                             char *strend,
2715                             SV *sv,
2716                             U32 flags,
2717                             bool utf8_target)
2718 {
2719     struct regexp *const prog = ReANY(rx);
2720
2721     if (flags & REXEC_COPY_STR) {
2722 #ifdef PERL_ANY_COW
2723         if (SvCANCOW(sv)) {
2724             if (DEBUG_C_TEST) {
2725                 PerlIO_printf(Perl_debug_log,
2726                               "Copy on write: regexp capture, type %d\n",
2727                               (int) SvTYPE(sv));
2728             }
2729             /* Create a new COW SV to share the match string and store
2730              * in saved_copy, unless the current COW SV in saved_copy
2731              * is valid and suitable for our purpose */
2732             if ((   prog->saved_copy
2733                  && SvIsCOW(prog->saved_copy)
2734                  && SvPOKp(prog->saved_copy)
2735                  && SvIsCOW(sv)
2736                  && SvPOKp(sv)
2737                  && SvPVX(sv) == SvPVX(prog->saved_copy)))
2738             {
2739                 /* just reuse saved_copy SV */
2740                 if (RXp_MATCH_COPIED(prog)) {
2741                     Safefree(prog->subbeg);
2742                     RXp_MATCH_COPIED_off(prog);
2743                 }
2744             }
2745             else {
2746                 /* create new COW SV to share string */
2747                 RX_MATCH_COPY_FREE(rx);
2748                 prog->saved_copy = sv_setsv_cow(prog->saved_copy, sv);
2749             }
2750             prog->subbeg = (char *)SvPVX_const(prog->saved_copy);
2751             assert (SvPOKp(prog->saved_copy));
2752             prog->sublen  = strend - strbeg;
2753             prog->suboffset = 0;
2754             prog->subcoffset = 0;
2755         } else
2756 #endif
2757         {
2758             SSize_t min = 0;
2759             SSize_t max = strend - strbeg;
2760             SSize_t sublen;
2761
2762             if (    (flags & REXEC_COPY_SKIP_POST)
2763                 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2764                 && !(PL_sawampersand & SAWAMPERSAND_RIGHT)
2765             ) { /* don't copy $' part of string */
2766                 U32 n = 0;
2767                 max = -1;
2768                 /* calculate the right-most part of the string covered
2769                  * by a capture. Due to lookahead, this may be to
2770                  * the right of $&, so we have to scan all captures */
2771                 while (n <= prog->lastparen) {
2772                     if (prog->offs[n].end > max)
2773                         max = prog->offs[n].end;
2774                     n++;
2775                 }
2776                 if (max == -1)
2777                     max = (PL_sawampersand & SAWAMPERSAND_LEFT)
2778                             ? prog->offs[0].start
2779                             : 0;
2780                 assert(max >= 0 && max <= strend - strbeg);
2781             }
2782
2783             if (    (flags & REXEC_COPY_SKIP_PRE)
2784                 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2785                 && !(PL_sawampersand & SAWAMPERSAND_LEFT)
2786             ) { /* don't copy $` part of string */
2787                 U32 n = 0;
2788                 min = max;
2789                 /* calculate the left-most part of the string covered
2790                  * by a capture. Due to lookbehind, this may be to
2791                  * the left of $&, so we have to scan all captures */
2792                 while (min && n <= prog->lastparen) {
2793                     if (   prog->offs[n].start != -1
2794                         && prog->offs[n].start < min)
2795                     {
2796                         min = prog->offs[n].start;
2797                     }
2798                     n++;
2799                 }
2800                 if ((PL_sawampersand & SAWAMPERSAND_RIGHT)
2801                     && min >  prog->offs[0].end
2802                 )
2803                     min = prog->offs[0].end;
2804
2805             }
2806
2807             assert(min >= 0 && min <= max && min <= strend - strbeg);
2808             sublen = max - min;
2809
2810             if (RX_MATCH_COPIED(rx)) {
2811                 if (sublen > prog->sublen)
2812                     prog->subbeg =
2813                             (char*)saferealloc(prog->subbeg, sublen+1);
2814             }
2815             else
2816                 prog->subbeg = (char*)safemalloc(sublen+1);
2817             Copy(strbeg + min, prog->subbeg, sublen, char);
2818             prog->subbeg[sublen] = '\0';
2819             prog->suboffset = min;
2820             prog->sublen = sublen;
2821             RX_MATCH_COPIED_on(rx);
2822         }
2823         prog->subcoffset = prog->suboffset;
2824         if (prog->suboffset && utf8_target) {
2825             /* Convert byte offset to chars.
2826              * XXX ideally should only compute this if @-/@+
2827              * has been seen, a la PL_sawampersand ??? */
2828
2829             /* If there's a direct correspondence between the
2830              * string which we're matching and the original SV,
2831              * then we can use the utf8 len cache associated with
2832              * the SV. In particular, it means that under //g,
2833              * sv_pos_b2u() will use the previously cached
2834              * position to speed up working out the new length of
2835              * subcoffset, rather than counting from the start of
2836              * the string each time. This stops
2837              *   $x = "\x{100}" x 1E6; 1 while $x =~ /(.)/g;
2838              * from going quadratic */
2839             if (SvPOKp(sv) && SvPVX(sv) == strbeg)
2840                 prog->subcoffset = sv_pos_b2u_flags(sv, prog->subcoffset,
2841                                                 SV_GMAGIC|SV_CONST_RETURN);
2842             else
2843                 prog->subcoffset = utf8_length((U8*)strbeg,
2844                                     (U8*)(strbeg+prog->suboffset));
2845         }
2846     }
2847     else {
2848         RX_MATCH_COPY_FREE(rx);
2849         prog->subbeg = strbeg;
2850         prog->suboffset = 0;
2851         prog->subcoffset = 0;
2852         prog->sublen = strend - strbeg;
2853     }
2854 }
2855
2856
2857
2858
2859 /*
2860  - regexec_flags - match a regexp against a string
2861  */
2862 I32
2863 Perl_regexec_flags(pTHX_ REGEXP * const rx, char *stringarg, char *strend,
2864               char *strbeg, SSize_t minend, SV *sv, void *data, U32 flags)
2865 /* stringarg: the point in the string at which to begin matching */
2866 /* strend:    pointer to null at end of string */
2867 /* strbeg:    real beginning of string */
2868 /* minend:    end of match must be >= minend bytes after stringarg. */
2869 /* sv:        SV being matched: only used for utf8 flag, pos() etc; string
2870  *            itself is accessed via the pointers above */
2871 /* data:      May be used for some additional optimizations.
2872               Currently unused. */
2873 /* flags:     For optimizations. See REXEC_* in regexp.h */
2874
2875 {
2876     struct regexp *const prog = ReANY(rx);
2877     char *s;
2878     regnode *c;
2879     char *startpos;
2880     SSize_t minlen;             /* must match at least this many chars */
2881     SSize_t dontbother = 0;     /* how many characters not to try at end */
2882     const bool utf8_target = cBOOL(DO_UTF8(sv));
2883     I32 multiline;
2884     RXi_GET_DECL(prog,progi);
2885     regmatch_info reginfo_buf;  /* create some info to pass to regtry etc */
2886     regmatch_info *const reginfo = &reginfo_buf;
2887     regexp_paren_pair *swap = NULL;
2888     I32 oldsave;
2889     GET_RE_DEBUG_FLAGS_DECL;
2890
2891     PERL_ARGS_ASSERT_REGEXEC_FLAGS;
2892     PERL_UNUSED_ARG(data);
2893
2894     /* Be paranoid... */
2895     if (prog == NULL) {
2896         Perl_croak(aTHX_ "NULL regexp parameter");
2897     }
2898
2899     DEBUG_EXECUTE_r(
2900         debug_start_match(rx, utf8_target, stringarg, strend,
2901         "Matching");
2902     );
2903
2904     startpos = stringarg;
2905
2906     /* set these early as they may be used by the HOP macros below */
2907     reginfo->strbeg = strbeg;
2908     reginfo->strend = strend;
2909     reginfo->is_utf8_target = cBOOL(utf8_target);
2910
2911     if (prog->intflags & PREGf_GPOS_SEEN) {
2912         MAGIC *mg;
2913
2914         /* set reginfo->ganch, the position where \G can match */
2915
2916         reginfo->ganch =
2917             (flags & REXEC_IGNOREPOS)
2918             ? stringarg /* use start pos rather than pos() */
2919             : ((mg = mg_find_mglob(sv)) && mg->mg_len >= 0)
2920               /* Defined pos(): */
2921             ? strbeg + MgBYTEPOS(mg, sv, strbeg, strend-strbeg)
2922             : strbeg; /* pos() not defined; use start of string */
2923
2924         DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
2925             "GPOS ganch set to strbeg[%"IVdf"]\n", (IV)(reginfo->ganch - strbeg)));
2926
2927         /* in the presence of \G, we may need to start looking earlier in
2928          * the string than the suggested start point of stringarg:
2929          * if prog->gofs is set, then that's a known, fixed minimum
2930          * offset, such as
2931          * /..\G/:   gofs = 2
2932          * /ab|c\G/: gofs = 1
2933          * or if the minimum offset isn't known, then we have to go back
2934          * to the start of the string, e.g. /w+\G/
2935          */
2936
2937         if (prog->intflags & PREGf_ANCH_GPOS) {
2938             if (prog->gofs) {
2939                 startpos = HOPBACKc(reginfo->ganch, prog->gofs);
2940                 if (!startpos ||
2941                     ((flags & REXEC_FAIL_ON_UNDERFLOW) && startpos < stringarg))
2942                 {
2943                     DEBUG_r(PerlIO_printf(Perl_debug_log,
2944                             "fail: ganch-gofs before earliest possible start\n"));
2945                     return 0;
2946                 }
2947             }
2948             else
2949                 startpos = reginfo->ganch;
2950         }
2951         else if (prog->gofs) {
2952             startpos = HOPBACKc(startpos, prog->gofs);
2953             if (!startpos)
2954                 startpos = strbeg;
2955         }
2956         else if (prog->intflags & PREGf_GPOS_FLOAT)
2957             startpos = strbeg;
2958     }
2959
2960     minlen = prog->minlen;
2961     if ((startpos + minlen) > strend || startpos < strbeg) {
2962         DEBUG_r(PerlIO_printf(Perl_debug_log,
2963                     "Regex match can't succeed, so not even tried\n"));
2964         return 0;
2965     }
2966
2967     /* at the end of this function, we'll do a LEAVE_SCOPE(oldsave),
2968      * which will call destuctors to reset PL_regmatch_state, free higher
2969      * PL_regmatch_slabs, and clean up regmatch_info_aux and
2970      * regmatch_info_aux_eval */
2971
2972     oldsave = PL_savestack_ix;
2973
2974     s = startpos;
2975
2976     if ((prog->extflags & RXf_USE_INTUIT)
2977         && !(flags & REXEC_CHECKED))
2978     {
2979         s = re_intuit_start(rx, sv, strbeg, startpos, strend,
2980                                     flags, NULL);
2981         if (!s)
2982             return 0;
2983
2984         if (prog->extflags & RXf_CHECK_ALL) {
2985             /* we can match based purely on the result of INTUIT.
2986              * Set up captures etc just for $& and $-[0]
2987              * (an intuit-only match wont have $1,$2,..) */
2988             assert(!prog->nparens);
2989
2990             /* s/// doesn't like it if $& is earlier than where we asked it to
2991              * start searching (which can happen on something like /.\G/) */
2992             if (       (flags & REXEC_FAIL_ON_UNDERFLOW)
2993                     && (s < stringarg))
2994             {
2995                 /* this should only be possible under \G */
2996                 assert(prog->intflags & PREGf_GPOS_SEEN);
2997                 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
2998                     "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
2999                 goto phooey;
3000             }
3001
3002             /* match via INTUIT shouldn't have any captures.
3003              * Let @-, @+, $^N know */
3004             prog->lastparen = prog->lastcloseparen = 0;
3005             RX_MATCH_UTF8_set(rx, utf8_target);
3006             prog->offs[0].start = s - strbeg;
3007             prog->offs[0].end = utf8_target
3008                 ? (char*)utf8_hop((U8*)s, prog->minlenret) - strbeg
3009                 : s - strbeg + prog->minlenret;
3010             if ( !(flags & REXEC_NOT_FIRST) )
3011                 S_reg_set_capture_string(aTHX_ rx,
3012                                         strbeg, strend,
3013                                         sv, flags, utf8_target);
3014
3015             return 1;
3016         }
3017     }
3018
3019     multiline = prog->extflags & RXf_PMf_MULTILINE;
3020     
3021     if (strend - s < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
3022         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
3023                               "String too short [regexec_flags]...\n"));
3024         goto phooey;
3025     }
3026     
3027     /* Check validity of program. */
3028     if (UCHARAT(progi->program) != REG_MAGIC) {
3029         Perl_croak(aTHX_ "corrupted regexp program");
3030     }
3031
3032     RX_MATCH_TAINTED_off(rx);
3033     RX_MATCH_UTF8_set(rx, utf8_target);
3034
3035     reginfo->prog = rx;  /* Yes, sorry that this is confusing.  */
3036     reginfo->intuit = 0;
3037     reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
3038     reginfo->warned = FALSE;
3039     reginfo->sv = sv;
3040     reginfo->poscache_maxiter = 0; /* not yet started a countdown */
3041     /* see how far we have to get to not match where we matched before */
3042     reginfo->till = stringarg + minend;
3043
3044     if (prog->extflags & RXf_EVAL_SEEN && SvPADTMP(sv)) {
3045         /* SAVEFREESV, not sv_mortalcopy, as this SV must last until after
3046            S_cleanup_regmatch_info_aux has executed (registered by
3047            SAVEDESTRUCTOR_X below).  S_cleanup_regmatch_info_aux modifies
3048            magic belonging to this SV.
3049            Not newSVsv, either, as it does not COW.
3050         */
3051         reginfo->sv = newSV(0);
3052         SvSetSV_nosteal(reginfo->sv, sv);
3053         SAVEFREESV(reginfo->sv);
3054     }
3055
3056     /* reserve next 2 or 3 slots in PL_regmatch_state:
3057      * slot N+0: may currently be in use: skip it
3058      * slot N+1: use for regmatch_info_aux struct
3059      * slot N+2: use for regmatch_info_aux_eval struct if we have (?{})'s
3060      * slot N+3: ready for use by regmatch()
3061      */
3062
3063     {
3064         regmatch_state *old_regmatch_state;
3065         regmatch_slab  *old_regmatch_slab;
3066         int i, max = (prog->extflags & RXf_EVAL_SEEN) ? 2 : 1;
3067
3068         /* on first ever match, allocate first slab */
3069         if (!PL_regmatch_slab) {
3070             Newx(PL_regmatch_slab, 1, regmatch_slab);
3071             PL_regmatch_slab->prev = NULL;
3072             PL_regmatch_slab->next = NULL;
3073             PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
3074         }
3075
3076         old_regmatch_state = PL_regmatch_state;
3077         old_regmatch_slab  = PL_regmatch_slab;
3078
3079         for (i=0; i <= max; i++) {
3080             if (i == 1)
3081                 reginfo->info_aux = &(PL_regmatch_state->u.info_aux);
3082             else if (i ==2)
3083                 reginfo->info_aux_eval =
3084                 reginfo->info_aux->info_aux_eval =
3085                             &(PL_regmatch_state->u.info_aux_eval);
3086
3087             if (++PL_regmatch_state >  SLAB_LAST(PL_regmatch_slab))
3088                 PL_regmatch_state = S_push_slab(aTHX);
3089         }
3090
3091         /* note initial PL_regmatch_state position; at end of match we'll
3092          * pop back to there and free any higher slabs */
3093
3094         reginfo->info_aux->old_regmatch_state = old_regmatch_state;
3095         reginfo->info_aux->old_regmatch_slab  = old_regmatch_slab;
3096         reginfo->info_aux->poscache = NULL;
3097
3098         SAVEDESTRUCTOR_X(S_cleanup_regmatch_info_aux, reginfo->info_aux);
3099
3100         if ((prog->extflags & RXf_EVAL_SEEN))
3101             S_setup_eval_state(aTHX_ reginfo);
3102         else
3103             reginfo->info_aux_eval = reginfo->info_aux->info_aux_eval = NULL;
3104     }
3105
3106     /* If there is a "must appear" string, look for it. */
3107
3108     if (PL_curpm && (PM_GETRE(PL_curpm) == rx)) {
3109         /* We have to be careful. If the previous successful match
3110            was from this regex we don't want a subsequent partially
3111            successful match to clobber the old results.
3112            So when we detect this possibility we add a swap buffer
3113            to the re, and switch the buffer each match. If we fail,
3114            we switch it back; otherwise we leave it swapped.
3115         */
3116         swap = prog->offs;
3117         /* do we need a save destructor here for eval dies? */
3118         Newxz(prog->offs, (prog->nparens + 1), regexp_paren_pair);
3119         DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
3120             "rex=0x%"UVxf" saving  offs: orig=0x%"UVxf" new=0x%"UVxf"\n",
3121             PTR2UV(prog),
3122             PTR2UV(swap),
3123             PTR2UV(prog->offs)
3124         ));
3125     }
3126
3127     /* Simplest case: anchored match need be tried only once, or with
3128      * MBOL, only at the beginning of each line.
3129      *
3130      * Note that /.*.../ sets PREGf_IMPLICIT|MBOL, while /.*.../s sets
3131      * PREGf_IMPLICIT|SBOL. The idea is that with /.*.../s, if it doesn't
3132      * match at the start of the string then it won't match anywhere else
3133      * either; while with /.*.../, if it doesn't match at the beginning,
3134      * the earliest it could match is at the start of the next line */
3135
3136     if (prog->intflags & (PREGf_ANCH & ~PREGf_ANCH_GPOS)) {
3137         char *end;
3138
3139         if (regtry(reginfo, &s))
3140             goto got_it;
3141
3142         if (!(prog->intflags & PREGf_ANCH_MBOL))
3143             goto phooey;
3144
3145         /* didn't match at start, try at other newline positions */
3146
3147         if (minlen)
3148             dontbother = minlen - 1;
3149         end = HOP3c(strend, -dontbother, strbeg) - 1;
3150
3151         /* skip to next newline */
3152
3153         while (s <= end) { /* note it could be possible to match at the end of the string */
3154             /* NB: newlines are the same in unicode as they are in latin */
3155             if (*s++ != '\n')
3156                 continue;
3157             if (prog->check_substr || prog->check_utf8) {
3158             /* note that with PREGf_IMPLICIT, intuit can only fail
3159              * or return the start position, so it's of limited utility.
3160              * Nevertheless, I made the decision that the potential for
3161              * quick fail was still worth it - DAPM */
3162                 s = re_intuit_start(rx, sv, strbeg, s, strend, flags, NULL);
3163                 if (!s)
3164                     goto phooey;
3165             }
3166             if (regtry(reginfo, &s))
3167                 goto got_it;
3168         }
3169         goto phooey;
3170     } /* end anchored search */
3171
3172     if (prog->intflags & PREGf_ANCH_GPOS)
3173     {
3174         /* PREGf_ANCH_GPOS should never be true if PREGf_GPOS_SEEN is not true */
3175         assert(prog->intflags & PREGf_GPOS_SEEN);
3176         /* For anchored \G, the only position it can match from is
3177          * (ganch-gofs); we already set startpos to this above; if intuit
3178          * moved us on from there, we can't possibly succeed */
3179         assert(startpos == HOPBACKc(reginfo->ganch, prog->gofs));
3180         if (s == startpos && regtry(reginfo, &s))
3181             goto got_it;
3182         goto phooey;
3183     }
3184
3185     /* Messy cases:  unanchored match. */
3186     if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
3187         /* we have /x+whatever/ */
3188         /* it must be a one character string (XXXX Except is_utf8_pat?) */
3189         char ch;
3190 #ifdef DEBUGGING
3191         int did_match = 0;
3192 #endif
3193         if (utf8_target) {
3194             if (! prog->anchored_utf8) {
3195                 to_utf8_substr(prog);
3196             }
3197             ch = SvPVX_const(prog->anchored_utf8)[0];
3198             REXEC_FBC_SCAN(
3199                 if (*s == ch) {
3200                     DEBUG_EXECUTE_r( did_match = 1 );
3201                     if (regtry(reginfo, &s)) goto got_it;
3202                     s += UTF8SKIP(s);
3203                     while (s < strend && *s == ch)
3204                         s += UTF8SKIP(s);
3205                 }
3206             );
3207
3208         }
3209         else {
3210             if (! prog->anchored_substr) {
3211                 if (! to_byte_substr(prog)) {
3212                     NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3213                 }
3214             }
3215             ch = SvPVX_const(prog->anchored_substr)[0];
3216             REXEC_FBC_SCAN(
3217                 if (*s == ch) {
3218                     DEBUG_EXECUTE_r( did_match = 1 );
3219                     if (regtry(reginfo, &s)) goto got_it;
3220                     s++;
3221                     while (s < strend && *s == ch)
3222                         s++;
3223                 }
3224             );
3225         }
3226         DEBUG_EXECUTE_r(if (!did_match)
3227                 PerlIO_printf(Perl_debug_log,
3228                                   "Did not find anchored character...\n")
3229                );
3230     }
3231     else if (prog->anchored_substr != NULL
3232               || prog->anchored_utf8 != NULL
3233               || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
3234                   && prog->float_max_offset < strend - s)) {
3235         SV *must;
3236         SSize_t back_max;
3237         SSize_t back_min;
3238         char *last;
3239         char *last1;            /* Last position checked before */
3240 #ifdef DEBUGGING
3241         int did_match = 0;
3242 #endif
3243         if (prog->anchored_substr || prog->anchored_utf8) {
3244             if (utf8_target) {
3245                 if (! prog->anchored_utf8) {
3246                     to_utf8_substr(prog);
3247                 }
3248                 must = prog->anchored_utf8;
3249             }
3250             else {
3251                 if (! prog->anchored_substr) {
3252                     if (! to_byte_substr(prog)) {
3253                         NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3254                     }
3255                 }
3256                 must = prog->anchored_substr;
3257             }
3258             back_max = back_min = prog->anchored_offset;
3259         } else {
3260             if (utf8_target) {
3261                 if (! prog->float_utf8) {
3262                     to_utf8_substr(prog);
3263                 }
3264                 must = prog->float_utf8;
3265             }
3266             else {
3267                 if (! prog->float_substr) {
3268                     if (! to_byte_substr(prog)) {
3269                         NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3270                     }
3271                 }
3272                 must = prog->float_substr;
3273             }
3274             back_max = prog->float_max_offset;
3275             back_min = prog->float_min_offset;
3276         }
3277             
3278         if (back_min<0) {
3279             last = strend;
3280         } else {
3281             last = HOP3c(strend,        /* Cannot start after this */
3282                   -(SSize_t)(CHR_SVLEN(must)
3283                          - (SvTAIL(must) != 0) + back_min), strbeg);
3284         }
3285         if (s > reginfo->strbeg)
3286             last1 = HOPc(s, -1);
3287         else
3288             last1 = s - 1;      /* bogus */
3289
3290         /* XXXX check_substr already used to find "s", can optimize if
3291            check_substr==must. */
3292         dontbother = 0;
3293         strend = HOPc(strend, -dontbother);
3294         while ( (s <= last) &&
3295                 (s = fbm_instr((unsigned char*)HOP4c(s, back_min, strbeg,  strend),
3296                                   (unsigned char*)strend, must,
3297                                   multiline ? FBMrf_MULTILINE : 0)) ) {
3298             DEBUG_EXECUTE_r( did_match = 1 );
3299             if (HOPc(s, -back_max) > last1) {
3300                 last1 = HOPc(s, -back_min);
3301                 s = HOPc(s, -back_max);
3302             }
3303             else {
3304                 char * const t = (last1 >= reginfo->strbeg)
3305                                     ? HOPc(last1, 1) : last1 + 1;
3306
3307                 last1 = HOPc(s, -back_min);
3308                 s = t;
3309             }
3310             if (utf8_target) {
3311                 while (s <= last1) {
3312                     if (regtry(reginfo, &s))
3313                         goto got_it;
3314                     if (s >= last1) {
3315                         s++; /* to break out of outer loop */
3316                         break;
3317                     }
3318                     s += UTF8SKIP(s);
3319                 }
3320             }
3321             else {
3322                 while (s <= last1) {
3323                     if (regtry(reginfo, &s))
3324                         goto got_it;
3325                     s++;
3326                 }
3327             }
3328         }
3329         DEBUG_EXECUTE_r(if (!did_match) {
3330             RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
3331                 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
3332             PerlIO_printf(Perl_debug_log, "Did not find %s substr %s%s...\n",
3333                               ((must == prog->anchored_substr || must == prog->anchored_utf8)
3334                                ? "anchored" : "floating"),
3335                 quoted, RE_SV_TAIL(must));
3336         });                 
3337         goto phooey;
3338     }
3339     else if ( (c = progi->regstclass) ) {
3340         if (minlen) {
3341             const OPCODE op = OP(progi->regstclass);
3342             /* don't bother with what can't match */
3343             if (PL_regkind[op] != EXACT && PL_regkind[op] != TRIE)
3344                 strend = HOPc(strend, -(minlen - 1));
3345         }
3346         DEBUG_EXECUTE_r({
3347             SV * const prop = sv_newmortal();
3348             regprop(prog, prop, c, reginfo, NULL);
3349             {
3350                 RE_PV_QUOTED_DECL(quoted,utf8_target,PERL_DEBUG_PAD_ZERO(1),
3351                     s,strend-s,60);
3352                 PerlIO_printf(Perl_debug_log,
3353                     "Matching stclass %.*s against %s (%d bytes)\n",
3354                     (int)SvCUR(prop), SvPVX_const(prop),
3355                      quoted, (int)(strend - s));
3356             }
3357         });
3358         if (find_byclass(prog, c, s, strend, reginfo))
3359             goto got_it;
3360         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Contradicts stclass... [regexec_flags]\n"));
3361     }
3362     else {
3363         dontbother = 0;
3364         if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
3365             /* Trim the end. */
3366             char *last= NULL;
3367             SV* float_real;
3368             STRLEN len;
3369             const char *little;
3370
3371             if (utf8_target) {
3372                 if (! prog->float_utf8) {
3373                     to_utf8_substr(prog);
3374                 }
3375                 float_real = prog->float_utf8;
3376             }
3377             else {
3378                 if (! prog->float_substr) {
3379                     if (! to_byte_substr(prog)) {
3380                         NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3381                     }
3382                 }
3383                 float_real = prog->float_substr;
3384             }
3385
3386             little = SvPV_const(float_real, len);
3387             if (SvTAIL(float_real)) {
3388                     /* This means that float_real contains an artificial \n on
3389                      * the end due to the presence of something like this:
3390                      * /foo$/ where we can match both "foo" and "foo\n" at the
3391                      * end of the string.  So we have to compare the end of the
3392                      * string first against the float_real without the \n and
3393                      * then against the full float_real with the string.  We
3394                      * have to watch out for cases where the string might be
3395                      * smaller than the float_real or the float_real without
3396                      * the \n. */
3397                     char *checkpos= strend - len;
3398                     DEBUG_OPTIMISE_r(
3399                         PerlIO_printf(Perl_debug_log,
3400                             "%sChecking for float_real.%s\n",
3401                             PL_colors[4], PL_colors[5]));
3402                     if (checkpos + 1 < strbeg) {
3403                         /* can't match, even if we remove the trailing \n
3404                          * string is too short to match */
3405                         DEBUG_EXECUTE_r(
3406                             PerlIO_printf(Perl_debug_log,
3407                                 "%sString shorter than required trailing substring, cannot match.%s\n",
3408                                 PL_colors[4], PL_colors[5]));
3409                         goto phooey;
3410                     } else if (memEQ(checkpos + 1, little, len - 1)) {
3411                         /* can match, the end of the string matches without the
3412                          * "\n" */
3413                         last = checkpos + 1;
3414                     } else if (checkpos < strbeg) {
3415                         /* cant match, string is too short when the "\n" is
3416                          * included */
3417                         DEBUG_EXECUTE_r(
3418                             PerlIO_printf(Perl_debug_log,
3419                                 "%sString does not contain required trailing substring, cannot match.%s\n",
3420                                 PL_colors[4], PL_colors[5]));
3421                         goto phooey;
3422                     } else if (!multiline) {
3423                         /* non multiline match, so compare with the "\n" at the
3424                          * end of the string */
3425                         if (memEQ(checkpos, little, len)) {
3426                             last= checkpos;
3427                         } else {
3428                             DEBUG_EXECUTE_r(
3429                                 PerlIO_printf(Perl_debug_log,
3430                                     "%sString does not contain required trailing substring, cannot match.%s\n",
3431                                     PL_colors[4], PL_colors[5]));
3432                             goto phooey;
3433                         }
3434                     } else {
3435                         /* multiline match, so we have to search for a place
3436                          * where the full string is located */
3437                         goto find_last;
3438                     }
3439             } else {
3440                   find_last:
3441                     if (len)
3442                         last = rninstr(s, strend, little, little + len);
3443                     else
3444                         last = strend;  /* matching "$" */
3445             }
3446             if (!last) {
3447                 /* at one point this block contained a comment which was
3448                  * probably incorrect, which said that this was a "should not
3449                  * happen" case.  Even if it was true when it was written I am
3450                  * pretty sure it is not anymore, so I have removed the comment
3451                  * and replaced it with this one. Yves */
3452                 DEBUG_EXECUTE_r(
3453                     PerlIO_printf(Perl_debug_log,
3454                         "%sString does not contain required substring, cannot match.%s\n",
3455                         PL_colors[4], PL_colors[5]
3456                     ));
3457                 goto phooey;
3458             }
3459             dontbother = strend - last + prog->float_min_offset;
3460         }
3461         if (minlen && (dontbother < minlen))
3462             dontbother = minlen - 1;
3463         strend -= dontbother;              /* this one's always in bytes! */
3464         /* We don't know much -- general case. */
3465         if (utf8_target) {
3466             for (;;) {
3467                 if (regtry(reginfo, &s))
3468                     goto got_it;
3469                 if (s >= strend)
3470                     break;
3471                 s += UTF8SKIP(s);
3472             };
3473         }
3474         else {
3475             do {
3476                 if (regtry(reginfo, &s))
3477                     goto got_it;
3478             } while (s++ < strend);
3479         }
3480     }
3481
3482     /* Failure. */
3483     goto phooey;
3484
3485   got_it:
3486     /* s/// doesn't like it if $& is earlier than where we asked it to
3487      * start searching (which can happen on something like /.\G/) */
3488     if (       (flags & REXEC_FAIL_ON_UNDERFLOW)
3489             && (prog->offs[0].start < stringarg - strbeg))
3490     {
3491         /* this should only be possible under \G */
3492         assert(prog->intflags & PREGf_GPOS_SEEN);
3493         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
3494             "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3495         goto phooey;
3496     }
3497
3498     DEBUG_BUFFERS_r(
3499         if (swap)
3500             PerlIO_printf(Perl_debug_log,
3501                 "rex=0x%"UVxf" freeing offs: 0x%"UVxf"\n",
3502                 PTR2UV(prog),
3503                 PTR2UV(swap)
3504             );
3505     );
3506     Safefree(swap);
3507
3508     /* clean up; this will trigger destructors that will free all slabs
3509      * above the current one, and cleanup the regmatch_info_aux
3510      * and regmatch_info_aux_eval sructs */
3511
3512     LEAVE_SCOPE(oldsave);
3513
3514     if (RXp_PAREN_NAMES(prog)) 
3515         (void)hv_iterinit(RXp_PAREN_NAMES(prog));
3516
3517     /* make sure $`, $&, $', and $digit will work later */
3518     if ( !(flags & REXEC_NOT_FIRST) )
3519         S_reg_set_capture_string(aTHX_ rx,
3520                                     strbeg, reginfo->strend,
3521                                     sv, flags, utf8_target);
3522
3523     return 1;
3524
3525   phooey:
3526     DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch failed%s\n",
3527                           PL_colors[4], PL_colors[5]));
3528
3529     /* clean up; this will trigger destructors that will free all slabs
3530      * above the current one, and cleanup the regmatch_info_aux
3531      * and regmatch_info_aux_eval sructs */
3532
3533     LEAVE_SCOPE(oldsave);
3534
3535     if (swap) {
3536         /* we failed :-( roll it back */
3537         DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
3538             "rex=0x%"UVxf" rolling back offs: freeing=0x%"UVxf" restoring=0x%"UVxf"\n",
3539             PTR2UV(prog),
3540             PTR2UV(prog->offs),
3541             PTR2UV(swap)
3542         ));
3543         Safefree(prog->offs);
3544         prog->offs = swap;
3545     }
3546     return 0;
3547 }
3548
3549
3550 /* Set which rex is pointed to by PL_reg_curpm, handling ref counting.
3551  * Do inc before dec, in case old and new rex are the same */
3552 #define SET_reg_curpm(Re2)                          \
3553     if (reginfo->info_aux_eval) {                   \
3554         (void)ReREFCNT_inc(Re2);                    \
3555         ReREFCNT_dec(PM_GETRE(PL_reg_curpm));       \
3556         PM_SETRE((PL_reg_curpm), (Re2));            \
3557     }
3558
3559
3560 /*
3561  - regtry - try match at specific point
3562  */
3563 STATIC bool                     /* 0 failure, 1 success */
3564 S_regtry(pTHX_ regmatch_info *reginfo, char **startposp)
3565 {
3566     CHECKPOINT lastcp;
3567     REGEXP *const rx = reginfo->prog;
3568     regexp *const prog = ReANY(rx);
3569     SSize_t result;
3570     RXi_GET_DECL(prog,progi);
3571     GET_RE_DEBUG_FLAGS_DECL;
3572
3573     PERL_ARGS_ASSERT_REGTRY;
3574
3575     reginfo->cutpoint=NULL;
3576
3577     prog->offs[0].start = *startposp - reginfo->strbeg;
3578     prog->lastparen = 0;
3579     prog->lastcloseparen = 0;
3580
3581     /* XXXX What this code is doing here?!!!  There should be no need
3582        to do this again and again, prog->lastparen should take care of
3583        this!  --ilya*/
3584
3585     /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
3586      * Actually, the code in regcppop() (which Ilya may be meaning by
3587      * prog->lastparen), is not needed at all by the test suite
3588      * (op/regexp, op/pat, op/split), but that code is needed otherwise
3589      * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
3590      * Meanwhile, this code *is* needed for the
3591      * above-mentioned test suite tests to succeed.  The common theme
3592      * on those tests seems to be returning null fields from matches.
3593      * --jhi updated by dapm */
3594 #if 1
3595     if (prog->nparens) {
3596         regexp_paren_pair *pp = prog->offs;
3597         I32 i;
3598         for (i = prog->nparens; i > (I32)prog->lastparen; i--) {
3599             ++pp;
3600             pp->start = -1;
3601             pp->end = -1;
3602         }
3603     }
3604 #endif
3605     REGCP_SET(lastcp);
3606     result = regmatch(reginfo, *startposp, progi->program + 1);
3607     if (result != -1) {
3608         prog->offs[0].end = result;
3609         return 1;
3610     }
3611     if (reginfo->cutpoint)
3612         *startposp= reginfo->cutpoint;
3613     REGCP_UNWIND(lastcp);
3614     return 0;
3615 }
3616
3617
3618 #define sayYES goto yes
3619 #define sayNO goto no
3620 #define sayNO_SILENT goto no_silent
3621
3622 /* we dont use STMT_START/END here because it leads to 
3623    "unreachable code" warnings, which are bogus, but distracting. */
3624 #define CACHEsayNO \
3625     if (ST.cache_mask) \
3626        reginfo->info_aux->poscache[ST.cache_offset] |= ST.cache_mask; \
3627     sayNO
3628
3629 /* this is used to determine how far from the left messages like
3630    'failed...' are printed. It should be set such that messages 
3631    are inline with the regop output that created them.
3632 */
3633 #define REPORT_CODE_OFF 32
3634
3635
3636 #define CHRTEST_UNINIT -1001 /* c1/c2 haven't been calculated yet */
3637 #define CHRTEST_VOID   -1000 /* the c1/c2 "next char" test should be skipped */
3638 #define CHRTEST_NOT_A_CP_1 -999
3639 #define CHRTEST_NOT_A_CP_2 -998
3640
3641 /* grab a new slab and return the first slot in it */
3642
3643 STATIC regmatch_state *
3644 S_push_slab(pTHX)
3645 {
3646 #if PERL_VERSION < 9 && !defined(PERL_CORE)
3647     dMY_CXT;
3648 #endif
3649     regmatch_slab *s = PL_regmatch_slab->next;
3650     if (!s) {
3651         Newx(s, 1, regmatch_slab);
3652         s->prev = PL_regmatch_slab;
3653         s->next = NULL;
3654         PL_regmatch_slab->next = s;
3655     }
3656     PL_regmatch_slab = s;
3657     return SLAB_FIRST(s);
3658 }
3659
3660
3661 /* push a new state then goto it */
3662
3663 #define PUSH_STATE_GOTO(state, node, input) \
3664     pushinput = input; \
3665     scan = node; \
3666     st->resume_state = state; \
3667     goto push_state;
3668
3669 /* push a new state with success backtracking, then goto it */
3670
3671 #define PUSH_YES_STATE_GOTO(state, node, input) \
3672     pushinput = input; \
3673     scan = node; \
3674     st->resume_state = state; \
3675     goto push_yes_state;
3676
3677
3678
3679
3680 /*
3681
3682 regmatch() - main matching routine
3683
3684 This is basically one big switch statement in a loop. We execute an op,
3685 set 'next' to point the next op, and continue. If we come to a point which
3686 we may need to backtrack to on failure such as (A|B|C), we push a
3687 backtrack state onto the backtrack stack. On failure, we pop the top
3688 state, and re-enter the loop at the state indicated. If there are no more
3689 states to pop, we return failure.
3690
3691 Sometimes we also need to backtrack on success; for example /A+/, where
3692 after successfully matching one A, we need to go back and try to
3693 match another one; similarly for lookahead assertions: if the assertion
3694 completes successfully, we backtrack to the state just before the assertion
3695 and then carry on.  In these cases, the pushed state is marked as
3696 'backtrack on success too'. This marking is in fact done by a chain of
3697 pointers, each pointing to the previous 'yes' state. On success, we pop to
3698 the nearest yes state, discarding any intermediate failure-only states.
3699 Sometimes a yes state is pushed just to force some cleanup code to be
3700 called at the end of a successful match or submatch; e.g. (??{$re}) uses
3701 it to free the inner regex.
3702
3703 Note that failure backtracking rewinds the cursor position, while
3704 success backtracking leaves it alone.
3705
3706 A pattern is complete when the END op is executed, while a subpattern
3707 such as (?=foo) is complete when the SUCCESS op is executed. Both of these
3708 ops trigger the "pop to last yes state if any, otherwise return true"
3709 behaviour.
3710
3711 A common convention in this function is to use A and B to refer to the two
3712 subpatterns (or to the first nodes thereof) in patterns like /A*B/: so A is
3713 the subpattern to be matched possibly multiple times, while B is the entire
3714 rest of the pattern. Variable and state names reflect this convention.
3715
3716 The states in the main switch are the union of ops and failure/success of
3717 substates associated with with that op.  For example, IFMATCH is the op
3718 that does lookahead assertions /(?=A)B/ and so the IFMATCH state means
3719 'execute IFMATCH'; while IFMATCH_A is a state saying that we have just
3720 successfully matched A and IFMATCH_A_fail is a state saying that we have
3721 just failed to match A. Resume states always come in pairs. The backtrack
3722 state we push is marked as 'IFMATCH_A', but when that is popped, we resume
3723 at IFMATCH_A or IFMATCH_A_fail, depending on whether we are backtracking
3724 on success or failure.
3725
3726 The struct that holds a backtracking state is actually a big union, with
3727 one variant for each major type of op. The variable st points to the
3728 top-most backtrack struct. To make the code clearer, within each
3729 block of code we #define ST to alias the relevant union.
3730
3731 Here's a concrete example of a (vastly oversimplified) IFMATCH
3732 implementation:
3733
3734     switch (state) {
3735     ....
3736
3737 #define ST st->u.ifmatch
3738
3739     case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3740         ST.foo = ...; // some state we wish to save
3741         ...
3742         // push a yes backtrack state with a resume value of
3743         // IFMATCH_A/IFMATCH_A_fail, then continue execution at the
3744         // first node of A:
3745         PUSH_YES_STATE_GOTO(IFMATCH_A, A, newinput);
3746         // NOTREACHED
3747
3748     case IFMATCH_A: // we have successfully executed A; now continue with B
3749         next = B;
3750         bar = ST.foo; // do something with the preserved value
3751         break;
3752
3753     case IFMATCH_A_fail: // A failed, so the assertion failed
3754         ...;   // do some housekeeping, then ...
3755         sayNO; // propagate the failure
3756
3757 #undef ST
3758
3759     ...
3760     }
3761
3762 For any old-timers reading this who are familiar with the old recursive
3763 approach, the code above is equivalent to:
3764
3765     case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3766     {
3767         int foo = ...
3768         ...
3769         if (regmatch(A)) {
3770             next = B;
3771             bar = foo;
3772             break;
3773         }
3774         ...;   // do some housekeeping, then ...
3775         sayNO; // propagate the failure
3776     }
3777
3778 The topmost backtrack state, pointed to by st, is usually free. If you
3779 want to claim it, populate any ST.foo fields in it with values you wish to
3780 save, then do one of
3781
3782         PUSH_STATE_GOTO(resume_state, node, newinput);
3783         PUSH_YES_STATE_GOTO(resume_state, node, newinput);
3784
3785 which sets that backtrack state's resume value to 'resume_state', pushes a
3786 new free entry to the top of the backtrack stack, then goes to 'node'.
3787 On backtracking, the free slot is popped, and the saved state becomes the
3788 new free state. An ST.foo field in this new top state can be temporarily
3789 accessed to retrieve values, but once the main loop is re-entered, it
3790 becomes available for reuse.
3791
3792 Note that the depth of the backtrack stack constantly increases during the
3793 left-to-right execution of the pattern, rather than going up and down with
3794 the pattern nesting. For example the stack is at its maximum at Z at the
3795 end of the pattern, rather than at X in the following:
3796
3797     /(((X)+)+)+....(Y)+....Z/
3798
3799 The only exceptions to this are lookahead/behind assertions and the cut,
3800 (?>A), which pop all the backtrack states associated with A before
3801 continuing.
3802  
3803 Backtrack state structs are allocated in slabs of about 4K in size.
3804 PL_regmatch_state and st always point to the currently active state,
3805 and PL_regmatch_slab points to the slab currently containing
3806 PL_regmatch_state.  The first time regmatch() is called, the first slab is
3807 allocated, and is never freed until interpreter destruction. When the slab
3808 is full, a new one is allocated and chained to the end. At exit from
3809 regmatch(), slabs allocated since entry are freed.
3810
3811 */
3812  
3813
3814 #define DEBUG_STATE_pp(pp)                                  \
3815     DEBUG_STATE_r({                                         \
3816         DUMP_EXEC_POS(locinput, scan, utf8_target);         \
3817         PerlIO_printf(Perl_debug_log,                       \
3818             "    %*s"pp" %s%s%s%s%s\n",                     \
3819             depth*2, "",                                    \
3820             PL_reg_name[st->resume_state],                  \
3821             ((st==yes_state||st==mark_state) ? "[" : ""),   \
3822             ((st==yes_state) ? "Y" : ""),                   \
3823             ((st==mark_state) ? "M" : ""),                  \
3824             ((st==yes_state||st==mark_state) ? "]" : "")    \
3825         );                                                  \
3826     });
3827
3828
3829 #define REG_NODE_NUM(x) ((x) ? (int)((x)-prog) : -1)
3830
3831 #ifdef DEBUGGING
3832
3833 STATIC void
3834 S_debug_start_match(pTHX_ const REGEXP *prog, const bool utf8_target,
3835     const char *start, const char *end, const char *blurb)
3836 {
3837     const bool utf8_pat = RX_UTF8(prog) ? 1 : 0;
3838
3839     PERL_ARGS_ASSERT_DEBUG_START_MATCH;
3840
3841     if (!PL_colorset)   
3842             reginitcolors();    
3843     {
3844         RE_PV_QUOTED_DECL(s0, utf8_pat, PERL_DEBUG_PAD_ZERO(0), 
3845             RX_PRECOMP_const(prog), RX_PRELEN(prog), 60);   
3846         
3847         RE_PV_QUOTED_DECL(s1, utf8_target, PERL_DEBUG_PAD_ZERO(1),
3848             start, end - start, 60); 
3849         
3850         PerlIO_printf(Perl_debug_log, 
3851             "%s%s REx%s %s against %s\n", 
3852                        PL_colors[4], blurb, PL_colors[5], s0, s1); 
3853         
3854         if (utf8_target||utf8_pat)
3855             PerlIO_printf(Perl_debug_log, "UTF-8 %s%s%s...\n",
3856                 utf8_pat ? "pattern" : "",
3857                 utf8_pat && utf8_target ? " and " : "",
3858                 utf8_target ? "string" : ""
3859             ); 
3860     }
3861 }
3862
3863 STATIC void
3864 S_dump_exec_pos(pTHX_ const char *locinput, 
3865                       const regnode *scan, 
3866                       const char *loc_regeol, 
3867                       const char *loc_bostr, 
3868                       const char *loc_reg_starttry,
3869                       const bool utf8_target)
3870 {
3871     const int docolor = *PL_colors[0] || *PL_colors[2] || *PL_colors[4];
3872     const int taill = (docolor ? 10 : 7); /* 3 chars for "> <" */
3873     int l = (loc_regeol - locinput) > taill ? taill : (loc_regeol - locinput);
3874     /* The part of the string before starttry has one color
3875        (pref0_len chars), between starttry and current
3876        position another one (pref_len - pref0_len chars),
3877        after the current position the third one.
3878        We assume that pref0_len <= pref_len, otherwise we
3879        decrease pref0_len.  */
3880     int pref_len = (locinput - loc_bostr) > (5 + taill) - l
3881         ? (5 + taill) - l : locinput - loc_bostr;
3882     int pref0_len;
3883
3884     PERL_ARGS_ASSERT_DUMP_EXEC_POS;
3885
3886     while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput - pref_len)))
3887         pref_len++;
3888     pref0_len = pref_len  - (locinput - loc_reg_starttry);
3889     if (l + pref_len < (5 + taill) && l < loc_regeol - locinput)
3890         l = ( loc_regeol - locinput > (5 + taill) - pref_len
3891               ? (5 + taill) - pref_len : loc_regeol - locinput);
3892     while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput + l)))
3893         l--;
3894     if (pref0_len < 0)
3895         pref0_len = 0;
3896     if (pref0_len > pref_len)
3897         pref0_len = pref_len;
3898     {
3899         const int is_uni = utf8_target ? 1 : 0;
3900
3901         RE_PV_COLOR_DECL(s0,len0,is_uni,PERL_DEBUG_PAD(0),
3902             (locinput - pref_len),pref0_len, 60, 4, 5);
3903         
3904         RE_PV_COLOR_DECL(s1,len1,is_uni,PERL_DEBUG_PAD(1),
3905                     (locinput - pref_len + pref0_len),
3906                     pref_len - pref0_len, 60, 2, 3);
3907         
3908         RE_PV_COLOR_DECL(s2,len2,is_uni,PERL_DEBUG_PAD(2),
3909                     locinput, loc_regeol - locinput, 10, 0, 1);
3910
3911         const STRLEN tlen=len0+len1+len2;
3912         PerlIO_printf(Perl_debug_log,
3913                     "%4"IVdf" <%.*s%.*s%s%.*s>%*s|",
3914                     (IV)(locinput - loc_bostr),
3915                     len0, s0,
3916                     len1, s1,
3917                     (docolor ? "" : "> <"),
3918                     len2, s2,
3919                     (int)(tlen > 19 ? 0 :  19 - tlen),
3920                     "");
3921     }
3922 }
3923
3924 #endif
3925
3926 /* reg_check_named_buff_matched()
3927  * Checks to see if a named buffer has matched. The data array of 
3928  * buffer numbers corresponding to the buffer is expected to reside
3929  * in the regexp->data->data array in the slot stored in the ARG() of
3930  * node involved. Note that this routine doesn't actually care about the
3931  * name, that information is not preserved from compilation to execution.
3932  * Returns the index of the leftmost defined buffer with the given name
3933  * or 0 if non of the buffers matched.
3934  */
3935 STATIC I32
3936 S_reg_check_named_buff_matched(const regexp *rex, const regnode *scan)
3937 {
3938     I32 n;
3939     RXi_GET_DECL(rex,rexi);
3940     SV *sv_dat= MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
3941     I32 *nums=(I32*)SvPVX(sv_dat);
3942
3943     PERL_ARGS_ASSERT_REG_CHECK_NAMED_BUFF_MATCHED;
3944
3945     for ( n=0; n<SvIVX(sv_dat); n++ ) {
3946         if ((I32)rex->lastparen >= nums[n] &&
3947             rex->offs[nums[n]].end != -1)
3948         {
3949             return nums[n];
3950         }
3951     }
3952     return 0;
3953 }
3954
3955
3956 static bool
3957 S_setup_EXACTISH_ST_c1_c2(pTHX_ const regnode * const text_node, int *c1p,
3958         U8* c1_utf8, int *c2p, U8* c2_utf8, regmatch_info *reginfo)
3959 {
3960     /* This function determines if there are one or two characters that match
3961      * the first character of the passed-in EXACTish node <text_node>, and if
3962      * so, returns them in the passed-in pointers.
3963      *
3964      * If it determines that no possible character in the target string can
3965      * match, it returns FALSE; otherwise TRUE.  (The FALSE situation occurs if
3966      * the first character in <text_node> requires UTF-8 to represent, and the
3967      * target string isn't in UTF-8.)
3968      *
3969      * If there are more than two characters that could match the beginning of
3970      * <text_node>, or if more context is required to determine a match or not,
3971      * it sets both *<c1p> and *<c2p> to CHRTEST_VOID.
3972      *
3973      * The motiviation behind this function is to allow the caller to set up
3974      * tight loops for matching.  If <text_node> is of type EXACT, there is
3975      * only one possible character that can match its first character, and so
3976      * the situation is quite simple.  But things get much more complicated if
3977      * folding is involved.  It may be that the first character of an EXACTFish
3978      * node doesn't participate in any possible fold, e.g., punctuation, so it
3979      * can be matched only by itself.  The vast majority of characters that are
3980      * in folds match just two things, their lower and upper-case equivalents.
3981      * But not all are like that; some have multiple possible matches, or match
3982      * sequences of more than one character.  This function sorts all that out.
3983      *
3984      * Consider the patterns A*B or A*?B where A and B are arbitrary.  In a
3985      * loop of trying to match A*, we know we can't exit where the thing
3986      * following it isn't a B.  And something can't be a B unless it is the
3987      * beginning of B.  By putting a quick test for that beginning in a tight
3988      * loop, we can rule out things that can't possibly be B without having to
3989      * break out of the loop, thus avoiding work.  Similarly, if A is a single
3990      * character, we can make a tight loop matching A*, using the outputs of
3991      * this function.
3992      *
3993      * If the target string to match isn't in UTF-8, and there aren't
3994      * complications which require CHRTEST_VOID, *<c1p> and *<c2p> are set to
3995      * the one or two possible octets (which are characters in this situation)
3996      * that can match.  In all cases, if there is only one character that can
3997      * match, *<c1p> and *<c2p> will be identical.
3998      *
3999      * If the target string is in UTF-8, the buffers pointed to by <c1_utf8>
4000      * and <c2_utf8> will contain the one or two UTF-8 sequences of bytes that
4001      * can match the beginning of <text_node>.  They should be declared with at
4002      * least length UTF8_MAXBYTES+1.  (If the target string isn't in UTF-8, it is
4003      * undefined what these contain.)  If one or both of the buffers are
4004      * invariant under UTF-8, *<c1p>, and *<c2p> will also be set to the
4005      * corresponding invariant.  If variant, the corresponding *<c1p> and/or
4006      * *<c2p> will be set to a negative number(s) that shouldn't match any code
4007      * point (unless inappropriately coerced to unsigned).   *<c1p> will equal
4008      * *<c2p> if and only if <c1_utf8> and <c2_utf8> are the same. */
4009
4010     const bool utf8_target = reginfo->is_utf8_target;
4011
4012     UV c1 = (UV)CHRTEST_NOT_A_CP_1;
4013     UV c2 = (UV)CHRTEST_NOT_A_CP_2;
4014     bool use_chrtest_void = FALSE;
4015     const bool is_utf8_pat = reginfo->is_utf8_pat;
4016
4017     /* Used when we have both utf8 input and utf8 output, to avoid converting
4018      * to/from code points */
4019     bool utf8_has_been_setup = FALSE;
4020
4021     dVAR;
4022
4023     U8 *pat = (U8*)STRING(text_node);
4024     U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' };
4025
4026     if (OP(text_node) == EXACT || OP(text_node) == EXACTL) {
4027
4028         /* In an exact node, only one thing can be matched, that first
4029          * character.  If both the pat and the target are UTF-8, we can just
4030          * copy the input to the output, avoiding finding the code point of
4031          * that character */
4032         if (!is_utf8_pat) {
4033             c2 = c1 = *pat;
4034         }
4035         else if (utf8_target) {
4036             Copy(pat, c1_utf8, UTF8SKIP(pat), U8);
4037             Copy(pat, c2_utf8, UTF8SKIP(pat), U8);
4038             utf8_has_been_setup = TRUE;
4039         }
4040         else {
4041             c2 = c1 = valid_utf8_to_uvchr(pat, NULL);
4042         }
4043     }
4044     else { /* an EXACTFish node */
4045         U8 *pat_end = pat + STR_LEN(text_node);
4046
4047         /* An EXACTFL node has at least some characters unfolded, because what
4048          * they match is not known until now.  So, now is the time to fold
4049          * the first few of them, as many as are needed to determine 'c1' and
4050          * 'c2' later in the routine.  If the pattern isn't UTF-8, we only need
4051          * to fold if in a UTF-8 locale, and then only the Sharp S; everything
4052          * else is 1-1 and isn't assumed to be folded.  In a UTF-8 pattern, we
4053          * need to fold as many characters as a single character can fold to,
4054          * so that later we can check if the first ones are such a multi-char
4055          * fold.  But, in such a pattern only locale-problematic characters
4056          * aren't folded, so we can skip this completely if the first character
4057          * in the node isn't one of the tricky ones */
4058         if (OP(text_node) == EXACTFL) {
4059
4060             if (! is_utf8_pat) {
4061                 if (IN_UTF8_CTYPE_LOCALE && *pat == LATIN_SMALL_LETTER_SHARP_S)
4062                 {
4063                     folded[0] = folded[1] = 's';
4064                     pat = folded;
4065                     pat_end = folded + 2;
4066                 }
4067             }
4068             else if (is_PROBLEMATIC_LOCALE_FOLDEDS_START_utf8(pat)) {
4069                 U8 *s = pat;
4070                 U8 *d = folded;
4071                 int i;
4072
4073                 for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < pat_end; i++) {
4074                     if (isASCII(*s)) {
4075                         *(d++) = (U8) toFOLD_LC(*s);
4076                         s++;
4077                     }
4078                     else {
4079                         STRLEN len;
4080                         _to_utf8_fold_flags(s,
4081                                             d,
4082                                             &len,
4083                                             FOLD_FLAGS_FULL | FOLD_FLAGS_LOCALE);
4084                         d += len;
4085                         s += UTF8SKIP(s);
4086                     }
4087                 }
4088
4089                 pat = folded;
4090                 pat_end = d;
4091             }
4092         }
4093
4094         if ((is_utf8_pat && is_MULTI_CHAR_FOLD_utf8_safe(pat, pat_end))
4095              || (!is_utf8_pat && is_MULTI_CHAR_FOLD_latin1_safe(pat, pat_end)))
4096         {
4097             /* Multi-character folds require more context to sort out.  Also
4098              * PL_utf8_foldclosures used below doesn't handle them, so have to
4099              * be handled outside this routine */
4100             use_chrtest_void = TRUE;
4101         }
4102         else { /* an EXACTFish node which doesn't begin with a multi-char fold */
4103             c1 = is_utf8_pat ? valid_utf8_to_uvchr(pat, NULL) : *pat;
4104             if (c1 > 255) {
4105                 /* Load the folds hash, if not already done */
4106                 SV** listp;
4107                 if (! PL_utf8_foldclosures) {
4108                     _load_PL_utf8_foldclosures();
4109                 }
4110
4111                 /* The fold closures data structure is a hash with the keys
4112                  * being the UTF-8 of every character that is folded to, like
4113                  * 'k', and the values each an array of all code points that
4114                  * fold to its key.  e.g. [ 'k', 'K', KELVIN_SIGN ].
4115                  * Multi-character folds are not included */
4116                 if ((! (listp = hv_fetch(PL_utf8_foldclosures,
4117                                         (char *) pat,
4118                                         UTF8SKIP(pat),
4119                                         FALSE))))
4120                 {
4121                     /* Not found in the hash, therefore there are no folds
4122                     * containing it, so there is only a single character that
4123                     * could match */
4124                     c2 = c1;
4125                 }
4126                 else {  /* Does participate in folds */
4127                     AV* list = (AV*) *listp;
4128                     if (av_tindex(list) != 1) {
4129
4130                         /* If there aren't exactly two folds to this, it is
4131                          * outside the scope of this function */
4132                         use_chrtest_void = TRUE;
4133                     }
4134                     else {  /* There are two.  Get them */
4135                         SV** c_p = av_fetch(list, 0, FALSE);
4136                         if (c_p == NULL) {
4137                             Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
4138                         }
4139                         c1 = SvUV(*c_p);
4140
4141                         c_p = av_fetch(list, 1, FALSE);
4142                         if (c_p == NULL) {
4143                             Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
4144                         }
4145                         c2 = SvUV(*c_p);
4146
4147                         /* Folds that cross the 255/256 boundary are forbidden
4148                          * if EXACTFL (and isnt a UTF8 locale), or EXACTFA and
4149                          * one is ASCIII.  Since the pattern character is above
4150                          * 255, and its only other match is below 256, the only
4151                          * legal match will be to itself.  We have thrown away
4152                          * the original, so have to compute which is the one
4153                          * above 255. */
4154                         if ((c1 < 256) != (c2 < 256)) {
4155                             if ((OP(text_node) == EXACTFL
4156                                  && ! IN_UTF8_CTYPE_LOCALE)
4157                                 || ((OP(text_node) == EXACTFA
4158                                     || OP(text_node) == EXACTFA_NO_TRIE)
4159                                     && (isASCII(c1) || isASCII(c2))))
4160                             {
4161                                 if (c1 < 256) {
4162                                     c1 = c2;
4163                                 }
4164                                 else {
4165                                     c2 = c1;
4166                                 }
4167                             }
4168                         }
4169                     }
4170                 }
4171             }
4172             else /* Here, c1 is <= 255 */
4173                 if (utf8_target
4174                     && HAS_NONLATIN1_FOLD_CLOSURE(c1)
4175                     && ( ! (OP(text_node) == EXACTFL && ! IN_UTF8_CTYPE_LOCALE))
4176                     && ((OP(text_node) != EXACTFA
4177                         && OP(text_node) != EXACTFA_NO_TRIE)
4178                         || ! isASCII(c1)))
4179             {
4180                 /* Here, there could be something above Latin1 in the target
4181                  * which folds to this character in the pattern.  All such
4182                  * cases except LATIN SMALL LETTER Y WITH DIAERESIS have more
4183                  * than two characters involved in their folds, so are outside
4184                  * the scope of this function */
4185                 if (UNLIKELY(c1 == LATIN_SMALL_LETTER_Y_WITH_DIAERESIS)) {
4186                     c2 = LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS;
4187                 }
4188                 else {
4189                     use_chrtest_void = TRUE;
4190                 }
4191             }
4192             else { /* Here nothing above Latin1 can fold to the pattern
4193                       character */
4194                 switch (OP(text_node)) {
4195
4196                     case EXACTFL:   /* /l rules */
4197                         c2 = PL_fold_locale[c1];
4198                         break;
4199
4200                     case EXACTF:   /* This node only generated for non-utf8
4201                                     patterns */
4202                         assert(! is_utf8_pat);
4203                         if (! utf8_target) {    /* /d rules */
4204                             c2 = PL_fold[c1];
4205                             break;
4206                         }
4207                         /* FALLTHROUGH */
4208                         /* /u rules for all these.  This happens to work for
4209                         * EXACTFA as nothing in Latin1 folds to ASCII */
4210                     case EXACTFA_NO_TRIE:   /* This node only generated for
4211                                             non-utf8 patterns */
4212                         assert(! is_utf8_pat);
4213                         /* FALLTHROUGH */
4214                     case EXACTFA:
4215                     case EXACTFU_SS:
4216                     case EXACTFU:
4217                         c2 = PL_fold_latin1[c1];
4218                         break;
4219
4220                     default:
4221                         Perl_croak(aTHX_ "panic: Unexpected op %u", OP(text_node));
4222                         NOT_REACHED; /* NOTREACHED */
4223                 }
4224             }
4225         }
4226     }
4227
4228     /* Here have figured things out.  Set up the returns */
4229     if (use_chrtest_void) {
4230         *c2p = *c1p = CHRTEST_VOID;
4231     }
4232     else if (utf8_target) {
4233         if (! utf8_has_been_setup) {    /* Don't have the utf8; must get it */
4234             uvchr_to_utf8(c1_utf8, c1);
4235             uvchr_to_utf8(c2_utf8, c2);
4236         }
4237
4238         /* Invariants are stored in both the utf8 and byte outputs; Use
4239          * negative numbers otherwise for the byte ones.  Make sure that the
4240          * byte ones are the same iff the utf8 ones are the same */
4241         *c1p = (UTF8_IS_INVARIANT(*c1_utf8)) ? *c1_utf8 : CHRTEST_NOT_A_CP_1;
4242         *c2p = (UTF8_IS_INVARIANT(*c2_utf8))
4243                 ? *c2_utf8
4244                 : (c1 == c2)
4245                   ? CHRTEST_NOT_A_CP_1
4246                   : CHRTEST_NOT_A_CP_2;
4247     }
4248     else if (c1 > 255) {
4249        if (c2 > 255) {  /* both possibilities are above what a non-utf8 string
4250                            can represent */
4251            return FALSE;
4252        }
4253
4254        *c1p = *c2p = c2;    /* c2 is the only representable value */
4255     }
4256     else {  /* c1 is representable; see about c2 */
4257        *c1p = c1;
4258        *c2p = (c2 < 256) ? c2 : c1;
4259     }
4260
4261     return TRUE;
4262 }
4263
4264 PERL_STATIC_INLINE bool
4265 S_isGCB(const GCB_enum before, const GCB_enum after)
4266 {
4267     /* returns a boolean indicating if there is a Grapheme Cluster Boundary
4268      * between the inputs.  See http://www.unicode.org/reports/tr29/ */
4269
4270     return GCB_table[before][after];
4271 }
4272
4273 /* Combining marks attach to most classes that precede them, but this defines
4274  * the exceptions (from TR14) */
4275 #define LB_CM_ATTACHES_TO(prev) ( ! (   prev == LB_EDGE                 \
4276                                      || prev == LB_Mandatory_Break      \
4277                                      || prev == LB_Carriage_Return      \
4278                                      || prev == LB_Line_Feed            \
4279                                      || prev == LB_Next_Line            \
4280                                      || prev == LB_Space                \
4281                                      || prev == LB_ZWSpace))
4282
4283 STATIC bool
4284 S_isLB(pTHX_ LB_enum before,
4285              LB_enum after,
4286              const U8 * const strbeg,
4287              const U8 * const curpos,
4288              const U8 * const strend,
4289              const bool utf8_target)
4290 {
4291     U8 * temp_pos = (U8 *) curpos;
4292     LB_enum prev = before;
4293
4294     /* Is the boundary between 'before' and 'after' line-breakable?
4295      * Most of this is just a table lookup of a generated table from Unicode
4296      * rules.  But some rules require context to decide, and so have to be
4297      * implemented in code */
4298
4299     PERL_ARGS_ASSERT_ISLB;
4300
4301     /* Rule numbers in the comments below are as of Unicode 8.0 */
4302
4303   redo:
4304     before = prev;
4305     switch (LB_table[before][after]) {
4306         case LB_BREAKABLE:
4307             return TRUE;
4308
4309         case LB_NOBREAK:
4310         case LB_NOBREAK_EVEN_WITH_SP_BETWEEN:
4311             return FALSE;
4312
4313         case LB_SP_foo + LB_BREAKABLE:
4314         case LB_SP_foo + LB_NOBREAK:
4315         case LB_SP_foo + LB_NOBREAK_EVEN_WITH_SP_BETWEEN:
4316
4317             /* When we have something following a SP, we have to look at the
4318              * context in order to know what to do.
4319              *
4320              * SP SP should not reach here because LB7: Do not break before
4321              * spaces.  (For two spaces in a row there is nothing that
4322              * overrides that) */
4323             assert(after != LB_Space);
4324
4325             /* Here we have a space followed by a non-space.  Mostly this is a
4326              * case of LB18: "Break after spaces".  But there are complications
4327              * as the handling of spaces is somewhat tricky.  They are in a
4328              * number of rules, which have to be applied in priority order, but
4329              * something earlier in the string can cause a rule to be skipped
4330              * and a lower priority rule invoked.  A prime example is LB7 which
4331              * says don't break before a space.  But rule LB8 (lower priority)
4332              * says that the first break opportunity after a ZW is after any
4333              * span of spaces immediately after it.  If a ZW comes before a SP
4334              * in the input, rule LB8 applies, and not LB7.  Other such rules
4335              * involve combining marks which are rules 9 and 10, but they may
4336              * override higher priority rules if they come earlier in the
4337              * string.  Since we're doing random access into the middle of the
4338              * string, we have to look for rules that should get applied based
4339              * on both string position and priority.  Combining marks do not
4340              * attach to either ZW nor SP, so we don't have to consider them
4341              * until later.
4342              *
4343              * To check for LB8, we have to find the first non-space character
4344              * before this span of spaces */
4345             do {
4346                 prev = backup_one_LB(strbeg, &temp_pos, utf8_target);
4347             }
4348             while (prev == LB_Space);
4349
4350             /* LB8 Break before any character following a zero-width space,
4351              * even if one or more spaces intervene.
4352              *      ZW SP* Ã·
4353              * So if we have a ZW just before this span, and to get here this
4354              * is the final space in the span. */
4355             if (prev == LB_ZWSpace) {
4356                 return TRUE;
4357             }
4358
4359             /* Here, not ZW SP+.  There are several rules that have higher
4360              * priority than LB18 and can be resolved now, as they don't depend
4361              * on anything earlier in the string (except ZW, which we have
4362              * already handled).  One of these rules is LB11 Do not break
4363              * before Word joiner, but we have specially encoded that in the
4364              * lookup table so it is caught by the single test below which
4365              * catches the other ones. */
4366             if (LB_table[LB_Space][after] - LB_SP_foo
4367                                             == LB_NOBREAK_EVEN_WITH_SP_BETWEEN)
4368             {
4369                 return FALSE;
4370             }
4371
4372             /* If we get here, we have to XXX consider combining marks. */
4373             if (prev == LB_Combining_Mark) {
4374
4375                 /* What happens with these depends on the character they
4376                  * follow.  */
4377                 do {
4378                     prev = backup_one_LB(strbeg, &temp_pos, utf8_target);
4379                 }
4380                 while (prev == LB_Combining_Mark);
4381
4382                 /* Most times these attach to and inherit the characteristics
4383                  * of that character, but not always, and when not, they are to
4384                  * be treated as AL by rule LB10. */
4385                 if (! LB_CM_ATTACHES_TO(prev)) {
4386                     prev = LB_Alphabetic;
4387                 }
4388             }
4389
4390             /* Here, we have the character preceding the span of spaces all set
4391              * up.  We follow LB18: "Break after spaces" unless the table shows
4392              * that is overriden */
4393             return LB_table[prev][after] != LB_NOBREAK_EVEN_WITH_SP_BETWEEN;
4394
4395         case LB_CM_foo:
4396
4397             /* We don't know how to treat the CM except by looking at the first
4398              * non-CM character preceding it */
4399             do {
4400                 prev = backup_one_LB(strbeg, &temp_pos, utf8_target);
4401             }
4402             while (prev == LB_Combining_Mark);
4403
4404             /* Here, 'prev' is that first earlier non-CM character.  If the CM
4405              * attatches to it, then it inherits the behavior of 'prev'.  If it
4406              * doesn't attach, it is to be treated as an AL */
4407             if (! LB_CM_ATTACHES_TO(prev)) {
4408                 prev = LB_Alphabetic;
4409             }
4410
4411             goto redo;
4412
4413         case LB_HY_or_BA_then_foo + LB_BREAKABLE:
4414         case LB_HY_or_BA_then_foo + LB_NOBREAK:
4415
4416             /* LB21a Don't break after Hebrew + Hyphen.
4417              * HL (HY | BA) Ã— */
4418
4419             if (backup_one_LB(strbeg, &temp_pos, utf8_target)
4420                                                           == LB_Hebrew_Letter)
4421             {
4422                 return FALSE;
4423             }
4424
4425             return LB_table[prev][after] - LB_HY_or_BA_then_foo == LB_BREAKABLE;
4426
4427         case LB_PR_or_PO_then_OP_or_HY + LB_BREAKABLE:
4428         case LB_PR_or_PO_then_OP_or_HY + LB_NOBREAK:
4429
4430             /* LB25a (PR | PO) Ã— ( OP | HY )? NU */
4431             if (advance_one_LB(&temp_pos, strend, utf8_target) == LB_Numeric) {
4432                 return FALSE;
4433             }
4434
4435             return LB_table[prev][after] - LB_PR_or_PO_then_OP_or_HY
4436                                                                 == LB_BREAKABLE;
4437
4438         case LB_SY_or_IS_then_various + LB_BREAKABLE:
4439         case LB_SY_or_IS_then_various + LB_NOBREAK:
4440         {
4441             /* LB25d NU (SY | IS)* Ã— (NU | SY | IS | CL | CP ) */
4442
4443             LB_enum temp = prev;
4444             do {
4445                 temp = backup_one_LB(strbeg, &temp_pos, utf8_target);
4446             }
4447             while (temp == LB_Break_Symbols || temp == LB_Infix_Numeric);
4448             if (temp == LB_Numeric) {
4449                 return FALSE;
4450             }
4451
4452             return LB_table[prev][after] - LB_SY_or_IS_then_various
4453                                                                == LB_BREAKABLE;
4454         }
4455
4456         case LB_various_then_PO_or_PR + LB_BREAKABLE:
4457         case LB_various_then_PO_or_PR + LB_NOBREAK:
4458         {
4459             /* LB25e NU (SY | IS)* (CL | CP)? Ã— (PO | PR) */
4460
4461             LB_enum temp = prev;
4462             if (temp == LB_Close_Punctuation || temp == LB_Close_Parenthesis)
4463             {
4464                 temp = backup_one_LB(strbeg, &temp_pos, utf8_target);
4465             }
4466             while (temp == LB_Break_Symbols || temp == LB_Infix_Numeric) {
4467                 temp = backup_one_LB(strbeg, &temp_pos, utf8_target);
4468             }
4469             if (temp == LB_Numeric) {
4470                 return FALSE;
4471             }
4472             return LB_various_then_PO_or_PR;
4473         }
4474
4475         default:
4476             break;
4477     }
4478
4479 #ifdef DEBUGGING
4480     PerlIO_printf(Perl_error_log, "Unhandled LB pair: LB_table[%d, %d] = %d\n",
4481                                   before, after, LB_table[before][after]);
4482     assert(0);
4483 #endif
4484     return TRUE;
4485 }
4486
4487 STATIC LB_enum
4488 S_advance_one_LB(pTHX_ U8 ** curpos, const U8 * const strend, const bool utf8_target)
4489 {
4490     LB_enum lb;
4491
4492     PERL_ARGS_ASSERT_ADVANCE_ONE_LB;
4493
4494     if (*curpos >= strend) {
4495         return LB_EDGE;
4496     }
4497
4498     if (utf8_target) {
4499         *curpos += UTF8SKIP(*curpos);
4500         if (*curpos >= strend) {
4501             return LB_EDGE;
4502         }
4503         lb = getLB_VAL_UTF8(*curpos, strend);
4504     }
4505     else {
4506         (*curpos)++;
4507         if (*curpos >= strend) {
4508             return LB_EDGE;
4509         }
4510         lb = getLB_VAL_CP(**curpos);
4511     }
4512
4513     return lb;
4514 }
4515
4516 STATIC LB_enum
4517 S_backup_one_LB(pTHX_ const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
4518 {
4519     LB_enum lb;
4520
4521     PERL_ARGS_ASSERT_BACKUP_ONE_LB;
4522
4523     if (*curpos < strbeg) {
4524         return LB_EDGE;
4525     }
4526
4527     if (utf8_target) {
4528         U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
4529         U8 * prev_prev_char_pos;
4530
4531         if (! prev_char_pos) {
4532             return LB_EDGE;
4533         }
4534
4535         if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos, -1, strbeg))) {
4536             lb = getLB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
4537             *curpos = prev_char_pos;
4538             prev_char_pos = prev_prev_char_pos;
4539         }
4540         else {
4541             *curpos = (U8 *) strbeg;
4542             return LB_EDGE;
4543         }
4544     }
4545     else {
4546         if (*curpos - 2 < strbeg) {
4547             *curpos = (U8 *) strbeg;
4548             return LB_EDGE;
4549         }
4550         (*curpos)--;
4551         lb = getLB_VAL_CP(*(*curpos - 1));
4552     }
4553
4554     return lb;
4555 }
4556
4557 STATIC bool
4558 S_isSB(pTHX_ SB_enum before,
4559              SB_enum after,
4560              const U8 * const strbeg,
4561              const U8 * const curpos,
4562              const U8 * const strend,
4563              const bool utf8_target)
4564 {
4565     /* returns a boolean indicating if there is a Sentence Boundary Break
4566      * between the inputs.  See http://www.unicode.org/reports/tr29/ */
4567
4568     U8 * lpos = (U8 *) curpos;
4569     bool has_para_sep = FALSE;
4570     bool has_sp = FALSE;
4571
4572     PERL_ARGS_ASSERT_ISSB;
4573
4574     /* Break at the start and end of text.
4575         SB1.  sot  Ã·
4576         SB2.  Ã·  eot
4577       But unstated in Unicode is don't break if the text is empty */
4578     if (before == SB_EDGE || after == SB_EDGE) {
4579         return before != after;
4580     }
4581
4582     /* SB 3: Do not break within CRLF. */
4583     if (before == SB_CR && after == SB_LF) {
4584         return FALSE;
4585     }
4586
4587     /* Break after paragraph separators.  CR and LF are considered
4588      * so because Unicode views text as like word processing text where there
4589      * are no newlines except between paragraphs, and the word processor takes
4590      * care of wrapping without there being hard line-breaks in the text *./
4591        SB4.  Sep | CR | LF  Ã· */
4592     if (before == SB_Sep || before == SB_CR || before == SB_LF) {
4593         return TRUE;
4594     }
4595
4596     /* Ignore Format and Extend characters, except after sot, Sep, CR, or LF.
4597      * (See Section 6.2, Replacing Ignore Rules.)
4598         SB5.  X (Extend | Format)*  â†’  X */
4599     if (after == SB_Extend || after == SB_Format) {
4600
4601         /* Implied is that the these characters attach to everything
4602          * immediately prior to them except for those separator-type
4603          * characters.  And the rules earlier have already handled the case
4604          * when one of those immediately precedes the extend char */
4605         return FALSE;
4606     }
4607
4608     if (before == SB_Extend || before == SB_Format) {
4609         U8 * temp_pos = lpos;
4610         const SB_enum backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4611         if (   backup != SB_EDGE
4612             && backup != SB_Sep
4613             && backup != SB_CR
4614             && backup != SB_LF)
4615         {
4616             before = backup;
4617             lpos = temp_pos;
4618         }
4619
4620         /* Here, both 'before' and 'backup' are these types; implied is that we
4621          * don't break between them */
4622         if (backup == SB_Extend || backup == SB_Format) {
4623             return FALSE;
4624         }
4625     }
4626
4627     /* Do not break after ambiguous terminators like period, if they are
4628      * immediately followed by a number or lowercase letter, if they are
4629      * between uppercase letters, if the first following letter (optionally
4630      * after certain punctuation) is lowercase, or if they are followed by
4631      * "continuation" punctuation such as comma, colon, or semicolon. For
4632      * example, a period may be an abbreviation or numeric period, and thus may
4633      * not mark the end of a sentence.
4634
4635      * SB6. ATerm  Ã—  Numeric */
4636     if (before == SB_ATerm && after == SB_Numeric) {
4637         return FALSE;
4638     }
4639
4640     /* SB7.  (Upper | Lower) ATerm  Ã—  Upper */
4641     if (before == SB_ATerm && after == SB_Upper) {
4642         U8 * temp_pos = lpos;
4643         SB_enum backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4644         if (backup == SB_Upper || backup == SB_Lower) {
4645             return FALSE;
4646         }
4647     }
4648
4649     /* The remaining rules that aren't the final one, all require an STerm or
4650      * an ATerm after having backed up over some Close* Sp*, and in one case an
4651      * optional Paragraph separator, although one rule doesn't have any Sp's in it.
4652      * So do that backup now, setting flags if either Sp or a paragraph
4653      * separator are found */
4654
4655     if (before == SB_Sep || before == SB_CR || before == SB_LF) {
4656         has_para_sep = TRUE;
4657         before = backup_one_SB(strbeg, &lpos, utf8_target);
4658     }
4659
4660     if (before == SB_Sp) {
4661         has_sp = TRUE;
4662         do {
4663             before = backup_one_SB(strbeg, &lpos, utf8_target);
4664         }
4665         while (before == SB_Sp);
4666     }
4667
4668     while (before == SB_Close) {
4669         before = backup_one_SB(strbeg, &lpos, utf8_target);
4670     }
4671
4672     /* The next few rules apply only when the backed-up-to is an ATerm, and in
4673      * most cases an STerm */
4674     if (before == SB_STerm || before == SB_ATerm) {
4675
4676         /* So, here the lhs matches
4677          *      (STerm | ATerm) Close* Sp* (Sep | CR | LF)?
4678          * and we have set flags if we found an Sp, or the optional Sep,CR,LF.
4679          * The rules that apply here are:
4680          *
4681          * SB8    ATerm Close* Sp*  Ã—  ( Â¬(OLetter | Upper | Lower | Sep | CR
4682                                            | LF | STerm | ATerm) )* Lower
4683            SB8a  (STerm | ATerm) Close* Sp*  Ã—  (SContinue | STerm | ATerm)
4684            SB9   (STerm | ATerm) Close*  Ã—  (Close | Sp | Sep | CR | LF)
4685            SB10  (STerm | ATerm) Close* Sp*  Ã—  (Sp | Sep | CR | LF)
4686            SB11  (STerm | ATerm) Close* Sp* (Sep | CR | LF)?  Ã·
4687          */
4688
4689         /* And all but SB11 forbid having seen a paragraph separator */
4690         if (! has_para_sep) {
4691             if (before == SB_ATerm) {          /* SB8 */
4692                 U8 * rpos = (U8 *) curpos;
4693                 SB_enum later = after;
4694
4695                 while (    later != SB_OLetter
4696                         && later != SB_Upper
4697                         && later != SB_Lower
4698                         && later != SB_Sep
4699                         && later != SB_CR
4700                         && later != SB_LF
4701                         && later != SB_STerm
4702                         && later != SB_ATerm
4703                         && later != SB_EDGE)
4704                 {
4705                     later = advance_one_SB(&rpos, strend, utf8_target);
4706                 }
4707                 if (later == SB_Lower) {
4708                     return FALSE;
4709                 }
4710             }
4711
4712             if (   after == SB_SContinue    /* SB8a */
4713                 || after == SB_STerm
4714                 || after == SB_ATerm)
4715             {
4716                 return FALSE;
4717             }
4718
4719             if (! has_sp) {     /* SB9 applies only if there was no Sp* */
4720                 if (   after == SB_Close
4721                     || after == SB_Sp
4722                     || after == SB_Sep
4723                     || after == SB_CR
4724                     || after == SB_LF)
4725                 {
4726                     return FALSE;
4727                 }
4728             }
4729
4730             /* SB10.  This and SB9 could probably be combined some way, but khw
4731              * has decided to follow the Unicode rule book precisely for
4732              * simplified maintenance */
4733             if (   after == SB_Sp
4734                 || after == SB_Sep
4735                 || after == SB_CR
4736                 || after == SB_LF)
4737             {
4738                 return FALSE;
4739             }
4740         }
4741
4742         /* SB11.  */
4743         return TRUE;
4744     }
4745
4746     /* Otherwise, do not break.
4747     SB12.  Any  Ã—  Any */
4748
4749     return FALSE;
4750 }
4751
4752 STATIC SB_enum
4753 S_advance_one_SB(pTHX_ U8 ** curpos, const U8 * const strend, const bool utf8_target)
4754 {
4755     SB_enum sb;
4756
4757     PERL_ARGS_ASSERT_ADVANCE_ONE_SB;
4758
4759     if (*curpos >= strend) {
4760         return SB_EDGE;
4761     }
4762
4763     if (utf8_target) {
4764         do {
4765             *curpos += UTF8SKIP(*curpos);
4766             if (*curpos >= strend) {
4767                 return SB_EDGE;
4768             }
4769             sb = getSB_VAL_UTF8(*curpos, strend);
4770         } while (sb == SB_Extend || sb == SB_Format);
4771     }
4772     else {
4773         do {
4774             (*curpos)++;
4775             if (*curpos >= strend) {
4776                 return SB_EDGE;
4777             }
4778             sb = getSB_VAL_CP(**curpos);
4779         } while (sb == SB_Extend || sb == SB_Format);
4780     }
4781
4782     return sb;
4783 }
4784
4785 STATIC SB_enum
4786 S_backup_one_SB(pTHX_ const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
4787 {
4788     SB_enum sb;
4789
4790     PERL_ARGS_ASSERT_BACKUP_ONE_SB;
4791
4792     if (*curpos < strbeg) {
4793         return SB_EDGE;
4794     }
4795
4796     if (utf8_target) {
4797         U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
4798         if (! prev_char_pos) {
4799             return SB_EDGE;
4800         }
4801
4802         /* Back up over Extend and Format.  curpos is always just to the right
4803          * of the characater whose value we are getting */
4804         do {
4805             U8 * prev_prev_char_pos;
4806             if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos, -1,
4807                                                                       strbeg)))
4808             {
4809                 sb = getSB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
4810                 *curpos = prev_char_pos;
4811                 prev_char_pos = prev_prev_char_pos;
4812             }
4813             else {
4814                 *curpos = (U8 *) strbeg;
4815                 return SB_EDGE;
4816             }
4817         } while (sb == SB_Extend || sb == SB_Format);
4818     }
4819     else {
4820         do {
4821             if (*curpos - 2 < strbeg) {
4822                 *curpos = (U8 *) strbeg;
4823                 return SB_EDGE;
4824             }
4825             (*curpos)--;
4826             sb = getSB_VAL_CP(*(*curpos - 1));
4827         } while (sb == SB_Extend || sb == SB_Format);
4828     }
4829
4830     return sb;
4831 }
4832
4833 STATIC bool
4834 S_isWB(pTHX_ WB_enum previous,
4835              WB_enum before,
4836              WB_enum after,
4837              const U8 * const strbeg,
4838              const U8 * const curpos,
4839              const U8 * const strend,
4840              const bool utf8_target)
4841 {
4842     /*  Return a boolean as to if the boundary between 'before' and 'after' is
4843      *  a Unicode word break, using their published algorithm, but tailored for
4844      *  Perl by treating spans of white space as one unit.  Context may be
4845      *  needed to make this determination.  If the value for the character
4846      *  before 'before' is known, it is passed as 'previous'; otherwise that
4847      *  should be set to WB_UNKNOWN.  The other input parameters give the
4848      *  boundaries and current position in the matching of the string.  That
4849      *  is, 'curpos' marks the position where the character whose wb value is
4850      *  'after' begins.  See http://www.unicode.org/reports/tr29/ */
4851
4852     U8 * before_pos = (U8 *) curpos;
4853     U8 * after_pos = (U8 *) curpos;
4854     WB_enum prev = before;
4855     WB_enum next;
4856
4857     PERL_ARGS_ASSERT_ISWB;
4858
4859     /* Rule numbers in the comments below are as of Unicode 8.0 */
4860
4861   redo:
4862     before = prev;
4863     switch (WB_table[before][after]) {
4864         case WB_BREAKABLE:
4865             return TRUE;
4866
4867         case WB_NOBREAK:
4868             return FALSE;
4869
4870         case WB_hs_then_hs:     /* 2 horizontal spaces in a row */
4871             next = advance_one_WB(&after_pos, strend, utf8_target,
4872                                  FALSE /* Don't skip Extend nor Format */ );
4873             /* A space immediately preceeding an Extend or Format is attached
4874              * to by them, and hence gets separated from previous spaces.
4875              * Otherwise don't break between horizontal white space */
4876             return next == WB_Extend || next == WB_Format;
4877
4878         /* WB4 Ignore Format and Extend characters, except when they appear at
4879          * the beginning of a region of text.  This code currently isn't
4880          * general purpose, but it works as the rules are currently and likely
4881          * to be laid out.  The reason it works is that when 'they appear at
4882          * the beginning of a region of text', the rule is to break before
4883          * them, just like any other character.  Therefore, the default rule
4884          * applies and we don't have to look in more depth.  Should this ever
4885          * change, we would have to have 2 'case' statements, like in the
4886          * rules below, and backup a single character (not spacing over the
4887          * extend ones) and then see if that is one of the region-end
4888          * characters and go from there */
4889         case WB_Ex_or_FO_then_foo:
4890             prev = backup_one_WB(&previous, strbeg, &before_pos, utf8_target);
4891             goto redo;
4892
4893         case WB_DQ_then_HL + WB_BREAKABLE:
4894         case WB_DQ_then_HL + WB_NOBREAK:
4895
4896             /* WB7c  Hebrew_Letter Double_Quote  Ã—  Hebrew_Letter */
4897
4898             if (backup_one_WB(&previous, strbeg, &before_pos, utf8_target)
4899                                                             == WB_Hebrew_Letter)
4900             {
4901                 return FALSE;
4902             }
4903
4904              return WB_table[before][after] - WB_DQ_then_HL == WB_BREAKABLE;
4905
4906         case WB_HL_then_DQ + WB_BREAKABLE:
4907         case WB_HL_then_DQ + WB_NOBREAK:
4908
4909             /* WB7b  Hebrew_Letter  Ã—  Double_Quote Hebrew_Letter */
4910
4911             if (advance_one_WB(&after_pos, strend, utf8_target,
4912                                        TRUE /* Do skip Extend and Format */ )
4913                                                             == WB_Hebrew_Letter)
4914             {
4915                 return FALSE;
4916             }
4917
4918             return WB_table[before][after] - WB_HL_then_DQ == WB_BREAKABLE;
4919
4920         case WB_LE_or_HL_then_MB_or_ML_or_SQ + WB_NOBREAK:
4921         case WB_LE_or_HL_then_MB_or_ML_or_SQ + WB_BREAKABLE:
4922
4923             /* WB6  (ALetter | Hebrew_Letter)  Ã—  (MidLetter | MidNumLet
4924              *       | Single_Quote) (ALetter | Hebrew_Letter) */
4925
4926             next = advance_one_WB(&after_pos, strend, utf8_target,
4927                                        TRUE /* Do skip Extend and Format */ );
4928
4929             if (next == WB_ALetter || next == WB_Hebrew_Letter)
4930             {
4931                 return FALSE;
4932             }
4933
4934             return WB_table[before][after]
4935                             - WB_LE_or_HL_then_MB_or_ML_or_SQ == WB_BREAKABLE;
4936
4937         case WB_MB_or_ML_or_SQ_then_LE_or_HL + WB_NOBREAK:
4938         case WB_MB_or_ML_or_SQ_then_LE_or_HL + WB_BREAKABLE:
4939
4940             /* WB7  (ALetter | Hebrew_Letter) (MidLetter | MidNumLet
4941              *       | Single_Quote)  Ã—  (ALetter | Hebrew_Letter) */
4942
4943             prev = backup_one_WB(&previous, strbeg, &before_pos, utf8_target);
4944             if (prev == WB_ALetter || prev == WB_Hebrew_Letter)
4945             {
4946                 return FALSE;
4947             }
4948
4949             return WB_table[before][after]
4950                             - WB_MB_or_ML_or_SQ_then_LE_or_HL == WB_BREAKABLE;
4951
4952         case WB_MB_or_MN_or_SQ_then_NU + WB_NOBREAK:
4953         case WB_MB_or_MN_or_SQ_then_NU + WB_BREAKABLE:
4954
4955             /* WB11  Numeric (MidNum | (MidNumLet | Single_Quote))  Ã—  Numeric
4956              * */
4957
4958             if (backup_one_WB(&previous, strbeg, &before_pos, utf8_target)
4959                                                             == WB_Numeric)
4960             {
4961                 return FALSE;
4962             }
4963
4964             return WB_table[before][after]
4965                                 - WB_MB_or_MN_or_SQ_then_NU == WB_BREAKABLE;
4966
4967         case WB_NU_then_MB_or_MN_or_SQ + WB_NOBREAK:
4968         case WB_NU_then_MB_or_MN_or_SQ + WB_BREAKABLE:
4969
4970             /* WB12  Numeric  Ã—  (MidNum | MidNumLet | Single_Quote) Numeric */
4971
4972             if (advance_one_WB(&after_pos, strend, utf8_target,
4973                                        TRUE /* Do skip Extend and Format */ )
4974                                                             == WB_Numeric)
4975             {
4976                 return FALSE;
4977             }
4978
4979             return WB_table[before][after]
4980                                 - WB_NU_then_MB_or_MN_or_SQ == WB_BREAKABLE;
4981
4982         default:
4983             break;
4984     }
4985
4986 #ifdef DEBUGGING
4987     PerlIO_printf(Perl_error_log, "Unhandled WB pair: WB_table[%d, %d] = %d\n",
4988                                   before, after, WB_table[before][after]);
4989     assert(0);
4990 #endif
4991     return TRUE;
4992 }
4993
4994 STATIC WB_enum
4995 S_advance_one_WB(pTHX_ U8 ** curpos,
4996                        const U8 * const strend,
4997                        const bool utf8_target,
4998                        const bool skip_Extend_Format)
4999 {
5000     WB_enum wb;
5001
5002     PERL_ARGS_ASSERT_ADVANCE_ONE_WB;
5003
5004     if (*curpos >= strend) {
5005         return WB_EDGE;
5006     }
5007
5008     if (utf8_target) {
5009
5010         /* Advance over Extend and Format */
5011         do {
5012             *curpos += UTF8SKIP(*curpos);
5013             if (*curpos >= strend) {
5014                 return WB_EDGE;
5015             }
5016             wb = getWB_VAL_UTF8(*curpos, strend);
5017         } while (    skip_Extend_Format
5018                  && (wb == WB_Extend || wb == WB_Format));
5019     }
5020     else {
5021         do {
5022             (*curpos)++;
5023             if (*curpos >= strend) {
5024                 return WB_EDGE;
5025             }
5026             wb = getWB_VAL_CP(**curpos);
5027         } while (    skip_Extend_Format
5028                  && (wb == WB_Extend || wb == WB_Format));
5029     }
5030
5031     return wb;
5032 }
5033
5034 STATIC WB_enum
5035 S_backup_one_WB(pTHX_ WB_enum * previous, const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
5036 {
5037     WB_enum wb;
5038
5039     PERL_ARGS_ASSERT_BACKUP_ONE_WB;
5040
5041     /* If we know what the previous character's break value is, don't have
5042         * to look it up */
5043     if (*previous != WB_UNKNOWN) {
5044         wb = *previous;
5045
5046         /* But we need to move backwards by one */
5047         if (utf8_target) {
5048             *curpos = reghopmaybe3(*curpos, -1, strbeg);
5049             if (! *curpos) {
5050                 *previous = WB_EDGE;
5051                 *curpos = (U8 *) strbeg;
5052             }
5053             else {
5054                 *previous = WB_UNKNOWN;
5055             }
5056         }
5057         else {
5058             (*curpos)--;
5059             *previous = (*curpos <= strbeg) ? WB_EDGE : WB_UNKNOWN;
5060         }
5061
5062         /* And we always back up over these two types */
5063         if (wb != WB_Extend && wb != WB_Format) {
5064             return wb;
5065         }
5066     }
5067
5068     if (*curpos < strbeg) {
5069         return WB_EDGE;
5070     }
5071
5072     if (utf8_target) {
5073         U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
5074         if (! prev_char_pos) {
5075             return WB_EDGE;
5076         }
5077
5078         /* Back up over Extend and Format.  curpos is always just to the right
5079          * of the characater whose value we are getting */
5080         do {
5081             U8 * prev_prev_char_pos;
5082             if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos,
5083                                                    -1,
5084                                                    strbeg)))
5085             {
5086                 wb = getWB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
5087                 *curpos = prev_char_pos;
5088                 prev_char_pos = prev_prev_char_pos;
5089             }
5090             else {
5091                 *curpos = (U8 *) strbeg;
5092                 return WB_EDGE;
5093             }
5094         } while (wb == WB_Extend || wb == WB_Format);
5095     }
5096     else {
5097         do {
5098             if (*curpos - 2 < strbeg) {
5099                 *curpos = (U8 *) strbeg;
5100                 return WB_EDGE;
5101             }
5102             (*curpos)--;
5103             wb = getWB_VAL_CP(*(*curpos - 1));
5104         } while (wb == WB_Extend || wb == WB_Format);
5105     }
5106
5107     return wb;
5108 }
5109
5110 /* returns -1 on failure, $+[0] on success */
5111 STATIC SSize_t
5112 S_regmatch(pTHX_ regmatch_info *reginfo, char *startpos, regnode *prog)
5113 {
5114
5115 #if PERL_VERSION < 9 && !defined(PERL_CORE)
5116     dMY_CXT;
5117 #endif
5118     dVAR;
5119     const bool utf8_target = reginfo->is_utf8_target;
5120     const U32 uniflags = UTF8_ALLOW_DEFAULT;
5121     REGEXP *rex_sv = reginfo->prog;
5122     regexp *rex = ReANY(rex_sv);
5123     RXi_GET_DECL(rex,rexi);
5124     /* the current state. This is a cached copy of PL_regmatch_state */
5125     regmatch_state *st;
5126     /* cache heavy used fields of st in registers */
5127     regnode *scan;
5128     regnode *next;
5129     U32 n = 0;  /* general value; init to avoid compiler warning */
5130     SSize_t ln = 0; /* len or last;  init to avoid compiler warning */
5131     char *locinput = startpos;
5132     char *pushinput; /* where to continue after a PUSH */
5133     I32 nextchr;   /* is always set to UCHARAT(locinput) */
5134
5135     bool result = 0;        /* return value of S_regmatch */
5136     int depth = 0;          /* depth of backtrack stack */
5137     U32 nochange_depth = 0; /* depth of GOSUB recursion with nochange */
5138     const U32 max_nochange_depth =
5139         (3 * rex->nparens > MAX_RECURSE_EVAL_NOCHANGE_DEPTH) ?
5140         3 * rex->nparens : MAX_RECURSE_EVAL_NOCHANGE_DEPTH;
5141     regmatch_state *yes_state = NULL; /* state to pop to on success of
5142                                                             subpattern */
5143     /* mark_state piggy backs on the yes_state logic so that when we unwind 
5144        the stack on success we can update the mark_state as we go */
5145     regmatch_state *mark_state = NULL; /* last mark state we have seen */
5146     regmatch_state *cur_eval = NULL; /* most recent EVAL_AB state */
5147     struct regmatch_state  *cur_curlyx = NULL; /* most recent curlyx */
5148     U32 state_num;
5149     bool no_final = 0;      /* prevent failure from backtracking? */
5150     bool do_cutgroup = 0;   /* no_final only until next branch/trie entry */
5151     char *startpoint = locinput;
5152     SV *popmark = NULL;     /* are we looking for a mark? */
5153     SV *sv_commit = NULL;   /* last mark name seen in failure */
5154     SV *sv_yes_mark = NULL; /* last mark name we have seen 
5155                                during a successful match */
5156     U32 lastopen = 0;       /* last open we saw */
5157     bool has_cutgroup = RX_HAS_CUTGROUP(rex) ? 1 : 0;   
5158     SV* const oreplsv = GvSVn(PL_replgv);
5159     /* these three flags are set by various ops to signal information to
5160      * the very next op. They have a useful lifetime of exactly one loop
5161      * iteration, and are not preserved or restored by state pushes/pops
5162      */
5163     bool sw = 0;            /* the condition value in (?(cond)a|b) */
5164     bool minmod = 0;        /* the next "{n,m}" is a "{n,m}?" */
5165     int logical = 0;        /* the following EVAL is:
5166                                 0: (?{...})
5167                                 1: (?(?{...})X|Y)
5168                                 2: (??{...})
5169                                or the following IFMATCH/UNLESSM is:
5170                                 false: plain (?=foo)
5171                                 true:  used as a condition: (?(?=foo))
5172                             */
5173     PAD* last_pad = NULL;
5174     dMULTICALL;
5175     U8 gimme = G_SCALAR;
5176     CV *caller_cv = NULL;       /* who called us */
5177     CV *last_pushed_cv = NULL;  /* most recently called (?{}) CV */
5178     CHECKPOINT runops_cp;       /* savestack position before executing EVAL */
5179     U32 maxopenparen = 0;       /* max '(' index seen so far */
5180     int to_complement;  /* Invert the result? */
5181     _char_class_number classnum;
5182     bool is_utf8_pat = reginfo->is_utf8_pat;
5183     bool match = FALSE;
5184
5185
5186 #ifdef DEBUGGING
5187     GET_RE_DEBUG_FLAGS_DECL;
5188 #endif
5189
5190     /* protect against undef(*^R) */
5191     SAVEFREESV(SvREFCNT_inc_simple_NN(oreplsv));
5192
5193     /* shut up 'may be used uninitialized' compiler warnings for dMULTICALL */
5194     multicall_oldcatch = 0;
5195     PERL_UNUSED_VAR(multicall_cop);
5196
5197     PERL_ARGS_ASSERT_REGMATCH;
5198
5199     DEBUG_OPTIMISE_r( DEBUG_EXECUTE_r({
5200             PerlIO_printf(Perl_debug_log,"regmatch start\n");
5201     }));
5202
5203     st = PL_regmatch_state;
5204
5205     /* Note that nextchr is a byte even in UTF */
5206     SET_nextchr;
5207     scan = prog;
5208     while (scan != NULL) {
5209
5210         DEBUG_EXECUTE_r( {
5211             SV * const prop = sv_newmortal();
5212             regnode *rnext=regnext(scan);
5213             DUMP_EXEC_POS( locinput, scan, utf8_target );
5214             regprop(rex, prop, scan, reginfo, NULL);
5215             
5216             PerlIO_printf(Perl_debug_log,
5217                     "%3"IVdf":%*s%s(%"IVdf")\n",
5218                     (IV)(scan - rexi->program), depth*2, "",
5219                     SvPVX_const(prop),
5220                     (PL_regkind[OP(scan)] == END || !rnext) ? 
5221                         0 : (IV)(rnext - rexi->program));
5222         });
5223
5224         next = scan + NEXT_OFF(scan);
5225         if (next == scan)
5226             next = NULL;
5227         state_num = OP(scan);
5228
5229       reenter_switch:
5230         to_complement = 0;
5231
5232         SET_nextchr;
5233         assert(nextchr < 256 && (nextchr >= 0 || nextchr == NEXTCHR_EOS));
5234
5235         switch (state_num) {
5236         case SBOL: /*  /^../ and /\A../  */
5237             if (locinput == reginfo->strbeg)
5238                 break;
5239             sayNO;
5240
5241         case MBOL: /*  /^../m  */
5242             if (locinput == reginfo->strbeg ||
5243                 (!NEXTCHR_IS_EOS && locinput[-1] == '\n'))
5244             {
5245                 break;
5246             }
5247             sayNO;
5248
5249         case GPOS: /*  \G  */
5250             if (locinput == reginfo->ganch)
5251                 break;
5252             sayNO;
5253
5254         case KEEPS: /*   \K  */
5255             /* update the startpoint */
5256             st->u.keeper.val = rex->offs[0].start;
5257             rex->offs[0].start = locinput - reginfo->strbeg;
5258             PUSH_STATE_GOTO(KEEPS_next, next, locinput);
5259             /* NOTREACHED */
5260             NOT_REACHED; /* NOTREACHED */
5261
5262         case KEEPS_next_fail:
5263             /* rollback the start point change */
5264             rex->offs[0].start = st->u.keeper.val;
5265             sayNO_SILENT;
5266             /* NOTREACHED */
5267             NOT_REACHED; /* NOTREACHED */
5268
5269         case MEOL: /* /..$/m  */
5270             if (!NEXTCHR_IS_EOS && nextchr != '\n')
5271                 sayNO;
5272             break;
5273
5274         case SEOL: /* /..$/  */
5275             if (!NEXTCHR_IS_EOS && nextchr != '\n')
5276                 sayNO;
5277             if (reginfo->strend - locinput > 1)
5278                 sayNO;
5279             break;
5280
5281         case EOS: /*  \z  */
5282             if (!NEXTCHR_IS_EOS)
5283                 sayNO;
5284             break;
5285
5286         case SANY: /*  /./s  */
5287             if (NEXTCHR_IS_EOS)
5288                 sayNO;
5289             goto increment_locinput;
5290
5291         case REG_ANY: /*  /./  */
5292             if ((NEXTCHR_IS_EOS) || nextchr == '\n')
5293                 sayNO;
5294             goto increment_locinput;
5295
5296
5297 #undef  ST
5298 #define ST st->u.trie
5299         case TRIEC: /* (ab|cd) with known charclass */
5300             /* In this case the charclass data is available inline so
5301                we can fail fast without a lot of extra overhead. 
5302              */
5303             if(!NEXTCHR_IS_EOS && !ANYOF_BITMAP_TEST(scan, nextchr)) {
5304                 DEBUG_EXECUTE_r(
5305                     PerlIO_printf(Perl_debug_log,
5306                               "%*s  %sfailed to match trie start class...%s\n",
5307                               REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
5308                 );
5309                 sayNO_SILENT;
5310                 /* NOTREACHED */
5311                 NOT_REACHED; /* NOTREACHED */
5312             }
5313             /* FALLTHROUGH */
5314         case TRIE:  /* (ab|cd)  */
5315             /* the basic plan of execution of the trie is:
5316              * At the beginning, run though all the states, and
5317              * find the longest-matching word. Also remember the position
5318              * of the shortest matching word. For example, this pattern:
5319              *    1  2 3 4    5
5320              *    ab|a|x|abcd|abc
5321              * when matched against the string "abcde", will generate
5322              * accept states for all words except 3, with the longest
5323              * matching word being 4, and the shortest being 2 (with
5324              * the position being after char 1 of the string).
5325              *
5326              * Then for each matching word, in word order (i.e. 1,2,4,5),
5327              * we run the remainder of the pattern; on each try setting
5328              * the current position to the character following the word,
5329              * returning to try the next word on failure.
5330              *
5331              * We avoid having to build a list of words at runtime by
5332              * using a compile-time structure, wordinfo[].prev, which
5333              * gives, for each word, the previous accepting word (if any).
5334              * In the case above it would contain the mappings 1->2, 2->0,
5335              * 3->0, 4->5, 5->1.  We can use this table to generate, from
5336              * the longest word (4 above), a list of all words, by
5337              * following the list of prev pointers; this gives us the
5338              * unordered list 4,5,1,2. Then given the current word we have
5339              * just tried, we can go through the list and find the
5340              * next-biggest word to try (so if we just failed on word 2,
5341              * the next in the list is 4).
5342              *
5343              * Since at runtime we don't record the matching position in
5344              * the string for each word, we have to work that out for
5345              * each word we're about to process. The wordinfo table holds
5346              * the character length of each word; given that we recorded
5347              * at the start: the position of the shortest word and its
5348              * length in chars, we just need to move the pointer the
5349              * difference between the two char lengths. Depending on
5350              * Unicode status and folding, that's cheap or expensive.
5351              *
5352              * This algorithm is optimised for the case where are only a
5353              * small number of accept states, i.e. 0,1, or maybe 2.
5354              * With lots of accepts states, and having to try all of them,
5355              * it becomes quadratic on number of accept states to find all
5356              * the next words.
5357              */
5358
5359             {
5360                 /* what type of TRIE am I? (utf8 makes this contextual) */
5361                 DECL_TRIE_TYPE(scan);
5362
5363                 /* what trie are we using right now */
5364                 reg_trie_data * const trie
5365                     = (reg_trie_data*)rexi->data->data[ ARG( scan ) ];
5366                 HV * widecharmap = MUTABLE_HV(rexi->data->data[ ARG( scan ) + 1 ]);
5367                 U32 state = trie->startstate;
5368
5369                 if (scan->flags == EXACTL || scan->flags == EXACTFLU8) {
5370                     _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5371                     if (utf8_target
5372                         && UTF8_IS_ABOVE_LATIN1(nextchr)
5373                         && scan->flags == EXACTL)
5374                     {
5375                         /* We only output for EXACTL, as we let the folder
5376                          * output this message for EXACTFLU8 to avoid
5377                          * duplication */
5378                         _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput,
5379                                                                reginfo->strend);
5380                     }
5381                 }
5382                 if (   trie->bitmap
5383                     && (NEXTCHR_IS_EOS || !TRIE_BITMAP_TEST(trie, nextchr)))
5384                 {
5385                     if (trie->states[ state ].wordnum) {
5386                          DEBUG_EXECUTE_r(
5387                             PerlIO_printf(Perl_debug_log,
5388                                           "%*s  %smatched empty string...%s\n",
5389                                           REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
5390                         );
5391                         if (!trie->jump)
5392                             break;
5393                     } else {
5394                         DEBUG_EXECUTE_r(
5395                             PerlIO_printf(Perl_debug_log,
5396                                           "%*s  %sfailed to match trie start class...%s\n",
5397                                           REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
5398                         );
5399                         sayNO_SILENT;
5400                    }
5401                 }
5402
5403             { 
5404                 U8 *uc = ( U8* )locinput;
5405
5406                 STRLEN len = 0;
5407                 STRLEN foldlen = 0;
5408                 U8 *uscan = (U8*)NULL;
5409                 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
5410                 U32 charcount = 0; /* how many input chars we have matched */
5411                 U32 accepted = 0; /* have we seen any accepting states? */
5412
5413                 ST.jump = trie->jump;
5414                 ST.me = scan;
5415                 ST.firstpos = NULL;
5416                 ST.longfold = FALSE; /* char longer if folded => it's harder */
5417                 ST.nextword = 0;
5418
5419                 /* fully traverse the TRIE; note the position of the
5420                    shortest accept state and the wordnum of the longest
5421                    accept state */
5422
5423                 while ( state && uc <= (U8*)(reginfo->strend) ) {
5424                     U32 base = trie->states[ state ].trans.base;
5425                     UV uvc = 0;
5426                     U16 charid = 0;
5427                     U16 wordnum;
5428                     wordnum = trie->states[ state ].wordnum;
5429
5430                     if (wordnum) { /* it's an accept state */
5431                         if (!accepted) {
5432                             accepted = 1;
5433                             /* record first match position */
5434                             if (ST.longfold) {
5435                                 ST.firstpos = (U8*)locinput;
5436                                 ST.firstchars = 0;
5437                             }
5438                             else {
5439                                 ST.firstpos = uc;
5440                                 ST.firstchars = charcount;
5441                             }
5442                         }
5443                         if (!ST.nextword || wordnum < ST.nextword)
5444                             ST.nextword = wordnum;
5445                         ST.topword = wordnum;
5446                     }
5447
5448                     DEBUG_TRIE_EXECUTE_r({
5449                                 DUMP_EXEC_POS( (char *)uc, scan, utf8_target );
5450                                 PerlIO_printf( Perl_debug_log,
5451                                     "%*s  %sState: %4"UVxf" Accepted: %c ",
5452                                     2+depth * 2, "", PL_colors[4],
5453                                     (UV)state, (accepted ? 'Y' : 'N'));
5454                     });
5455
5456                     /* read a char and goto next state */
5457                     if ( base && (foldlen || uc < (U8*)(reginfo->strend))) {
5458                         I32 offset;
5459                         REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
5460                                              uscan, len, uvc, charid, foldlen,
5461                                              foldbuf, uniflags);
5462                         charcount++;
5463                         if (foldlen>0)
5464                             ST.longfold = TRUE;
5465                         if (charid &&
5466                              ( ((offset =
5467                               base + charid - 1 - trie->uniquecharcount)) >= 0)
5468
5469                              && ((U32)offset < trie->lasttrans)
5470                              && trie->trans[offset].check == state)
5471                         {
5472                             state = trie->trans[offset].next;
5473                         }
5474                         else {
5475                             state = 0;
5476                         }
5477                         uc += len;
5478
5479                     }
5480                     else {
5481                         state = 0;
5482                     }
5483                     DEBUG_TRIE_EXECUTE_r(
5484                         PerlIO_printf( Perl_debug_log,
5485                             "Charid:%3x CP:%4"UVxf" After State: %4"UVxf"%s\n",
5486                             charid, uvc, (UV)state, PL_colors[5] );
5487                     );
5488                 }
5489                 if (!accepted)
5490                    sayNO;
5491
5492                 /* calculate total number of accept states */
5493                 {
5494                     U16 w = ST.topword;
5495                     accepted = 0;
5496                     while (w) {
5497                         w = trie->wordinfo[w].prev;
5498                         accepted++;
5499                     }
5500                     ST.accepted = accepted;
5501                 }
5502
5503                 DEBUG_EXECUTE_r(
5504                     PerlIO_printf( Perl_debug_log,
5505                         "%*s  %sgot %"IVdf" possible matches%s\n",
5506                         REPORT_CODE_OFF + depth * 2, "",
5507                         PL_colors[4], (IV)ST.accepted, PL_colors[5] );
5508                 );
5509                 goto trie_first_try; /* jump into the fail handler */
5510             }}
5511             /* NOTREACHED */
5512             NOT_REACHED; /* NOTREACHED */
5513
5514         case TRIE_next_fail: /* we failed - try next alternative */
5515         {
5516             U8 *uc;
5517             if ( ST.jump) {
5518                 REGCP_UNWIND(ST.cp);
5519                 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
5520             }
5521             if (!--ST.accepted) {
5522                 DEBUG_EXECUTE_r({
5523                     PerlIO_printf( Perl_debug_log,
5524                         "%*s  %sTRIE failed...%s\n",
5525                         REPORT_CODE_OFF+depth*2, "", 
5526                         PL_colors[4],
5527                         PL_colors[5] );
5528                 });
5529                 sayNO_SILENT;
5530             }
5531             {
5532                 /* Find next-highest word to process.  Note that this code
5533                  * is O(N^2) per trie run (O(N) per branch), so keep tight */
5534                 U16 min = 0;
5535                 U16 word;
5536                 U16 const nextword = ST.nextword;
5537                 reg_trie_wordinfo * const wordinfo
5538                     = ((reg_trie_data*)rexi->data->data[ARG(ST.me)])->wordinfo;
5539                 for (word=ST.topword; word; word=wordinfo[word].prev) {
5540                     if (word > nextword && (!min || word < min))
5541                         min = word;
5542                 }
5543                 ST.nextword = min;
5544             }
5545
5546           trie_first_try:
5547             if (do_cutgroup) {
5548                 do_cutgroup = 0;
5549                 no_final = 0;
5550             }
5551
5552             if ( ST.jump) {
5553                 ST.lastparen = rex->lastparen;
5554                 ST.lastcloseparen = rex->lastcloseparen;
5555                 REGCP_SET(ST.cp);
5556             }
5557
5558             /* find start char of end of current word */
5559             {
5560                 U32 chars; /* how many chars to skip */
5561                 reg_trie_data * const trie
5562                     = (reg_trie_data*)rexi->data->data[ARG(ST.me)];
5563
5564                 assert((trie->wordinfo[ST.nextword].len - trie->prefixlen)
5565                             >=  ST.firstchars);
5566                 chars = (trie->wordinfo[ST.nextword].len - trie->prefixlen)
5567                             - ST.firstchars;
5568                 uc = ST.firstpos;
5569
5570                 if (ST.longfold) {
5571                     /* the hard option - fold each char in turn and find
5572                      * its folded length (which may be different */
5573                     U8 foldbuf[UTF8_MAXBYTES_CASE + 1];
5574                     STRLEN foldlen;
5575                     STRLEN len;
5576                     UV uvc;
5577                     U8 *uscan;
5578
5579                     while (chars) {
5580                         if (utf8_target) {
5581                             uvc = utf8n_to_uvchr((U8*)uc, UTF8_MAXLEN, &len,
5582                                                     uniflags);
5583                             uc += len;
5584                         }
5585                         else {
5586                             uvc = *uc;
5587                             uc++;
5588                         }
5589                         uvc = to_uni_fold(uvc, foldbuf, &foldlen);
5590                         uscan = foldbuf;
5591                         while (foldlen) {
5592                             if (!--chars)
5593                                 break;
5594                             uvc = utf8n_to_uvchr(uscan, UTF8_MAXLEN, &len,
5595                                             uniflags);
5596                             uscan += len;
5597                             foldlen -= len;
5598                         }
5599                     }
5600                 }
5601                 else {
5602                     if (utf8_target)
5603                         while (chars--)
5604                             uc += UTF8SKIP(uc);
5605                     else
5606                         uc += chars;
5607                 }
5608             }
5609
5610             scan = ST.me + ((ST.jump && ST.jump[ST.nextword])
5611                             ? ST.jump[ST.nextword]
5612                             : NEXT_OFF(ST.me));
5613
5614             DEBUG_EXECUTE_r({
5615                 PerlIO_printf( Perl_debug_log,
5616                     "%*s  %sTRIE matched word #%d, continuing%s\n",
5617                     REPORT_CODE_OFF+depth*2, "", 
5618                     PL_colors[4],
5619                     ST.nextword,
5620                     PL_colors[5]
5621                     );
5622             });
5623
5624             if (ST.accepted > 1 || has_cutgroup) {
5625                 PUSH_STATE_GOTO(TRIE_next, scan, (char*)uc);
5626                 /* NOTREACHED */
5627                 NOT_REACHED; /* NOTREACHED */
5628             }
5629             /* only one choice left - just continue */
5630             DEBUG_EXECUTE_r({
5631                 AV *const trie_words
5632                     = MUTABLE_AV(rexi->data->data[ARG(ST.me)+TRIE_WORDS_OFFSET]);
5633                 SV ** const tmp = trie_words
5634                         ? av_fetch(trie_words, ST.nextword - 1, 0) : NULL;
5635                 SV *sv= tmp ? sv_newmortal() : NULL;
5636
5637                 PerlIO_printf( Perl_debug_log,
5638                     "%*s  %sonly one match left, short-circuiting: #%d <%s>%s\n",
5639                     REPORT_CODE_OFF+depth*2, "", PL_colors[4],
5640                     ST.nextword,
5641                     tmp ? pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 0,
5642                             PL_colors[0], PL_colors[1],
5643                             (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)|PERL_PV_ESCAPE_NONASCII
5644                         ) 
5645                     : "not compiled under -Dr",
5646                     PL_colors[5] );
5647             });
5648
5649             locinput = (char*)uc;
5650             continue; /* execute rest of RE */
5651             /* NOTREACHED */
5652         }
5653 #undef  ST
5654
5655         case EXACTL:             /*  /abc/l       */
5656             _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5657
5658             /* Complete checking would involve going through every character
5659              * matched by the string to see if any is above latin1.  But the
5660              * comparision otherwise might very well be a fast assembly
5661              * language routine, and I (khw) don't think slowing things down
5662              * just to check for this warning is worth it.  So this just checks
5663              * the first character */
5664             if (utf8_target && UTF8_IS_ABOVE_LATIN1(*locinput)) {
5665                 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput, reginfo->strend);
5666             }
5667             /* FALLTHROUGH */
5668         case EXACT: {            /*  /abc/        */
5669             char *s = STRING(scan);
5670             ln = STR_LEN(scan);
5671             if (utf8_target != is_utf8_pat) {
5672                 /* The target and the pattern have differing utf8ness. */
5673                 char *l = locinput;
5674                 const char * const e = s + ln;
5675
5676                 if (utf8_target) {
5677                     /* The target is utf8, the pattern is not utf8.
5678                      * Above-Latin1 code points can't match the pattern;
5679                      * invariants match exactly, and the other Latin1 ones need
5680                      * to be downgraded to a single byte in order to do the
5681                      * comparison.  (If we could be confident that the target
5682                      * is not malformed, this could be refactored to have fewer
5683                      * tests by just assuming that if the first bytes match, it
5684                      * is an invariant, but there are tests in the test suite
5685                      * dealing with (??{...}) which violate this) */
5686                     while (s < e) {
5687                         if (l >= reginfo->strend
5688                             || UTF8_IS_ABOVE_LATIN1(* (U8*) l))
5689                         {
5690                             sayNO;
5691                         }
5692                         if (UTF8_IS_INVARIANT(*(U8*)l)) {
5693                             if (*l != *s) {
5694                                 sayNO;
5695                             }
5696                             l++;
5697                         }
5698                         else {
5699                             if (EIGHT_BIT_UTF8_TO_NATIVE(*l, *(l+1)) != * (U8*) s)
5700                             {
5701                                 sayNO;
5702                             }
5703                             l += 2;
5704                         }
5705                         s++;
5706                     }
5707                 }
5708                 else {
5709                     /* The target is not utf8, the pattern is utf8. */
5710                     while (s < e) {
5711                         if (l >= reginfo->strend
5712                             || UTF8_IS_ABOVE_LATIN1(* (U8*) s))
5713                         {
5714                             sayNO;
5715                         }
5716                         if (UTF8_IS_INVARIANT(*(U8*)s)) {
5717                             if (*s != *l) {
5718                                 sayNO;
5719                             }
5720                             s++;
5721                         }
5722                         else {
5723                             if (EIGHT_BIT_UTF8_TO_NATIVE(*s, *(s+1)) != * (U8*) l)
5724                             {
5725                                 sayNO;
5726                             }
5727                             s += 2;
5728                         }
5729                         l++;
5730                     }
5731                 }
5732                 locinput = l;
5733             }
5734             else {
5735                 /* The target and the pattern have the same utf8ness. */
5736                 /* Inline the first character, for speed. */
5737                 if (reginfo->strend - locinput < ln
5738                     || UCHARAT(s) != nextchr
5739                     || (ln > 1 && memNE(s, locinput, ln)))
5740                 {
5741                     sayNO;
5742                 }
5743                 locinput += ln;
5744             }
5745             break;
5746             }
5747
5748         case EXACTFL: {          /*  /abc/il      */
5749             re_fold_t folder;
5750             const U8 * fold_array;
5751             const char * s;
5752             U32 fold_utf8_flags;
5753
5754             _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5755             folder = foldEQ_locale;
5756             fold_array = PL_fold_locale;
5757             fold_utf8_flags = FOLDEQ_LOCALE;
5758             goto do_exactf;
5759
5760         case EXACTFLU8:           /*  /abc/il; but all 'abc' are above 255, so
5761                                       is effectively /u; hence to match, target
5762                                       must be UTF-8. */
5763             if (! utf8_target) {
5764                 sayNO;
5765             }
5766             fold_utf8_flags =  FOLDEQ_LOCALE | FOLDEQ_S1_ALREADY_FOLDED
5767                                              | FOLDEQ_S1_FOLDS_SANE;
5768             folder = foldEQ_latin1;
5769             fold_array = PL_fold_latin1;
5770             goto do_exactf;
5771
5772         case EXACTFU_SS:         /*  /\x{df}/iu   */
5773         case EXACTFU:            /*  /abc/iu      */
5774             folder = foldEQ_latin1;
5775             fold_array = PL_fold_latin1;
5776             fold_utf8_flags = is_utf8_pat ? FOLDEQ_S1_ALREADY_FOLDED : 0;
5777             goto do_exactf;
5778
5779         case EXACTFA_NO_TRIE:   /* This node only generated for non-utf8
5780                                    patterns */
5781             assert(! is_utf8_pat);
5782             /* FALLTHROUGH */
5783         case EXACTFA:            /*  /abc/iaa     */
5784             folder = foldEQ_latin1;
5785             fold_array = PL_fold_latin1;
5786             fold_utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
5787             goto do_exactf;
5788
5789         case EXACTF:             /*  /abc/i    This node only generated for
5790                                                non-utf8 patterns */
5791             assert(! is_utf8_pat);
5792             folder = foldEQ;
5793             fold_array = PL_fold;
5794             fold_utf8_flags = 0;
5795
5796           do_exactf:
5797             s = STRING(scan);
5798             ln = STR_LEN(scan);
5799
5800             if (utf8_target
5801                 || is_utf8_pat
5802                 || state_num == EXACTFU_SS
5803                 || (state_num == EXACTFL && IN_UTF8_CTYPE_LOCALE))
5804             {
5805               /* Either target or the pattern are utf8, or has the issue where
5806                * the fold lengths may differ. */
5807                 const char * const l = locinput;
5808                 char *e = reginfo->strend;
5809
5810                 if (! foldEQ_utf8_flags(s, 0,  ln, is_utf8_pat,
5811                                         l, &e, 0,  utf8_target, fold_utf8_flags))
5812                 {
5813                     sayNO;
5814                 }
5815                 locinput = e;
5816                 break;
5817             }
5818
5819             /* Neither the target nor the pattern are utf8 */
5820             if (UCHARAT(s) != nextchr
5821                 && !NEXTCHR_IS_EOS
5822                 && UCHARAT(s) != fold_array[nextchr])
5823             {
5824                 sayNO;
5825             }
5826             if (reginfo->strend - locinput < ln)
5827                 sayNO;
5828             if (ln > 1 && ! folder(s, locinput, ln))
5829                 sayNO;
5830             locinput += ln;
5831             break;
5832         }
5833
5834         case NBOUNDL: /*  /\B/l  */
5835             to_complement = 1;
5836             /* FALLTHROUGH */
5837
5838         case BOUNDL:  /*  /\b/l  */
5839         {
5840             bool b1, b2;
5841             _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5842
5843             if (FLAGS(scan) != TRADITIONAL_BOUND) {
5844                 if (! IN_UTF8_CTYPE_LOCALE) {
5845                     Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
5846                                                 B_ON_NON_UTF8_LOCALE_IS_WRONG);
5847                 }
5848                 goto boundu;
5849             }
5850
5851             if (utf8_target) {
5852                 if (locinput == reginfo->strbeg)
5853                     b1 = isWORDCHAR_LC('\n');
5854                 else {
5855                     b1 = isWORDCHAR_LC_utf8(reghop3((U8*)locinput, -1,
5856                                                         (U8*)(reginfo->strbeg)));
5857                 }
5858                 b2 = (NEXTCHR_IS_EOS)
5859                     ? isWORDCHAR_LC('\n')
5860                     : isWORDCHAR_LC_utf8((U8*)locinput);
5861             }
5862             else { /* Here the string isn't utf8 */
5863                 b1 = (locinput == reginfo->strbeg)
5864                      ? isWORDCHAR_LC('\n')
5865                      : isWORDCHAR_LC(UCHARAT(locinput - 1));
5866                 b2 = (NEXTCHR_IS_EOS)
5867                     ? isWORDCHAR_LC('\n')
5868                     : isWORDCHAR_LC(nextchr);
5869             }
5870             if (to_complement ^ (b1 == b2)) {
5871                 sayNO;
5872             }
5873             break;
5874         }
5875
5876         case NBOUND:  /*  /\B/   */
5877             to_complement = 1;
5878             /* FALLTHROUGH */
5879
5880         case BOUND:   /*  /\b/   */
5881             if (utf8_target) {
5882                 goto bound_utf8;
5883             }
5884             goto bound_ascii_match_only;
5885
5886         case NBOUNDA: /*  /\B/a  */
5887             to_complement = 1;
5888             /* FALLTHROUGH */
5889
5890         case BOUNDA:  /*  /\b/a  */
5891         {
5892             bool b1, b2;
5893
5894           bound_ascii_match_only:
5895             /* Here the string isn't utf8, or is utf8 and only ascii characters
5896              * are to match \w.  In the latter case looking at the byte just
5897              * prior to the current one may be just the final byte of a
5898              * multi-byte character.  This is ok.  There are two cases:
5899              * 1) it is a single byte character, and then the test is doing
5900              *    just what it's supposed to.
5901              * 2) it is a multi-byte character, in which case the final byte is
5902              *    never mistakable for ASCII, and so the test will say it is
5903              *    not a word character, which is the correct answer. */
5904             b1 = (locinput == reginfo->strbeg)
5905                  ? isWORDCHAR_A('\n')
5906                  : isWORDCHAR_A(UCHARAT(locinput - 1));
5907             b2 = (NEXTCHR_IS_EOS)
5908                 ? isWORDCHAR_A('\n')
5909                 : isWORDCHAR_A(nextchr);
5910             if (to_complement ^ (b1 == b2)) {
5911                 sayNO;
5912             }
5913             break;
5914         }
5915
5916         case NBOUNDU: /*  /\B/u  */
5917             to_complement = 1;
5918             /* FALLTHROUGH */
5919
5920         case BOUNDU:  /*  /\b/u  */
5921
5922           boundu:
5923             if (UNLIKELY(reginfo->strbeg >= reginfo->strend)) {
5924                 match = FALSE;
5925             }
5926             else if (utf8_target) {
5927               bound_utf8:
5928                 switch((bound_type) FLAGS(scan)) {
5929                     case TRADITIONAL_BOUND:
5930                     {
5931                         bool b1, b2;
5932                         b1 = (locinput == reginfo->strbeg)
5933                              ? 0 /* isWORDCHAR_L1('\n') */
5934                              : isWORDCHAR_utf8(reghop3((U8*)locinput, -1,
5935                                                                 (U8*)(reginfo->strbeg)));
5936                         b2 = (NEXTCHR_IS_EOS)
5937                             ? 0 /* isWORDCHAR_L1('\n') */
5938                             : isWORDCHAR_utf8((U8*)locinput);
5939                         match = cBOOL(b1 != b2);
5940                         break;
5941                     }
5942                     case GCB_BOUND:
5943                         if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
5944                             match = TRUE; /* GCB always matches at begin and
5945                                              end */
5946                         }
5947                         else {
5948                             /* Find the gcb values of previous and current
5949                              * chars, then see if is a break point */
5950                             match = isGCB(getGCB_VAL_UTF8(
5951                                                 reghop3((U8*)locinput,
5952                                                         -1,
5953                                                         (U8*)(reginfo->strbeg)),
5954                                                 (U8*) reginfo->strend),
5955                                           getGCB_VAL_UTF8((U8*) locinput,
5956                                                         (U8*) reginfo->strend));
5957                         }
5958                         break;
5959
5960                     case LB_BOUND:
5961                         if (locinput == reginfo->strbeg) {
5962                             match = FALSE;
5963                         }
5964                         else if (NEXTCHR_IS_EOS) {
5965                             match = TRUE;
5966                         }
5967                         else {
5968                             match = isLB(getLB_VAL_UTF8(
5969                                                 reghop3((U8*)locinput,
5970                                                         -1,
5971                                                         (U8*)(reginfo->strbeg)),
5972                                                 (U8*) reginfo->strend),
5973                                           getLB_VAL_UTF8((U8*) locinput,
5974                                                         (U8*) reginfo->strend),
5975                                           (U8*) reginfo->strbeg,
5976                                           (U8*) locinput,
5977                                           (U8*) reginfo->strend,
5978                                           utf8_target);
5979                         }
5980                         break;
5981
5982                     case SB_BOUND: /* Always matches at begin and end */
5983                         if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
5984                             match = TRUE;
5985                         }
5986                         else {
5987                             match = isSB(getSB_VAL_UTF8(
5988                                                 reghop3((U8*)locinput,
5989                                                         -1,
5990                                                         (U8*)(reginfo->strbeg)),
5991                                                 (U8*) reginfo->strend),
5992                                           getSB_VAL_UTF8((U8*) locinput,
5993                                                         (U8*) reginfo->strend),
5994                                           (U8*) reginfo->strbeg,
5995                                           (U8*) locinput,
5996                                           (U8*) reginfo->strend,
5997                                           utf8_target);
5998                         }
5999                         break;
6000
6001                     case WB_BOUND:
6002                         if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6003                             match = TRUE;
6004                         }
6005                         else {
6006                             match = isWB(WB_UNKNOWN,
6007                                          getWB_VAL_UTF8(
6008                                                 reghop3((U8*)locinput,
6009                                                         -1,
6010                                                         (U8*)(reginfo->strbeg)),
6011                                                 (U8*) reginfo->strend),
6012                                           getWB_VAL_UTF8((U8*) locinput,
6013                                                         (U8*) reginfo->strend),
6014                                           (U8*) reginfo->strbeg,
6015                                           (U8*) locinput,
6016                                           (U8*) reginfo->strend,
6017                                           utf8_target);
6018                         }
6019                         break;
6020                 }
6021             }
6022             else {  /* Not utf8 target */
6023                 switch((bound_type) FLAGS(scan)) {
6024                     case TRADITIONAL_BOUND:
6025                     {
6026                         bool b1, b2;
6027                         b1 = (locinput == reginfo->strbeg)
6028                             ? 0 /* isWORDCHAR_L1('\n') */
6029                             : isWORDCHAR_L1(UCHARAT(locinput - 1));
6030                         b2 = (NEXTCHR_IS_EOS)
6031                             ? 0 /* isWORDCHAR_L1('\n') */
6032                             : isWORDCHAR_L1(nextchr);
6033                         match = cBOOL(b1 != b2);
6034                         break;
6035                     }
6036
6037                     case GCB_BOUND:
6038                         if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6039                             match = TRUE; /* GCB always matches at begin and
6040                                              end */
6041                         }
6042                         else {  /* Only CR-LF combo isn't a GCB in 0-255
6043                                    range */
6044                             match =    UCHARAT(locinput - 1) != '\r'
6045                                     || UCHARAT(locinput) != '\n';
6046                         }
6047                         break;
6048
6049                     case LB_BOUND:
6050                         if (locinput == reginfo->strbeg) {
6051                             match = FALSE;
6052                         }
6053                         else if (NEXTCHR_IS_EOS) {
6054                             match = TRUE;
6055                         }
6056                         else {
6057                             match = isLB(getLB_VAL_CP(UCHARAT(locinput -1)),
6058                                          getLB_VAL_CP(UCHARAT(locinput)),
6059                                          (U8*) reginfo->strbeg,
6060                                          (U8*) locinput,
6061                                          (U8*) reginfo->strend,
6062                                          utf8_target);
6063                         }
6064                         break;
6065
6066                     case SB_BOUND: /* Always matches at begin and end */
6067                         if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6068                             match = TRUE;
6069                         }
6070                         else {
6071                             match = isSB(getSB_VAL_CP(UCHARAT(locinput -1)),
6072                                          getSB_VAL_CP(UCHARAT(locinput)),
6073                                          (U8*) reginfo->strbeg,
6074                                          (U8*) locinput,
6075                                          (U8*) reginfo->strend,
6076                                          utf8_target);
6077                         }
6078                         break;
6079
6080                     case WB_BOUND:
6081                         if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6082                             match = TRUE;
6083                         }
6084                         else {
6085                             match = isWB(WB_UNKNOWN,
6086                                          getWB_VAL_CP(UCHARAT(locinput -1)),
6087                                          getWB_VAL_CP(UCHARAT(locinput)),
6088                                          (U8*) reginfo->strbeg,
6089                                          (U8*) locinput,
6090                                          (U8*) reginfo->strend,
6091                                          utf8_target);
6092                         }
6093                         break;
6094                 }
6095             }
6096
6097             if (to_complement ^ ! match) {
6098                 sayNO;
6099             }
6100             break;
6101
6102         case ANYOFL:  /*  /[abc]/l      */
6103             _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6104
6105             if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(scan)) && ! IN_UTF8_CTYPE_LOCALE)
6106             {
6107               Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
6108             }
6109             /* FALLTHROUGH */
6110         case ANYOFD:  /*   /[abc]/d       */
6111         case ANYOF:  /*   /[abc]/       */
6112             if (NEXTCHR_IS_EOS)
6113                 sayNO;
6114             if (utf8_target && ! UTF8_IS_INVARIANT(*locinput)) {
6115                 if (!reginclass(rex, scan, (U8*)locinput, (U8*)reginfo->strend,
6116                                                                    utf8_target))
6117                     sayNO;
6118                 locinput += UTF8SKIP(locinput);
6119             }
6120             else {
6121                 if (!REGINCLASS(rex, scan, (U8*)locinput))
6122                     sayNO;
6123                 locinput++;
6124             }
6125             break;
6126
6127         /* The argument (FLAGS) to all the POSIX node types is the class number
6128          * */
6129
6130         case NPOSIXL:   /* \W or [:^punct:] etc. under /l */
6131             to_complement = 1;
6132             /* FALLTHROUGH */
6133
6134         case POSIXL:    /* \w or [:punct:] etc. under /l */
6135             _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6136             if (NEXTCHR_IS_EOS)
6137                 sayNO;
6138
6139             /* Use isFOO_lc() for characters within Latin1.  (Note that
6140              * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
6141              * wouldn't be invariant) */
6142             if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
6143                 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan), (U8) nextchr)))) {
6144                     sayNO;
6145                 }
6146             }
6147             else if (UTF8_IS_DOWNGRADEABLE_START(nextchr)) {
6148                 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan),
6149                                                EIGHT_BIT_UTF8_TO_NATIVE(nextchr,
6150                                                *(locinput + 1))))))
6151                 {
6152                     sayNO;
6153                 }
6154             }
6155             else { /* Here, must be an above Latin-1 code point */
6156                 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput, reginfo->strend);
6157                 goto utf8_posix_above_latin1;
6158             }
6159
6160             /* Here, must be utf8 */
6161             locinput += UTF8SKIP(locinput);
6162             break;
6163
6164         case NPOSIXD:   /* \W or [:^punct:] etc. under /d */
6165             to_complement = 1;
6166             /* FALLTHROUGH */
6167
6168         case POSIXD:    /* \w or [:punct:] etc. under /d */
6169             if (utf8_target) {
6170                 goto utf8_posix;
6171             }
6172             goto posixa;
6173
6174         case NPOSIXA:   /* \W or [:^punct:] etc. under /a */
6175
6176             if (NEXTCHR_IS_EOS) {
6177                 sayNO;
6178             }
6179
6180             /* All UTF-8 variants match */
6181             if (! UTF8_IS_INVARIANT(nextchr)) {
6182                 goto increment_locinput;
6183             }
6184
6185             to_complement = 1;
6186             /* FALLTHROUGH */
6187
6188         case POSIXA:    /* \w or [:punct:] etc. under /a */
6189
6190           posixa:
6191             /* We get here through POSIXD, NPOSIXD, and NPOSIXA when not in
6192              * UTF-8, and also from NPOSIXA even in UTF-8 when the current
6193              * character is a single byte */
6194
6195             if (NEXTCHR_IS_EOS
6196                 || ! (to_complement ^ cBOOL(_generic_isCC_A(nextchr,
6197                                                             FLAGS(scan)))))
6198             {
6199                 sayNO;
6200             }
6201
6202             /* Here we are either not in utf8, or we matched a utf8-invariant,
6203              * so the next char is the next byte */
6204             locinput++;
6205             break;
6206
6207         case NPOSIXU:   /* \W or [:^punct:] etc. under /u */
6208             to_complement = 1;
6209             /* FALLTHROUGH */
6210
6211         case POSIXU:    /* \w or [:punct:] etc. under /u */
6212           utf8_posix:
6213             if (NEXTCHR_IS_EOS) {
6214                 sayNO;
6215             }
6216
6217             /* Use _generic_isCC() for characters within Latin1.  (Note that
6218              * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
6219              * wouldn't be invariant) */
6220             if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
6221                 if (! (to_complement ^ cBOOL(_generic_isCC(nextchr,
6222                                                            FLAGS(scan)))))
6223                 {
6224                     sayNO;
6225                 }
6226                 locinput++;
6227             }
6228             else if (UTF8_IS_DOWNGRADEABLE_START(nextchr)) {
6229                 if (! (to_complement
6230                        ^ cBOOL(_generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(nextchr,
6231                                                                *(locinput + 1)),
6232                                              FLAGS(scan)))))
6233                 {
6234                     sayNO;
6235                 }
6236                 locinput += 2;
6237             }
6238             else {  /* Handle above Latin-1 code points */
6239               utf8_posix_above_latin1:
6240                 classnum = (_char_class_number) FLAGS(scan);
6241                 if (classnum < _FIRST_NON_SWASH_CC) {
6242
6243                     /* Here, uses a swash to find such code points.  Load if if
6244                      * not done already */
6245                     if (! PL_utf8_swash_ptrs[classnum]) {
6246                         U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
6247                         PL_utf8_swash_ptrs[classnum]
6248                                 = _core_swash_init("utf8",
6249                                         "",
6250                                         &PL_sv_undef, 1, 0,
6251                                         PL_XPosix_ptrs[classnum], &flags);
6252                     }
6253                     if (! (to_complement
6254                            ^ cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum],
6255                                                (U8 *) locinput, TRUE))))
6256                     {
6257                         sayNO;
6258                     }
6259                 }
6260                 else {  /* Here, uses macros to find above Latin-1 code points */
6261                     switch (classnum) {
6262                         case _CC_ENUM_SPACE:
6263                             if (! (to_complement
6264                                         ^ cBOOL(is_XPERLSPACE_high(locinput))))
6265                             {
6266                                 sayNO;
6267                             }
6268                             break;
6269                         case _CC_ENUM_BLANK:
6270                             if (! (to_complement
6271                                             ^ cBOOL(is_HORIZWS_high(locinput))))
6272                             {
6273                                 sayNO;
6274                             }
6275                             break;
6276                         case _CC_ENUM_XDIGIT:
6277                             if (! (to_complement
6278                                             ^ cBOOL(is_XDIGIT_high(locinput))))
6279                             {
6280                                 sayNO;
6281                             }
6282                             break;
6283                         case _CC_ENUM_VERTSPACE:
6284                             if (! (to_complement
6285                                             ^ cBOOL(is_VERTWS_high(locinput))))
6286                             {
6287                                 sayNO;
6288                             }
6289                             break;
6290                         default:    /* The rest, e.g. [:cntrl:], can't match
6291                                        above Latin1 */
6292                             if (! to_complement) {
6293                                 sayNO;
6294                             }
6295                             break;
6296                     }
6297                 }
6298                 locinput += UTF8SKIP(locinput);
6299             }
6300             break;
6301
6302         case CLUMP: /* Match \X: logical Unicode character.  This is defined as
6303                        a Unicode extended Grapheme Cluster */
6304             if (NEXTCHR_IS_EOS)
6305                 sayNO;
6306             if  (! utf8_target) {
6307
6308                 /* Match either CR LF  or '.', as all the other possibilities
6309                  * require utf8 */
6310                 locinput++;         /* Match the . or CR */
6311                 if (nextchr == '\r' /* And if it was CR, and the next is LF,
6312                                        match the LF */
6313                     && locinput < reginfo->strend
6314                     && UCHARAT(locinput) == '\n')
6315                 {
6316                     locinput++;
6317                 }
6318             }
6319             else {
6320
6321                 /* Get the gcb type for the current character */
6322                 GCB_enum prev_gcb = getGCB_VAL_UTF8((U8*) locinput,
6323                                                        (U8*) reginfo->strend);
6324
6325                 /* Then scan through the input until we get to the first
6326                  * character whose type is supposed to be a gcb with the
6327                  * current character.  (There is always a break at the
6328                  * end-of-input) */
6329                 locinput += UTF8SKIP(locinput);
6330                 while (locinput < reginfo->strend) {
6331                     GCB_enum cur_gcb = getGCB_VAL_UTF8((U8*) locinput,
6332                                                          (U8*) reginfo->strend);
6333                     if (isGCB(prev_gcb, cur_gcb)) {
6334                         break;
6335                     }
6336
6337                     prev_gcb = cur_gcb;
6338                     locinput += UTF8SKIP(locinput);
6339                 }
6340
6341
6342             }
6343             break;
6344             
6345         case NREFFL:  /*  /\g{name}/il  */
6346         {   /* The capture buffer cases.  The ones beginning with N for the
6347                named buffers just convert to the equivalent numbered and
6348                pretend they were called as the corresponding numbered buffer
6349                op.  */
6350             /* don't initialize these in the declaration, it makes C++
6351                unhappy */
6352             const char *s;
6353             char type;
6354             re_fold_t folder;
6355             const U8 *fold_array;
6356             UV utf8_fold_flags;
6357
6358             _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6359             folder = foldEQ_locale;
6360             fold_array = PL_fold_locale;
6361             type = REFFL;
6362             utf8_fold_flags = FOLDEQ_LOCALE;
6363             goto do_nref;
6364
6365         case NREFFA:  /*  /\g{name}/iaa  */
6366             folder = foldEQ_latin1;
6367             fold_array = PL_fold_latin1;
6368             type = REFFA;
6369             utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
6370             goto do_nref;
6371
6372         case NREFFU:  /*  /\g{name}/iu  */
6373             folder = foldEQ_latin1;
6374             fold_array = PL_fold_latin1;
6375             type = REFFU;
6376             utf8_fold_flags = 0;
6377             goto do_nref;
6378
6379         case NREFF:  /*  /\g{name}/i  */
6380             folder = foldEQ;
6381             fold_array = PL_fold;
6382             type = REFF;
6383             utf8_fold_flags = 0;
6384             goto do_nref;
6385
6386         case NREF:  /*  /\g{name}/   */
6387             type = REF;
6388             folder = NULL;
6389             fold_array = NULL;
6390             utf8_fold_flags = 0;
6391           do_nref:
6392
6393             /* For the named back references, find the corresponding buffer
6394              * number */
6395             n = reg_check_named_buff_matched(rex,scan);
6396
6397             if ( ! n ) {
6398                 sayNO;
6399             }
6400             goto do_nref_ref_common;
6401
6402         case REFFL:  /*  /\1/il  */
6403             _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6404             folder = foldEQ_locale;
6405             fold_array = PL_fold_locale;
6406             utf8_fold_flags = FOLDEQ_LOCALE;
6407             goto do_ref;
6408
6409         case REFFA:  /*  /\1/iaa  */
6410             folder = foldEQ_latin1;
6411             fold_array = PL_fold_latin1;
6412             utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
6413             goto do_ref;
6414
6415         case REFFU:  /*  /\1/iu  */
6416             folder = foldEQ_latin1;
6417             fold_array = PL_fold_latin1;
6418             utf8_fold_flags = 0;
6419             goto do_ref;
6420
6421         case REFF:  /*  /\1/i  */
6422             folder = foldEQ;
6423             fold_array = PL_fold;
6424             utf8_fold_flags = 0;
6425             goto do_ref;
6426
6427         case REF:  /*  /\1/    */
6428             folder = NULL;
6429             fold_array = NULL;
6430             utf8_fold_flags = 0;
6431
6432           do_ref:
6433             type = OP(scan);
6434             n = ARG(scan);  /* which paren pair */
6435
6436           do_nref_ref_common:
6437             ln = rex->offs[n].start;
6438             reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
6439             if (rex->lastparen < n || ln == -1)
6440                 sayNO;                  /* Do not match unless seen CLOSEn. */
6441             if (ln == rex->offs[n].end)
6442                 break;
6443
6444             s = reginfo->strbeg + ln;
6445             if (type != REF     /* REF can do byte comparison */
6446                 && (utf8_target || type == REFFU || type == REFFL))
6447             {
6448                 char * limit = reginfo->strend;
6449
6450                 /* This call case insensitively compares the entire buffer
6451                     * at s, with the current input starting at locinput, but
6452                     * not going off the end given by reginfo->strend, and
6453                     * returns in <limit> upon success, how much of the
6454                     * current input was matched */
6455                 if (! foldEQ_utf8_flags(s, NULL, rex->offs[n].end - ln, utf8_target,
6456                                     locinput, &limit, 0, utf8_target, utf8_fold_flags))
6457                 {
6458                     sayNO;
6459                 }
6460                 locinput = limit;
6461                 break;
6462             }
6463
6464             /* Not utf8:  Inline the first character, for speed. */
6465             if (!NEXTCHR_IS_EOS &&
6466                 UCHARAT(s) != nextchr &&
6467                 (type == REF ||
6468                  UCHARAT(s) != fold_array[nextchr]))
6469                 sayNO;
6470             ln = rex->offs[n].end - ln;
6471             if (locinput + ln > reginfo->strend)
6472                 sayNO;
6473             if (ln > 1 && (type == REF
6474                            ? memNE(s, locinput, ln)
6475                            : ! folder(s, locinput, ln)))
6476                 sayNO;
6477             locinput += ln;
6478             break;
6479         }
6480
6481         case NOTHING: /* null op; e.g. the 'nothing' following
6482                        * the '*' in m{(a+|b)*}' */
6483             break;
6484         case TAIL: /* placeholder while compiling (A|B|C) */
6485             break;
6486
6487 #undef  ST
6488 #define ST st->u.eval
6489         {
6490             SV *ret;
6491             REGEXP *re_sv;
6492             regexp *re;
6493             regexp_internal *rei;
6494             regnode *startpoint;
6495
6496         case GOSTART: /*  (?R)  */
6497         case GOSUB: /*    /(...(?1))/   /(...(?&foo))/   */
6498             if (cur_eval && cur_eval->locinput==locinput) {
6499                 if (cur_eval->u.eval.close_paren == (U32)ARG(scan)) 
6500                     Perl_croak(aTHX_ "Infinite recursion in regex");
6501                 if ( ++nochange_depth > max_nochange_depth )
6502                     Perl_croak(aTHX_ 
6503                         "Pattern subroutine nesting without pos change"
6504                         " exceeded limit in regex");
6505             } else {
6506                 nochange_depth = 0;
6507             }
6508             re_sv = rex_sv;
6509             re = rex;
6510             rei = rexi;
6511             if (OP(scan)==GOSUB) {
6512                 startpoint = scan + ARG2L(scan);
6513                 ST.close_paren = ARG(scan);
6514             } else {
6515                 startpoint = rei->program+1;
6516                 ST.close_paren = 0;
6517             }
6518
6519             /* Save all the positions seen so far. */
6520             ST.cp = regcppush(rex, 0, maxopenparen);
6521             REGCP_SET(ST.lastcp);
6522
6523             /* and then jump to the code we share with EVAL */
6524             goto eval_recurse_doit;
6525             /* NOTREACHED */
6526
6527         case EVAL:  /*   /(?{A})B/   /(??{A})B/  and /(?(?{A})X|Y)B/   */        
6528             if (cur_eval && cur_eval->locinput==locinput) {
6529                 if ( ++nochange_depth > max_nochange_depth )
6530                     Perl_croak(aTHX_ "EVAL without pos change exceeded limit in regex");
6531             } else {
6532                 nochange_depth = 0;
6533             }    
6534             {
6535                 /* execute the code in the {...} */
6536
6537                 dSP;
6538                 IV before;
6539                 OP * const oop = PL_op;
6540                 COP * const ocurcop = PL_curcop;
6541                 OP *nop;
6542                 CV *newcv;
6543
6544                 /* save *all* paren positions */
6545                 regcppush(rex, 0, maxopenparen);
6546                 REGCP_SET(runops_cp);
6547
6548                 if (!caller_cv)
6549                     caller_cv = find_runcv(NULL);
6550
6551                 n = ARG(scan);
6552
6553                 if (rexi->data->what[n] == 'r') { /* code from an external qr */
6554                     newcv = (ReANY(
6555                                                 (REGEXP*)(rexi->data->data[n])
6556                                             ))->qr_anoncv
6557                                         ;
6558                     nop = (OP*)rexi->data->data[n+1];
6559                 }
6560                 else if (rexi->data->what[n] == 'l') { /* literal code */
6561                     newcv = caller_cv;
6562                     nop = (OP*)rexi->data->data[n];
6563                     assert(CvDEPTH(newcv));
6564                 }
6565                 else {
6566                     /* literal with own CV */
6567                     assert(rexi->data->what[n] == 'L');
6568                     newcv = rex->qr_anoncv;
6569                     nop = (OP*)rexi->data->data[n];
6570                 }
6571
6572                 /* normally if we're about to execute code from the same
6573                  * CV that we used previously, we just use the existing
6574                  * CX stack entry. However, its possible that in the
6575                  * meantime we may have backtracked, popped from the save
6576                  * stack, and undone the SAVECOMPPAD(s) associated with
6577                  * PUSH_MULTICALL; in which case PL_comppad no longer
6578                  * points to newcv's pad. */
6579                 if (newcv != last_pushed_cv || PL_comppad != last_pad)
6580                 {
6581                     U8 flags = (CXp_SUB_RE |
6582                                 ((newcv == caller_cv) ? CXp_SUB_RE_FAKE : 0));
6583                     if (last_pushed_cv) {
6584                         /* PUSH/POP_MULTICALL save and restore the
6585                          * caller's PL_comppad; if we call multiple subs
6586                          * using the same CX block, we have to save and
6587                          * unwind the varying PL_comppad's ourselves,
6588                          * especially restoring the right PL_comppad on
6589                          * backtrack - so save it on the save stack */
6590                         SAVECOMPPAD();
6591                         CHANGE_MULTICALL_FLAGS(newcv, flags);
6592                     }
6593                     else {
6594                         PUSH_MULTICALL_FLAGS(newcv, flags);
6595                     }
6596                     last_pushed_cv = newcv;
6597                 }
6598                 else {
6599                     /* these assignments are just to silence compiler
6600                      * warnings */
6601                     multicall_cop = NULL;
6602                 }
6603                 last_pad = PL_comppad;
6604
6605                 /* the initial nextstate you would normally execute
6606                  * at the start of an eval (which would cause error
6607                  * messages to come from the eval), may be optimised
6608                  * away from the execution path in the regex code blocks;
6609                  * so manually set PL_curcop to it initially */
6610                 {
6611                     OP *o = cUNOPx(nop)->op_first;
6612                     assert(o->op_type == OP_NULL);
6613                     if (o->op_targ == OP_SCOPE) {
6614                         o = cUNOPo->op_first;
6615                     }
6616                     else {
6617                         assert(o->op_targ == OP_LEAVE);
6618                         o = cUNOPo->op_first;
6619                         assert(o->op_type == OP_ENTER);
6620                         o = OpSIBLING(o);
6621                     }
6622
6623                     if (o->op_type != OP_STUB) {
6624                         assert(    o->op_type == OP_NEXTSTATE
6625                                 || o->op_type == OP_DBSTATE
6626                                 || (o->op_type == OP_NULL
6627                                     &&  (  o->op_targ == OP_NEXTSTATE
6628                                         || o->op_targ == OP_DBSTATE
6629                                         )
6630                                     )
6631                         );
6632                         PL_curcop = (COP*)o;
6633                     }
6634                 }
6635                 nop = nop->op_next;
6636
6637                 DEBUG_STATE_r( PerlIO_printf(Perl_debug_log, 
6638                     "  re EVAL PL_op=0x%"UVxf"\n", PTR2UV(nop)) );
6639
6640                 rex->offs[0].end = locinput - reginfo->strbeg;
6641                 if (reginfo->info_aux_eval->pos_magic)
6642                     MgBYTEPOS_set(reginfo->info_aux_eval->pos_magic,
6643                                   reginfo->sv, reginfo->strbeg,
6644                                   locinput - reginfo->strbeg);
6645
6646                 if (sv_yes_mark) {
6647                     SV *sv_mrk = get_sv("REGMARK", 1);
6648                     sv_setsv(sv_mrk, sv_yes_mark);
6649                 }
6650
6651                 /* we don't use MULTICALL here as we want to call the
6652                  * first op of the block of interest, rather than the
6653                  * first op of the sub. Also, we don't want to free
6654                  * the savestack frame */
6655                 before = (IV)(SP-PL_stack_base);
6656                 PL_op = nop;
6657                 CALLRUNOPS(aTHX);                       /* Scalar context. */
6658                 SPAGAIN;
6659                 if ((IV)(SP-PL_stack_base) == before)
6660                     ret = &PL_sv_undef;   /* protect against empty (?{}) blocks. */
6661                 else {
6662                     ret = POPs;
6663                     PUTBACK;
6664                 }
6665
6666                 /* before restoring everything, evaluate the returned
6667                  * value, so that 'uninit' warnings don't use the wrong
6668                  * PL_op or pad. Also need to process any magic vars
6669                  * (e.g. $1) *before* parentheses are restored */
6670
6671                 PL_op = NULL;
6672
6673                 re_sv = NULL;
6674                 if (logical == 0)        /*   (?{})/   */
6675                     sv_setsv(save_scalar(PL_replgv), ret); /* $^R */
6676                 else if (logical == 1) { /*   /(?(?{...})X|Y)/    */
6677                     sw = cBOOL(SvTRUE(ret));
6678                     logical = 0;
6679                 }
6680                 else {                   /*  /(??{})  */
6681                     /*  if its overloaded, let the regex compiler handle
6682                      *  it; otherwise extract regex, or stringify  */
6683                     if (SvGMAGICAL(ret))
6684                         ret = sv_mortalcopy(ret);
6685                     if (!SvAMAGIC(ret)) {
6686                         SV *sv = ret;
6687                         if (SvROK(sv))
6688                             sv = SvRV(sv);
6689                         if (SvTYPE(sv) == SVt_REGEXP)
6690                             re_sv = (REGEXP*) sv;
6691                         else if (SvSMAGICAL(ret)) {
6692                             MAGIC *mg = mg_find(ret, PERL_MAGIC_qr);
6693                             if (mg)
6694                                 re_sv = (REGEXP *) mg->mg_obj;
6695                         }
6696
6697                         /* force any undef warnings here */
6698                         if (!re_sv && !SvPOK(ret) && !SvNIOK(ret)) {
6699                             ret = sv_mortalcopy(ret);
6700                             (void) SvPV_force_nolen(ret);
6701                         }
6702                     }
6703
6704                 }
6705
6706                 /* *** Note that at this point we don't restore
6707                  * PL_comppad, (or pop the CxSUB) on the assumption it may
6708                  * be used again soon. This is safe as long as nothing
6709                  * in the regexp code uses the pad ! */
6710                 PL_op = oop;
6711                 PL_curcop = ocurcop;
6712                 S_regcp_restore(aTHX_ rex, runops_cp, &maxopenparen);
6713                 PL_curpm = PL_reg_curpm;
6714
6715                 if (logical != 2)
6716                     break;
6717             }
6718
6719                 /* only /(??{})/  from now on */
6720                 logical = 0;
6721                 {
6722                     /* extract RE object from returned value; compiling if
6723                      * necessary */
6724
6725                     if (re_sv) {
6726                         re_sv = reg_temp_copy(NULL, re_sv);
6727                     }
6728                     else {
6729                         U32 pm_flags = 0;
6730
6731                         if (SvUTF8(ret) && IN_BYTES) {
6732                             /* In use 'bytes': make a copy of the octet
6733                              * sequence, but without the flag on */
6734                             STRLEN len;
6735                             const char *const p = SvPV(ret, len);
6736                             ret = newSVpvn_flags(p, len, SVs_TEMP);
6737                         }
6738                         if (rex->intflags & PREGf_USE_RE_EVAL)
6739                             pm_flags |= PMf_USE_RE_EVAL;
6740
6741                         /* if we got here, it should be an engine which
6742                          * supports compiling code blocks and stuff */
6743                         assert(rex->engine && rex->engine->op_comp);
6744                         assert(!(scan->flags & ~RXf_PMf_COMPILETIME));
6745                         re_sv = rex->engine->op_comp(aTHX_ &ret, 1, NULL,
6746                                     rex->engine, NULL, NULL,
6747                                     /* copy /msixn etc to inner pattern */
6748                                     ARG2L(scan),
6749                                     pm_flags);
6750
6751                         if (!(SvFLAGS(ret)
6752                               & (SVs_TEMP | SVs_GMG | SVf_ROK))
6753                          && (!SvPADTMP(ret) || SvREADONLY(ret))) {
6754                             /* This isn't a first class regexp. Instead, it's
6755                                caching a regexp onto an existing, Perl visible
6756                                scalar.  */
6757                             sv_magic(ret, MUTABLE_SV(re_sv), PERL_MAGIC_qr, 0, 0);
6758                         }
6759                     }
6760                     SAVEFREESV(re_sv);
6761                     re = ReANY(re_sv);
6762                 }
6763                 RXp_MATCH_COPIED_off(re);
6764                 re->subbeg = rex->subbeg;
6765                 re->sublen = rex->sublen;
6766                 re->suboffset = rex->suboffset;
6767                 re->subcoffset = rex->subcoffset;
6768                 re->lastparen = 0;
6769                 re->lastcloseparen = 0;
6770                 rei = RXi_GET(re);
6771                 DEBUG_EXECUTE_r(
6772                     debug_start_match(re_sv, utf8_target, locinput,
6773                                     reginfo->strend, "Matching embedded");
6774                 );              
6775                 startpoint = rei->program + 1;
6776                 ST.close_paren = 0; /* only used for GOSUB */
6777                 /* Save all the seen positions so far. */
6778                 ST.cp = regcppush(rex, 0, maxopenparen);
6779                 REGCP_SET(ST.lastcp);
6780                 /* and set maxopenparen to 0, since we are starting a "fresh" match */
6781                 maxopenparen = 0;
6782                 /* run the pattern returned from (??{...}) */
6783
6784               eval_recurse_doit: /* Share code with GOSUB below this line
6785                             * At this point we expect the stack context to be
6786                             * set up correctly */
6787
6788                 /* invalidate the S-L poscache. We're now executing a
6789                  * different set of WHILEM ops (and their associated
6790                  * indexes) against the same string, so the bits in the
6791                  * cache are meaningless. Setting maxiter to zero forces
6792                  * the cache to be invalidated and zeroed before reuse.
6793                  * XXX This is too dramatic a measure. Ideally we should
6794                  * save the old cache and restore when running the outer
6795                  * pattern again */
6796                 reginfo->poscache_maxiter = 0;
6797
6798                 /* the new regexp might have a different is_utf8_pat than we do */
6799                 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(re_sv));
6800
6801                 ST.prev_rex = rex_sv;
6802                 ST.prev_curlyx = cur_curlyx;
6803                 rex_sv = re_sv;
6804                 SET_reg_curpm(rex_sv);
6805                 rex = re;
6806                 rexi = rei;
6807                 cur_curlyx = NULL;
6808                 ST.B = next;
6809                 ST.prev_eval = cur_eval;
6810                 cur_eval = st;
6811                 /* now continue from first node in postoned RE */
6812                 PUSH_YES_STATE_GOTO(EVAL_AB, startpoint, locinput);
6813                 /* NOTREACHED */
6814                 NOT_REACHED; /* NOTREACHED */
6815         }
6816
6817         case EVAL_AB: /* cleanup after a successful (??{A})B */
6818             /* note: this is called twice; first after popping B, then A */
6819             rex_sv = ST.prev_rex;
6820             is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
6821             SET_reg_curpm(rex_sv);
6822             rex = ReANY(rex_sv);
6823             rexi = RXi_GET(rex);
6824             {
6825                 /* preserve $^R across LEAVE's. See Bug 121070. */
6826                 SV *save_sv= GvSV(PL_replgv);
6827                 SvREFCNT_inc(save_sv);
6828                 regcpblow(ST.cp); /* LEAVE in disguise */
6829                 sv_setsv(GvSV(PL_replgv), save_sv);
6830                 SvREFCNT_dec(save_sv);
6831             }
6832             cur_eval = ST.prev_eval;
6833             cur_curlyx = ST.prev_curlyx;
6834
6835             /* Invalidate cache. See "invalidate" comment above. */
6836             reginfo->poscache_maxiter = 0;
6837             if ( nochange_depth )
6838                 nochange_depth--;
6839             sayYES;
6840
6841
6842         case EVAL_AB_fail: /* unsuccessfully ran A or B in (??{A})B */
6843             /* note: this is called twice; first after popping B, then A */
6844             rex_sv = ST.prev_rex;
6845             is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
6846             SET_reg_curpm(rex_sv);
6847             rex = ReANY(rex_sv);
6848             rexi = RXi_GET(rex); 
6849
6850             REGCP_UNWIND(ST.lastcp);
6851             regcppop(rex, &maxopenparen);
6852             cur_eval = ST.prev_eval;
6853             cur_curlyx = ST.prev_curlyx;
6854             /* Invalidate cache. See "invalidate" comment above. */
6855             reginfo->poscache_maxiter = 0;
6856             if ( nochange_depth )
6857                 nochange_depth--;
6858             sayNO_SILENT;
6859 #undef ST
6860
6861         case OPEN: /*  (  */
6862             n = ARG(scan);  /* which paren pair */
6863             rex->offs[n].start_tmp = locinput - reginfo->strbeg;
6864             if (n > maxopenparen)
6865                 maxopenparen = n;
6866             DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
6867                 "rex=0x%"UVxf" offs=0x%"UVxf": \\%"UVuf": set %"IVdf" tmp; maxopenparen=%"UVuf"\n",
6868                 PTR2UV(rex),
6869                 PTR2UV(rex->offs),
6870                 (UV)n,
6871                 (IV)rex->offs[n].start_tmp,
6872                 (UV)maxopenparen
6873             ));
6874             lastopen = n;
6875             break;
6876
6877 /* XXX really need to log other places start/end are set too */
6878 #define CLOSE_CAPTURE \
6879     rex->offs[n].start = rex->offs[n].start_tmp; \
6880     rex->offs[n].end = locinput - reginfo->strbeg; \
6881     DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log, \
6882         "rex=0x%"UVxf" offs=0x%"UVxf": \\%"UVuf": set %"IVdf"..%"IVdf"\n", \
6883         PTR2UV(rex), \
6884         PTR2UV(rex->offs), \
6885         (UV)n, \
6886         (IV)rex->offs[n].start, \
6887         (IV)rex->offs[n].end \
6888     ))
6889
6890         case CLOSE:  /*  )  */
6891             n = ARG(scan);  /* which paren pair */
6892             CLOSE_CAPTURE;
6893             if (n > rex->lastparen)
6894                 rex->lastparen = n;
6895             rex->lastcloseparen = n;
6896             if (cur_eval && cur_eval->u.eval.close_paren == n) {
6897                 goto fake_end;
6898             }    
6899             break;
6900
6901         case ACCEPT:  /*  (*ACCEPT)  */
6902             if (scan->flags)
6903                 sv_yes_mark = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
6904             if (ARG2L(scan)){
6905                 regnode *cursor;
6906                 for (cursor=scan;
6907                      cursor && OP(cursor)!=END; 
6908                      cursor=regnext(cursor)) 
6909                 {
6910                     if ( OP(cursor)==CLOSE ){
6911                         n = ARG(cursor);
6912                         if ( n <= lastopen ) {
6913                             CLOSE_CAPTURE;
6914                             if (n > rex->lastparen)
6915                                 rex->lastparen = n;
6916                             rex->lastcloseparen = n;
6917                             if ( n == ARG(scan) || (cur_eval &&
6918                                 cur_eval->u.eval.close_paren == n))
6919                                 break;
6920                         }
6921                     }
6922                 }
6923             }
6924             goto fake_end;
6925             /* NOTREACHED */
6926
6927         case GROUPP:  /*  (?(1))  */
6928             n = ARG(scan);  /* which paren pair */
6929             sw = cBOOL(rex->lastparen >= n && rex->offs[n].end != -1);
6930             break;
6931
6932         case NGROUPP:  /*  (?(<name>))  */
6933             /* reg_check_named_buff_matched returns 0 for no match */
6934             sw = cBOOL(0 < reg_check_named_buff_matched(rex,scan));
6935             break;
6936
6937         case INSUBP:   /*  (?(R))  */
6938             n = ARG(scan);
6939             sw = (cur_eval && (!n || cur_eval->u.eval.close_paren == n));
6940             break;
6941
6942         case DEFINEP:  /*  (?(DEFINE))  */
6943             sw = 0;
6944             break;
6945
6946         case IFTHEN:   /*  (?(cond)A|B)  */
6947             reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
6948             if (sw)
6949                 next = NEXTOPER(NEXTOPER(scan));
6950             else {
6951                 next = scan + ARG(scan);
6952                 if (OP(next) == IFTHEN) /* Fake one. */
6953                     next = NEXTOPER(NEXTOPER(next));
6954             }
6955             break;
6956
6957         case LOGICAL:  /* modifier for EVAL and IFMATCH */
6958             logical = scan->flags;
6959             break;
6960
6961 /*******************************************************************
6962
6963 The CURLYX/WHILEM pair of ops handle the most generic case of the /A*B/
6964 pattern, where A and B are subpatterns. (For simple A, CURLYM or
6965 STAR/PLUS/CURLY/CURLYN are used instead.)
6966
6967 A*B is compiled as <CURLYX><A><WHILEM><B>
6968
6969 On entry to the subpattern, CURLYX is called. This pushes a CURLYX
6970 state, which contains the current count, initialised to -1. It also sets
6971 cur_curlyx to point to this state, with any previous value saved in the
6972 state block.
6973
6974 CURLYX then jumps straight to the WHILEM op, rather than executing A,
6975 since the pattern may possibly match zero times (i.e. it's a while {} loop
6976 rather than a do {} while loop).
6977
6978 Each entry to WHILEM represents a successful match of A. The count in the
6979 CURLYX block is incremented, another WHILEM state is pushed, and execution
6980 passes to A or B depending on greediness and the current count.
6981
6982 For example, if matching against the string a1a2a3b (where the aN are
6983 substrings that match /A/), then the match progresses as follows: (the
6984 pushed states are interspersed with the bits of strings matched so far):
6985
6986     <CURLYX cnt=-1>
6987     <CURLYX cnt=0><WHILEM>
6988     <CURLYX cnt=1><WHILEM> a1 <WHILEM>
6989     <CURLYX cnt=2><WHILEM> a1 <WHILEM> a2 <WHILEM>
6990     <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM>
6991     <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM> b
6992
6993 (Contrast this with something like CURLYM, which maintains only a single
6994 backtrack state:
6995
6996     <CURLYM cnt=0> a1
6997     a1 <CURLYM cnt=1> a2
6998     a1 a2 <CURLYM cnt=2> a3
6999     a1 a2 a3 <CURLYM cnt=3> b
7000 )
7001
7002 Each WHILEM state block marks a point to backtrack to upon partial failure
7003 of A or B, and also contains some minor state data related to that
7004 iteration.  The CURLYX block, pointed to by cur_curlyx, contains the
7005 overall state, such as the count, and pointers to the A and B ops.
7006
7007 This is complicated slightly by nested CURLYX/WHILEM's. Since cur_curlyx
7008 must always point to the *current* CURLYX block, the rules are:
7009
7010 When executing CURLYX, save the old cur_curlyx in the CURLYX state block,
7011 and set cur_curlyx to point the new block.
7012
7013 When popping the CURLYX block after a successful or unsuccessful match,
7014 restore the previous cur_curlyx.
7015
7016 When WHILEM is about to execute B, save the current cur_curlyx, and set it
7017 to the outer one saved in the CURLYX block.
7018
7019 When popping the WHILEM block after a successful or unsuccessful B match,
7020 restore the previous cur_curlyx.
7021
7022 Here's an example for the pattern (AI* BI)*BO
7023 I and O refer to inner and outer, C and W refer to CURLYX and WHILEM:
7024
7025 cur_
7026 curlyx backtrack stack
7027 ------ ---------------
7028 NULL   
7029 CO     <CO prev=NULL> <WO>
7030 CI     <CO prev=NULL> <WO> <CI prev=CO> <WI> ai 
7031 CO     <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi 
7032 NULL   <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi <WO prev=CO> bo
7033
7034 At this point the pattern succeeds, and we work back down the stack to
7035 clean up, restoring as we go:
7036
7037 CO     <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi 
7038 CI     <CO prev=NULL> <WO> <CI prev=CO> <WI> ai 
7039 CO     <CO prev=NULL> <WO>
7040 NULL   
7041
7042 *******************************************************************/
7043
7044 #define ST st->u.curlyx
7045
7046         case CURLYX:    /* start of /A*B/  (for complex A) */
7047         {
7048             /* No need to save/restore up to this paren */
7049             I32 parenfloor = scan->flags;
7050             
7051             assert(next); /* keep Coverity happy */
7052             if (OP(PREVOPER(next)) == NOTHING) /* LONGJMP */
7053                 next += ARG(next);
7054
7055             /* XXXX Probably it is better to teach regpush to support
7056                parenfloor > maxopenparen ... */
7057             if (parenfloor > (I32)rex->lastparen)
7058                 parenfloor = rex->lastparen; /* Pessimization... */
7059
7060             ST.prev_curlyx= cur_curlyx;
7061             cur_curlyx = st;
7062             ST.cp = PL_savestack_ix;
7063
7064             /* these fields contain the state of the current curly.
7065              * they are accessed by subsequent WHILEMs */
7066             ST.parenfloor = parenfloor;
7067             ST.me = scan;
7068             ST.B = next;
7069             ST.minmod = minmod;
7070             minmod = 0;
7071             ST.count = -1;      /* this will be updated by WHILEM */
7072             ST.lastloc = NULL;  /* this will be updated by WHILEM */
7073
7074             PUSH_YES_STATE_GOTO(CURLYX_end, PREVOPER(next), locinput);
7075             /* NOTREACHED */
7076             NOT_REACHED; /* NOTREACHED */
7077         }
7078
7079         case CURLYX_end: /* just finished matching all of A*B */
7080             cur_curlyx = ST.prev_curlyx;
7081             sayYES;
7082             /* NOTREACHED */
7083             NOT_REACHED; /* NOTREACHED */
7084
7085         case CURLYX_end_fail: /* just failed to match all of A*B */
7086             regcpblow(ST.cp);
7087             cur_curlyx = ST.prev_curlyx;
7088             sayNO;
7089             /* NOTREACHED */
7090             NOT_REACHED; /* NOTREACHED */
7091
7092
7093 #undef ST
7094 #define ST st->u.whilem
7095
7096         case WHILEM:     /* just matched an A in /A*B/  (for complex A) */
7097         {
7098             /* see the discussion above about CURLYX/WHILEM */
7099             I32 n;
7100             int min, max;
7101             regnode *A;
7102
7103             assert(cur_curlyx); /* keep Coverity happy */
7104
7105             min = ARG1(cur_curlyx->u.curlyx.me);
7106             max = ARG2(cur_curlyx->u.curlyx.me);
7107             A = NEXTOPER(cur_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS;
7108             n = ++cur_curlyx->u.curlyx.count; /* how many A's matched */
7109             ST.save_lastloc = cur_curlyx->u.curlyx.lastloc;
7110             ST.cache_offset = 0;
7111             ST.cache_mask = 0;
7112             
7113
7114             DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
7115                   "%*s  whilem: matched %ld out of %d..%d\n",
7116                   REPORT_CODE_OFF+depth*2, "", (long)n, min, max)
7117             );
7118
7119             /* First just match a string of min A's. */
7120
7121             if (n < min) {
7122                 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
7123                                     maxopenparen);
7124                 cur_curlyx->u.curlyx.lastloc = locinput;
7125                 REGCP_SET(ST.lastcp);
7126
7127                 PUSH_STATE_GOTO(WHILEM_A_pre, A, locinput);
7128                 /* NOTREACHED */
7129                 NOT_REACHED; /* NOTREACHED */
7130             }
7131
7132             /* If degenerate A matches "", assume A done. */
7133
7134             if (locinput == cur_curlyx->u.curlyx.lastloc) {
7135                 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
7136                    "%*s  whilem: empty match detected, trying continuation...\n",
7137                    REPORT_CODE_OFF+depth*2, "")
7138                 );
7139                 goto do_whilem_B_max;
7140             }
7141
7142             /* super-linear cache processing.
7143              *
7144              * The idea here is that for certain types of CURLYX/WHILEM -
7145              * principally those whose upper bound is infinity (and
7146              * excluding regexes that have things like \1 and other very
7147              * non-regular expresssiony things), then if a pattern like
7148              * /....A*.../ fails and we backtrack to the WHILEM, then we
7149              * make a note that this particular WHILEM op was at string
7150              * position 47 (say) when the rest of pattern failed. Then, if
7151              * we ever find ourselves back at that WHILEM, and at string
7152              * position 47 again, we can just fail immediately rather than
7153              * running the rest of the pattern again.
7154              *
7155              * This is very handy when patterns start to go
7156              * 'super-linear', like in (a+)*(a+)*(a+)*, where you end up
7157              * with a combinatorial explosion of backtracking.
7158              *
7159              * The cache is implemented as a bit array, with one bit per
7160              * string byte position per WHILEM op (up to 16) - so its
7161              * between 0.25 and 2x the string size.
7162              *
7163              * To avoid allocating a poscache buffer every time, we do an
7164              * initially countdown; only after we have  executed a WHILEM
7165              * op (string-length x #WHILEMs) times do we allocate the
7166              * cache.
7167              *
7168              * The top 4 bits of scan->flags byte say how many different
7169              * relevant CURLLYX/WHILEM op pairs there are, while the
7170              * bottom 4-bits is the identifying index number of this
7171              * WHILEM.
7172              */
7173
7174             if (scan->flags) {
7175
7176                 if (!reginfo->poscache_maxiter) {
7177                     /* start the countdown: Postpone detection until we
7178                      * know the match is not *that* much linear. */
7179                     reginfo->poscache_maxiter
7180                         =    (reginfo->strend - reginfo->strbeg + 1)
7181                            * (scan->flags>>4);
7182                     /* possible overflow for long strings and many CURLYX's */
7183                     if (reginfo->poscache_maxiter < 0)
7184                         reginfo->poscache_maxiter = I32_MAX;
7185                     reginfo->poscache_iter = reginfo->poscache_maxiter;
7186                 }
7187
7188                 if (reginfo->poscache_iter-- == 0) {
7189                     /* initialise cache */
7190                     const SSize_t size = (reginfo->poscache_maxiter + 7)/8;
7191                     regmatch_info_aux *const aux = reginfo->info_aux;
7192                     if (aux->poscache) {
7193                         if ((SSize_t)reginfo->poscache_size < size) {
7194                             Renew(aux->poscache, size, char);
7195                             reginfo->poscache_size = size;
7196                         }
7197                         Zero(aux->poscache, size, char);
7198                     }
7199                     else {
7200                         reginfo->poscache_size = size;
7201                         Newxz(aux->poscache, size, char);
7202                     }
7203                     DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
7204       "%swhilem: Detected a super-linear match, switching on caching%s...\n",
7205                               PL_colors[4], PL_colors[5])
7206                     );
7207                 }
7208
7209                 if (reginfo->poscache_iter < 0) {
7210                     /* have we already failed at this position? */
7211                     SSize_t offset, mask;
7212
7213                     reginfo->poscache_iter = -1; /* stop eventual underflow */
7214                     offset  = (scan->flags & 0xf) - 1
7215                                 +   (locinput - reginfo->strbeg)
7216                                   * (scan->flags>>4);
7217                     mask    = 1 << (offset % 8);
7218                     offset /= 8;
7219                     if (reginfo->info_aux->poscache[offset] & mask) {
7220                         DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
7221                             "%*s  whilem: (cache) already tried at this position...\n",
7222                             REPORT_CODE_OFF+depth*2, "")
7223                         );
7224                         sayNO; /* cache records failure */
7225                     }
7226                     ST.cache_offset = offset;
7227                     ST.cache_mask   = mask;
7228                 }
7229             }
7230
7231             /* Prefer B over A for minimal matching. */
7232
7233             if (cur_curlyx->u.curlyx.minmod) {
7234                 ST.save_curlyx = cur_curlyx;
7235                 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
7236                 ST.cp = regcppush(rex, ST.save_curlyx->u.curlyx.parenfloor,
7237                             maxopenparen);
7238                 REGCP_SET(ST.lastcp);
7239                 PUSH_YES_STATE_GOTO(WHILEM_B_min, ST.save_curlyx->u.curlyx.B,
7240                                     locinput);
7241                 /* NOTREACHED */
7242                 NOT_REACHED; /* NOTREACHED */
7243             }
7244
7245             /* Prefer A over B for maximal matching. */
7246
7247             if (n < max) { /* More greed allowed? */
7248                 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
7249                             maxopenparen);
7250                 cur_curlyx->u.curlyx.lastloc = locinput;
7251                 REGCP_SET(ST.lastcp);
7252                 PUSH_STATE_GOTO(WHILEM_A_max, A, locinput);
7253                 /* NOTREACHED */
7254                 NOT_REACHED; /* NOTREACHED */
7255             }
7256             goto do_whilem_B_max;
7257         }
7258         /* NOTREACHED */
7259         NOT_REACHED; /* NOTREACHED */
7260
7261         case WHILEM_B_min: /* just matched B in a minimal match */
7262         case WHILEM_B_max: /* just matched B in a maximal match */
7263             cur_curlyx = ST.save_curlyx;
7264             sayYES;
7265             /* NOTREACHED */
7266             NOT_REACHED; /* NOTREACHED */
7267
7268         case WHILEM_B_max_fail: /* just failed to match B in a maximal match */
7269             cur_curlyx = ST.save_curlyx;
7270             cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
7271             cur_curlyx->u.curlyx.count--;
7272             CACHEsayNO;
7273             /* NOTREACHED */
7274             NOT_REACHED; /* NOTREACHED */
7275
7276         case WHILEM_A_min_fail: /* just failed to match A in a minimal match */
7277             /* FALLTHROUGH */
7278         case WHILEM_A_pre_fail: /* just failed to match even minimal A */
7279             REGCP_UNWIND(ST.lastcp);
7280             regcppop(rex, &maxopenparen);
7281             cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
7282             cur_curlyx->u.curlyx.count--;
7283             CACHEsayNO;
7284             /* NOTREACHED */
7285             NOT_REACHED; /* NOTREACHED */
7286
7287         case WHILEM_A_max_fail: /* just failed to match A in a maximal match */
7288             REGCP_UNWIND(ST.lastcp);
7289             regcppop(rex, &maxopenparen); /* Restore some previous $<digit>s? */
7290             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
7291                 "%*s  whilem: failed, trying continuation...\n",
7292                 REPORT_CODE_OFF+depth*2, "")
7293             );
7294           do_whilem_B_max:
7295             if (cur_curlyx->u.curlyx.count >= REG_INFTY
7296                 && ckWARN(WARN_REGEXP)
7297                 && !reginfo->warned)
7298             {
7299                 reginfo->warned = TRUE;
7300                 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
7301                      "Complex regular subexpression recursion limit (%d) "
7302                      "exceeded",
7303                      REG_INFTY - 1);
7304             }
7305
7306             /* now try B */
7307             ST.save_curlyx = cur_curlyx;
7308             cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
7309             PUSH_YES_STATE_GOTO(WHILEM_B_max, ST.save_curlyx->u.curlyx.B,
7310                                 locinput);
7311             /* NOTREACHED */
7312             NOT_REACHED; /* NOTREACHED */
7313
7314         case WHILEM_B_min_fail: /* just failed to match B in a minimal match */
7315             cur_curlyx = ST.save_curlyx;
7316             REGCP_UNWIND(ST.lastcp);
7317             regcppop(rex, &maxopenparen);
7318
7319             if (cur_curlyx->u.curlyx.count >= /*max*/ARG2(cur_curlyx->u.curlyx.me)) {
7320                 /* Maximum greed exceeded */
7321                 if (cur_curlyx->u.curlyx.count >= REG_INFTY
7322                     && ckWARN(WARN_REGEXP)
7323                     && !reginfo->warned)
7324                 {
7325                     reginfo->warned     = TRUE;
7326                     Perl_warner(aTHX_ packWARN(WARN_REGEXP),
7327                         "Complex regular subexpression recursion "
7328                         "limit (%d) exceeded",
7329                         REG_INFTY - 1);
7330                 }
7331                 cur_curlyx->u.curlyx.count--;
7332                 CACHEsayNO;
7333             }
7334
7335             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
7336                 "%*s  trying longer...\n", REPORT_CODE_OFF+depth*2, "")
7337             );
7338             /* Try grabbing another A and see if it helps. */
7339             cur_curlyx->u.curlyx.lastloc = locinput;
7340             ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
7341                             maxopenparen);
7342             REGCP_SET(ST.lastcp);
7343             PUSH_STATE_GOTO(WHILEM_A_min,
7344                 /*A*/ NEXTOPER(ST.save_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS,
7345                 locinput);
7346             /* NOTREACHED */
7347             NOT_REACHED; /* NOTREACHED */
7348
7349 #undef  ST
7350 #define ST st->u.branch
7351
7352         case BRANCHJ:       /*  /(...|A|...)/ with long next pointer */
7353             next = scan + ARG(scan);
7354             if (next == scan)
7355                 next = NULL;
7356             scan = NEXTOPER(scan);
7357             /* FALLTHROUGH */
7358
7359         case BRANCH:        /*  /(...|A|...)/ */
7360             scan = NEXTOPER(scan); /* scan now points to inner node */
7361             ST.lastparen = rex->lastparen;
7362             ST.lastcloseparen = rex->lastcloseparen;
7363             ST.next_branch = next;
7364             REGCP_SET(ST.cp);
7365
7366             /* Now go into the branch */
7367             if (has_cutgroup) {
7368                 PUSH_YES_STATE_GOTO(BRANCH_next, scan, locinput);
7369             } else {
7370                 PUSH_STATE_GOTO(BRANCH_next, scan, locinput);
7371             }
7372             /* NOTREACHED */
7373             NOT_REACHED; /* NOTREACHED */
7374
7375         case CUTGROUP:  /*  /(*THEN)/  */
7376             sv_yes_mark = st->u.mark.mark_name = scan->flags
7377                 ? MUTABLE_SV(rexi->data->data[ ARG( scan ) ])
7378                 : NULL;
7379             PUSH_STATE_GOTO(CUTGROUP_next, next, locinput);
7380             /* NOTREACHED */
7381             NOT_REACHED; /* NOTREACHED */
7382
7383         case CUTGROUP_next_fail:
7384             do_cutgroup = 1;
7385             no_final = 1;
7386             if (st->u.mark.mark_name)
7387                 sv_commit = st->u.mark.mark_name;
7388             sayNO;          
7389             /* NOTREACHED */
7390             NOT_REACHED; /* NOTREACHED */
7391
7392         case BRANCH_next:
7393             sayYES;
7394             /* NOTREACHED */
7395             NOT_REACHED; /* NOTREACHED */
7396
7397         case BRANCH_next_fail: /* that branch failed; try the next, if any */
7398             if (do_cutgroup) {
7399                 do_cutgroup = 0;
7400                 no_final = 0;
7401             }
7402             REGCP_UNWIND(ST.cp);
7403             UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7404             scan = ST.next_branch;
7405             /* no more branches? */
7406             if (!scan || (OP(scan) != BRANCH && OP(scan) != BRANCHJ)) {
7407                 DEBUG_EXECUTE_r({
7408                     PerlIO_printf( Perl_debug_log,
7409                         "%*s  %sBRANCH failed...%s\n",
7410                         REPORT_CODE_OFF+depth*2, "", 
7411                         PL_colors[4],
7412                         PL_colors[5] );
7413                 });
7414                 sayNO_SILENT;
7415             }
7416             continue; /* execute next BRANCH[J] op */
7417             /* NOTREACHED */
7418     
7419         case MINMOD: /* next op will be non-greedy, e.g. A*?  */
7420             minmod = 1;
7421             break;
7422
7423 #undef  ST
7424 #define ST st->u.curlym
7425
7426         case CURLYM:    /* /A{m,n}B/ where A is fixed-length */
7427
7428             /* This is an optimisation of CURLYX that enables us to push
7429              * only a single backtracking state, no matter how many matches
7430              * there are in {m,n}. It relies on the pattern being constant
7431              * length, with no parens to influence future backrefs
7432              */
7433
7434             ST.me = scan;
7435             scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
7436
7437             ST.lastparen      = rex->lastparen;
7438             ST.lastcloseparen = rex->lastcloseparen;
7439
7440             /* if paren positive, emulate an OPEN/CLOSE around A */
7441             if (ST.me->flags) {
7442                 U32 paren = ST.me->flags;
7443                 if (paren > maxopenparen)
7444                     maxopenparen = paren;
7445                 scan += NEXT_OFF(scan); /* Skip former OPEN. */
7446             }
7447             ST.A = scan;
7448             ST.B = next;
7449             ST.alen = 0;
7450             ST.count = 0;
7451             ST.minmod = minmod;
7452             minmod = 0;
7453             ST.c1 = CHRTEST_UNINIT;
7454             REGCP_SET(ST.cp);
7455
7456             if (!(ST.minmod ? ARG1(ST.me) : ARG2(ST.me))) /* min/max */
7457                 goto curlym_do_B;
7458
7459           curlym_do_A: /* execute the A in /A{m,n}B/  */
7460             PUSH_YES_STATE_GOTO(CURLYM_A, ST.A, locinput); /* match A */
7461             /* NOTREACHED */
7462             NOT_REACHED; /* NOTREACHED */
7463
7464         case CURLYM_A: /* we've just matched an A */
7465             ST.count++;
7466             /* after first match, determine A's length: u.curlym.alen */
7467             if (ST.count == 1) {
7468                 if (reginfo->is_utf8_target) {
7469                     char *s = st->locinput;
7470                     while (s < locinput) {
7471                         ST.alen++;
7472                         s += UTF8SKIP(s);
7473                     }
7474                 }
7475                 else {
7476                     ST.alen = locinput - st->locinput;
7477                 }
7478                 if (ST.alen == 0)
7479                     ST.count = ST.minmod ? ARG1(ST.me) : ARG2(ST.me);
7480             }
7481             DEBUG_EXECUTE_r(
7482                 PerlIO_printf(Perl_debug_log,
7483                           "%*s  CURLYM now matched %"IVdf" times, len=%"IVdf"...\n",
7484                           (int)(REPORT_CODE_OFF+(depth*2)), "",
7485                           (IV) ST.count, (IV)ST.alen)
7486             );
7487
7488             if (cur_eval && cur_eval->u.eval.close_paren && 
7489                 cur_eval->u.eval.close_paren == (U32)ST.me->flags) 
7490                 goto fake_end;
7491                 
7492             {
7493                 I32 max = (ST.minmod ? ARG1(ST.me) : ARG2(ST.me));
7494                 if ( max == REG_INFTY || ST.count < max )
7495                     goto curlym_do_A; /* try to match another A */
7496             }
7497             goto curlym_do_B; /* try to match B */
7498
7499         case CURLYM_A_fail: /* just failed to match an A */
7500             REGCP_UNWIND(ST.cp);
7501
7502             if (ST.minmod || ST.count < ARG1(ST.me) /* min*/ 
7503                 || (cur_eval && cur_eval->u.eval.close_paren &&
7504                     cur_eval->u.eval.close_paren == (U32)ST.me->flags))
7505                 sayNO;
7506
7507           curlym_do_B: /* execute the B in /A{m,n}B/  */
7508             if (ST.c1 == CHRTEST_UNINIT) {
7509                 /* calculate c1 and c2 for possible match of 1st char
7510                  * following curly */
7511                 ST.c1 = ST.c2 = CHRTEST_VOID;
7512                 assert(ST.B);
7513                 if (HAS_TEXT(ST.B) || JUMPABLE(ST.B)) {
7514                     regnode *text_node = ST.B;
7515                     if (! HAS_TEXT(text_node))
7516                         FIND_NEXT_IMPT(text_node);
7517                     /* this used to be 
7518                         
7519                         (HAS_TEXT(text_node) && PL_regkind[OP(text_node)] == EXACT)
7520                         
7521                         But the former is redundant in light of the latter.
7522                         
7523                         if this changes back then the macro for 
7524                         IS_TEXT and friends need to change.
7525                      */
7526                     if (PL_regkind[OP(text_node)] == EXACT) {
7527                         if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
7528                            text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
7529                            reginfo))
7530                         {
7531                             sayNO;
7532                         }
7533                     }
7534                 }
7535             }
7536
7537             DEBUG_EXECUTE_r(
7538                 PerlIO_printf(Perl_debug_log,
7539                     "%*s  CURLYM trying tail with matches=%"IVdf"...\n",
7540                     (int)(REPORT_CODE_OFF+(depth*2)),
7541                     "", (IV)ST.count)
7542                 );
7543             if (! NEXTCHR_IS_EOS && ST.c1 != CHRTEST_VOID) {
7544                 if (! UTF8_IS_INVARIANT(nextchr) && utf8_target) {
7545                     if (memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
7546                         && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
7547                     {
7548                         /* simulate B failing */
7549                         DEBUG_OPTIMISE_r(
7550                             PerlIO_printf(Perl_debug_log,
7551                                 "%*s  CURLYM Fast bail next target=0x%"UVXf" c1=0x%"UVXf" c2=0x%"UVXf"\n",
7552                                 (int)(REPORT_CODE_OFF+(depth*2)),"",
7553                                 valid_utf8_to_uvchr((U8 *) locinput, NULL),
7554                                 valid_utf8_to_uvchr(ST.c1_utf8, NULL),
7555                                 valid_utf8_to_uvchr(ST.c2_utf8, NULL))
7556                         );
7557                         state_num = CURLYM_B_fail;
7558                         goto reenter_switch;
7559                     }
7560                 }
7561                 else if (nextchr != ST.c1 && nextchr != ST.c2) {
7562                     /* simulate B failing */
7563                     DEBUG_OPTIMISE_r(
7564                         PerlIO_printf(Perl_debug_log,
7565                             "%*s  CURLYM Fast bail next target=0x%X c1=0x%X c2=0x%X\n",
7566                             (int)(REPORT_CODE_OFF+(depth*2)),"",
7567                             (int) nextchr, ST.c1, ST.c2)
7568                     );
7569                     state_num = CURLYM_B_fail;
7570                     goto reenter_switch;
7571                 }
7572             }
7573
7574             if (ST.me->flags) {
7575                 /* emulate CLOSE: mark current A as captured */
7576                 I32 paren = ST.me->flags;
7577                 if (ST.count) {
7578                     rex->offs[paren].start
7579                         = HOPc(locinput, -ST.alen) - reginfo->strbeg;
7580                     rex->offs[paren].end = locinput - reginfo->strbeg;
7581                     if ((U32)paren > rex->lastparen)
7582                         rex->lastparen = paren;
7583                     rex->lastcloseparen = paren;
7584                 }
7585                 else
7586                     rex->offs[paren].end = -1;
7587                 if (cur_eval && cur_eval->u.eval.close_paren &&
7588                     cur_eval->u.eval.close_paren == (U32)ST.me->flags) 
7589                 {
7590                     if (ST.count) 
7591                         goto fake_end;
7592                     else
7593                         sayNO;
7594                 }
7595             }
7596             
7597             PUSH_STATE_GOTO(CURLYM_B, ST.B, locinput); /* match B */
7598             /* NOTREACHED */
7599             NOT_REACHED; /* NOTREACHED */
7600
7601         case CURLYM_B_fail: /* just failed to match a B */
7602             REGCP_UNWIND(ST.cp);
7603             UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7604             if (ST.minmod) {
7605                 I32 max = ARG2(ST.me);
7606                 if (max != REG_INFTY && ST.count == max)
7607                     sayNO;
7608                 goto curlym_do_A; /* try to match a further A */
7609             }
7610             /* backtrack one A */
7611             if (ST.count == ARG1(ST.me) /* min */)
7612                 sayNO;
7613             ST.count--;
7614             SET_locinput(HOPc(locinput, -ST.alen));
7615             goto curlym_do_B; /* try to match B */
7616
7617 #undef ST
7618 #define ST st->u.curly
7619
7620 #define CURLY_SETPAREN(paren, success) \
7621     if (paren) { \
7622         if (success) { \
7623             rex->offs[paren].start = HOPc(locinput, -1) - reginfo->strbeg; \
7624             rex->offs[paren].end = locinput - reginfo->strbeg; \
7625             if (paren > rex->lastparen) \
7626                 rex->lastparen = paren; \
7627             rex->lastcloseparen = paren; \
7628         } \
7629         else { \
7630             rex->offs[paren].end = -1; \
7631             rex->lastparen      = ST.lastparen; \
7632             rex->lastcloseparen = ST.lastcloseparen; \
7633         } \
7634     }
7635
7636         case STAR:              /*  /A*B/ where A is width 1 char */
7637             ST.paren = 0;
7638             ST.min = 0;
7639             ST.max = REG_INFTY;
7640             scan = NEXTOPER(scan);
7641             goto repeat;
7642
7643         case PLUS:              /*  /A+B/ where A is width 1 char */
7644             ST.paren = 0;
7645             ST.min = 1;
7646             ST.max = REG_INFTY;
7647             scan = NEXTOPER(scan);
7648             goto repeat;
7649
7650         case CURLYN:            /*  /(A){m,n}B/ where A is width 1 char */
7651             ST.paren = scan->flags;     /* Which paren to set */
7652             ST.lastparen      = rex->lastparen;
7653             ST.lastcloseparen = rex->lastcloseparen;
7654             if (ST.paren > maxopenparen)
7655                 maxopenparen = ST.paren;
7656             ST.min = ARG1(scan);  /* min to match */
7657             ST.max = ARG2(scan);  /* max to match */
7658             if (cur_eval && cur_eval->u.eval.close_paren &&
7659                 cur_eval->u.eval.close_paren == (U32)ST.paren) {
7660                 ST.min=1;
7661                 ST.max=1;
7662             }
7663             scan = regnext(NEXTOPER(scan) + NODE_STEP_REGNODE);
7664             goto repeat;
7665
7666         case CURLY:             /*  /A{m,n}B/ where A is width 1 char */
7667             ST.paren = 0;
7668             ST.min = ARG1(scan);  /* min to match */
7669             ST.max = ARG2(scan);  /* max to match */
7670             scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
7671           repeat:
7672             /*
7673             * Lookahead to avoid useless match attempts
7674             * when we know what character comes next.
7675             *
7676             * Used to only do .*x and .*?x, but now it allows
7677             * for )'s, ('s and (?{ ... })'s to be in the way
7678             * of the quantifier and the EXACT-like node.  -- japhy
7679             */
7680
7681             assert(ST.min <= ST.max);
7682             if (! HAS_TEXT(next) && ! JUMPABLE(next)) {
7683                 ST.c1 = ST.c2 = CHRTEST_VOID;
7684             }
7685             else {
7686                 regnode *text_node = next;
7687
7688                 if (! HAS_TEXT(text_node)) 
7689                     FIND_NEXT_IMPT(text_node);
7690
7691                 if (! HAS_TEXT(text_node))
7692                     ST.c1 = ST.c2 = CHRTEST_VOID;
7693                 else {
7694                     if ( PL_regkind[OP(text_node)] != EXACT ) {
7695                         ST.c1 = ST.c2 = CHRTEST_VOID;
7696                     }
7697                     else {
7698                     
7699                     /*  Currently we only get here when 
7700                         
7701                         PL_rekind[OP(text_node)] == EXACT
7702                     
7703                         if this changes back then the macro for IS_TEXT and 
7704                         friends need to change. */
7705                         if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
7706                            text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
7707                            reginfo))
7708                         {
7709                             sayNO;
7710                         }
7711                     }
7712                 }
7713             }
7714
7715             ST.A = scan;
7716             ST.B = next;
7717             if (minmod) {
7718                 char *li = locinput;
7719                 minmod = 0;
7720                 if (ST.min &&
7721                         regrepeat(rex, &li, ST.A, reginfo, ST.min, depth)
7722                             < ST.min)
7723                     sayNO;
7724                 SET_locinput(li);
7725                 ST.count = ST.min;
7726                 REGCP_SET(ST.cp);
7727                 if (ST.c1 == CHRTEST_VOID)
7728                     goto curly_try_B_min;
7729
7730                 ST.oldloc = locinput;
7731
7732                 /* set ST.maxpos to the furthest point along the
7733                  * string that could possibly match */
7734                 if  (ST.max == REG_INFTY) {
7735                     ST.maxpos = reginfo->strend - 1;
7736                     if (utf8_target)
7737                         while (UTF8_IS_CONTINUATION(*(U8*)ST.maxpos))
7738                             ST.maxpos--;
7739                 }
7740                 else if (utf8_target) {
7741                     int m = ST.max - ST.min;
7742                     for (ST.maxpos = locinput;
7743                          m >0 && ST.maxpos < reginfo->strend; m--)
7744                         ST.maxpos += UTF8SKIP(ST.maxpos);
7745                 }
7746                 else {
7747                     ST.maxpos = locinput + ST.max - ST.min;
7748                     if (ST.maxpos >= reginfo->strend)
7749                         ST.maxpos = reginfo->strend - 1;
7750                 }
7751                 goto curly_try_B_min_known;
7752
7753             }
7754             else {
7755                 /* avoid taking address of locinput, so it can remain
7756                  * a register var */
7757                 char *li = locinput;
7758                 ST.count = regrepeat(rex, &li, ST.A, reginfo, ST.max, depth);
7759                 if (ST.count < ST.min)
7760                     sayNO;
7761                 SET_locinput(li);
7762                 if ((ST.count > ST.min)
7763                     && (PL_regkind[OP(ST.B)] == EOL) && (OP(ST.B) != MEOL))
7764                 {
7765                     /* A{m,n} must come at the end of the string, there's
7766                      * no point in backing off ... */
7767                     ST.min = ST.count;
7768                     /* ...except that $ and \Z can match before *and* after
7769                        newline at the end.  Consider "\n\n" =~ /\n+\Z\n/.
7770                        We may back off by one in this case. */
7771                     if (UCHARAT(locinput - 1) == '\n' && OP(ST.B) != EOS)
7772                         ST.min--;
7773                 }
7774                 REGCP_SET(ST.cp);
7775                 goto curly_try_B_max;
7776             }
7777             /* NOTREACHED */
7778             NOT_REACHED; /* NOTREACHED */
7779
7780         case CURLY_B_min_known_fail:
7781             /* failed to find B in a non-greedy match where c1,c2 valid */
7782
7783             REGCP_UNWIND(ST.cp);
7784             if (ST.paren) {
7785                 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7786             }
7787             /* Couldn't or didn't -- move forward. */
7788             ST.oldloc = locinput;
7789             if (utf8_target)
7790                 locinput += UTF8SKIP(locinput);
7791             else
7792                 locinput++;
7793             ST.count++;
7794           curly_try_B_min_known:
7795              /* find the next place where 'B' could work, then call B */
7796             {
7797                 int n;
7798                 if (utf8_target) {
7799                     n = (ST.oldloc == locinput) ? 0 : 1;
7800                     if (ST.c1 == ST.c2) {
7801                         /* set n to utf8_distance(oldloc, locinput) */
7802                         while (locinput <= ST.maxpos
7803                               && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput)))
7804                         {
7805                             locinput += UTF8SKIP(locinput);
7806                             n++;
7807                         }
7808                     }
7809                     else {
7810                         /* set n to utf8_distance(oldloc, locinput) */
7811                         while (locinput <= ST.maxpos
7812                               && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
7813                               && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
7814                         {
7815                             locinput += UTF8SKIP(locinput);
7816                             n++;
7817                         }
7818                     }
7819                 }
7820                 else {  /* Not utf8_target */
7821                     if (ST.c1 == ST.c2) {
7822                         while (locinput <= ST.maxpos &&
7823                                UCHARAT(locinput) != ST.c1)
7824                             locinput++;
7825                     }
7826                     else {
7827                         while (locinput <= ST.maxpos
7828                                && UCHARAT(locinput) != ST.c1
7829                                && UCHARAT(locinput) != ST.c2)
7830                             locinput++;
7831                     }
7832                     n = locinput - ST.oldloc;
7833                 }
7834                 if (locinput > ST.maxpos)
7835                     sayNO;
7836                 if (n) {
7837                     /* In /a{m,n}b/, ST.oldloc is at "a" x m, locinput is
7838                      * at b; check that everything between oldloc and
7839                      * locinput matches */
7840                     char *li = ST.oldloc;
7841                     ST.count += n;
7842                     if (regrepeat(rex, &li, ST.A, reginfo, n, depth) < n)
7843                         sayNO;
7844                     assert(n == REG_INFTY || locinput == li);
7845                 }
7846                 CURLY_SETPAREN(ST.paren, ST.count);
7847                 if (cur_eval && cur_eval->u.eval.close_paren && 
7848                     cur_eval->u.eval.close_paren == (U32)ST.paren) {
7849                     goto fake_end;
7850                 }
7851                 PUSH_STATE_GOTO(CURLY_B_min_known, ST.B, locinput);
7852             }
7853             /* NOTREACHED */
7854             NOT_REACHED; /* NOTREACHED */
7855
7856         case CURLY_B_min_fail:
7857             /* failed to find B in a non-greedy match where c1,c2 invalid */
7858
7859             REGCP_UNWIND(ST.cp);
7860             if (ST.paren) {
7861                 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7862             }
7863             /* failed -- move forward one */
7864             {
7865                 char *li = locinput;
7866                 if (!regrepeat(rex, &li, ST.A, reginfo, 1, depth)) {
7867                     sayNO;
7868                 }
7869                 locinput = li;
7870             }
7871             {
7872                 ST.count++;
7873                 if (ST.count <= ST.max || (ST.max == REG_INFTY &&
7874                         ST.count > 0)) /* count overflow ? */
7875                 {
7876                   curly_try_B_min:
7877                     CURLY_SETPAREN(ST.paren, ST.count);
7878                     if (cur_eval && cur_eval->u.eval.close_paren &&
7879                         cur_eval->u.eval.close_paren == (U32)ST.paren) {
7880                         goto fake_end;
7881                     }
7882                     PUSH_STATE_GOTO(CURLY_B_min, ST.B, locinput);
7883                 }
7884             }
7885             sayNO;
7886             /* NOTREACHED */
7887             NOT_REACHED; /* NOTREACHED */
7888
7889           curly_try_B_max:
7890             /* a successful greedy match: now try to match B */
7891             if (cur_eval && cur_eval->u.eval.close_paren &&
7892                 cur_eval->u.eval.close_paren == (U32)ST.paren) {
7893                 goto fake_end;
7894             }
7895             {
7896                 bool could_match = locinput < reginfo->strend;
7897
7898                 /* If it could work, try it. */
7899                 if (ST.c1 != CHRTEST_VOID && could_match) {
7900                     if (! UTF8_IS_INVARIANT(UCHARAT(locinput)) && utf8_target)
7901                     {
7902                         could_match = memEQ(locinput,
7903                                             ST.c1_utf8,
7904                                             UTF8SKIP(locinput))
7905                                     || memEQ(locinput,
7906                                              ST.c2_utf8,
7907                                              UTF8SKIP(locinput));
7908                     }
7909                     else {
7910                         could_match = UCHARAT(locinput) == ST.c1
7911                                       || UCHARAT(locinput) == ST.c2;
7912                     }
7913                 }
7914                 if (ST.c1 == CHRTEST_VOID || could_match) {
7915                     CURLY_SETPAREN(ST.paren, ST.count);
7916                     PUSH_STATE_GOTO(CURLY_B_max, ST.B, locinput);
7917                     /* NOTREACHED */
7918                     NOT_REACHED; /* NOTREACHED */
7919                 }
7920             }
7921             /* FALLTHROUGH */
7922
7923         case CURLY_B_max_fail:
7924             /* failed to find B in a greedy match */
7925
7926             REGCP_UNWIND(ST.cp);
7927             if (ST.paren) {
7928                 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7929             }
7930             /*  back up. */
7931             if (--ST.count < ST.min)
7932                 sayNO;
7933             locinput = HOPc(locinput, -1);
7934             goto curly_try_B_max;
7935
7936 #undef ST
7937
7938         case END: /*  last op of main pattern  */
7939           fake_end:
7940             if (cur_eval) {
7941                 /* we've just finished A in /(??{A})B/; now continue with B */
7942
7943                 st->u.eval.prev_rex = rex_sv;           /* inner */
7944
7945                 /* Save *all* the positions. */
7946                 st->u.eval.cp = regcppush(rex, 0, maxopenparen);
7947                 rex_sv = cur_eval->u.eval.prev_rex;
7948                 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
7949                 SET_reg_curpm(rex_sv);
7950                 rex = ReANY(rex_sv);
7951                 rexi = RXi_GET(rex);
7952                 cur_curlyx = cur_eval->u.eval.prev_curlyx;
7953
7954                 REGCP_SET(st->u.eval.lastcp);
7955
7956                 /* Restore parens of the outer rex without popping the
7957                  * savestack */
7958                 S_regcp_restore(aTHX_ rex, cur_eval->u.eval.lastcp,
7959                                         &maxopenparen);
7960
7961                 st->u.eval.prev_eval = cur_eval;
7962                 cur_eval = cur_eval->u.eval.prev_eval;
7963                 DEBUG_EXECUTE_r(
7964                     PerlIO_printf(Perl_debug_log, "%*s  EVAL trying tail ... %"UVxf"\n",
7965                                       REPORT_CODE_OFF+depth*2, "",PTR2UV(cur_eval)););
7966                 if ( nochange_depth )
7967                     nochange_depth--;
7968
7969                 PUSH_YES_STATE_GOTO(EVAL_AB, st->u.eval.prev_eval->u.eval.B,
7970                                     locinput); /* match B */
7971             }
7972
7973             if (locinput < reginfo->till) {
7974                 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
7975                                       "%sMatch possible, but length=%ld is smaller than requested=%ld, failing!%s\n",
7976                                       PL_colors[4],
7977                                       (long)(locinput - startpos),
7978                                       (long)(reginfo->till - startpos),
7979                                       PL_colors[5]));
7980                                               
7981                 sayNO_SILENT;           /* Cannot match: too short. */
7982             }
7983             sayYES;                     /* Success! */
7984
7985         case SUCCEED: /* successful SUSPEND/UNLESSM/IFMATCH/CURLYM */
7986             DEBUG_EXECUTE_r(
7987             PerlIO_printf(Perl_debug_log,
7988                 "%*s  %ssubpattern success...%s\n",
7989                 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5]));
7990             sayYES;                     /* Success! */
7991
7992 #undef  ST
7993 #define ST st->u.ifmatch
7994
7995         {
7996             char *newstart;
7997
7998         case SUSPEND:   /* (?>A) */
7999             ST.wanted = 1;
8000             newstart = locinput;
8001             goto do_ifmatch;    
8002
8003         case UNLESSM:   /* -ve lookaround: (?!A), or with flags, (?<!A) */
8004             ST.wanted = 0;
8005             goto ifmatch_trivial_fail_test;
8006
8007         case IFMATCH:   /* +ve lookaround: (?=A), or with flags, (?<=A) */
8008             ST.wanted = 1;
8009           ifmatch_trivial_fail_test:
8010             if (scan->flags) {
8011                 char * const s = HOPBACKc(locinput, scan->flags);
8012                 if (!s) {
8013                     /* trivial fail */
8014                     if (logical) {
8015                         logical = 0;
8016                         sw = 1 - cBOOL(ST.wanted);
8017                     }
8018                     else if (ST.wanted)
8019                         sayNO;
8020                     next = scan + ARG(scan);
8021                     if (next == scan)
8022                         next = NULL;
8023                     break;
8024                 }
8025                 newstart = s;
8026             }
8027             else
8028                 newstart = locinput;
8029
8030           do_ifmatch:
8031             ST.me = scan;
8032             ST.logical = logical;
8033             logical = 0; /* XXX: reset state of logical once it has been saved into ST */
8034             
8035             /* execute body of (?...A) */
8036             PUSH_YES_STATE_GOTO(IFMATCH_A, NEXTOPER(NEXTOPER(scan)), newstart);
8037             /* NOTREACHED */
8038             NOT_REACHED; /* NOTREACHED */
8039         }
8040
8041         case IFMATCH_A_fail: /* body of (?...A) failed */
8042             ST.wanted = !ST.wanted;
8043             /* FALLTHROUGH */
8044
8045         case IFMATCH_A: /* body of (?...A) succeeded */
8046             if (ST.logical) {
8047                 sw = cBOOL(ST.wanted);
8048             }
8049             else if (!ST.wanted)
8050                 sayNO;
8051
8052             if (OP(ST.me) != SUSPEND) {
8053                 /* restore old position except for (?>...) */
8054                 locinput = st->locinput;
8055             }
8056             scan = ST.me + ARG(ST.me);
8057             if (scan == ST.me)
8058                 scan = NULL;
8059             continue; /* execute B */
8060
8061 #undef ST
8062
8063         case LONGJMP: /*  alternative with many branches compiles to
8064                        * (BRANCHJ; EXACT ...; LONGJMP ) x N */
8065             next = scan + ARG(scan);
8066             if (next == scan)
8067                 next = NULL;
8068             break;
8069
8070         case COMMIT:  /*  (*COMMIT)  */
8071             reginfo->cutpoint = reginfo->strend;
8072             /* FALLTHROUGH */
8073
8074         case PRUNE:   /*  (*PRUNE)   */
8075             if (scan->flags)
8076                 sv_yes_mark = sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8077             PUSH_STATE_GOTO(COMMIT_next, next, locinput);
8078             /* NOTREACHED */
8079             NOT_REACHED; /* NOTREACHED */
8080
8081         case COMMIT_next_fail:
8082             no_final = 1;    
8083             /* FALLTHROUGH */       
8084             sayNO;
8085             NOT_REACHED; /* NOTREACHED */
8086
8087         case OPFAIL:   /* (*FAIL)  */
8088             if (scan->flags)
8089                 sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8090             if (logical) {
8091                 /* deal with (?(?!)X|Y) properly,
8092                  * make sure we trigger the no branch
8093                  * of the trailing IFTHEN structure*/
8094                 sw= 0;
8095                 break;
8096             } else {
8097                 sayNO;
8098             }
8099             /* NOTREACHED */
8100             NOT_REACHED; /* NOTREACHED */
8101
8102 #define ST st->u.mark
8103         case MARKPOINT: /*  (*MARK:foo)  */
8104             ST.prev_mark = mark_state;
8105             ST.mark_name = sv_commit = sv_yes_mark 
8106                 = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8107             mark_state = st;
8108             ST.mark_loc = locinput;
8109             PUSH_YES_STATE_GOTO(MARKPOINT_next, next, locinput);
8110             /* NOTREACHED */
8111             NOT_REACHED; /* NOTREACHED */
8112
8113         case MARKPOINT_next:
8114             mark_state = ST.prev_mark;
8115             sayYES;
8116             /* NOTREACHED */
8117             NOT_REACHED; /* NOTREACHED */
8118
8119         case MARKPOINT_next_fail:
8120             if (popmark && sv_eq(ST.mark_name,popmark)) 
8121             {
8122                 if (ST.mark_loc > startpoint)
8123                     reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
8124                 popmark = NULL; /* we found our mark */
8125                 sv_commit = ST.mark_name;
8126
8127                 DEBUG_EXECUTE_r({
8128                         PerlIO_printf(Perl_debug_log,
8129                             "%*s  %ssetting cutpoint to mark:%"SVf"...%s\n",
8130                             REPORT_CODE_OFF+depth*2, "", 
8131                             PL_colors[4], SVfARG(sv_commit), PL_colors[5]);
8132                 });
8133             }
8134             mark_state = ST.prev_mark;
8135             sv_yes_mark = mark_state ? 
8136                 mark_state->u.mark.mark_name : NULL;
8137             sayNO;
8138             /* NOTREACHED */
8139             NOT_REACHED; /* NOTREACHED */
8140
8141         case SKIP:  /*  (*SKIP)  */
8142             if (!scan->flags) {
8143                 /* (*SKIP) : if we fail we cut here*/
8144                 ST.mark_name = NULL;
8145                 ST.mark_loc = locinput;
8146                 PUSH_STATE_GOTO(SKIP_next,next, locinput);
8147             } else {
8148                 /* (*SKIP:NAME) : if there is a (*MARK:NAME) fail where it was, 
8149                    otherwise do nothing.  Meaning we need to scan 
8150                  */
8151                 regmatch_state *cur = mark_state;
8152                 SV *find = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8153                 
8154                 while (cur) {
8155                     if ( sv_eq( cur->u.mark.mark_name, 
8156                                 find ) ) 
8157                     {
8158                         ST.mark_name = find;
8159                         PUSH_STATE_GOTO( SKIP_next, next, locinput);
8160                     }
8161                     cur = cur->u.mark.prev_mark;
8162                 }
8163             }    
8164             /* Didn't find our (*MARK:NAME) so ignore this (*SKIP:NAME) */
8165             break;    
8166
8167         case SKIP_next_fail:
8168             if (ST.mark_name) {
8169                 /* (*CUT:NAME) - Set up to search for the name as we 
8170                    collapse the stack*/
8171                 popmark = ST.mark_name;    
8172             } else {
8173                 /* (*CUT) - No name, we cut here.*/
8174                 if (ST.mark_loc > startpoint)
8175                     reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
8176                 /* but we set sv_commit to latest mark_name if there
8177                    is one so they can test to see how things lead to this
8178                    cut */    
8179                 if (mark_state) 
8180                     sv_commit=mark_state->u.mark.mark_name;                 
8181             } 
8182             no_final = 1; 
8183             sayNO;
8184             /* NOTREACHED */
8185             NOT_REACHED; /* NOTREACHED */
8186 #undef ST
8187
8188         case LNBREAK: /* \R */
8189             if ((n=is_LNBREAK_safe(locinput, reginfo->strend, utf8_target))) {
8190                 locinput += n;
8191             } else
8192                 sayNO;
8193             break;
8194
8195         default:
8196             PerlIO_printf(Perl_error_log, "%"UVxf" %d\n",
8197                           PTR2UV(scan), OP(scan));
8198             Perl_croak(aTHX_ "regexp memory corruption");
8199
8200         /* this is a point to jump to in order to increment
8201          * locinput by one character */
8202           increment_locinput:
8203             assert(!NEXTCHR_IS_EOS);
8204             if (utf8_target) {
8205                 locinput += PL_utf8skip[nextchr];
8206                 /* locinput is allowed to go 1 char off the end, but not 2+ */
8207                 if (locinput > reginfo->strend)
8208                     sayNO;
8209             }
8210             else
8211                 locinput++;
8212             break;
8213             
8214         } /* end switch */ 
8215
8216         /* switch break jumps here */
8217         scan = next; /* prepare to execute the next op and ... */
8218         continue;    /* ... jump back to the top, reusing st */
8219         /* NOTREACHED */
8220
8221       push_yes_state:
8222         /* push a state that backtracks on success */
8223         st->u.yes.prev_yes_state = yes_state;
8224         yes_state = st;
8225         /* FALLTHROUGH */
8226       push_state:
8227         /* push a new regex state, then continue at scan  */
8228         {
8229             regmatch_state *newst;
8230
8231             DEBUG_STACK_r({
8232                 regmatch_state *cur = st;
8233                 regmatch_state *curyes = yes_state;
8234                 int curd = depth;
8235                 regmatch_slab *slab = PL_regmatch_slab;
8236                 for (;curd > -1;cur--,curd--) {
8237                     if (cur < SLAB_FIRST(slab)) {
8238                         slab = slab->prev;
8239                         cur = SLAB_LAST(slab);
8240                     }
8241                     PerlIO_printf(Perl_error_log, "%*s#%-3d %-10s %s\n",
8242                         REPORT_CODE_OFF + 2 + depth * 2,"",
8243                         curd, PL_reg_name[cur->resume_state],
8244                         (curyes == cur) ? "yes" : ""
8245                     );
8246                     if (curyes == cur)
8247                         curyes = cur->u.yes.prev_yes_state;
8248                 }
8249             } else 
8250                 DEBUG_STATE_pp("push")
8251             );
8252             depth++;
8253             st->locinput = locinput;
8254             newst = st+1; 
8255             if (newst >  SLAB_LAST(PL_regmatch_slab))
8256                 newst = S_push_slab(aTHX);
8257             PL_regmatch_state = newst;
8258
8259             locinput = pushinput;
8260             st = newst;
8261             continue;
8262             /* NOTREACHED */
8263         }
8264     }
8265
8266     /*
8267     * We get here only if there's trouble -- normally "case END" is
8268     * the terminating point.
8269     */
8270     Perl_croak(aTHX_ "corrupted regexp pointers");
8271     /* NOTREACHED */
8272     sayNO;
8273     NOT_REACHED; /* NOTREACHED */
8274
8275   yes:
8276     if (yes_state) {
8277         /* we have successfully completed a subexpression, but we must now
8278          * pop to the state marked by yes_state and continue from there */
8279         assert(st != yes_state);
8280 #ifdef DEBUGGING
8281         while (st != yes_state) {
8282             st--;
8283             if (st < SLAB_FIRST(PL_regmatch_slab)) {
8284                 PL_regmatch_slab = PL_regmatch_slab->prev;
8285                 st = SLAB_LAST(PL_regmatch_slab);
8286             }
8287             DEBUG_STATE_r({
8288                 if (no_final) {
8289                     DEBUG_STATE_pp("pop (no final)");        
8290                 } else {
8291                     DEBUG_STATE_pp("pop (yes)");
8292                 }
8293             });
8294             depth--;
8295         }
8296 #else
8297         while (yes_state < SLAB_FIRST(PL_regmatch_slab)
8298             || yes_state > SLAB_LAST(PL_regmatch_slab))
8299         {
8300             /* not in this slab, pop slab */
8301             depth -= (st - SLAB_FIRST(PL_regmatch_slab) + 1);
8302             PL_regmatch_slab = PL_regmatch_slab->prev;
8303             st = SLAB_LAST(PL_regmatch_slab);
8304         }
8305         depth -= (st - yes_state);
8306 #endif
8307         st = yes_state;
8308         yes_state = st->u.yes.prev_yes_state;
8309         PL_regmatch_state = st;
8310         
8311         if (no_final)
8312             locinput= st->locinput;
8313         state_num = st->resume_state + no_final;
8314         goto reenter_switch;
8315     }
8316
8317     DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch successful!%s\n",
8318                           PL_colors[4], PL_colors[5]));
8319
8320     if (reginfo->info_aux_eval) {
8321         /* each successfully executed (?{...}) block does the equivalent of
8322          *   local $^R = do {...}
8323          * When popping the save stack, all these locals would be undone;
8324          * bypass this by setting the outermost saved $^R to the latest
8325          * value */
8326         /* I dont know if this is needed or works properly now.
8327          * see code related to PL_replgv elsewhere in this file.
8328          * Yves
8329          */
8330         if (oreplsv != GvSV(PL_replgv))
8331             sv_setsv(oreplsv, GvSV(PL_replgv));
8332     }
8333     result = 1;
8334     goto final_exit;
8335
8336   no:
8337     DEBUG_EXECUTE_r(
8338         PerlIO_printf(Perl_debug_log,
8339             "%*s  %sfailed...%s\n",
8340             REPORT_CODE_OFF+depth*2, "", 
8341             PL_colors[4], PL_colors[5])
8342         );
8343
8344   no_silent:
8345     if (no_final) {
8346         if (yes_state) {
8347             goto yes;
8348         } else {
8349             goto final_exit;
8350         }
8351     }    
8352     if (depth) {
8353         /* there's a previous state to backtrack to */
8354         st--;
8355         if (st < SLAB_FIRST(PL_regmatch_slab)) {
8356             PL_regmatch_slab = PL_regmatch_slab->prev;
8357             st = SLAB_LAST(PL_regmatch_slab);
8358         }
8359         PL_regmatch_state = st;
8360         locinput= st->locinput;
8361
8362         DEBUG_STATE_pp("pop");
8363         depth--;
8364         if (yes_state == st)
8365             yes_state = st->u.yes.prev_yes_state;
8366
8367         state_num = st->resume_state + 1; /* failure = success + 1 */
8368         goto reenter_switch;
8369     }
8370     result = 0;
8371
8372   final_exit:
8373     if (rex->intflags & PREGf_VERBARG_SEEN) {
8374         SV *sv_err = get_sv("REGERROR", 1);
8375         SV *sv_mrk = get_sv("REGMARK", 1);
8376         if (result) {
8377             sv_commit = &PL_sv_no;
8378             if (!sv_yes_mark) 
8379                 sv_yes_mark = &PL_sv_yes;
8380         } else {
8381             if (!sv_commit) 
8382                 sv_commit = &PL_sv_yes;
8383             sv_yes_mark = &PL_sv_no;
8384         }
8385         assert(sv_err);
8386         assert(sv_mrk);
8387         sv_setsv(sv_err, sv_commit);
8388         sv_setsv(sv_mrk, sv_yes_mark);
8389     }
8390
8391
8392     if (last_pushed_cv) {
8393         dSP;
8394         POP_MULTICALL;
8395         PERL_UNUSED_VAR(SP);
8396     }
8397
8398     assert(!result ||  locinput - reginfo->strbeg >= 0);
8399     return result ?  locinput - reginfo->strbeg : -1;
8400 }
8401
8402 /*
8403  - regrepeat - repeatedly match something simple, report how many
8404  *
8405  * What 'simple' means is a node which can be the operand of a quantifier like
8406  * '+', or {1,3}
8407  *
8408  * startposp - pointer a pointer to the start position.  This is updated
8409  *             to point to the byte following the highest successful
8410  *             match.
8411  * p         - the regnode to be repeatedly matched against.
8412  * reginfo   - struct holding match state, such as strend
8413  * max       - maximum number of things to match.
8414  * depth     - (for debugging) backtracking depth.
8415  */
8416 STATIC I32
8417 S_regrepeat(pTHX_ regexp *prog, char **startposp, const regnode *p,
8418             regmatch_info *const reginfo, I32 max, int depth)
8419 {
8420     char *scan;     /* Pointer to current position in target string */
8421     I32 c;
8422     char *loceol = reginfo->strend;   /* local version */
8423     I32 hardcount = 0;  /* How many matches so far */
8424     bool utf8_target = reginfo->is_utf8_target;
8425     unsigned int to_complement = 0;  /* Invert the result? */
8426     UV utf8_flags;
8427     _char_class_number classnum;
8428 #ifndef DEBUGGING
8429     PERL_UNUSED_ARG(depth);
8430 #endif
8431
8432     PERL_ARGS_ASSERT_REGREPEAT;
8433
8434     scan = *startposp;
8435     if (max == REG_INFTY)
8436         max = I32_MAX;
8437     else if (! utf8_target && loceol - scan > max)
8438         loceol = scan + max;
8439
8440     /* Here, for the case of a non-UTF-8 target we have adjusted <loceol> down
8441      * to the maximum of how far we should go in it (leaving it set to the real
8442      * end, if the maximum permissible would take us beyond that).  This allows
8443      * us to make the loop exit condition that we haven't gone past <loceol> to
8444      * also mean that we haven't exceeded the max permissible count, saving a
8445      * test each time through the loop.  But it assumes that the OP matches a
8446      * single byte, which is true for most of the OPs below when applied to a
8447      * non-UTF-8 target.  Those relatively few OPs that don't have this
8448      * characteristic will have to compensate.
8449      *
8450      * There is no adjustment for UTF-8 targets, as the number of bytes per
8451      * character varies.  OPs will have to test both that the count is less
8452      * than the max permissible (using <hardcount> to keep track), and that we
8453      * are still within the bounds of the string (using <loceol>.  A few OPs
8454      * match a single byte no matter what the encoding.  They can omit the max
8455      * test if, for the UTF-8 case, they do the adjustment that was skipped
8456      * above.
8457      *
8458      * Thus, the code above sets things up for the common case; and exceptional
8459      * cases need extra work; the common case is to make sure <scan> doesn't
8460      * go past <loceol>, and for UTF-8 to also use <hardcount> to make sure the
8461      * count doesn't exceed the maximum permissible */
8462
8463     switch (OP(p)) {
8464     case REG_ANY:
8465         if (utf8_target) {
8466             while (scan < loceol && hardcount < max && *scan != '\n') {
8467                 scan += UTF8SKIP(scan);
8468                 hardcount++;
8469             }
8470         } else {
8471             while (scan < loceol && *scan != '\n')
8472                 scan++;
8473         }
8474         break;
8475     case SANY:
8476         if (utf8_target) {
8477             while (scan < loceol && hardcount < max) {
8478                 scan += UTF8SKIP(scan);
8479                 hardcount++;
8480             }
8481         }
8482         else
8483             scan = loceol;
8484         break;
8485     case EXACTL:
8486         _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8487         if (utf8_target && UTF8_IS_ABOVE_LATIN1(*scan)) {
8488             _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(scan, loceol);
8489         }
8490         /* FALLTHROUGH */
8491     case EXACT:
8492         assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
8493
8494         c = (U8)*STRING(p);
8495
8496         /* Can use a simple loop if the pattern char to match on is invariant
8497          * under UTF-8, or both target and pattern aren't UTF-8.  Note that we
8498          * can use UTF8_IS_INVARIANT() even if the pattern isn't UTF-8, as it's
8499          * true iff it doesn't matter if the argument is in UTF-8 or not */
8500         if (UTF8_IS_INVARIANT(c) || (! utf8_target && ! reginfo->is_utf8_pat)) {
8501             if (utf8_target && loceol - scan > max) {
8502                 /* We didn't adjust <loceol> because is UTF-8, but ok to do so,
8503                  * since here, to match at all, 1 char == 1 byte */
8504                 loceol = scan + max;
8505             }
8506             while (scan < loceol && UCHARAT(scan) == c) {
8507                 scan++;
8508             }
8509         }
8510         else if (reginfo->is_utf8_pat) {
8511             if (utf8_target) {
8512                 STRLEN scan_char_len;
8513
8514                 /* When both target and pattern are UTF-8, we have to do
8515                  * string EQ */
8516                 while (hardcount < max
8517                        && scan < loceol
8518                        && (scan_char_len = UTF8SKIP(scan)) <= STR_LEN(p)
8519                        && memEQ(scan, STRING(p), scan_char_len))
8520                 {
8521                     scan += scan_char_len;
8522                     hardcount++;
8523                 }
8524             }
8525             else if (! UTF8_IS_ABOVE_LATIN1(c)) {
8526
8527                 /* Target isn't utf8; convert the character in the UTF-8
8528                  * pattern to non-UTF8, and do a simple loop */
8529                 c = EIGHT_BIT_UTF8_TO_NATIVE(c, *(STRING(p) + 1));
8530                 while (scan < loceol && UCHARAT(scan) == c) {
8531                     scan++;
8532                 }
8533             } /* else pattern char is above Latin1, can't possibly match the
8534                  non-UTF-8 target */
8535         }
8536         else {
8537
8538             /* Here, the string must be utf8; pattern isn't, and <c> is
8539              * different in utf8 than not, so can't compare them directly.
8540              * Outside the loop, find the two utf8 bytes that represent c, and
8541              * then look for those in sequence in the utf8 string */
8542             U8 high = UTF8_TWO_BYTE_HI(c);
8543             U8 low = UTF8_TWO_BYTE_LO(c);
8544
8545             while (hardcount < max
8546                     && scan + 1 < loceol
8547                     && UCHARAT(scan) == high
8548                     && UCHARAT(scan + 1) == low)
8549             {
8550                 scan += 2;
8551                 hardcount++;
8552             }
8553         }
8554         break;
8555
8556     case EXACTFA_NO_TRIE:   /* This node only generated for non-utf8 patterns */
8557         assert(! reginfo->is_utf8_pat);
8558         /* FALLTHROUGH */
8559     case EXACTFA:
8560         utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
8561         goto do_exactf;
8562
8563     case EXACTFL:
8564         _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8565         utf8_flags = FOLDEQ_LOCALE;
8566         goto do_exactf;
8567
8568     case EXACTF:   /* This node only generated for non-utf8 patterns */
8569         assert(! reginfo->is_utf8_pat);
8570         utf8_flags = 0;
8571         goto do_exactf;
8572
8573     case EXACTFLU8:
8574         if (! utf8_target) {
8575             break;
8576         }
8577         utf8_flags =  FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
8578                                     | FOLDEQ_S2_FOLDS_SANE;
8579         goto do_exactf;
8580
8581     case EXACTFU_SS:
8582     case EXACTFU:
8583         utf8_flags = reginfo->is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
8584
8585       do_exactf: {
8586         int c1, c2;
8587         U8 c1_utf8[UTF8_MAXBYTES+1], c2_utf8[UTF8_MAXBYTES+1];
8588
8589         assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
8590
8591         if (S_setup_EXACTISH_ST_c1_c2(aTHX_ p, &c1, c1_utf8, &c2, c2_utf8,
8592                                         reginfo))
8593         {
8594             if (c1 == CHRTEST_VOID) {
8595                 /* Use full Unicode fold matching */
8596                 char *tmpeol = reginfo->strend;
8597                 STRLEN pat_len = reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1;
8598                 while (hardcount < max
8599                         && foldEQ_utf8_flags(scan, &tmpeol, 0, utf8_target,
8600                                              STRING(p), NULL, pat_len,
8601                                              reginfo->is_utf8_pat, utf8_flags))
8602                 {
8603                     scan = tmpeol;
8604                     tmpeol = reginfo->strend;
8605                     hardcount++;
8606                 }
8607             }
8608             else if (utf8_target) {
8609                 if (c1 == c2) {
8610                     while (scan < loceol
8611                            && hardcount < max
8612                            && memEQ(scan, c1_utf8, UTF8SKIP(scan)))
8613                     {
8614                         scan += UTF8SKIP(scan);
8615                         hardcount++;
8616                     }
8617                 }
8618                 else {
8619                     while (scan < loceol
8620                            && hardcount < max
8621                            && (memEQ(scan, c1_utf8, UTF8SKIP(scan))
8622                                || memEQ(scan, c2_utf8, UTF8SKIP(scan))))
8623                     {
8624                         scan += UTF8SKIP(scan);
8625                         hardcount++;
8626                     }
8627                 }
8628             }
8629             else if (c1 == c2) {
8630                 while (scan < loceol && UCHARAT(scan) == c1) {
8631                     scan++;
8632                 }
8633             }
8634             else {
8635                 while (scan < loceol &&
8636                     (UCHARAT(scan) == c1 || UCHARAT(scan) == c2))
8637                 {
8638                     scan++;
8639                 }
8640             }
8641         }
8642         break;
8643     }
8644     case ANYOFL:
8645         _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8646
8647         if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(p)) && ! IN_UTF8_CTYPE_LOCALE) {
8648             Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
8649         }
8650         /* FALLTHROUGH */
8651     case ANYOFD:
8652     case ANYOF:
8653         if (utf8_target) {
8654             while (hardcount < max
8655                    && scan < loceol
8656                    && reginclass(prog, p, (U8*)scan, (U8*) loceol, utf8_target))
8657             {
8658                 scan += UTF8SKIP(scan);
8659                 hardcount++;
8660             }
8661         } else {
8662             while (scan < loceol && REGINCLASS(prog, p, (U8*)scan))
8663                 scan++;
8664         }
8665         break;
8666
8667     /* The argument (FLAGS) to all the POSIX node types is the class number */
8668
8669     case NPOSIXL:
8670         to_complement = 1;
8671         /* FALLTHROUGH */
8672
8673     case POSIXL:
8674         _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8675         if (! utf8_target) {
8676             while (scan < loceol && to_complement ^ cBOOL(isFOO_lc(FLAGS(p),
8677                                                                    *scan)))
8678             {
8679                 scan++;
8680             }
8681         } else {
8682             while (hardcount < max && scan < loceol
8683                    && to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(p),
8684                                                                   (U8 *) scan)))
8685             {
8686                 scan += UTF8SKIP(scan);
8687                 hardcount++;
8688             }
8689         }
8690         break;
8691
8692     case POSIXD:
8693         if (utf8_target) {
8694             goto utf8_posix;
8695         }
8696         /* FALLTHROUGH */
8697
8698     case POSIXA:
8699         if (utf8_target && loceol - scan > max) {
8700
8701             /* We didn't adjust <loceol> at the beginning of this routine
8702              * because is UTF-8, but it is actually ok to do so, since here, to
8703              * match, 1 char == 1 byte. */
8704             loceol = scan + max;
8705         }
8706         while (scan < loceol && _generic_isCC_A((U8) *scan, FLAGS(p))) {
8707             scan++;
8708         }
8709         break;
8710
8711     case NPOSIXD:
8712         if (utf8_target) {
8713             to_complement = 1;
8714             goto utf8_posix;
8715         }
8716         /* FALLTHROUGH */
8717
8718     case NPOSIXA:
8719         if (! utf8_target) {
8720             while (scan < loceol && ! _generic_isCC_A((U8) *scan, FLAGS(p))) {
8721                 scan++;
8722             }
8723         }
8724         else {
8725
8726             /* The complement of something that matches only ASCII matches all
8727              * non-ASCII, plus everything in ASCII that isn't in the class. */
8728             while (hardcount < max && scan < loceol
8729                    && (! isASCII_utf8(scan)
8730                        || ! _generic_isCC_A((U8) *scan, FLAGS(p))))
8731             {
8732                 scan += UTF8SKIP(scan);
8733                 hardcount++;
8734             }
8735         }
8736         break;
8737
8738     case NPOSIXU:
8739         to_complement = 1;
8740         /* FALLTHROUGH */
8741
8742     case POSIXU:
8743         if (! utf8_target) {
8744             while (scan < loceol && to_complement
8745                                 ^ cBOOL(_generic_isCC((U8) *scan, FLAGS(p))))
8746             {
8747                 scan++;
8748             }
8749         }
8750         else {
8751           utf8_posix:
8752             classnum = (_char_class_number) FLAGS(p);
8753             if (classnum < _FIRST_NON_SWASH_CC) {
8754
8755                 /* Here, a swash is needed for above-Latin1 code points.
8756                  * Process as many Latin1 code points using the built-in rules.
8757                  * Go to another loop to finish processing upon encountering
8758                  * the first Latin1 code point.  We could do that in this loop
8759                  * as well, but the other way saves having to test if the swash
8760                  * has been loaded every time through the loop: extra space to
8761                  * save a test. */
8762                 while (hardcount < max && scan < loceol) {
8763                     if (UTF8_IS_INVARIANT(*scan)) {
8764                         if (! (to_complement ^ cBOOL(_generic_isCC((U8) *scan,
8765                                                                    classnum))))
8766                         {
8767                             break;
8768                         }
8769                         scan++;
8770                     }
8771                     else if (UTF8_IS_DOWNGRADEABLE_START(*scan)) {
8772                         if (! (to_complement
8773                               ^ cBOOL(_generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(*scan,
8774                                                                      *(scan + 1)),
8775                                                     classnum))))
8776                         {
8777                             break;
8778                         }
8779                         scan += 2;
8780                     }
8781                     else {
8782                         goto found_above_latin1;
8783                     }
8784
8785                     hardcount++;
8786                 }
8787             }
8788             else {
8789                 /* For these character classes, the knowledge of how to handle
8790                  * every code point is compiled in to Perl via a macro.  This
8791                  * code is written for making the loops as tight as possible.
8792                  * It could be refactored to save space instead */
8793                 switch (classnum) {
8794                     case _CC_ENUM_SPACE:
8795                         while (hardcount < max
8796                                && scan < loceol
8797                                && (to_complement ^ cBOOL(isSPACE_utf8(scan))))
8798                         {
8799                             scan += UTF8SKIP(scan);
8800                             hardcount++;
8801                         }
8802                         break;
8803                     case _CC_ENUM_BLANK:
8804                         while (hardcount < max
8805                                && scan < loceol
8806                                && (to_complement ^ cBOOL(isBLANK_utf8(scan))))
8807                         {
8808                             scan += UTF8SKIP(scan);
8809                             hardcount++;
8810                         }
8811                         break;
8812                     case _CC_ENUM_XDIGIT:
8813                         while (hardcount < max
8814                                && scan < loceol
8815                                && (to_complement ^ cBOOL(isXDIGIT_utf8(scan))))
8816                         {
8817                             scan += UTF8SKIP(scan);
8818                             hardcount++;
8819                         }
8820                         break;
8821                     case _CC_ENUM_VERTSPACE:
8822                         while (hardcount < max
8823                                && scan < loceol
8824                                && (to_complement ^ cBOOL(isVERTWS_utf8(scan))))
8825                         {
8826                             scan += UTF8SKIP(scan);
8827                             hardcount++;
8828                         }
8829                         break;
8830                     case _CC_ENUM_CNTRL:
8831                         while (hardcount < max
8832                                && scan < loceol
8833                                && (to_complement ^ cBOOL(isCNTRL_utf8(scan))))
8834                         {
8835                             scan += UTF8SKIP(scan);
8836                             hardcount++;
8837                         }
8838                         break;
8839                     default:
8840                         Perl_croak(aTHX_ "panic: regrepeat() node %d='%s' has an unexpected character class '%d'", OP(p), PL_reg_name[OP(p)], classnum);
8841                 }
8842             }
8843         }
8844         break;
8845
8846       found_above_latin1:   /* Continuation of POSIXU and NPOSIXU */
8847
8848         /* Load the swash if not already present */
8849         if (! PL_utf8_swash_ptrs[classnum]) {
8850             U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
8851             PL_utf8_swash_ptrs[classnum] = _core_swash_init(
8852                                         "utf8",
8853                                         "",
8854                                         &PL_sv_undef, 1, 0,
8855                                         PL_XPosix_ptrs[classnum], &flags);
8856         }
8857
8858         while (hardcount < max && scan < loceol
8859                && to_complement ^ cBOOL(_generic_utf8(
8860                                        classnum,
8861                                        scan,
8862                                        swash_fetch(PL_utf8_swash_ptrs[classnum],
8863                                                    (U8 *) scan,
8864                                                    TRUE))))
8865         {
8866             scan += UTF8SKIP(scan);
8867             hardcount++;
8868         }
8869         break;
8870
8871     case LNBREAK:
8872         if (utf8_target) {
8873             while (hardcount < max && scan < loceol &&
8874                     (c=is_LNBREAK_utf8_safe(scan, loceol))) {
8875                 scan += c;
8876                 hardcount++;
8877             }
8878         } else {
8879             /* LNBREAK can match one or two latin chars, which is ok, but we
8880              * have to use hardcount in this situation, and throw away the
8881              * adjustment to <loceol> done before the switch statement */
8882             loceol = reginfo->strend;
8883             while (scan < loceol && (c=is_LNBREAK_latin1_safe(scan, loceol))) {
8884                 scan+=c;
8885                 hardcount++;
8886             }
8887         }
8888         break;
8889
8890     case BOUNDL:
8891     case NBOUNDL:
8892         _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8893         /* FALLTHROUGH */
8894     case BOUND:
8895     case BOUNDA:
8896     case BOUNDU:
8897     case EOS:
8898     case GPOS:
8899     case KEEPS:
8900     case NBOUND:
8901     case NBOUNDA:
8902     case NBOUNDU:
8903     case OPFAIL:
8904     case SBOL:
8905     case SEOL:
8906         /* These are all 0 width, so match right here or not at all. */
8907         break;
8908
8909     default:
8910         Perl_croak(aTHX_ "panic: regrepeat() called with unrecognized node type %d='%s'", OP(p), PL_reg_name[OP(p)]);
8911         /* NOTREACHED */
8912         NOT_REACHED; /* NOTREACHED */
8913
8914     }
8915
8916     if (hardcount)
8917         c = hardcount;
8918     else
8919         c = scan - *startposp;
8920     *startposp = scan;
8921
8922     DEBUG_r({
8923         GET_RE_DEBUG_FLAGS_DECL;
8924         DEBUG_EXECUTE_r({
8925             SV * const prop = sv_newmortal();
8926             regprop(prog, prop, p, reginfo, NULL);
8927             PerlIO_printf(Perl_debug_log,
8928                         "%*s  %s can match %"IVdf" times out of %"IVdf"...\n",
8929                         REPORT_CODE_OFF + depth*2, "", SvPVX_const(prop),(IV)c,(IV)max);
8930         });
8931     });
8932
8933     return(c);
8934 }
8935
8936
8937 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
8938 /*
8939 - regclass_swash - prepare the utf8 swash.  Wraps the shared core version to
8940 create a copy so that changes the caller makes won't change the shared one.
8941 If <altsvp> is non-null, will return NULL in it, for back-compat.
8942  */
8943 SV *
8944 Perl_regclass_swash(pTHX_ const regexp *prog, const regnode* node, bool doinit, SV** listsvp, SV **altsvp)
8945 {
8946     PERL_ARGS_ASSERT_REGCLASS_SWASH;
8947
8948     if (altsvp) {
8949         *altsvp = NULL;
8950     }
8951
8952     return newSVsv(_get_regclass_nonbitmap_data(prog, node, doinit, listsvp, NULL, NULL));
8953 }
8954
8955 #endif /* !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION) */
8956
8957 /*
8958  - reginclass - determine if a character falls into a character class
8959  
8960   n is the ANYOF-type regnode
8961   p is the target string
8962   p_end points to one byte beyond the end of the target string
8963   utf8_target tells whether p is in UTF-8.
8964
8965   Returns true if matched; false otherwise.
8966
8967   Note that this can be a synthetic start class, a combination of various
8968   nodes, so things you think might be mutually exclusive, such as locale,
8969   aren't.  It can match both locale and non-locale
8970
8971  */
8972
8973 STATIC bool
8974 S_reginclass(pTHX_ regexp * const prog, const regnode * const n, const U8* const p, const U8* const p_end, const bool utf8_target)
8975 {
8976     dVAR;
8977     const char flags = ANYOF_FLAGS(n);
8978     bool match = FALSE;
8979     UV c = *p;
8980
8981     PERL_ARGS_ASSERT_REGINCLASS;
8982
8983     /* If c is not already the code point, get it.  Note that
8984      * UTF8_IS_INVARIANT() works even if not in UTF-8 */
8985     if (! UTF8_IS_INVARIANT(c) && utf8_target) {
8986         STRLEN c_len = 0;
8987         c = utf8n_to_uvchr(p, p_end - p, &c_len,
8988                 (UTF8_ALLOW_DEFAULT & UTF8_ALLOW_ANYUV)
8989                 | UTF8_ALLOW_FFFF | UTF8_CHECK_ONLY);
8990                 /* see [perl #37836] for UTF8_ALLOW_ANYUV; [perl #38293] for
8991                  * UTF8_ALLOW_FFFF */
8992         if (c_len == (STRLEN)-1)
8993             Perl_croak(aTHX_ "Malformed UTF-8 character (fatal)");
8994         if (c > 255 && OP(n) == ANYOFL && ! ANYOFL_UTF8_LOCALE_REQD(flags)) {
8995             _CHECK_AND_OUTPUT_WIDE_LOCALE_CP_MSG(c);
8996         }
8997     }
8998
8999     /* If this character is potentially in the bitmap, check it */
9000     if (c < NUM_ANYOF_CODE_POINTS) {
9001         if (ANYOF_BITMAP_TEST(n, c))
9002             match = TRUE;
9003         else if ((flags
9004                 & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
9005                   && OP(n) == ANYOFD
9006                   && ! utf8_target
9007                   && ! isASCII(c))
9008         {
9009             match = TRUE;
9010         }
9011         else if (flags & ANYOF_LOCALE_FLAGS) {
9012             if ((flags & ANYOFL_FOLD)
9013                 && c < 256
9014                 && ANYOF_BITMAP_TEST(n, PL_fold_locale[c]))
9015             {
9016                 match = TRUE;
9017             }
9018             else if (ANYOF_POSIXL_TEST_ANY_SET(n)
9019                      && c < 256
9020             ) {
9021
9022                 /* The data structure is arranged so bits 0, 2, 4, ... are set
9023                  * if the class includes the Posix character class given by
9024                  * bit/2; and 1, 3, 5, ... are set if the class includes the
9025                  * complemented Posix class given by int(bit/2).  So we loop
9026                  * through the bits, each time changing whether we complement
9027                  * the result or not.  Suppose for the sake of illustration
9028                  * that bits 0-3 mean respectively, \w, \W, \s, \S.  If bit 0
9029                  * is set, it means there is a match for this ANYOF node if the
9030                  * character is in the class given by the expression (0 / 2 = 0
9031                  * = \w).  If it is in that class, isFOO_lc() will return 1,
9032                  * and since 'to_complement' is 0, the result will stay TRUE,
9033                  * and we exit the loop.  Suppose instead that bit 0 is 0, but
9034                  * bit 1 is 1.  That means there is a match if the character
9035                  * matches \W.  We won't bother to call isFOO_lc() on bit 0,
9036                  * but will on bit 1.  On the second iteration 'to_complement'
9037                  * will be 1, so the exclusive or will reverse things, so we
9038                  * are testing for \W.  On the third iteration, 'to_complement'
9039                  * will be 0, and we would be testing for \s; the fourth
9040                  * iteration would test for \S, etc.
9041                  *
9042                  * Note that this code assumes that all the classes are closed
9043                  * under folding.  For example, if a character matches \w, then
9044                  * its fold does too; and vice versa.  This should be true for
9045                  * any well-behaved locale for all the currently defined Posix
9046                  * classes, except for :lower: and :upper:, which are handled
9047                  * by the pseudo-class :cased: which matches if either of the
9048                  * other two does.  To get rid of this assumption, an outer
9049                  * loop could be used below to iterate over both the source
9050                  * character, and its fold (if different) */
9051
9052                 int count = 0;
9053                 int to_complement = 0;
9054
9055                 while (count < ANYOF_MAX) {
9056                     if (ANYOF_POSIXL_TEST(n, count)
9057                         && to_complement ^ cBOOL(isFOO_lc(count/2, (U8) c)))
9058                     {
9059                         match = TRUE;
9060                         break;
9061                     }
9062                     count++;
9063                     to_complement ^= 1;
9064                 }
9065             }
9066         }
9067     }
9068
9069
9070     /* If the bitmap didn't (or couldn't) match, and something outside the
9071      * bitmap could match, try that. */
9072     if (!match) {
9073         if (c >= NUM_ANYOF_CODE_POINTS
9074             && (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP))
9075         {
9076             match = TRUE;       /* Everything above the bitmap matches */
9077         }
9078             /* Here doesn't match everything above the bitmap.  If there is
9079              * some information available beyond the bitmap, we may find a
9080              * match in it.  If so, this is most likely because the code point
9081              * is outside the bitmap range.  But rarely, it could be because of
9082              * some other reason.  If so, various flags are set to indicate
9083              * this possibility.  On ANYOFD nodes, there may be matches that
9084              * happen only when the target string is UTF-8; or for other node
9085              * types, because runtime lookup is needed, regardless of the
9086              * UTF-8ness of the target string.  Finally, under /il, there may
9087              * be some matches only possible if the locale is a UTF-8 one. */
9088         else if (    ARG(n) != ANYOF_ONLY_HAS_BITMAP
9089                  && (   c >= NUM_ANYOF_CODE_POINTS
9090                      || (   (flags & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)
9091                          && (   UNLIKELY(OP(n) != ANYOFD)
9092                              || (utf8_target && ! isASCII_uni(c)
9093 #                               if NUM_ANYOF_CODE_POINTS > 256
9094                                                                  && c < 256
9095 #                               endif
9096                                 )))
9097                      || (   ANYOFL_SOME_FOLDS_ONLY_IN_UTF8_LOCALE(flags)
9098                          && IN_UTF8_CTYPE_LOCALE)))
9099         {
9100             SV* only_utf8_locale = NULL;
9101             SV * const sw = _get_regclass_nonbitmap_data(prog, n, TRUE, 0,
9102                                                        &only_utf8_locale, NULL);
9103             if (sw) {
9104                 U8 utf8_buffer[2];
9105                 U8 * utf8_p;
9106                 if (utf8_target) {
9107                     utf8_p = (U8 *) p;
9108                 } else { /* Convert to utf8 */
9109                     utf8_p = utf8_buffer;
9110                     append_utf8_from_native_byte(*p, &utf8_p);
9111                     utf8_p = utf8_buffer;
9112                 }
9113
9114                 if (swash_fetch(sw, utf8_p, TRUE)) {
9115                     match = TRUE;
9116                 }
9117             }
9118             if (! match && only_utf8_locale && IN_UTF8_CTYPE_LOCALE) {
9119                 match = _invlist_contains_cp(only_utf8_locale, c);
9120             }
9121         }
9122
9123         if (UNICODE_IS_SUPER(c)
9124             && (flags
9125                & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
9126             && OP(n) != ANYOFD
9127             && ckWARN_d(WARN_NON_UNICODE))
9128         {
9129             Perl_warner(aTHX_ packWARN(WARN_NON_UNICODE),
9130                 "Matched non-Unicode code point 0x%04"UVXf" against Unicode property; may not be portable", c);
9131         }
9132     }
9133
9134 #if ANYOF_INVERT != 1
9135     /* Depending on compiler optimization cBOOL takes time, so if don't have to
9136      * use it, don't */
9137 #   error ANYOF_INVERT needs to be set to 1, or guarded with cBOOL below,
9138 #endif
9139
9140     /* The xor complements the return if to invert: 1^1 = 0, 1^0 = 1 */
9141     return (flags & ANYOF_INVERT) ^ match;
9142 }
9143
9144 STATIC U8 *
9145 S_reghop3(U8 *s, SSize_t off, const U8* lim)
9146 {
9147     /* return the position 'off' UTF-8 characters away from 's', forward if
9148      * 'off' >= 0, backwards if negative.  But don't go outside of position
9149      * 'lim', which better be < s  if off < 0 */
9150
9151     PERL_ARGS_ASSERT_REGHOP3;
9152
9153     if (off >= 0) {
9154         while (off-- && s < lim) {
9155             /* XXX could check well-formedness here */
9156             s += UTF8SKIP(s);
9157         }
9158     }
9159     else {
9160         while (off++ && s > lim) {
9161             s--;
9162             if (UTF8_IS_CONTINUED(*s)) {
9163                 while (s > lim && UTF8_IS_CONTINUATION(*s))
9164                     s--;
9165                 if (! UTF8_IS_START(*s)) {
9166                     Perl_croak_nocontext("Malformed UTF-8 character (fatal)");
9167                 }
9168             }
9169             /* XXX could check well-formedness here */
9170         }
9171     }
9172     return s;
9173 }
9174
9175 STATIC U8 *
9176 S_reghop4(U8 *s, SSize_t off, const U8* llim, const U8* rlim)
9177 {
9178     PERL_ARGS_ASSERT_REGHOP4;
9179
9180     if (off >= 0) {
9181         while (off-- && s < rlim) {
9182             /* XXX could check well-formedness here */
9183             s += UTF8SKIP(s);
9184         }
9185     }
9186     else {
9187         while (off++ && s > llim) {
9188             s--;
9189             if (UTF8_IS_CONTINUED(*s)) {
9190                 while (s > llim && UTF8_IS_CONTINUATION(*s))
9191                     s--;
9192                 if (! UTF8_IS_START(*s)) {
9193                     Perl_croak_nocontext("Malformed UTF-8 character (fatal)");
9194                 }
9195             }
9196             /* XXX could check well-formedness here */
9197         }
9198     }
9199     return s;
9200 }
9201
9202 /* like reghop3, but returns NULL on overrun, rather than returning last
9203  * char pos */
9204
9205 STATIC U8 *
9206 S_reghopmaybe3(U8* s, SSize_t off, const U8* lim)
9207 {
9208     PERL_ARGS_ASSERT_REGHOPMAYBE3;
9209
9210     if (off >= 0) {
9211         while (off-- && s < lim) {
9212             /* XXX could check well-formedness here */
9213             s += UTF8SKIP(s);
9214         }
9215         if (off >= 0)
9216             return NULL;
9217     }
9218     else {
9219         while (off++ && s > lim) {
9220             s--;
9221             if (UTF8_IS_CONTINUED(*s)) {
9222                 while (s > lim && UTF8_IS_CONTINUATION(*s))
9223                     s--;
9224                 if (! UTF8_IS_START(*s)) {
9225                     Perl_croak_nocontext("Malformed UTF-8 character (fatal)");
9226                 }
9227             }
9228             /* XXX could check well-formedness here */
9229         }
9230         if (off <= 0)
9231             return NULL;
9232     }
9233     return s;
9234 }
9235
9236
9237 /* when executing a regex that may have (?{}), extra stuff needs setting
9238    up that will be visible to the called code, even before the current
9239    match has finished. In particular:
9240
9241    * $_ is localised to the SV currently being matched;
9242    * pos($_) is created if necessary, ready to be updated on each call-out
9243      to code;
9244    * a fake PMOP is created that can be set to PL_curpm (normally PL_curpm
9245      isn't set until the current pattern is successfully finished), so that
9246      $1 etc of the match-so-far can be seen;
9247    * save the old values of subbeg etc of the current regex, and  set then
9248      to the current string (again, this is normally only done at the end
9249      of execution)
9250 */
9251
9252 static void
9253 S_setup_eval_state(pTHX_ regmatch_info *const reginfo)
9254 {
9255     MAGIC *mg;
9256     regexp *const rex = ReANY(reginfo->prog);
9257     regmatch_info_aux_eval *eval_state = reginfo->info_aux_eval;
9258
9259     eval_state->rex = rex;
9260
9261     if (reginfo->sv) {
9262         /* Make $_ available to executed code. */
9263         if (reginfo->sv != DEFSV) {
9264             SAVE_DEFSV;
9265             DEFSV_set(reginfo->sv);
9266         }
9267
9268         if (!(mg = mg_find_mglob(reginfo->sv))) {
9269             /* prepare for quick setting of pos */
9270             mg = sv_magicext_mglob(reginfo->sv);
9271             mg->mg_len = -1;
9272         }
9273         eval_state->pos_magic = mg;
9274         eval_state->pos       = mg->mg_len;
9275         eval_state->pos_flags = mg->mg_flags;
9276     }
9277     else
9278         eval_state->pos_magic = NULL;
9279
9280     if (!PL_reg_curpm) {
9281         /* PL_reg_curpm is a fake PMOP that we can attach the current
9282          * regex to and point PL_curpm at, so that $1 et al are visible
9283          * within a /(?{})/. It's just allocated once per interpreter the
9284          * first time its needed */
9285         Newxz(PL_reg_curpm, 1, PMOP);
9286 #ifdef USE_ITHREADS
9287         {
9288             SV* const repointer = &PL_sv_undef;
9289             /* this regexp is also owned by the new PL_reg_curpm, which
9290                will try to free it.  */
9291             av_push(PL_regex_padav, repointer);
9292             PL_reg_curpm->op_pmoffset = av_tindex(PL_regex_padav);
9293             PL_regex_pad = AvARRAY(PL_regex_padav);
9294         }
9295 #endif
9296     }
9297     SET_reg_curpm(reginfo->prog);
9298     eval_state->curpm = PL_curpm;
9299     PL_curpm = PL_reg_curpm;
9300     if (RXp_MATCH_COPIED(rex)) {
9301         /*  Here is a serious problem: we cannot rewrite subbeg,
9302             since it may be needed if this match fails.  Thus
9303             $` inside (?{}) could fail... */
9304         eval_state->subbeg     = rex->subbeg;
9305         eval_state->sublen     = rex->sublen;
9306         eval_state->suboffset  = rex->suboffset;
9307         eval_state->subcoffset = rex->subcoffset;
9308 #ifdef PERL_ANY_COW
9309         eval_state->saved_copy = rex->saved_copy;
9310 #endif
9311         RXp_MATCH_COPIED_off(rex);
9312     }
9313     else
9314         eval_state->subbeg = NULL;
9315     rex->subbeg = (char *)reginfo->strbeg;
9316     rex->suboffset = 0;
9317     rex->subcoffset = 0;
9318     rex->sublen = reginfo->strend - reginfo->strbeg;
9319 }
9320
9321
9322 /* destructor to clear up regmatch_info_aux and regmatch_info_aux_eval */
9323
9324 static void
9325 S_cleanup_regmatch_info_aux(pTHX_ void *arg)
9326 {
9327     regmatch_info_aux *aux = (regmatch_info_aux *) arg;
9328     regmatch_info_aux_eval *eval_state =  aux->info_aux_eval;
9329     regmatch_slab *s;
9330
9331     Safefree(aux->poscache);
9332
9333     if (eval_state) {
9334
9335         /* undo the effects of S_setup_eval_state() */
9336
9337         if (eval_state->subbeg) {
9338             regexp * const rex = eval_state->rex;
9339             rex->subbeg     = eval_state->subbeg;
9340             rex->sublen     = eval_state->sublen;
9341             rex->suboffset  = eval_state->suboffset;
9342             rex->subcoffset = eval_state->subcoffset;
9343 #ifdef PERL_ANY_COW
9344             rex->saved_copy = eval_state->saved_copy;
9345 #endif
9346             RXp_MATCH_COPIED_on(rex);
9347         }
9348         if (eval_state->pos_magic)
9349         {
9350             eval_state->pos_magic->mg_len = eval_state->pos;
9351             eval_state->pos_magic->mg_flags =
9352                  (eval_state->pos_magic->mg_flags & ~MGf_BYTES)
9353                | (eval_state->pos_flags & MGf_BYTES);
9354         }
9355
9356         PL_curpm = eval_state->curpm;
9357     }
9358
9359     PL_regmatch_state = aux->old_regmatch_state;
9360     PL_regmatch_slab  = aux->old_regmatch_slab;
9361
9362     /* free all slabs above current one - this must be the last action
9363      * of this function, as aux and eval_state are allocated within
9364      * slabs and may be freed here */
9365
9366     s = PL_regmatch_slab->next;
9367     if (s) {
9368         PL_regmatch_slab->next = NULL;
9369         while (s) {
9370             regmatch_slab * const osl = s;
9371             s = s->next;
9372             Safefree(osl);
9373         }
9374     }
9375 }
9376
9377
9378 STATIC void
9379 S_to_utf8_substr(pTHX_ regexp *prog)
9380 {
9381     /* Converts substr fields in prog from bytes to UTF-8, calling fbm_compile
9382      * on the converted value */
9383
9384     int i = 1;
9385
9386     PERL_ARGS_ASSERT_TO_UTF8_SUBSTR;
9387
9388     do {
9389         if (prog->substrs->data[i].substr
9390             && !prog->substrs->data[i].utf8_substr) {
9391             SV* const sv = newSVsv(prog->substrs->data[i].substr);
9392             prog->substrs->data[i].utf8_substr = sv;
9393             sv_utf8_upgrade(sv);
9394             if (SvVALID(prog->substrs->data[i].substr)) {
9395                 if (SvTAIL(prog->substrs->data[i].substr)) {
9396                     /* Trim the trailing \n that fbm_compile added last
9397                        time.  */
9398                     SvCUR_set(sv, SvCUR(sv) - 1);
9399                     /* Whilst this makes the SV technically "invalid" (as its
9400                        buffer is no longer followed by "\0") when fbm_compile()
9401                        adds the "\n" back, a "\0" is restored.  */
9402                     fbm_compile(sv, FBMcf_TAIL);
9403                 } else
9404                     fbm_compile(sv, 0);
9405             }
9406             if (prog->substrs->data[i].substr == prog->check_substr)
9407                 prog->check_utf8 = sv;
9408         }
9409     } while (i--);
9410 }
9411
9412 STATIC bool
9413 S_to_byte_substr(pTHX_ regexp *prog)
9414 {
9415     /* Converts substr fields in prog from UTF-8 to bytes, calling fbm_compile
9416      * on the converted value; returns FALSE if can't be converted. */
9417
9418     int i = 1;
9419
9420     PERL_ARGS_ASSERT_TO_BYTE_SUBSTR;
9421
9422     do {
9423         if (prog->substrs->data[i].utf8_substr
9424             && !prog->substrs->data[i].substr) {
9425             SV* sv = newSVsv(prog->substrs->data[i].utf8_substr);
9426             if (! sv_utf8_downgrade(sv, TRUE)) {
9427                 return FALSE;
9428             }
9429             if (SvVALID(prog->substrs->data[i].utf8_substr)) {
9430                 if (SvTAIL(prog->substrs->data[i].utf8_substr)) {
9431                     /* Trim the trailing \n that fbm_compile added last
9432                         time.  */
9433                     SvCUR_set(sv, SvCUR(sv) - 1);
9434                     fbm_compile(sv, FBMcf_TAIL);
9435                 } else
9436                     fbm_compile(sv, 0);
9437             }
9438             prog->substrs->data[i].substr = sv;
9439             if (prog->substrs->data[i].utf8_substr == prog->check_utf8)
9440                 prog->check_substr = sv;
9441         }
9442     } while (i--);
9443
9444     return TRUE;
9445 }
9446
9447 /*
9448  * ex: set ts=8 sts=4 sw=4 et:
9449  */