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