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