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