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