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