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