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