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