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