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