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