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