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