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