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