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