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