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