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