This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Add av_tindex_nomg()
[perl5.git] / regexec.c
1 /*    regexec.c
2  */
3
4 /*
5  *      One Ring to rule them all, One Ring to find them
6  *
7  *     [p.v of _The Lord of the Rings_, opening poem]
8  *     [p.50 of _The Lord of the Rings_, I/iii: "The Shadow of the Past"]
9  *     [p.254 of _The Lord of the Rings_, II/ii: "The Council of Elrond"]
10  */
11
12 /* This file contains functions for executing a regular expression.  See
13  * also regcomp.c which funnily enough, contains functions for compiling
14  * a regular expression.
15  *
16  * This file is also copied at build time to ext/re/re_exec.c, where
17  * it's built with -DPERL_EXT_RE_BUILD -DPERL_EXT_RE_DEBUG -DPERL_EXT.
18  * This causes the main functions to be compiled under new names and with
19  * debugging support added, which makes "use re 'debug'" work.
20  */
21
22 /* NOTE: this is derived from Henry Spencer's regexp code, and should not
23  * confused with the original package (see point 3 below).  Thanks, Henry!
24  */
25
26 /* Additional note: this code is very heavily munged from Henry's version
27  * in places.  In some spots I've traded clarity for efficiency, so don't
28  * blame Henry for some of the lack of readability.
29  */
30
31 /* The names of the functions have been changed from regcomp and
32  * regexec to  pregcomp and pregexec in order to avoid conflicts
33  * with the POSIX routines of the same names.
34 */
35
36 #ifdef PERL_EXT_RE_BUILD
37 #include "re_top.h"
38 #endif
39
40 /*
41  * pregcomp and pregexec -- regsub and regerror are not used in perl
42  *
43  *      Copyright (c) 1986 by University of Toronto.
44  *      Written by Henry Spencer.  Not derived from licensed software.
45  *
46  *      Permission is granted to anyone to use this software for any
47  *      purpose on any computer system, and to redistribute it freely,
48  *      subject to the following restrictions:
49  *
50  *      1. The author is not responsible for the consequences of use of
51  *              this software, no matter how awful, even if they arise
52  *              from defects in it.
53  *
54  *      2. The origin of this software must not be misrepresented, either
55  *              by explicit claim or by omission.
56  *
57  *      3. Altered versions must be plainly marked as such, and must not
58  *              be misrepresented as being the original software.
59  *
60  ****    Alterations to Henry's code are...
61  ****
62  ****    Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
63  ****    2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
64  ****    by Larry Wall and others
65  ****
66  ****    You may distribute under the terms of either the GNU General Public
67  ****    License or the Artistic License, as specified in the README file.
68  *
69  * Beware that some of this code is subtly aware of the way operator
70  * precedence is structured in regular expressions.  Serious changes in
71  * regular-expression syntax might require a total rethink.
72  */
73 #include "EXTERN.h"
74 #define PERL_IN_REGEXEC_C
75 #include "perl.h"
76
77 #ifdef PERL_IN_XSUB_RE
78 #  include "re_comp.h"
79 #else
80 #  include "regcomp.h"
81 #endif
82
83 #include "invlist_inline.h"
84 #include "unicode_constants.h"
85
86 #define B_ON_NON_UTF8_LOCALE_IS_WRONG            \
87  "Use of \\b{} or \\B{} for non-UTF-8 locale is wrong.  Assuming a UTF-8 locale"
88
89 static const char utf8_locale_required[] =
90       "Use of (?[ ]) for non-UTF-8 locale is wrong.  Assuming a UTF-8 locale";
91
92 #ifdef DEBUGGING
93 /* At least one required character in the target string is expressible only in
94  * UTF-8. */
95 static const char* const non_utf8_target_but_utf8_required
96                 = "Can't match, because target string needs to be in UTF-8\n";
97 #endif
98
99 #define NON_UTF8_TARGET_BUT_UTF8_REQUIRED(target) STMT_START { \
100     DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%s", non_utf8_target_but_utf8_required));\
101     goto target; \
102 } STMT_END
103
104 #define HAS_NONLATIN1_FOLD_CLOSURE(i) _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
105
106 #ifndef STATIC
107 #define STATIC  static
108 #endif
109
110 /* Valid only if 'c', the character being looke-up, is an invariant under
111  * UTF-8: it avoids the reginclass call if there are no complications: i.e., if
112  * everything matchable is straight forward in the bitmap */
113 #define REGINCLASS(prog,p,c,u)  (ANYOF_FLAGS(p)                             \
114                                 ? reginclass(prog,p,c,c+1,u)                \
115                                 : ANYOF_BITMAP_TEST(p,*(c)))
116
117 /*
118  * Forwards.
119  */
120
121 #define CHR_SVLEN(sv) (utf8_target ? sv_len_utf8(sv) : SvCUR(sv))
122 #define CHR_DIST(a,b) (reginfo->is_utf8_target ? utf8_distance(a,b) : a - b)
123
124 #define HOPc(pos,off) \
125         (char *)(reginfo->is_utf8_target \
126             ? reghop3((U8*)pos, off, \
127                     (U8*)(off >= 0 ? reginfo->strend : reginfo->strbeg)) \
128             : (U8*)(pos + off))
129
130 #define HOPBACKc(pos, off) \
131         (char*)(reginfo->is_utf8_target \
132             ? reghopmaybe3((U8*)pos, -off, (U8*)(reginfo->strbeg)) \
133             : (pos - off >= reginfo->strbeg)    \
134                 ? (U8*)pos - off                \
135                 : NULL)
136
137 #define HOP3(pos,off,lim) (reginfo->is_utf8_target  ? reghop3((U8*)(pos), off, (U8*)(lim)) : (U8*)(pos + off))
138 #define HOP3c(pos,off,lim) ((char*)HOP3(pos,off,lim))
139
140 /* lim must be +ve. Returns NULL on overshoot */
141 #define HOPMAYBE3(pos,off,lim) \
142         (reginfo->is_utf8_target                        \
143             ? reghopmaybe3((U8*)pos, off, (U8*)(lim))   \
144             : ((U8*)pos + off <= lim)                   \
145                 ? (U8*)pos + off                        \
146                 : NULL)
147
148 /* like HOP3, but limits the result to <= lim even for the non-utf8 case.
149  * off must be >=0; args should be vars rather than expressions */
150 #define HOP3lim(pos,off,lim) (reginfo->is_utf8_target \
151     ? reghop3((U8*)(pos), off, (U8*)(lim)) \
152     : (U8*)((pos + off) > lim ? lim : (pos + off)))
153
154 #define HOP4(pos,off,llim, rlim) (reginfo->is_utf8_target \
155     ? reghop4((U8*)(pos), off, (U8*)(llim), (U8*)(rlim)) \
156     : (U8*)(pos + off))
157 #define HOP4c(pos,off,llim, rlim) ((char*)HOP4(pos,off,llim, rlim))
158
159 #define NEXTCHR_EOS -10 /* nextchr has fallen off the end */
160 #define NEXTCHR_IS_EOS (nextchr < 0)
161
162 #define SET_nextchr \
163     nextchr = ((locinput < reginfo->strend) ? UCHARAT(locinput) : NEXTCHR_EOS)
164
165 #define SET_locinput(p) \
166     locinput = (p);  \
167     SET_nextchr
168
169
170 #define LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist) STMT_START {   \
171         if (!swash_ptr) {                                                     \
172             U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;                       \
173             swash_ptr = _core_swash_init("utf8", property_name, &PL_sv_undef, \
174                                          1, 0, invlist, &flags);              \
175             assert(swash_ptr);                                                \
176         }                                                                     \
177     } STMT_END
178
179 /* If in debug mode, we test that a known character properly matches */
180 #ifdef DEBUGGING
181 #   define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr,                          \
182                                           property_name,                      \
183                                           invlist,                            \
184                                           utf8_char_in_property)              \
185         LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist);               \
186         assert(swash_fetch(swash_ptr, (U8 *) utf8_char_in_property, TRUE));
187 #else
188 #   define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr,                          \
189                                           property_name,                      \
190                                           invlist,                            \
191                                           utf8_char_in_property)              \
192         LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist)
193 #endif
194
195 #define LOAD_UTF8_CHARCLASS_ALNUM() LOAD_UTF8_CHARCLASS_DEBUG_TEST(           \
196                                         PL_utf8_swash_ptrs[_CC_WORDCHAR],     \
197                                         "",                                   \
198                                         PL_XPosix_ptrs[_CC_WORDCHAR],         \
199                                         LATIN_SMALL_LIGATURE_LONG_S_T_UTF8);
200
201 #define PLACEHOLDER     /* Something for the preprocessor to grab onto */
202 /* TODO: Combine JUMPABLE and HAS_TEXT to cache OP(rn) */
203
204 /* for use after a quantifier and before an EXACT-like node -- japhy */
205 /* it would be nice to rework regcomp.sym to generate this stuff. sigh
206  *
207  * NOTE that *nothing* that affects backtracking should be in here, specifically
208  * VERBS must NOT be included. JUMPABLE is used to determine  if we can ignore a
209  * node that is in between two EXACT like nodes when ascertaining what the required
210  * "follow" character is. This should probably be moved to regex compile time
211  * although it may be done at run time beause of the REF possibility - more
212  * investigation required. -- demerphq
213 */
214 #define JUMPABLE(rn) (                                                             \
215     OP(rn) == OPEN ||                                                              \
216     (OP(rn) == CLOSE &&                                                            \
217      !EVAL_CLOSE_PAREN_IS(cur_eval,ARG(rn)) ) ||                                   \
218     OP(rn) == EVAL ||                                                              \
219     OP(rn) == SUSPEND || OP(rn) == IFMATCH ||                                      \
220     OP(rn) == PLUS || OP(rn) == MINMOD ||                                          \
221     OP(rn) == KEEPS ||                                                             \
222     (PL_regkind[OP(rn)] == CURLY && ARG1(rn) > 0)                                  \
223 )
224 #define IS_EXACT(rn) (PL_regkind[OP(rn)] == EXACT)
225
226 #define HAS_TEXT(rn) ( IS_EXACT(rn) || PL_regkind[OP(rn)] == REF )
227
228 #if 0 
229 /* Currently these are only used when PL_regkind[OP(rn)] == EXACT so
230    we don't need this definition.  XXX These are now out-of-sync*/
231 #define IS_TEXT(rn)   ( OP(rn)==EXACT   || OP(rn)==REF   || OP(rn)==NREF   )
232 #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 )
233 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL || OP(rn)==REFFL || OP(rn)==NREFFL )
234
235 #else
236 /* ... so we use this as its faster. */
237 #define IS_TEXT(rn)   ( OP(rn)==EXACT || OP(rn)==EXACTL )
238 #define IS_TEXTFU(rn)  ( OP(rn)==EXACTFU || OP(rn)==EXACTFLU8 || OP(rn)==EXACTFU_SS || OP(rn) == EXACTFA || OP(rn) == EXACTFA_NO_TRIE)
239 #define IS_TEXTF(rn)  ( OP(rn)==EXACTF  )
240 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL )
241
242 #endif
243
244 /*
245   Search for mandatory following text node; for lookahead, the text must
246   follow but for lookbehind (rn->flags != 0) we skip to the next step.
247 */
248 #define FIND_NEXT_IMPT(rn) STMT_START {                                   \
249     while (JUMPABLE(rn)) { \
250         const OPCODE type = OP(rn); \
251         if (type == SUSPEND || PL_regkind[type] == CURLY) \
252             rn = NEXTOPER(NEXTOPER(rn)); \
253         else if (type == PLUS) \
254             rn = NEXTOPER(rn); \
255         else if (type == IFMATCH) \
256             rn = (rn->flags == 0) ? NEXTOPER(NEXTOPER(rn)) : rn + ARG(rn); \
257         else rn += NEXT_OFF(rn); \
258     } \
259 } STMT_END 
260
261 #define SLAB_FIRST(s) (&(s)->states[0])
262 #define SLAB_LAST(s)  (&(s)->states[PERL_REGMATCH_SLAB_SLOTS-1])
263
264 static void S_setup_eval_state(pTHX_ regmatch_info *const reginfo);
265 static void S_cleanup_regmatch_info_aux(pTHX_ void *arg);
266 static regmatch_state * S_push_slab(pTHX);
267
268 #define REGCP_PAREN_ELEMS 3
269 #define REGCP_OTHER_ELEMS 3
270 #define REGCP_FRAME_ELEMS 1
271 /* REGCP_FRAME_ELEMS are not part of the REGCP_OTHER_ELEMS and
272  * are needed for the regexp context stack bookkeeping. */
273
274 STATIC CHECKPOINT
275 S_regcppush(pTHX_ const regexp *rex, I32 parenfloor, U32 maxopenparen)
276 {
277     const int retval = PL_savestack_ix;
278     const int paren_elems_to_push =
279                 (maxopenparen - parenfloor) * REGCP_PAREN_ELEMS;
280     const UV total_elems = paren_elems_to_push + REGCP_OTHER_ELEMS;
281     const UV elems_shifted = total_elems << SAVE_TIGHT_SHIFT;
282     I32 p;
283     GET_RE_DEBUG_FLAGS_DECL;
284
285     PERL_ARGS_ASSERT_REGCPPUSH;
286
287     if (paren_elems_to_push < 0)
288         Perl_croak(aTHX_ "panic: paren_elems_to_push, %i < 0, maxopenparen: %i parenfloor: %i REGCP_PAREN_ELEMS: %u",
289                    (int)paren_elems_to_push, (int)maxopenparen,
290                    (int)parenfloor, (unsigned)REGCP_PAREN_ELEMS);
291
292     if ((elems_shifted >> SAVE_TIGHT_SHIFT) != total_elems)
293         Perl_croak(aTHX_ "panic: paren_elems_to_push offset %"UVuf
294                    " out of range (%lu-%ld)",
295                    total_elems,
296                    (unsigned long)maxopenparen,
297                    (long)parenfloor);
298
299     SSGROW(total_elems + REGCP_FRAME_ELEMS);
300     
301     DEBUG_BUFFERS_r(
302         if ((int)maxopenparen > (int)parenfloor)
303             PerlIO_printf(Perl_debug_log,
304                 "rex=0x%"UVxf" offs=0x%"UVxf": saving capture indices:\n",
305                 PTR2UV(rex),
306                 PTR2UV(rex->offs)
307             );
308     );
309     for (p = parenfloor+1; p <= (I32)maxopenparen;  p++) {
310 /* REGCP_PARENS_ELEMS are pushed per pairs of parentheses. */
311         SSPUSHIV(rex->offs[p].end);
312         SSPUSHIV(rex->offs[p].start);
313         SSPUSHINT(rex->offs[p].start_tmp);
314         DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
315             "    \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"\n",
316             (UV)p,
317             (IV)rex->offs[p].start,
318             (IV)rex->offs[p].start_tmp,
319             (IV)rex->offs[p].end
320         ));
321     }
322 /* REGCP_OTHER_ELEMS are pushed in any case, parentheses or no. */
323     SSPUSHINT(maxopenparen);
324     SSPUSHINT(rex->lastparen);
325     SSPUSHINT(rex->lastcloseparen);
326     SSPUSHUV(SAVEt_REGCONTEXT | elems_shifted); /* Magic cookie. */
327
328     return retval;
329 }
330
331 /* These are needed since we do not localize EVAL nodes: */
332 #define REGCP_SET(cp)                                           \
333     DEBUG_STATE_r(                                              \
334             PerlIO_printf(Perl_debug_log,                       \
335                 "  Setting an EVAL scope, savestack=%"IVdf"\n", \
336                 (IV)PL_savestack_ix));                          \
337     cp = PL_savestack_ix
338
339 #define REGCP_UNWIND(cp)                                        \
340     DEBUG_STATE_r(                                              \
341         if (cp != PL_savestack_ix)                              \
342             PerlIO_printf(Perl_debug_log,                       \
343                 "  Clearing an EVAL scope, savestack=%"IVdf"..%"IVdf"\n", \
344                 (IV)(cp), (IV)PL_savestack_ix));                \
345     regcpblow(cp)
346
347 #define UNWIND_PAREN(lp, lcp)               \
348     for (n = rex->lastparen; n > lp; n--)   \
349         rex->offs[n].end = -1;              \
350     rex->lastparen = n;                     \
351     rex->lastcloseparen = lcp;
352
353
354 STATIC void
355 S_regcppop(pTHX_ regexp *rex, U32 *maxopenparen_p)
356 {
357     UV i;
358     U32 paren;
359     GET_RE_DEBUG_FLAGS_DECL;
360
361     PERL_ARGS_ASSERT_REGCPPOP;
362
363     /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
364     i = SSPOPUV;
365     assert((i & SAVE_MASK) == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
366     i >>= SAVE_TIGHT_SHIFT; /* Parentheses elements to pop. */
367     rex->lastcloseparen = SSPOPINT;
368     rex->lastparen = SSPOPINT;
369     *maxopenparen_p = SSPOPINT;
370
371     i -= REGCP_OTHER_ELEMS;
372     /* Now restore the parentheses context. */
373     DEBUG_BUFFERS_r(
374         if (i || rex->lastparen + 1 <= rex->nparens)
375             PerlIO_printf(Perl_debug_log,
376                 "rex=0x%"UVxf" offs=0x%"UVxf": restoring capture indices to:\n",
377                 PTR2UV(rex),
378                 PTR2UV(rex->offs)
379             );
380     );
381     paren = *maxopenparen_p;
382     for ( ; i > 0; i -= REGCP_PAREN_ELEMS) {
383         SSize_t tmps;
384         rex->offs[paren].start_tmp = SSPOPINT;
385         rex->offs[paren].start = SSPOPIV;
386         tmps = SSPOPIV;
387         if (paren <= rex->lastparen)
388             rex->offs[paren].end = tmps;
389         DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
390             "    \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"%s\n",
391             (UV)paren,
392             (IV)rex->offs[paren].start,
393             (IV)rex->offs[paren].start_tmp,
394             (IV)rex->offs[paren].end,
395             (paren > rex->lastparen ? "(skipped)" : ""));
396         );
397         paren--;
398     }
399 #if 1
400     /* It would seem that the similar code in regtry()
401      * already takes care of this, and in fact it is in
402      * a better location to since this code can #if 0-ed out
403      * but the code in regtry() is needed or otherwise tests
404      * requiring null fields (pat.t#187 and split.t#{13,14}
405      * (as of patchlevel 7877)  will fail.  Then again,
406      * this code seems to be necessary or otherwise
407      * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
408      * --jhi updated by dapm */
409     for (i = rex->lastparen + 1; i <= rex->nparens; i++) {
410         if (i > *maxopenparen_p)
411             rex->offs[i].start = -1;
412         rex->offs[i].end = -1;
413         DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
414             "    \\%"UVuf": %s   ..-1 undeffing\n",
415             (UV)i,
416             (i > *maxopenparen_p) ? "-1" : "  "
417         ));
418     }
419 #endif
420 }
421
422 /* restore the parens and associated vars at savestack position ix,
423  * but without popping the stack */
424
425 STATIC void
426 S_regcp_restore(pTHX_ regexp *rex, I32 ix, U32 *maxopenparen_p)
427 {
428     I32 tmpix = PL_savestack_ix;
429     PL_savestack_ix = ix;
430     regcppop(rex, maxopenparen_p);
431     PL_savestack_ix = tmpix;
432 }
433
434 #define regcpblow(cp) LEAVE_SCOPE(cp)   /* Ignores regcppush()ed data. */
435
436 STATIC bool
437 S_isFOO_lc(pTHX_ const U8 classnum, const U8 character)
438 {
439     /* Returns a boolean as to whether or not 'character' is a member of the
440      * Posix character class given by 'classnum' that should be equivalent to a
441      * value in the typedef '_char_class_number'.
442      *
443      * Ideally this could be replaced by a just an array of function pointers
444      * to the C library functions that implement the macros this calls.
445      * However, to compile, the precise function signatures are required, and
446      * these may vary from platform to to platform.  To avoid having to figure
447      * out what those all are on each platform, I (khw) am using this method,
448      * which adds an extra layer of function call overhead (unless the C
449      * optimizer strips it away).  But we don't particularly care about
450      * performance with locales anyway. */
451
452     switch ((_char_class_number) classnum) {
453         case _CC_ENUM_ALPHANUMERIC: return isALPHANUMERIC_LC(character);
454         case _CC_ENUM_ALPHA:     return isALPHA_LC(character);
455         case _CC_ENUM_ASCII:     return isASCII_LC(character);
456         case _CC_ENUM_BLANK:     return isBLANK_LC(character);
457         case _CC_ENUM_CASED:     return isLOWER_LC(character)
458                                         || isUPPER_LC(character);
459         case _CC_ENUM_CNTRL:     return isCNTRL_LC(character);
460         case _CC_ENUM_DIGIT:     return isDIGIT_LC(character);
461         case _CC_ENUM_GRAPH:     return isGRAPH_LC(character);
462         case _CC_ENUM_LOWER:     return isLOWER_LC(character);
463         case _CC_ENUM_PRINT:     return isPRINT_LC(character);
464         case _CC_ENUM_PUNCT:     return isPUNCT_LC(character);
465         case _CC_ENUM_SPACE:     return isSPACE_LC(character);
466         case _CC_ENUM_UPPER:     return isUPPER_LC(character);
467         case _CC_ENUM_WORDCHAR:  return isWORDCHAR_LC(character);
468         case _CC_ENUM_XDIGIT:    return isXDIGIT_LC(character);
469         default:    /* VERTSPACE should never occur in locales */
470             Perl_croak(aTHX_ "panic: isFOO_lc() has an unexpected character class '%d'", classnum);
471     }
472
473     NOT_REACHED; /* NOTREACHED */
474     return FALSE;
475 }
476
477 STATIC bool
478 S_isFOO_utf8_lc(pTHX_ const U8 classnum, const U8* character)
479 {
480     /* Returns a boolean as to whether or not the (well-formed) UTF-8-encoded
481      * 'character' is a member of the Posix character class given by 'classnum'
482      * that should be equivalent to a value in the typedef
483      * '_char_class_number'.
484      *
485      * This just calls isFOO_lc on the code point for the character if it is in
486      * the range 0-255.  Outside that range, all characters use Unicode
487      * rules, ignoring any locale.  So use the Unicode function if this class
488      * requires a swash, and use the Unicode macro otherwise. */
489
490     PERL_ARGS_ASSERT_ISFOO_UTF8_LC;
491
492     if (UTF8_IS_INVARIANT(*character)) {
493         return isFOO_lc(classnum, *character);
494     }
495     else if (UTF8_IS_DOWNGRADEABLE_START(*character)) {
496         return isFOO_lc(classnum,
497                         EIGHT_BIT_UTF8_TO_NATIVE(*character, *(character + 1)));
498     }
499
500     _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(character, character + UTF8SKIP(character));
501
502     if (classnum < _FIRST_NON_SWASH_CC) {
503
504         /* Initialize the swash unless done already */
505         if (! PL_utf8_swash_ptrs[classnum]) {
506             U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
507             PL_utf8_swash_ptrs[classnum] =
508                     _core_swash_init("utf8",
509                                      "",
510                                      &PL_sv_undef, 1, 0,
511                                      PL_XPosix_ptrs[classnum], &flags);
512         }
513
514         return cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum], (U8 *)
515                                  character,
516                                  TRUE /* is UTF */ ));
517     }
518
519     switch ((_char_class_number) classnum) {
520         case _CC_ENUM_SPACE:     return is_XPERLSPACE_high(character);
521         case _CC_ENUM_BLANK:     return is_HORIZWS_high(character);
522         case _CC_ENUM_XDIGIT:    return is_XDIGIT_high(character);
523         case _CC_ENUM_VERTSPACE: return is_VERTWS_high(character);
524         default:                 break;
525     }
526
527     return FALSE; /* Things like CNTRL are always below 256 */
528 }
529
530 /*
531  * pregexec and friends
532  */
533
534 #ifndef PERL_IN_XSUB_RE
535 /*
536  - pregexec - match a regexp against a string
537  */
538 I32
539 Perl_pregexec(pTHX_ REGEXP * const prog, char* stringarg, char *strend,
540          char *strbeg, SSize_t minend, SV *screamer, U32 nosave)
541 /* stringarg: the point in the string at which to begin matching */
542 /* strend:    pointer to null at end of string */
543 /* strbeg:    real beginning of string */
544 /* minend:    end of match must be >= minend bytes after stringarg. */
545 /* screamer:  SV being matched: only used for utf8 flag, pos() etc; string
546  *            itself is accessed via the pointers above */
547 /* nosave:    For optimizations. */
548 {
549     PERL_ARGS_ASSERT_PREGEXEC;
550
551     return
552         regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
553                       nosave ? 0 : REXEC_COPY_STR);
554 }
555 #endif
556
557
558
559 /* re_intuit_start():
560  *
561  * Based on some optimiser hints, try to find the earliest position in the
562  * string where the regex could match.
563  *
564  *   rx:     the regex to match against
565  *   sv:     the SV being matched: only used for utf8 flag; the string
566  *           itself is accessed via the pointers below. Note that on
567  *           something like an overloaded SV, SvPOK(sv) may be false
568  *           and the string pointers may point to something unrelated to
569  *           the SV itself.
570  *   strbeg: real beginning of string
571  *   strpos: the point in the string at which to begin matching
572  *   strend: pointer to the byte following the last char of the string
573  *   flags   currently unused; set to 0
574  *   data:   currently unused; set to NULL
575  *
576  * The basic idea of re_intuit_start() is to use some known information
577  * about the pattern, namely:
578  *
579  *   a) the longest known anchored substring (i.e. one that's at a
580  *      constant offset from the beginning of the pattern; but not
581  *      necessarily at a fixed offset from the beginning of the
582  *      string);
583  *   b) the longest floating substring (i.e. one that's not at a constant
584  *      offset from the beginning of the pattern);
585  *   c) Whether the pattern is anchored to the string; either
586  *      an absolute anchor: /^../, or anchored to \n: /^.../m,
587  *      or anchored to pos(): /\G/;
588  *   d) A start class: a real or synthetic character class which
589  *      represents which characters are legal at the start of the pattern;
590  *
591  * to either quickly reject the match, or to find the earliest position
592  * within the string at which the pattern might match, thus avoiding
593  * running the full NFA engine at those earlier locations, only to
594  * eventually fail and retry further along.
595  *
596  * Returns NULL if the pattern can't match, or returns the address within
597  * the string which is the earliest place the match could occur.
598  *
599  * The longest of the anchored and floating substrings is called 'check'
600  * and is checked first. The other is called 'other' and is checked
601  * second. The 'other' substring may not be present.  For example,
602  *
603  *    /(abc|xyz)ABC\d{0,3}DEFG/
604  *
605  * will have
606  *
607  *   check substr (float)    = "DEFG", offset 6..9 chars
608  *   other substr (anchored) = "ABC",  offset 3..3 chars
609  *   stclass = [ax]
610  *
611  * Be aware that during the course of this function, sometimes 'anchored'
612  * refers to a substring being anchored relative to the start of the
613  * pattern, and sometimes to the pattern itself being anchored relative to
614  * the string. For example:
615  *
616  *   /\dabc/:   "abc" is anchored to the pattern;
617  *   /^\dabc/:  "abc" is anchored to the pattern and the string;
618  *   /\d+abc/:  "abc" is anchored to neither the pattern nor the string;
619  *   /^\d+abc/: "abc" is anchored to neither the pattern nor the string,
620  *                    but the pattern is anchored to the string.
621  */
622
623 char *
624 Perl_re_intuit_start(pTHX_
625                     REGEXP * const rx,
626                     SV *sv,
627                     const char * const strbeg,
628                     char *strpos,
629                     char *strend,
630                     const U32 flags,
631                     re_scream_pos_data *data)
632 {
633     struct regexp *const prog = ReANY(rx);
634     SSize_t start_shift = prog->check_offset_min;
635     /* Should be nonnegative! */
636     SSize_t end_shift   = 0;
637     /* current lowest pos in string where the regex can start matching */
638     char *rx_origin = strpos;
639     SV *check;
640     const bool utf8_target = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
641     U8   other_ix = 1 - prog->substrs->check_ix;
642     bool ml_anch = 0;
643     char *other_last = strpos;/* latest pos 'other' substr already checked to */
644     char *check_at = NULL;              /* check substr found at this pos */
645     const I32 multiline = prog->extflags & RXf_PMf_MULTILINE;
646     RXi_GET_DECL(prog,progi);
647     regmatch_info reginfo_buf;  /* create some info to pass to find_byclass */
648     regmatch_info *const reginfo = &reginfo_buf;
649     GET_RE_DEBUG_FLAGS_DECL;
650
651     PERL_ARGS_ASSERT_RE_INTUIT_START;
652     PERL_UNUSED_ARG(flags);
653     PERL_UNUSED_ARG(data);
654
655     DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
656                 "Intuit: trying to determine minimum start position...\n"));
657
658     /* for now, assume that all substr offsets are positive. If at some point
659      * in the future someone wants to do clever things with lookbehind and
660      * -ve offsets, they'll need to fix up any code in this function
661      * which uses these offsets. See the thread beginning
662      * <20140113145929.GF27210@iabyn.com>
663      */
664     assert(prog->substrs->data[0].min_offset >= 0);
665     assert(prog->substrs->data[0].max_offset >= 0);
666     assert(prog->substrs->data[1].min_offset >= 0);
667     assert(prog->substrs->data[1].max_offset >= 0);
668     assert(prog->substrs->data[2].min_offset >= 0);
669     assert(prog->substrs->data[2].max_offset >= 0);
670
671     /* for now, assume that if both present, that the floating substring
672      * doesn't start before the anchored substring.
673      * If you break this assumption (e.g. doing better optimisations
674      * with lookahead/behind), then you'll need to audit the code in this
675      * function carefully first
676      */
677     assert(
678             ! (  (prog->anchored_utf8 || prog->anchored_substr)
679               && (prog->float_utf8    || prog->float_substr))
680            || (prog->float_min_offset >= prog->anchored_offset));
681
682     /* byte rather than char calculation for efficiency. It fails
683      * to quickly reject some cases that can't match, but will reject
684      * them later after doing full char arithmetic */
685     if (prog->minlen > strend - strpos) {
686         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
687                               "  String too short...\n"));
688         goto fail;
689     }
690
691     RX_MATCH_UTF8_set(rx,utf8_target);
692     reginfo->is_utf8_target = cBOOL(utf8_target);
693     reginfo->info_aux = NULL;
694     reginfo->strbeg = strbeg;
695     reginfo->strend = strend;
696     reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
697     reginfo->intuit = 1;
698     /* not actually used within intuit, but zero for safety anyway */
699     reginfo->poscache_maxiter = 0;
700
701     if (utf8_target) {
702         if (!prog->check_utf8 && prog->check_substr)
703             to_utf8_substr(prog);
704         check = prog->check_utf8;
705     } else {
706         if (!prog->check_substr && prog->check_utf8) {
707             if (! to_byte_substr(prog)) {
708                 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(fail);
709             }
710         }
711         check = prog->check_substr;
712     }
713
714     /* dump the various substring data */
715     DEBUG_OPTIMISE_MORE_r({
716         int i;
717         for (i=0; i<=2; i++) {
718             SV *sv = (utf8_target ? prog->substrs->data[i].utf8_substr
719                                   : prog->substrs->data[i].substr);
720             if (!sv)
721                 continue;
722
723             PerlIO_printf(Perl_debug_log,
724                 "  substrs[%d]: min=%"IVdf" max=%"IVdf" end shift=%"IVdf
725                 " useful=%"IVdf" utf8=%d [%s]\n",
726                 i,
727                 (IV)prog->substrs->data[i].min_offset,
728                 (IV)prog->substrs->data[i].max_offset,
729                 (IV)prog->substrs->data[i].end_shift,
730                 BmUSEFUL(sv),
731                 utf8_target ? 1 : 0,
732                 SvPEEK(sv));
733         }
734     });
735
736     if (prog->intflags & PREGf_ANCH) { /* Match at \G, beg-of-str or after \n */
737
738         /* ml_anch: check after \n?
739          *
740          * A note about PREGf_IMPLICIT: on an un-anchored pattern beginning
741          * with /.*.../, these flags will have been added by the
742          * compiler:
743          *   /.*abc/, /.*abc/m:  PREGf_IMPLICIT | PREGf_ANCH_MBOL
744          *   /.*abc/s:           PREGf_IMPLICIT | PREGf_ANCH_SBOL
745          */
746         ml_anch =      (prog->intflags & PREGf_ANCH_MBOL)
747                    && !(prog->intflags & PREGf_IMPLICIT);
748
749         if (!ml_anch && !(prog->intflags & PREGf_IMPLICIT)) {
750             /* we are only allowed to match at BOS or \G */
751
752             /* trivially reject if there's a BOS anchor and we're not at BOS.
753              *
754              * Note that we don't try to do a similar quick reject for
755              * \G, since generally the caller will have calculated strpos
756              * based on pos() and gofs, so the string is already correctly
757              * anchored by definition; and handling the exceptions would
758              * be too fiddly (e.g. REXEC_IGNOREPOS).
759              */
760             if (   strpos != strbeg
761                 && (prog->intflags & PREGf_ANCH_SBOL))
762             {
763                 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
764                                 "  Not at start...\n"));
765                 goto fail;
766             }
767
768             /* in the presence of an anchor, the anchored (relative to the
769              * start of the regex) substr must also be anchored relative
770              * to strpos. So quickly reject if substr isn't found there.
771              * This works for \G too, because the caller will already have
772              * subtracted gofs from pos, and gofs is the offset from the
773              * \G to the start of the regex. For example, in /.abc\Gdef/,
774              * where substr="abcdef", pos()=3, gofs=4, offset_min=1:
775              * caller will have set strpos=pos()-4; we look for the substr
776              * at position pos()-4+1, which lines up with the "a" */
777
778             if (prog->check_offset_min == prog->check_offset_max) {
779                 /* Substring at constant offset from beg-of-str... */
780                 SSize_t slen = SvCUR(check);
781                 char *s = HOP3c(strpos, prog->check_offset_min, strend);
782             
783                 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
784                     "  Looking for check substr at fixed offset %"IVdf"...\n",
785                     (IV)prog->check_offset_min));
786
787                 if (SvTAIL(check)) {
788                     /* In this case, the regex is anchored at the end too.
789                      * Unless it's a multiline match, the lengths must match
790                      * exactly, give or take a \n.  NB: slen >= 1 since
791                      * the last char of check is \n */
792                     if (!multiline
793                         && (   strend - s > slen
794                             || strend - s < slen - 1
795                             || (strend - s == slen && strend[-1] != '\n')))
796                     {
797                         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
798                                             "  String too long...\n"));
799                         goto fail_finish;
800                     }
801                     /* Now should match s[0..slen-2] */
802                     slen--;
803                 }
804                 if (slen && (*SvPVX_const(check) != *s
805                     || (slen > 1 && memNE(SvPVX_const(check), s, slen))))
806                 {
807                     DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
808                                     "  String not equal...\n"));
809                     goto fail_finish;
810                 }
811
812                 check_at = s;
813                 goto success_at_start;
814             }
815         }
816     }
817
818     end_shift = prog->check_end_shift;
819
820 #ifdef DEBUGGING        /* 7/99: reports of failure (with the older version) */
821     if (end_shift < 0)
822         Perl_croak(aTHX_ "panic: end_shift: %"IVdf" pattern:\n%s\n ",
823                    (IV)end_shift, RX_PRECOMP(prog));
824 #endif
825
826   restart:
827     
828     /* This is the (re)entry point of the main loop in this function.
829      * The goal of this loop is to:
830      * 1) find the "check" substring in the region rx_origin..strend
831      *    (adjusted by start_shift / end_shift). If not found, reject
832      *    immediately.
833      * 2) If it exists, look for the "other" substr too if defined; for
834      *    example, if the check substr maps to the anchored substr, then
835      *    check the floating substr, and vice-versa. If not found, go
836      *    back to (1) with rx_origin suitably incremented.
837      * 3) If we find an rx_origin position that doesn't contradict
838      *    either of the substrings, then check the possible additional
839      *    constraints on rx_origin of /^.../m or a known start class.
840      *    If these fail, then depending on which constraints fail, jump
841      *    back to here, or to various other re-entry points further along
842      *    that skip some of the first steps.
843      * 4) If we pass all those tests, update the BmUSEFUL() count on the
844      *    substring. If the start position was determined to be at the
845      *    beginning of the string  - so, not rejected, but not optimised,
846      *    since we have to run regmatch from position 0 - decrement the
847      *    BmUSEFUL() count. Otherwise increment it.
848      */
849
850
851     /* first, look for the 'check' substring */
852
853     {
854         U8* start_point;
855         U8* end_point;
856
857         DEBUG_OPTIMISE_MORE_r({
858             PerlIO_printf(Perl_debug_log,
859                 "  At restart: rx_origin=%"IVdf" Check offset min: %"IVdf
860                 " Start shift: %"IVdf" End shift %"IVdf
861                 " Real end Shift: %"IVdf"\n",
862                 (IV)(rx_origin - strbeg),
863                 (IV)prog->check_offset_min,
864                 (IV)start_shift,
865                 (IV)end_shift,
866                 (IV)prog->check_end_shift);
867         });
868         
869         end_point = HOP3(strend, -end_shift, strbeg);
870         start_point = HOPMAYBE3(rx_origin, start_shift, end_point);
871         if (!start_point)
872             goto fail_finish;
873
874
875         /* If the regex is absolutely anchored to either the start of the
876          * string (SBOL) or to pos() (ANCH_GPOS), then
877          * check_offset_max represents an upper bound on the string where
878          * the substr could start. For the ANCH_GPOS case, we assume that
879          * the caller of intuit will have already set strpos to
880          * pos()-gofs, so in this case strpos + offset_max will still be
881          * an upper bound on the substr.
882          */
883         if (!ml_anch
884             && prog->intflags & PREGf_ANCH
885             && prog->check_offset_max != SSize_t_MAX)
886         {
887             SSize_t len = SvCUR(check) - !!SvTAIL(check);
888             const char * const anchor =
889                         (prog->intflags & PREGf_ANCH_GPOS ? strpos : strbeg);
890
891             /* do a bytes rather than chars comparison. It's conservative;
892              * so it skips doing the HOP if the result can't possibly end
893              * up earlier than the old value of end_point.
894              */
895             if ((char*)end_point - anchor > prog->check_offset_max) {
896                 end_point = HOP3lim((U8*)anchor,
897                                 prog->check_offset_max,
898                                 end_point -len)
899                             + len;
900             }
901         }
902
903         check_at = fbm_instr( start_point, end_point,
904                       check, multiline ? FBMrf_MULTILINE : 0);
905
906         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
907             "  doing 'check' fbm scan, [%"IVdf"..%"IVdf"] gave %"IVdf"\n",
908             (IV)((char*)start_point - strbeg),
909             (IV)((char*)end_point   - strbeg),
910             (IV)(check_at ? check_at - strbeg : -1)
911         ));
912
913         /* Update the count-of-usability, remove useless subpatterns,
914             unshift s.  */
915
916         DEBUG_EXECUTE_r({
917             RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
918                 SvPVX_const(check), RE_SV_DUMPLEN(check), 30);
919             PerlIO_printf(Perl_debug_log, "  %s %s substr %s%s%s",
920                               (check_at ? "Found" : "Did not find"),
921                 (check == (utf8_target ? prog->anchored_utf8 : prog->anchored_substr)
922                     ? "anchored" : "floating"),
923                 quoted,
924                 RE_SV_TAIL(check),
925                 (check_at ? " at offset " : "...\n") );
926         });
927
928         if (!check_at)
929             goto fail_finish;
930         /* set rx_origin to the minimum position where the regex could start
931          * matching, given the constraint of the just-matched check substring.
932          * But don't set it lower than previously.
933          */
934
935         if (check_at - rx_origin > prog->check_offset_max)
936             rx_origin = HOP3c(check_at, -prog->check_offset_max, rx_origin);
937         /* Finish the diagnostic message */
938         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
939             "%ld (rx_origin now %"IVdf")...\n",
940             (long)(check_at - strbeg),
941             (IV)(rx_origin - strbeg)
942         ));
943     }
944
945
946     /* now look for the 'other' substring if defined */
947
948     if (utf8_target ? prog->substrs->data[other_ix].utf8_substr
949                     : prog->substrs->data[other_ix].substr)
950     {
951         /* Take into account the "other" substring. */
952         char *last, *last1;
953         char *s;
954         SV* must;
955         struct reg_substr_datum *other;
956
957       do_other_substr:
958         other = &prog->substrs->data[other_ix];
959
960         /* if "other" is anchored:
961          * we've previously found a floating substr starting at check_at.
962          * This means that the regex origin must lie somewhere
963          * between min (rx_origin): HOP3(check_at, -check_offset_max)
964          * and max:                 HOP3(check_at, -check_offset_min)
965          * (except that min will be >= strpos)
966          * So the fixed  substr must lie somewhere between
967          *  HOP3(min, anchored_offset)
968          *  HOP3(max, anchored_offset) + SvCUR(substr)
969          */
970
971         /* if "other" is floating
972          * Calculate last1, the absolute latest point where the
973          * floating substr could start in the string, ignoring any
974          * constraints from the earlier fixed match. It is calculated
975          * as follows:
976          *
977          * strend - prog->minlen (in chars) is the absolute latest
978          * position within the string where the origin of the regex
979          * could appear. The latest start point for the floating
980          * substr is float_min_offset(*) on from the start of the
981          * regex.  last1 simply combines thee two offsets.
982          *
983          * (*) You might think the latest start point should be
984          * float_max_offset from the regex origin, and technically
985          * you'd be correct. However, consider
986          *    /a\d{2,4}bcd\w/
987          * Here, float min, max are 3,5 and minlen is 7.
988          * This can match either
989          *    /a\d\dbcd\w/
990          *    /a\d\d\dbcd\w/
991          *    /a\d\d\d\dbcd\w/
992          * In the first case, the regex matches minlen chars; in the
993          * second, minlen+1, in the third, minlen+2.
994          * In the first case, the floating offset is 3 (which equals
995          * float_min), in the second, 4, and in the third, 5 (which
996          * equals float_max). In all cases, the floating string bcd
997          * can never start more than 4 chars from the end of the
998          * string, which equals minlen - float_min. As the substring
999          * starts to match more than float_min from the start of the
1000          * regex, it makes the regex match more than minlen chars,
1001          * and the two cancel each other out. So we can always use
1002          * float_min - minlen, rather than float_max - minlen for the
1003          * latest position in the string.
1004          *
1005          * Note that -minlen + float_min_offset is equivalent (AFAIKT)
1006          * to CHR_SVLEN(must) - !!SvTAIL(must) + prog->float_end_shift
1007          */
1008
1009         assert(prog->minlen >= other->min_offset);
1010         last1 = HOP3c(strend,
1011                         other->min_offset - prog->minlen, strbeg);
1012
1013         if (other_ix) {/* i.e. if (other-is-float) */
1014             /* last is the latest point where the floating substr could
1015              * start, *given* any constraints from the earlier fixed
1016              * match. This constraint is that the floating string starts
1017              * <= float_max_offset chars from the regex origin (rx_origin).
1018              * If this value is less than last1, use it instead.
1019              */
1020             assert(rx_origin <= last1);
1021             last =
1022                 /* this condition handles the offset==infinity case, and
1023                  * is a short-cut otherwise. Although it's comparing a
1024                  * byte offset to a char length, it does so in a safe way,
1025                  * since 1 char always occupies 1 or more bytes,
1026                  * so if a string range is  (last1 - rx_origin) bytes,
1027                  * it will be less than or equal to  (last1 - rx_origin)
1028                  * chars; meaning it errs towards doing the accurate HOP3
1029                  * rather than just using last1 as a short-cut */
1030                 (last1 - rx_origin) < other->max_offset
1031                     ? last1
1032                     : (char*)HOP3lim(rx_origin, other->max_offset, last1);
1033         }
1034         else {
1035             assert(strpos + start_shift <= check_at);
1036             last = HOP4c(check_at, other->min_offset - start_shift,
1037                         strbeg, strend);
1038         }
1039
1040         s = HOP3c(rx_origin, other->min_offset, strend);
1041         if (s < other_last)     /* These positions already checked */
1042             s = other_last;
1043
1044         must = utf8_target ? other->utf8_substr : other->substr;
1045         assert(SvPOK(must));
1046         {
1047             char *from = s;
1048             char *to   = last + SvCUR(must) - (SvTAIL(must)!=0);
1049
1050             if (from > to) {
1051                 s = NULL;
1052                 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1053                     "  skipping 'other' fbm scan: %"IVdf" > %"IVdf"\n",
1054                     (IV)(from - strbeg),
1055                     (IV)(to   - strbeg)
1056                 ));
1057             }
1058             else {
1059                 s = fbm_instr(
1060                     (unsigned char*)from,
1061                     (unsigned char*)to,
1062                     must,
1063                     multiline ? FBMrf_MULTILINE : 0
1064                 );
1065                 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1066                     "  doing 'other' fbm scan, [%"IVdf"..%"IVdf"] gave %"IVdf"\n",
1067                     (IV)(from - strbeg),
1068                     (IV)(to   - strbeg),
1069                     (IV)(s ? s - strbeg : -1)
1070                 ));
1071             }
1072         }
1073
1074         DEBUG_EXECUTE_r({
1075             RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
1076                 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
1077             PerlIO_printf(Perl_debug_log, "  %s %s substr %s%s",
1078                 s ? "Found" : "Contradicts",
1079                 other_ix ? "floating" : "anchored",
1080                 quoted, RE_SV_TAIL(must));
1081         });
1082
1083
1084         if (!s) {
1085             /* last1 is latest possible substr location. If we didn't
1086              * find it before there, we never will */
1087             if (last >= last1) {
1088                 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1089                                         "; giving up...\n"));
1090                 goto fail_finish;
1091             }
1092
1093             /* try to find the check substr again at a later
1094              * position. Maybe next time we'll find the "other" substr
1095              * in range too */
1096             other_last = HOP3c(last, 1, strend) /* highest failure */;
1097             rx_origin =
1098                 other_ix /* i.e. if other-is-float */
1099                     ? HOP3c(rx_origin, 1, strend)
1100                     : HOP4c(last, 1 - other->min_offset, strbeg, strend);
1101             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1102                 "; about to retry %s at offset %ld (rx_origin now %"IVdf")...\n",
1103                 (other_ix ? "floating" : "anchored"),
1104                 (long)(HOP3c(check_at, 1, strend) - strbeg),
1105                 (IV)(rx_origin - strbeg)
1106             ));
1107             goto restart;
1108         }
1109         else {
1110             if (other_ix) { /* if (other-is-float) */
1111                 /* other_last is set to s, not s+1, since its possible for
1112                  * a floating substr to fail first time, then succeed
1113                  * second time at the same floating position; e.g.:
1114                  *     "-AB--AABZ" =~ /\wAB\d*Z/
1115                  * The first time round, anchored and float match at
1116                  * "-(AB)--AAB(Z)" then fail on the initial \w character
1117                  * class. Second time round, they match at "-AB--A(AB)(Z)".
1118                  */
1119                 other_last = s;
1120             }
1121             else {
1122                 rx_origin = HOP3c(s, -other->min_offset, strbeg);
1123                 other_last = HOP3c(s, 1, strend);
1124             }
1125             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1126                 " at offset %ld (rx_origin now %"IVdf")...\n",
1127                   (long)(s - strbeg),
1128                 (IV)(rx_origin - strbeg)
1129               ));
1130
1131         }
1132     }
1133     else {
1134         DEBUG_OPTIMISE_MORE_r(
1135             PerlIO_printf(Perl_debug_log,
1136                 "  Check-only match: offset min:%"IVdf" max:%"IVdf
1137                 " check_at:%"IVdf" rx_origin:%"IVdf" rx_origin-check_at:%"IVdf
1138                 " strend:%"IVdf"\n",
1139                 (IV)prog->check_offset_min,
1140                 (IV)prog->check_offset_max,
1141                 (IV)(check_at-strbeg),
1142                 (IV)(rx_origin-strbeg),
1143                 (IV)(rx_origin-check_at),
1144                 (IV)(strend-strbeg)
1145             )
1146         );
1147     }
1148
1149   postprocess_substr_matches:
1150
1151     /* handle the extra constraint of /^.../m if present */
1152
1153     if (ml_anch && rx_origin != strbeg && rx_origin[-1] != '\n') {
1154         char *s;
1155
1156         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1157                         "  looking for /^/m anchor"));
1158
1159         /* we have failed the constraint of a \n before rx_origin.
1160          * Find the next \n, if any, even if it's beyond the current
1161          * anchored and/or floating substrings. Whether we should be
1162          * scanning ahead for the next \n or the next substr is debatable.
1163          * On the one hand you'd expect rare substrings to appear less
1164          * often than \n's. On the other hand, searching for \n means
1165          * we're effectively flipping between check_substr and "\n" on each
1166          * iteration as the current "rarest" string candidate, which
1167          * means for example that we'll quickly reject the whole string if
1168          * hasn't got a \n, rather than trying every substr position
1169          * first
1170          */
1171
1172         s = HOP3c(strend, - prog->minlen, strpos);
1173         if (s <= rx_origin ||
1174             ! ( rx_origin = (char *)memchr(rx_origin, '\n', s - rx_origin)))
1175         {
1176             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1177                             "  Did not find /%s^%s/m...\n",
1178                             PL_colors[0], PL_colors[1]));
1179             goto fail_finish;
1180         }
1181
1182         /* earliest possible origin is 1 char after the \n.
1183          * (since *rx_origin == '\n', it's safe to ++ here rather than
1184          * HOP(rx_origin, 1)) */
1185         rx_origin++;
1186
1187         if (prog->substrs->check_ix == 0  /* check is anchored */
1188             || rx_origin >= HOP3c(check_at,  - prog->check_offset_min, strpos))
1189         {
1190             /* Position contradicts check-string; either because
1191              * check was anchored (and thus has no wiggle room),
1192              * or check was float and rx_origin is above the float range */
1193             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1194                 "  Found /%s^%s/m, about to restart lookup for check-string with rx_origin %ld...\n",
1195                 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1196             goto restart;
1197         }
1198
1199         /* if we get here, the check substr must have been float,
1200          * is in range, and we may or may not have had an anchored
1201          * "other" substr which still contradicts */
1202         assert(prog->substrs->check_ix); /* check is float */
1203
1204         if (utf8_target ? prog->anchored_utf8 : prog->anchored_substr) {
1205             /* whoops, the anchored "other" substr exists, so we still
1206              * contradict. On the other hand, the float "check" substr
1207              * didn't contradict, so just retry the anchored "other"
1208              * substr */
1209             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1210                 "  Found /%s^%s/m, rescanning for anchored from offset %"IVdf" (rx_origin now %"IVdf")...\n",
1211                 PL_colors[0], PL_colors[1],
1212                 (IV)(rx_origin - strbeg + prog->anchored_offset),
1213                 (IV)(rx_origin - strbeg)
1214             ));
1215             goto do_other_substr;
1216         }
1217
1218         /* success: we don't contradict the found floating substring
1219          * (and there's no anchored substr). */
1220         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1221             "  Found /%s^%s/m with rx_origin %ld...\n",
1222             PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1223     }
1224     else {
1225         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1226             "  (multiline anchor test skipped)\n"));
1227     }
1228
1229   success_at_start:
1230
1231
1232     /* if we have a starting character class, then test that extra constraint.
1233      * (trie stclasses are too expensive to use here, we are better off to
1234      * leave it to regmatch itself) */
1235
1236     if (progi->regstclass && PL_regkind[OP(progi->regstclass)]!=TRIE) {
1237         const U8* const str = (U8*)STRING(progi->regstclass);
1238
1239         /* XXX this value could be pre-computed */
1240         const int cl_l = (PL_regkind[OP(progi->regstclass)] == EXACT
1241                     ?  (reginfo->is_utf8_pat
1242                         ? utf8_distance(str + STR_LEN(progi->regstclass), str)
1243                         : STR_LEN(progi->regstclass))
1244                     : 1);
1245         char * endpos;
1246         char *s;
1247         /* latest pos that a matching float substr constrains rx start to */
1248         char *rx_max_float = NULL;
1249
1250         /* if the current rx_origin is anchored, either by satisfying an
1251          * anchored substring constraint, or a /^.../m constraint, then we
1252          * can reject the current origin if the start class isn't found
1253          * at the current position. If we have a float-only match, then
1254          * rx_origin is constrained to a range; so look for the start class
1255          * in that range. if neither, then look for the start class in the
1256          * whole rest of the string */
1257
1258         /* XXX DAPM it's not clear what the minlen test is for, and why
1259          * it's not used in the floating case. Nothing in the test suite
1260          * causes minlen == 0 here. See <20140313134639.GS12844@iabyn.com>.
1261          * Here are some old comments, which may or may not be correct:
1262          *
1263          *   minlen == 0 is possible if regstclass is \b or \B,
1264          *   and the fixed substr is ''$.
1265          *   Since minlen is already taken into account, rx_origin+1 is
1266          *   before strend; accidentally, minlen >= 1 guaranties no false
1267          *   positives at rx_origin + 1 even for \b or \B.  But (minlen? 1 :
1268          *   0) below assumes that regstclass does not come from lookahead...
1269          *   If regstclass takes bytelength more than 1: If charlength==1, OK.
1270          *   This leaves EXACTF-ish only, which are dealt with in
1271          *   find_byclass().
1272          */
1273
1274         if (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
1275             endpos= HOP3c(rx_origin, (prog->minlen ? cl_l : 0), strend);
1276         else if (prog->float_substr || prog->float_utf8) {
1277             rx_max_float = HOP3c(check_at, -start_shift, strbeg);
1278             endpos= HOP3c(rx_max_float, cl_l, strend);
1279         }
1280         else 
1281             endpos= strend;
1282                     
1283         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1284             "  looking for class: start_shift: %"IVdf" check_at: %"IVdf
1285             " rx_origin: %"IVdf" endpos: %"IVdf"\n",
1286               (IV)start_shift, (IV)(check_at - strbeg),
1287               (IV)(rx_origin - strbeg), (IV)(endpos - strbeg)));
1288
1289         s = find_byclass(prog, progi->regstclass, rx_origin, endpos,
1290                             reginfo);
1291         if (!s) {
1292             if (endpos == strend) {
1293                 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1294                                 "  Could not match STCLASS...\n") );
1295                 goto fail;
1296             }
1297             DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1298                                "  This position contradicts STCLASS...\n") );
1299             if ((prog->intflags & PREGf_ANCH) && !ml_anch
1300                         && !(prog->intflags & PREGf_IMPLICIT))
1301                 goto fail;
1302
1303             /* Contradict one of substrings */
1304             if (prog->anchored_substr || prog->anchored_utf8) {
1305                 if (prog->substrs->check_ix == 1) { /* check is float */
1306                     /* Have both, check_string is floating */
1307                     assert(rx_origin + start_shift <= check_at);
1308                     if (rx_origin + start_shift != check_at) {
1309                         /* not at latest position float substr could match:
1310                          * Recheck anchored substring, but not floating.
1311                          * The condition above is in bytes rather than
1312                          * chars for efficiency. It's conservative, in
1313                          * that it errs on the side of doing 'goto
1314                          * do_other_substr'. In this case, at worst,
1315                          * an extra anchored search may get done, but in
1316                          * practice the extra fbm_instr() is likely to
1317                          * get skipped anyway. */
1318                         DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1319                             "  about to retry anchored at offset %ld (rx_origin now %"IVdf")...\n",
1320                             (long)(other_last - strbeg),
1321                             (IV)(rx_origin - strbeg)
1322                         ));
1323                         goto do_other_substr;
1324                     }
1325                 }
1326             }
1327             else {
1328                 /* float-only */
1329
1330                 if (ml_anch) {
1331                     /* In the presence of ml_anch, we might be able to
1332                      * find another \n without breaking the current float
1333                      * constraint. */
1334
1335                     /* strictly speaking this should be HOP3c(..., 1, ...),
1336                      * but since we goto a block of code that's going to
1337                      * search for the next \n if any, its safe here */
1338                     rx_origin++;
1339                     DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1340                               "  about to look for /%s^%s/m starting at rx_origin %ld...\n",
1341                               PL_colors[0], PL_colors[1],
1342                               (long)(rx_origin - strbeg)) );
1343                     goto postprocess_substr_matches;
1344                 }
1345
1346                 /* strictly speaking this can never be true; but might
1347                  * be if we ever allow intuit without substrings */
1348                 if (!(utf8_target ? prog->float_utf8 : prog->float_substr))
1349                     goto fail;
1350
1351                 rx_origin = rx_max_float;
1352             }
1353
1354             /* at this point, any matching substrings have been
1355              * contradicted. Start again... */
1356
1357             rx_origin = HOP3c(rx_origin, 1, strend);
1358
1359             /* uses bytes rather than char calculations for efficiency.
1360              * It's conservative: it errs on the side of doing 'goto restart',
1361              * where there is code that does a proper char-based test */
1362             if (rx_origin + start_shift + end_shift > strend) {
1363                 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1364                                        "  Could not match STCLASS...\n") );
1365                 goto fail;
1366             }
1367             DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1368                 "  about to look for %s substr starting at offset %ld (rx_origin now %"IVdf")...\n",
1369                 (prog->substrs->check_ix ? "floating" : "anchored"),
1370                 (long)(rx_origin + start_shift - strbeg),
1371                 (IV)(rx_origin - strbeg)
1372             ));
1373             goto restart;
1374         }
1375
1376         /* Success !!! */
1377
1378         if (rx_origin != s) {
1379             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1380                         "  By STCLASS: moving %ld --> %ld\n",
1381                                   (long)(rx_origin - strbeg), (long)(s - strbeg))
1382                    );
1383         }
1384         else {
1385             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1386                                   "  Does not contradict STCLASS...\n");
1387                    );
1388         }
1389     }
1390
1391     /* Decide whether using the substrings helped */
1392
1393     if (rx_origin != strpos) {
1394         /* Fixed substring is found far enough so that the match
1395            cannot start at strpos. */
1396
1397         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "  try at offset...\n"));
1398         ++BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr);        /* hooray/5 */
1399     }
1400     else {
1401         /* The found rx_origin position does not prohibit matching at
1402          * strpos, so calling intuit didn't gain us anything. Decrement
1403          * the BmUSEFUL() count on the check substring, and if we reach
1404          * zero, free it.  */
1405         if (!(prog->intflags & PREGf_NAUGHTY)
1406             && (utf8_target ? (
1407                 prog->check_utf8                /* Could be deleted already */
1408                 && --BmUSEFUL(prog->check_utf8) < 0
1409                 && (prog->check_utf8 == prog->float_utf8)
1410             ) : (
1411                 prog->check_substr              /* Could be deleted already */
1412                 && --BmUSEFUL(prog->check_substr) < 0
1413                 && (prog->check_substr == prog->float_substr)
1414             )))
1415         {
1416             /* If flags & SOMETHING - do not do it many times on the same match */
1417             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "  ... Disabling check substring...\n"));
1418             /* XXX Does the destruction order has to change with utf8_target? */
1419             SvREFCNT_dec(utf8_target ? prog->check_utf8 : prog->check_substr);
1420             SvREFCNT_dec(utf8_target ? prog->check_substr : prog->check_utf8);
1421             prog->check_substr = prog->check_utf8 = NULL;       /* disable */
1422             prog->float_substr = prog->float_utf8 = NULL;       /* clear */
1423             check = NULL;                       /* abort */
1424             /* XXXX This is a remnant of the old implementation.  It
1425                     looks wasteful, since now INTUIT can use many
1426                     other heuristics. */
1427             prog->extflags &= ~RXf_USE_INTUIT;
1428         }
1429     }
1430
1431     DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1432             "Intuit: %sSuccessfully guessed:%s match at offset %ld\n",
1433              PL_colors[4], PL_colors[5], (long)(rx_origin - strbeg)) );
1434
1435     return rx_origin;
1436
1437   fail_finish:                          /* Substring not found */
1438     if (prog->check_substr || prog->check_utf8)         /* could be removed already */
1439         BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
1440   fail:
1441     DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch rejected by optimizer%s\n",
1442                           PL_colors[4], PL_colors[5]));
1443     return NULL;
1444 }
1445
1446
1447 #define DECL_TRIE_TYPE(scan) \
1448     const enum { trie_plain, trie_utf8, trie_utf8_fold, trie_latin_utf8_fold,       \
1449                  trie_utf8_exactfa_fold, trie_latin_utf8_exactfa_fold,              \
1450                  trie_utf8l, trie_flu8 }                                            \
1451                     trie_type = ((scan->flags == EXACT)                             \
1452                                  ? (utf8_target ? trie_utf8 : trie_plain)           \
1453                                  : (scan->flags == EXACTL)                          \
1454                                     ? (utf8_target ? trie_utf8l : trie_plain)       \
1455                                     : (scan->flags == EXACTFA)                      \
1456                                       ? (utf8_target                                \
1457                                          ? trie_utf8_exactfa_fold                   \
1458                                          : trie_latin_utf8_exactfa_fold)            \
1459                                       : (scan->flags == EXACTFLU8                   \
1460                                          ? trie_flu8                                \
1461                                          : (utf8_target                             \
1462                                            ? trie_utf8_fold                         \
1463                                            :   trie_latin_utf8_fold)))
1464
1465 #define REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc, uscan, len, uvc, charid, foldlen, foldbuf, uniflags) \
1466 STMT_START {                                                                        \
1467     STRLEN skiplen;                                                                 \
1468     U8 flags = FOLD_FLAGS_FULL;                                                     \
1469     switch (trie_type) {                                                            \
1470     case trie_flu8:                                                                 \
1471         _CHECK_AND_WARN_PROBLEMATIC_LOCALE;                                         \
1472         if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) {                             \
1473             _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc));          \
1474         }                                                                           \
1475         goto do_trie_utf8_fold;                                                     \
1476     case trie_utf8_exactfa_fold:                                                    \
1477         flags |= FOLD_FLAGS_NOMIX_ASCII;                                            \
1478         /* FALLTHROUGH */                                                           \
1479     case trie_utf8_fold:                                                            \
1480       do_trie_utf8_fold:                                                            \
1481         if ( foldlen>0 ) {                                                          \
1482             uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1483             foldlen -= len;                                                         \
1484             uscan += len;                                                           \
1485             len=0;                                                                  \
1486         } else {                                                                    \
1487             uvc = _to_utf8_fold_flags( (const U8*) uc, foldbuf, &foldlen, flags);   \
1488             len = UTF8SKIP(uc);                                                     \
1489             skiplen = UVCHR_SKIP( uvc );                                            \
1490             foldlen -= skiplen;                                                     \
1491             uscan = foldbuf + skiplen;                                              \
1492         }                                                                           \
1493         break;                                                                      \
1494     case trie_latin_utf8_exactfa_fold:                                              \
1495         flags |= FOLD_FLAGS_NOMIX_ASCII;                                            \
1496         /* FALLTHROUGH */                                                           \
1497     case trie_latin_utf8_fold:                                                      \
1498         if ( foldlen>0 ) {                                                          \
1499             uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1500             foldlen -= len;                                                         \
1501             uscan += len;                                                           \
1502             len=0;                                                                  \
1503         } else {                                                                    \
1504             len = 1;                                                                \
1505             uvc = _to_fold_latin1( (U8) *uc, foldbuf, &foldlen, flags);             \
1506             skiplen = UVCHR_SKIP( uvc );                                            \
1507             foldlen -= skiplen;                                                     \
1508             uscan = foldbuf + skiplen;                                              \
1509         }                                                                           \
1510         break;                                                                      \
1511     case trie_utf8l:                                                                \
1512         _CHECK_AND_WARN_PROBLEMATIC_LOCALE;                                         \
1513         if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) {                             \
1514             _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc));          \
1515         }                                                                           \
1516         /* FALLTHROUGH */                                                           \
1517     case trie_utf8:                                                                 \
1518         uvc = utf8n_to_uvchr( (const U8*) uc, UTF8_MAXLEN, &len, uniflags );        \
1519         break;                                                                      \
1520     case trie_plain:                                                                \
1521         uvc = (UV)*uc;                                                              \
1522         len = 1;                                                                    \
1523     }                                                                               \
1524     if (uvc < 256) {                                                                \
1525         charid = trie->charmap[ uvc ];                                              \
1526     }                                                                               \
1527     else {                                                                          \
1528         charid = 0;                                                                 \
1529         if (widecharmap) {                                                          \
1530             SV** const svpp = hv_fetch(widecharmap,                                 \
1531                         (char*)&uvc, sizeof(UV), 0);                                \
1532             if (svpp)                                                               \
1533                 charid = (U16)SvIV(*svpp);                                          \
1534         }                                                                           \
1535     }                                                                               \
1536 } STMT_END
1537
1538 #define DUMP_EXEC_POS(li,s,doutf8)                          \
1539     dump_exec_pos(li,s,(reginfo->strend),(reginfo->strbeg), \
1540                 startpos, doutf8)
1541
1542 #define REXEC_FBC_EXACTISH_SCAN(COND)                     \
1543 STMT_START {                                              \
1544     while (s <= e) {                                      \
1545         if ( (COND)                                       \
1546              && (ln == 1 || folder(s, pat_string, ln))    \
1547              && (reginfo->intuit || regtry(reginfo, &s)) )\
1548             goto got_it;                                  \
1549         s++;                                              \
1550     }                                                     \
1551 } STMT_END
1552
1553 #define REXEC_FBC_UTF8_SCAN(CODE)                     \
1554 STMT_START {                                          \
1555     while (s < strend) {                              \
1556         CODE                                          \
1557         s += UTF8SKIP(s);                             \
1558     }                                                 \
1559 } STMT_END
1560
1561 #define REXEC_FBC_SCAN(CODE)                          \
1562 STMT_START {                                          \
1563     while (s < strend) {                              \
1564         CODE                                          \
1565         s++;                                          \
1566     }                                                 \
1567 } STMT_END
1568
1569 #define REXEC_FBC_UTF8_CLASS_SCAN(COND)                        \
1570 REXEC_FBC_UTF8_SCAN( /* Loops while (s < strend) */            \
1571     if (COND) {                                                \
1572         if (tmp && (reginfo->intuit || regtry(reginfo, &s)))   \
1573             goto got_it;                                       \
1574         else                                                   \
1575             tmp = doevery;                                     \
1576     }                                                          \
1577     else                                                       \
1578         tmp = 1;                                               \
1579 )
1580
1581 #define REXEC_FBC_CLASS_SCAN(COND)                             \
1582 REXEC_FBC_SCAN( /* Loops while (s < strend) */                 \
1583     if (COND) {                                                \
1584         if (tmp && (reginfo->intuit || regtry(reginfo, &s)))   \
1585             goto got_it;                                       \
1586         else                                                   \
1587             tmp = doevery;                                     \
1588     }                                                          \
1589     else                                                       \
1590         tmp = 1;                                               \
1591 )
1592
1593 #define REXEC_FBC_CSCAN(CONDUTF8,COND)                         \
1594     if (utf8_target) {                                         \
1595         REXEC_FBC_UTF8_CLASS_SCAN(CONDUTF8);                   \
1596     }                                                          \
1597     else {                                                     \
1598         REXEC_FBC_CLASS_SCAN(COND);                            \
1599     }
1600
1601 /* The three macros below are slightly different versions of the same logic.
1602  *
1603  * The first is for /a and /aa when the target string is UTF-8.  This can only
1604  * match ascii, but it must advance based on UTF-8.   The other two handle the
1605  * non-UTF-8 and the more generic UTF-8 cases.   In all three, we are looking
1606  * for the boundary (or non-boundary) between a word and non-word character.
1607  * The utf8 and non-utf8 cases have the same logic, but the details must be
1608  * different.  Find the "wordness" of the character just prior to this one, and
1609  * compare it with the wordness of this one.  If they differ, we have a
1610  * boundary.  At the beginning of the string, pretend that the previous
1611  * character was a new-line.
1612  *
1613  * All these macros uncleanly have side-effects with each other and outside
1614  * variables.  So far it's been too much trouble to clean-up
1615  *
1616  * TEST_NON_UTF8 is the macro or function to call to test if its byte input is
1617  *               a word character or not.
1618  * IF_SUCCESS    is code to do if it finds that we are at a boundary between
1619  *               word/non-word
1620  * IF_FAIL       is code to do if we aren't at a boundary between word/non-word
1621  *
1622  * Exactly one of the two IF_FOO parameters is a no-op, depending on whether we
1623  * are looking for a boundary or for a non-boundary.  If we are looking for a
1624  * boundary, we want IF_FAIL to be the no-op, and for IF_SUCCESS to go out and
1625  * see if this tentative match actually works, and if so, to quit the loop
1626  * here.  And vice-versa if we are looking for a non-boundary.
1627  *
1628  * 'tmp' below in the next three macros in the REXEC_FBC_SCAN and
1629  * REXEC_FBC_UTF8_SCAN loops is a loop invariant, a bool giving the return of
1630  * TEST_NON_UTF8(s-1).  To see this, note that that's what it is defined to be
1631  * at entry to the loop, and to get to the IF_FAIL branch, tmp must equal
1632  * TEST_NON_UTF8(s), and in the opposite branch, IF_SUCCESS, tmp is that
1633  * complement.  But in that branch we complement tmp, meaning that at the
1634  * bottom of the loop tmp is always going to be equal to TEST_NON_UTF8(s),
1635  * which means at the top of the loop in the next iteration, it is
1636  * TEST_NON_UTF8(s-1) */
1637 #define FBC_UTF8_A(TEST_NON_UTF8, IF_SUCCESS, IF_FAIL)                         \
1638     tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n';                      \
1639     tmp = TEST_NON_UTF8(tmp);                                                  \
1640     REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */                     \
1641         if (tmp == ! TEST_NON_UTF8((U8) *s)) {                                 \
1642             tmp = !tmp;                                                        \
1643             IF_SUCCESS; /* Is a boundary if values for s-1 and s differ */     \
1644         }                                                                      \
1645         else {                                                                 \
1646             IF_FAIL;                                                           \
1647         }                                                                      \
1648     );                                                                         \
1649
1650 /* Like FBC_UTF8_A, but TEST_UV is a macro which takes a UV as its input, and
1651  * TEST_UTF8 is a macro that for the same input code points returns identically
1652  * to TEST_UV, but takes a pointer to a UTF-8 encoded string instead */
1653 #define FBC_UTF8(TEST_UV, TEST_UTF8, IF_SUCCESS, IF_FAIL)                      \
1654     if (s == reginfo->strbeg) {                                                \
1655         tmp = '\n';                                                            \
1656     }                                                                          \
1657     else { /* Back-up to the start of the previous character */                \
1658         U8 * const r = reghop3((U8*)s, -1, (U8*)reginfo->strbeg);              \
1659         tmp = utf8n_to_uvchr(r, (U8*) reginfo->strend - r,                     \
1660                                                        0, UTF8_ALLOW_DEFAULT); \
1661     }                                                                          \
1662     tmp = TEST_UV(tmp);                                                        \
1663     LOAD_UTF8_CHARCLASS_ALNUM();                                               \
1664     REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */                     \
1665         if (tmp == ! (TEST_UTF8((U8 *) s))) {                                  \
1666             tmp = !tmp;                                                        \
1667             IF_SUCCESS;                                                        \
1668         }                                                                      \
1669         else {                                                                 \
1670             IF_FAIL;                                                           \
1671         }                                                                      \
1672     );
1673
1674 /* Like the above two macros.  UTF8_CODE is the complete code for handling
1675  * UTF-8.  Common to the BOUND and NBOUND cases, set-up by the FBC_BOUND, etc
1676  * macros below */
1677 #define FBC_BOUND_COMMON(UTF8_CODE, TEST_NON_UTF8, IF_SUCCESS, IF_FAIL)        \
1678     if (utf8_target) {                                                         \
1679         UTF8_CODE                                                              \
1680     }                                                                          \
1681     else {  /* Not utf8 */                                                     \
1682         tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n';                  \
1683         tmp = TEST_NON_UTF8(tmp);                                              \
1684         REXEC_FBC_SCAN( /* advances s while s < strend */                      \
1685             if (tmp == ! TEST_NON_UTF8((U8) *s)) {                             \
1686                 IF_SUCCESS;                                                    \
1687                 tmp = !tmp;                                                    \
1688             }                                                                  \
1689             else {                                                             \
1690                 IF_FAIL;                                                       \
1691             }                                                                  \
1692         );                                                                     \
1693     }                                                                          \
1694     /* Here, things have been set up by the previous code so that tmp is the   \
1695      * return of TEST_NON_UTF(s-1) or TEST_UTF8(s-1) (depending on the         \
1696      * utf8ness of the target).  We also have to check if this matches against \
1697      * the EOS, which we treat as a \n (which is the same value in both UTF-8  \
1698      * or non-UTF8, so can use the non-utf8 test condition even for a UTF-8    \
1699      * string */                                                               \
1700     if (tmp == ! TEST_NON_UTF8('\n')) {                                        \
1701         IF_SUCCESS;                                                            \
1702     }                                                                          \
1703     else {                                                                     \
1704         IF_FAIL;                                                               \
1705     }
1706
1707 /* This is the macro to use when we want to see if something that looks like it
1708  * could match, actually does, and if so exits the loop */
1709 #define REXEC_FBC_TRYIT                            \
1710     if ((reginfo->intuit || regtry(reginfo, &s)))  \
1711         goto got_it
1712
1713 /* The only difference between the BOUND and NBOUND cases is that
1714  * REXEC_FBC_TRYIT is called when matched in BOUND, and when non-matched in
1715  * NBOUND.  This is accomplished by passing it as either the if or else clause,
1716  * with the other one being empty (PLACEHOLDER is defined as empty).
1717  *
1718  * The TEST_FOO parameters are for operating on different forms of input, but
1719  * all should be ones that return identically for the same underlying code
1720  * points */
1721 #define FBC_BOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8)                           \
1722     FBC_BOUND_COMMON(                                                          \
1723           FBC_UTF8(TEST_UV, TEST_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER),          \
1724           TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1725
1726 #define FBC_BOUND_A(TEST_NON_UTF8)                                             \
1727     FBC_BOUND_COMMON(                                                          \
1728             FBC_UTF8_A(TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER),           \
1729             TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1730
1731 #define FBC_NBOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8)                          \
1732     FBC_BOUND_COMMON(                                                          \
1733           FBC_UTF8(TEST_UV, TEST_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT),          \
1734           TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1735
1736 #define FBC_NBOUND_A(TEST_NON_UTF8)                                            \
1737     FBC_BOUND_COMMON(                                                          \
1738             FBC_UTF8_A(TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT),           \
1739             TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1740
1741 #ifdef DEBUGGING
1742 static IV
1743 S_get_break_val_cp_checked(SV* const invlist, const UV cp_in) {
1744   IV cp_out = Perl__invlist_search(invlist, cp_in);
1745   assert(cp_out >= 0);
1746   return cp_out;
1747 }
1748 #  define _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp) \
1749         invmap[S_get_break_val_cp_checked(invlist, cp)]
1750 #else
1751 #  define _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp) \
1752         invmap[_invlist_search(invlist, cp)]
1753 #endif
1754
1755 /* Takes a pointer to an inversion list, a pointer to its corresponding
1756  * inversion map, and a code point, and returns the code point's value
1757  * according to the two arrays.  It assumes that all code points have a value.
1758  * This is used as the base macro for macros for particular properties */
1759 #define _generic_GET_BREAK_VAL_CP(invlist, invmap, cp)              \
1760         _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp)
1761
1762 /* Same as above, but takes begin, end ptrs to a UTF-8 encoded string instead
1763  * of a code point, returning the value for the first code point in the string.
1764  * And it takes the particular macro name that finds the desired value given a
1765  * code point.  Merely convert the UTF-8 to code point and call the cp macro */
1766 #define _generic_GET_BREAK_VAL_UTF8(cp_macro, pos, strend)                     \
1767              (__ASSERT_(pos < strend)                                          \
1768                  /* Note assumes is valid UTF-8 */                             \
1769              (cp_macro(utf8_to_uvchr_buf((pos), (strend), NULL))))
1770
1771 /* Returns the GCB value for the input code point */
1772 #define getGCB_VAL_CP(cp)                                                      \
1773           _generic_GET_BREAK_VAL_CP(                                           \
1774                                     PL_GCB_invlist,                            \
1775                                     _Perl_GCB_invmap,                          \
1776                                     (cp))
1777
1778 /* Returns the GCB value for the first code point in the UTF-8 encoded string
1779  * bounded by pos and strend */
1780 #define getGCB_VAL_UTF8(pos, strend)                                           \
1781     _generic_GET_BREAK_VAL_UTF8(getGCB_VAL_CP, pos, strend)
1782
1783 /* Returns the LB value for the input code point */
1784 #define getLB_VAL_CP(cp)                                                       \
1785           _generic_GET_BREAK_VAL_CP(                                           \
1786                                     PL_LB_invlist,                             \
1787                                     _Perl_LB_invmap,                           \
1788                                     (cp))
1789
1790 /* Returns the LB value for the first code point in the UTF-8 encoded string
1791  * bounded by pos and strend */
1792 #define getLB_VAL_UTF8(pos, strend)                                            \
1793     _generic_GET_BREAK_VAL_UTF8(getLB_VAL_CP, pos, strend)
1794
1795
1796 /* Returns the SB value for the input code point */
1797 #define getSB_VAL_CP(cp)                                                       \
1798           _generic_GET_BREAK_VAL_CP(                                           \
1799                                     PL_SB_invlist,                             \
1800                                     _Perl_SB_invmap,                     \
1801                                     (cp))
1802
1803 /* Returns the SB value for the first code point in the UTF-8 encoded string
1804  * bounded by pos and strend */
1805 #define getSB_VAL_UTF8(pos, strend)                                            \
1806     _generic_GET_BREAK_VAL_UTF8(getSB_VAL_CP, pos, strend)
1807
1808 /* Returns the WB value for the input code point */
1809 #define getWB_VAL_CP(cp)                                                       \
1810           _generic_GET_BREAK_VAL_CP(                                           \
1811                                     PL_WB_invlist,                             \
1812                                     _Perl_WB_invmap,                         \
1813                                     (cp))
1814
1815 /* Returns the WB value for the first code point in the UTF-8 encoded string
1816  * bounded by pos and strend */
1817 #define getWB_VAL_UTF8(pos, strend)                                            \
1818     _generic_GET_BREAK_VAL_UTF8(getWB_VAL_CP, pos, strend)
1819
1820 /* We know what class REx starts with.  Try to find this position... */
1821 /* if reginfo->intuit, its a dryrun */
1822 /* annoyingly all the vars in this routine have different names from their counterparts
1823    in regmatch. /grrr */
1824 STATIC char *
1825 S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s, 
1826     const char *strend, regmatch_info *reginfo)
1827 {
1828     dVAR;
1829     const I32 doevery = (prog->intflags & PREGf_SKIP) == 0;
1830     char *pat_string;   /* The pattern's exactish string */
1831     char *pat_end;          /* ptr to end char of pat_string */
1832     re_fold_t folder;   /* Function for computing non-utf8 folds */
1833     const U8 *fold_array;   /* array for folding ords < 256 */
1834     STRLEN ln;
1835     STRLEN lnc;
1836     U8 c1;
1837     U8 c2;
1838     char *e;
1839     I32 tmp = 1;        /* Scratch variable? */
1840     const bool utf8_target = reginfo->is_utf8_target;
1841     UV utf8_fold_flags = 0;
1842     const bool is_utf8_pat = reginfo->is_utf8_pat;
1843     bool to_complement = FALSE; /* Invert the result?  Taking the xor of this
1844                                    with a result inverts that result, as 0^1 =
1845                                    1 and 1^1 = 0 */
1846     _char_class_number classnum;
1847
1848     RXi_GET_DECL(prog,progi);
1849
1850     PERL_ARGS_ASSERT_FIND_BYCLASS;
1851
1852     /* We know what class it must start with. */
1853     switch (OP(c)) {
1854     case ANYOFL:
1855         _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1856
1857         if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(c)) && ! IN_UTF8_CTYPE_LOCALE) {
1858             Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
1859         }
1860
1861         /* FALLTHROUGH */
1862     case ANYOFD:
1863     case ANYOF:
1864         if (utf8_target) {
1865             REXEC_FBC_UTF8_CLASS_SCAN(
1866                       reginclass(prog, c, (U8*)s, (U8*) strend, utf8_target));
1867         }
1868         else {
1869             REXEC_FBC_CLASS_SCAN(REGINCLASS(prog, c, (U8*)s, 0));
1870         }
1871         break;
1872
1873     case EXACTFA_NO_TRIE:   /* This node only generated for non-utf8 patterns */
1874         assert(! is_utf8_pat);
1875         /* FALLTHROUGH */
1876     case EXACTFA:
1877         if (is_utf8_pat || utf8_target) {
1878             utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
1879             goto do_exactf_utf8;
1880         }
1881         fold_array = PL_fold_latin1;    /* Latin1 folds are not affected by */
1882         folder = foldEQ_latin1;         /* /a, except the sharp s one which */
1883         goto do_exactf_non_utf8;        /* isn't dealt with by these */
1884
1885     case EXACTF:   /* This node only generated for non-utf8 patterns */
1886         assert(! is_utf8_pat);
1887         if (utf8_target) {
1888             utf8_fold_flags = 0;
1889             goto do_exactf_utf8;
1890         }
1891         fold_array = PL_fold;
1892         folder = foldEQ;
1893         goto do_exactf_non_utf8;
1894
1895     case EXACTFL:
1896         _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1897         if (is_utf8_pat || utf8_target || IN_UTF8_CTYPE_LOCALE) {
1898             utf8_fold_flags = FOLDEQ_LOCALE;
1899             goto do_exactf_utf8;
1900         }
1901         fold_array = PL_fold_locale;
1902         folder = foldEQ_locale;
1903         goto do_exactf_non_utf8;
1904
1905     case EXACTFU_SS:
1906         if (is_utf8_pat) {
1907             utf8_fold_flags = FOLDEQ_S2_ALREADY_FOLDED;
1908         }
1909         goto do_exactf_utf8;
1910
1911     case EXACTFLU8:
1912             if (! utf8_target) {    /* All code points in this node require
1913                                        UTF-8 to express.  */
1914                 break;
1915             }
1916             utf8_fold_flags =  FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
1917                                              | FOLDEQ_S2_FOLDS_SANE;
1918             goto do_exactf_utf8;
1919
1920     case EXACTFU:
1921         if (is_utf8_pat || utf8_target) {
1922             utf8_fold_flags = is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
1923             goto do_exactf_utf8;
1924         }
1925
1926         /* Any 'ss' in the pattern should have been replaced by regcomp,
1927          * so we don't have to worry here about this single special case
1928          * in the Latin1 range */
1929         fold_array = PL_fold_latin1;
1930         folder = foldEQ_latin1;
1931
1932         /* FALLTHROUGH */
1933
1934       do_exactf_non_utf8: /* Neither pattern nor string are UTF8, and there
1935                            are no glitches with fold-length differences
1936                            between the target string and pattern */
1937
1938         /* The idea in the non-utf8 EXACTF* cases is to first find the
1939          * first character of the EXACTF* node and then, if necessary,
1940          * case-insensitively compare the full text of the node.  c1 is the
1941          * first character.  c2 is its fold.  This logic will not work for
1942          * Unicode semantics and the german sharp ss, which hence should
1943          * not be compiled into a node that gets here. */
1944         pat_string = STRING(c);
1945         ln  = STR_LEN(c);       /* length to match in octets/bytes */
1946
1947         /* We know that we have to match at least 'ln' bytes (which is the
1948          * same as characters, since not utf8).  If we have to match 3
1949          * characters, and there are only 2 availabe, we know without
1950          * trying that it will fail; so don't start a match past the
1951          * required minimum number from the far end */
1952         e = HOP3c(strend, -((SSize_t)ln), s);
1953
1954         if (reginfo->intuit && e < s) {
1955             e = s;                      /* Due to minlen logic of intuit() */
1956         }
1957
1958         c1 = *pat_string;
1959         c2 = fold_array[c1];
1960         if (c1 == c2) { /* If char and fold are the same */
1961             REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1);
1962         }
1963         else {
1964             REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1 || *(U8*)s == c2);
1965         }
1966         break;
1967
1968       do_exactf_utf8:
1969       {
1970         unsigned expansion;
1971
1972         /* If one of the operands is in utf8, we can't use the simpler folding
1973          * above, due to the fact that many different characters can have the
1974          * same fold, or portion of a fold, or different- length fold */
1975         pat_string = STRING(c);
1976         ln  = STR_LEN(c);       /* length to match in octets/bytes */
1977         pat_end = pat_string + ln;
1978         lnc = is_utf8_pat       /* length to match in characters */
1979                 ? utf8_length((U8 *) pat_string, (U8 *) pat_end)
1980                 : ln;
1981
1982         /* We have 'lnc' characters to match in the pattern, but because of
1983          * multi-character folding, each character in the target can match
1984          * up to 3 characters (Unicode guarantees it will never exceed
1985          * this) if it is utf8-encoded; and up to 2 if not (based on the
1986          * fact that the Latin 1 folds are already determined, and the
1987          * only multi-char fold in that range is the sharp-s folding to
1988          * 'ss'.  Thus, a pattern character can match as little as 1/3 of a
1989          * string character.  Adjust lnc accordingly, rounding up, so that
1990          * if we need to match at least 4+1/3 chars, that really is 5. */
1991         expansion = (utf8_target) ? UTF8_MAX_FOLD_CHAR_EXPAND : 2;
1992         lnc = (lnc + expansion - 1) / expansion;
1993
1994         /* As in the non-UTF8 case, if we have to match 3 characters, and
1995          * only 2 are left, it's guaranteed to fail, so don't start a
1996          * match that would require us to go beyond the end of the string
1997          */
1998         e = HOP3c(strend, -((SSize_t)lnc), s);
1999
2000         if (reginfo->intuit && e < s) {
2001             e = s;                      /* Due to minlen logic of intuit() */
2002         }
2003
2004         /* XXX Note that we could recalculate e to stop the loop earlier,
2005          * as the worst case expansion above will rarely be met, and as we
2006          * go along we would usually find that e moves further to the left.
2007          * This would happen only after we reached the point in the loop
2008          * where if there were no expansion we should fail.  Unclear if
2009          * worth the expense */
2010
2011         while (s <= e) {
2012             char *my_strend= (char *)strend;
2013             if (foldEQ_utf8_flags(s, &my_strend, 0,  utf8_target,
2014                   pat_string, NULL, ln, is_utf8_pat, utf8_fold_flags)
2015                 && (reginfo->intuit || regtry(reginfo, &s)) )
2016             {
2017                 goto got_it;
2018             }
2019             s += (utf8_target) ? UTF8SKIP(s) : 1;
2020         }
2021         break;
2022     }
2023
2024     case BOUNDL:
2025         _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2026         if (FLAGS(c) != TRADITIONAL_BOUND) {
2027             if (! IN_UTF8_CTYPE_LOCALE) {
2028                 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2029                                                 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2030             }
2031             goto do_boundu;
2032         }
2033
2034         FBC_BOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8);
2035         break;
2036
2037     case NBOUNDL:
2038         _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2039         if (FLAGS(c) != TRADITIONAL_BOUND) {
2040             if (! IN_UTF8_CTYPE_LOCALE) {
2041                 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2042                                                 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2043             }
2044             goto do_nboundu;
2045         }
2046
2047         FBC_NBOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8);
2048         break;
2049
2050     case BOUND: /* regcomp.c makes sure that this only has the traditional \b
2051                    meaning */
2052         assert(FLAGS(c) == TRADITIONAL_BOUND);
2053
2054         FBC_BOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8);
2055         break;
2056
2057     case BOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2058                    meaning */
2059         assert(FLAGS(c) == TRADITIONAL_BOUND);
2060
2061         FBC_BOUND_A(isWORDCHAR_A);
2062         break;
2063
2064     case NBOUND: /* regcomp.c makes sure that this only has the traditional \b
2065                    meaning */
2066         assert(FLAGS(c) == TRADITIONAL_BOUND);
2067
2068         FBC_NBOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8);
2069         break;
2070
2071     case NBOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2072                    meaning */
2073         assert(FLAGS(c) == TRADITIONAL_BOUND);
2074
2075         FBC_NBOUND_A(isWORDCHAR_A);
2076         break;
2077
2078     case NBOUNDU:
2079         if ((bound_type) FLAGS(c) == TRADITIONAL_BOUND) {
2080             FBC_NBOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8);
2081             break;
2082         }
2083
2084       do_nboundu:
2085
2086         to_complement = 1;
2087         /* FALLTHROUGH */
2088
2089     case BOUNDU:
2090       do_boundu:
2091         switch((bound_type) FLAGS(c)) {
2092             case TRADITIONAL_BOUND:
2093                 FBC_BOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8);
2094                 break;
2095             case GCB_BOUND:
2096                 if (s == reginfo->strbeg) {
2097                     if (reginfo->intuit || regtry(reginfo, &s))
2098                     {
2099                         goto got_it;
2100                     }
2101
2102                     /* Didn't match.  Try at the next position (if there is one) */
2103                     s += (utf8_target) ? UTF8SKIP(s) : 1;
2104                     if (UNLIKELY(s >= reginfo->strend)) {
2105                         break;
2106                     }
2107                 }
2108
2109                 if (utf8_target) {
2110                     GCB_enum before = getGCB_VAL_UTF8(
2111                                                reghop3((U8*)s, -1,
2112                                                        (U8*)(reginfo->strbeg)),
2113                                                (U8*) reginfo->strend);
2114                     while (s < strend) {
2115                         GCB_enum after = getGCB_VAL_UTF8((U8*) s,
2116                                                         (U8*) reginfo->strend);
2117                         if (   (to_complement ^ isGCB(before, after))
2118                             && (reginfo->intuit || regtry(reginfo, &s)))
2119                         {
2120                             goto got_it;
2121                         }
2122                         before = after;
2123                         s += UTF8SKIP(s);
2124                     }
2125                 }
2126                 else {  /* Not utf8.  Everything is a GCB except between CR and
2127                            LF */
2128                     while (s < strend) {
2129                         if ((to_complement ^ (   UCHARAT(s - 1) != '\r'
2130                                               || UCHARAT(s) != '\n'))
2131                             && (reginfo->intuit || regtry(reginfo, &s)))
2132                         {
2133                             goto got_it;
2134                         }
2135                         s++;
2136                     }
2137                 }
2138
2139                 /* And, since this is a bound, it can match after the final
2140                  * character in the string */
2141                 if ((reginfo->intuit || regtry(reginfo, &s))) {
2142                     goto got_it;
2143                 }
2144                 break;
2145
2146             case LB_BOUND:
2147                 if (s == reginfo->strbeg) {
2148                     if (reginfo->intuit || regtry(reginfo, &s)) {
2149                         goto got_it;
2150                     }
2151                     s += (utf8_target) ? UTF8SKIP(s) : 1;
2152                     if (UNLIKELY(s >= reginfo->strend)) {
2153                         break;
2154                     }
2155                 }
2156
2157                 if (utf8_target) {
2158                     LB_enum before = getLB_VAL_UTF8(reghop3((U8*)s,
2159                                                                -1,
2160                                                                (U8*)(reginfo->strbeg)),
2161                                                        (U8*) reginfo->strend);
2162                     while (s < strend) {
2163                         LB_enum after = getLB_VAL_UTF8((U8*) s, (U8*) reginfo->strend);
2164                         if (to_complement ^ isLB(before,
2165                                                  after,
2166                                                  (U8*) reginfo->strbeg,
2167                                                  (U8*) s,
2168                                                  (U8*) reginfo->strend,
2169                                                  utf8_target)
2170                             && (reginfo->intuit || regtry(reginfo, &s)))
2171                         {
2172                             goto got_it;
2173                         }
2174                         before = after;
2175                         s += UTF8SKIP(s);
2176                     }
2177                 }
2178                 else {  /* Not utf8. */
2179                     LB_enum before = getLB_VAL_CP((U8) *(s -1));
2180                     while (s < strend) {
2181                         LB_enum after = getLB_VAL_CP((U8) *s);
2182                         if (to_complement ^ isLB(before,
2183                                                  after,
2184                                                  (U8*) reginfo->strbeg,
2185                                                  (U8*) s,
2186                                                  (U8*) reginfo->strend,
2187                                                  utf8_target)
2188                             && (reginfo->intuit || regtry(reginfo, &s)))
2189                         {
2190                             goto got_it;
2191                         }
2192                         before = after;
2193                         s++;
2194                     }
2195                 }
2196
2197                 if (reginfo->intuit || regtry(reginfo, &s)) {
2198                     goto got_it;
2199                 }
2200
2201                 break;
2202
2203             case SB_BOUND:
2204                 if (s == reginfo->strbeg) {
2205                     if (reginfo->intuit || regtry(reginfo, &s)) {
2206                         goto got_it;
2207                     }
2208                     s += (utf8_target) ? UTF8SKIP(s) : 1;
2209                     if (UNLIKELY(s >= reginfo->strend)) {
2210                         break;
2211                     }
2212                 }
2213
2214                 if (utf8_target) {
2215                     SB_enum before = getSB_VAL_UTF8(reghop3((U8*)s,
2216                                                         -1,
2217                                                         (U8*)(reginfo->strbeg)),
2218                                                       (U8*) reginfo->strend);
2219                     while (s < strend) {
2220                         SB_enum after = getSB_VAL_UTF8((U8*) s,
2221                                                          (U8*) reginfo->strend);
2222                         if ((to_complement ^ isSB(before,
2223                                                   after,
2224                                                   (U8*) reginfo->strbeg,
2225                                                   (U8*) s,
2226                                                   (U8*) reginfo->strend,
2227                                                   utf8_target))
2228                             && (reginfo->intuit || regtry(reginfo, &s)))
2229                         {
2230                             goto got_it;
2231                         }
2232                         before = after;
2233                         s += UTF8SKIP(s);
2234                     }
2235                 }
2236                 else {  /* Not utf8. */
2237                     SB_enum before = getSB_VAL_CP((U8) *(s -1));
2238                     while (s < strend) {
2239                         SB_enum after = getSB_VAL_CP((U8) *s);
2240                         if ((to_complement ^ isSB(before,
2241                                                   after,
2242                                                   (U8*) reginfo->strbeg,
2243                                                   (U8*) s,
2244                                                   (U8*) reginfo->strend,
2245                                                   utf8_target))
2246                             && (reginfo->intuit || regtry(reginfo, &s)))
2247                         {
2248                             goto got_it;
2249                         }
2250                         before = after;
2251                         s++;
2252                     }
2253                 }
2254
2255                 /* Here are at the final position in the target string.  The SB
2256                  * value is always true here, so matches, depending on other
2257                  * constraints */
2258                 if (reginfo->intuit || regtry(reginfo, &s)) {
2259                     goto got_it;
2260                 }
2261
2262                 break;
2263
2264             case WB_BOUND:
2265                 if (s == reginfo->strbeg) {
2266                     if (reginfo->intuit || regtry(reginfo, &s)) {
2267                         goto got_it;
2268                     }
2269                     s += (utf8_target) ? UTF8SKIP(s) : 1;
2270                     if (UNLIKELY(s >= reginfo->strend)) {
2271                         break;
2272                     }
2273                 }
2274
2275                 if (utf8_target) {
2276                     /* We are at a boundary between char_sub_0 and char_sub_1.
2277                      * We also keep track of the value for char_sub_-1 as we
2278                      * loop through the line.   Context may be needed to make a
2279                      * determination, and if so, this can save having to
2280                      * recalculate it */
2281                     WB_enum previous = WB_UNKNOWN;
2282                     WB_enum before = getWB_VAL_UTF8(
2283                                               reghop3((U8*)s,
2284                                                       -1,
2285                                                       (U8*)(reginfo->strbeg)),
2286                                               (U8*) reginfo->strend);
2287                     while (s < strend) {
2288                         WB_enum after = getWB_VAL_UTF8((U8*) s,
2289                                                         (U8*) reginfo->strend);
2290                         if ((to_complement ^ isWB(previous,
2291                                                   before,
2292                                                   after,
2293                                                   (U8*) reginfo->strbeg,
2294                                                   (U8*) s,
2295                                                   (U8*) reginfo->strend,
2296                                                   utf8_target))
2297                             && (reginfo->intuit || regtry(reginfo, &s)))
2298                         {
2299                             goto got_it;
2300                         }
2301                         previous = before;
2302                         before = after;
2303                         s += UTF8SKIP(s);
2304                     }
2305                 }
2306                 else {  /* Not utf8. */
2307                     WB_enum previous = WB_UNKNOWN;
2308                     WB_enum before = getWB_VAL_CP((U8) *(s -1));
2309                     while (s < strend) {
2310                         WB_enum after = getWB_VAL_CP((U8) *s);
2311                         if ((to_complement ^ isWB(previous,
2312                                                   before,
2313                                                   after,
2314                                                   (U8*) reginfo->strbeg,
2315                                                   (U8*) s,
2316                                                   (U8*) reginfo->strend,
2317                                                   utf8_target))
2318                             && (reginfo->intuit || regtry(reginfo, &s)))
2319                         {
2320                             goto got_it;
2321                         }
2322                         previous = before;
2323                         before = after;
2324                         s++;
2325                     }
2326                 }
2327
2328                 if (reginfo->intuit || regtry(reginfo, &s)) {
2329                     goto got_it;
2330                 }
2331         }
2332         break;
2333
2334     case LNBREAK:
2335         REXEC_FBC_CSCAN(is_LNBREAK_utf8_safe(s, strend),
2336                         is_LNBREAK_latin1_safe(s, strend)
2337         );
2338         break;
2339
2340     /* The argument to all the POSIX node types is the class number to pass to
2341      * _generic_isCC() to build a mask for searching in PL_charclass[] */
2342
2343     case NPOSIXL:
2344         to_complement = 1;
2345         /* FALLTHROUGH */
2346
2347     case POSIXL:
2348         _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2349         REXEC_FBC_CSCAN(to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(c), (U8 *) s)),
2350                         to_complement ^ cBOOL(isFOO_lc(FLAGS(c), *s)));
2351         break;
2352
2353     case NPOSIXD:
2354         to_complement = 1;
2355         /* FALLTHROUGH */
2356
2357     case POSIXD:
2358         if (utf8_target) {
2359             goto posix_utf8;
2360         }
2361         goto posixa;
2362
2363     case NPOSIXA:
2364         if (utf8_target) {
2365             /* The complement of something that matches only ASCII matches all
2366              * non-ASCII, plus everything in ASCII that isn't in the class. */
2367             REXEC_FBC_UTF8_CLASS_SCAN(! isASCII_utf8(s)
2368                                       || ! _generic_isCC_A(*s, FLAGS(c)));
2369             break;
2370         }
2371
2372         to_complement = 1;
2373         /* FALLTHROUGH */
2374
2375     case POSIXA:
2376       posixa:
2377         /* Don't need to worry about utf8, as it can match only a single
2378          * byte invariant character. */
2379         REXEC_FBC_CLASS_SCAN(
2380                         to_complement ^ cBOOL(_generic_isCC_A(*s, FLAGS(c))));
2381         break;
2382
2383     case NPOSIXU:
2384         to_complement = 1;
2385         /* FALLTHROUGH */
2386
2387     case POSIXU:
2388         if (! utf8_target) {
2389             REXEC_FBC_CLASS_SCAN(to_complement ^ cBOOL(_generic_isCC(*s,
2390                                                                     FLAGS(c))));
2391         }
2392         else {
2393
2394           posix_utf8:
2395             classnum = (_char_class_number) FLAGS(c);
2396             if (classnum < _FIRST_NON_SWASH_CC) {
2397                 while (s < strend) {
2398
2399                     /* We avoid loading in the swash as long as possible, but
2400                      * should we have to, we jump to a separate loop.  This
2401                      * extra 'if' statement is what keeps this code from being
2402                      * just a call to REXEC_FBC_UTF8_CLASS_SCAN() */
2403                     if (UTF8_IS_ABOVE_LATIN1(*s)) {
2404                         goto found_above_latin1;
2405                     }
2406                     if ((UTF8_IS_INVARIANT(*s)
2407                          && to_complement ^ cBOOL(_generic_isCC((U8) *s,
2408                                                                 classnum)))
2409                         || (UTF8_IS_DOWNGRADEABLE_START(*s)
2410                             && to_complement ^ cBOOL(
2411                                 _generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(*s,
2412                                                                       *(s + 1)),
2413                                               classnum))))
2414                     {
2415                         if (tmp && (reginfo->intuit || regtry(reginfo, &s)))
2416                             goto got_it;
2417                         else {
2418                             tmp = doevery;
2419                         }
2420                     }
2421                     else {
2422                         tmp = 1;
2423                     }
2424                     s += UTF8SKIP(s);
2425                 }
2426             }
2427             else switch (classnum) {    /* These classes are implemented as
2428                                            macros */
2429                 case _CC_ENUM_SPACE:
2430                     REXEC_FBC_UTF8_CLASS_SCAN(
2431                                         to_complement ^ cBOOL(isSPACE_utf8(s)));
2432                     break;
2433
2434                 case _CC_ENUM_BLANK:
2435                     REXEC_FBC_UTF8_CLASS_SCAN(
2436                                         to_complement ^ cBOOL(isBLANK_utf8(s)));
2437                     break;
2438
2439                 case _CC_ENUM_XDIGIT:
2440                     REXEC_FBC_UTF8_CLASS_SCAN(
2441                                        to_complement ^ cBOOL(isXDIGIT_utf8(s)));
2442                     break;
2443
2444                 case _CC_ENUM_VERTSPACE:
2445                     REXEC_FBC_UTF8_CLASS_SCAN(
2446                                        to_complement ^ cBOOL(isVERTWS_utf8(s)));
2447                     break;
2448
2449                 case _CC_ENUM_CNTRL:
2450                     REXEC_FBC_UTF8_CLASS_SCAN(
2451                                         to_complement ^ cBOOL(isCNTRL_utf8(s)));
2452                     break;
2453
2454                 default:
2455                     Perl_croak(aTHX_ "panic: find_byclass() node %d='%s' has an unexpected character class '%d'", OP(c), PL_reg_name[OP(c)], classnum);
2456                     NOT_REACHED; /* NOTREACHED */
2457             }
2458         }
2459         break;
2460
2461       found_above_latin1:   /* Here we have to load a swash to get the result
2462                                for the current code point */
2463         if (! PL_utf8_swash_ptrs[classnum]) {
2464             U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
2465             PL_utf8_swash_ptrs[classnum] =
2466                     _core_swash_init("utf8",
2467                                      "",
2468                                      &PL_sv_undef, 1, 0,
2469                                      PL_XPosix_ptrs[classnum], &flags);
2470         }
2471
2472         /* This is a copy of the loop above for swash classes, though using the
2473          * FBC macro instead of being expanded out.  Since we've loaded the
2474          * swash, we don't have to check for that each time through the loop */
2475         REXEC_FBC_UTF8_CLASS_SCAN(
2476                 to_complement ^ cBOOL(_generic_utf8(
2477                                       classnum,
2478                                       s,
2479                                       swash_fetch(PL_utf8_swash_ptrs[classnum],
2480                                                   (U8 *) s, TRUE))));
2481         break;
2482
2483     case AHOCORASICKC:
2484     case AHOCORASICK:
2485         {
2486             DECL_TRIE_TYPE(c);
2487             /* what trie are we using right now */
2488             reg_ac_data *aho = (reg_ac_data*)progi->data->data[ ARG( c ) ];
2489             reg_trie_data *trie = (reg_trie_data*)progi->data->data[ aho->trie ];
2490             HV *widecharmap = MUTABLE_HV(progi->data->data[ aho->trie + 1 ]);
2491
2492             const char *last_start = strend - trie->minlen;
2493 #ifdef DEBUGGING
2494             const char *real_start = s;
2495 #endif
2496             STRLEN maxlen = trie->maxlen;
2497             SV *sv_points;
2498             U8 **points; /* map of where we were in the input string
2499                             when reading a given char. For ASCII this
2500                             is unnecessary overhead as the relationship
2501                             is always 1:1, but for Unicode, especially
2502                             case folded Unicode this is not true. */
2503             U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
2504             U8 *bitmap=NULL;
2505
2506
2507             GET_RE_DEBUG_FLAGS_DECL;
2508
2509             /* We can't just allocate points here. We need to wrap it in
2510              * an SV so it gets freed properly if there is a croak while
2511              * running the match */
2512             ENTER;
2513             SAVETMPS;
2514             sv_points=newSV(maxlen * sizeof(U8 *));
2515             SvCUR_set(sv_points,
2516                 maxlen * sizeof(U8 *));
2517             SvPOK_on(sv_points);
2518             sv_2mortal(sv_points);
2519             points=(U8**)SvPV_nolen(sv_points );
2520             if ( trie_type != trie_utf8_fold
2521                  && (trie->bitmap || OP(c)==AHOCORASICKC) )
2522             {
2523                 if (trie->bitmap)
2524                     bitmap=(U8*)trie->bitmap;
2525                 else
2526                     bitmap=(U8*)ANYOF_BITMAP(c);
2527             }
2528             /* this is the Aho-Corasick algorithm modified a touch
2529                to include special handling for long "unknown char" sequences.
2530                The basic idea being that we use AC as long as we are dealing
2531                with a possible matching char, when we encounter an unknown char
2532                (and we have not encountered an accepting state) we scan forward
2533                until we find a legal starting char.
2534                AC matching is basically that of trie matching, except that when
2535                we encounter a failing transition, we fall back to the current
2536                states "fail state", and try the current char again, a process
2537                we repeat until we reach the root state, state 1, or a legal
2538                transition. If we fail on the root state then we can either
2539                terminate if we have reached an accepting state previously, or
2540                restart the entire process from the beginning if we have not.
2541
2542              */
2543             while (s <= last_start) {
2544                 const U32 uniflags = UTF8_ALLOW_DEFAULT;
2545                 U8 *uc = (U8*)s;
2546                 U16 charid = 0;
2547                 U32 base = 1;
2548                 U32 state = 1;
2549                 UV uvc = 0;
2550                 STRLEN len = 0;
2551                 STRLEN foldlen = 0;
2552                 U8 *uscan = (U8*)NULL;
2553                 U8 *leftmost = NULL;
2554 #ifdef DEBUGGING
2555                 U32 accepted_word= 0;
2556 #endif
2557                 U32 pointpos = 0;
2558
2559                 while ( state && uc <= (U8*)strend ) {
2560                     int failed=0;
2561                     U32 word = aho->states[ state ].wordnum;
2562
2563                     if( state==1 ) {
2564                         if ( bitmap ) {
2565                             DEBUG_TRIE_EXECUTE_r(
2566                                 if ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2567                                     dump_exec_pos( (char *)uc, c, strend, real_start,
2568                                         (char *)uc, utf8_target );
2569                                     PerlIO_printf( Perl_debug_log,
2570                                         " Scanning for legal start char...\n");
2571                                 }
2572                             );
2573                             if (utf8_target) {
2574                                 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2575                                     uc += UTF8SKIP(uc);
2576                                 }
2577                             } else {
2578                                 while ( uc <= (U8*)last_start  && !BITMAP_TEST(bitmap,*uc) ) {
2579                                     uc++;
2580                                 }
2581                             }
2582                             s= (char *)uc;
2583                         }
2584                         if (uc >(U8*)last_start) break;
2585                     }
2586
2587                     if ( word ) {
2588                         U8 *lpos= points[ (pointpos - trie->wordinfo[word].len) % maxlen ];
2589                         if (!leftmost || lpos < leftmost) {
2590                             DEBUG_r(accepted_word=word);
2591                             leftmost= lpos;
2592                         }
2593                         if (base==0) break;
2594
2595                     }
2596                     points[pointpos++ % maxlen]= uc;
2597                     if (foldlen || uc < (U8*)strend) {
2598                         REXEC_TRIE_READ_CHAR(trie_type, trie,
2599                                          widecharmap, uc,
2600                                          uscan, len, uvc, charid, foldlen,
2601                                          foldbuf, uniflags);
2602                         DEBUG_TRIE_EXECUTE_r({
2603                             dump_exec_pos( (char *)uc, c, strend,
2604                                         real_start, s, utf8_target);
2605                             PerlIO_printf(Perl_debug_log,
2606                                 " Charid:%3u CP:%4"UVxf" ",
2607                                  charid, uvc);
2608                         });
2609                     }
2610                     else {
2611                         len = 0;
2612                         charid = 0;
2613                     }
2614
2615
2616                     do {
2617 #ifdef DEBUGGING
2618                         word = aho->states[ state ].wordnum;
2619 #endif
2620                         base = aho->states[ state ].trans.base;
2621
2622                         DEBUG_TRIE_EXECUTE_r({
2623                             if (failed)
2624                                 dump_exec_pos( (char *)uc, c, strend, real_start,
2625                                     s,   utf8_target );
2626                             PerlIO_printf( Perl_debug_log,
2627                                 "%sState: %4"UVxf", word=%"UVxf,
2628                                 failed ? " Fail transition to " : "",
2629                                 (UV)state, (UV)word);
2630                         });
2631                         if ( base ) {
2632                             U32 tmp;
2633                             I32 offset;
2634                             if (charid &&
2635                                  ( ((offset = base + charid
2636                                     - 1 - trie->uniquecharcount)) >= 0)
2637                                  && ((U32)offset < trie->lasttrans)
2638                                  && trie->trans[offset].check == state
2639                                  && (tmp=trie->trans[offset].next))
2640                             {
2641                                 DEBUG_TRIE_EXECUTE_r(
2642                                     PerlIO_printf( Perl_debug_log," - legal\n"));
2643                                 state = tmp;
2644                                 break;
2645                             }
2646                             else {
2647                                 DEBUG_TRIE_EXECUTE_r(
2648                                     PerlIO_printf( Perl_debug_log," - fail\n"));
2649                                 failed = 1;
2650                                 state = aho->fail[state];
2651                             }
2652                         }
2653                         else {
2654                             /* we must be accepting here */
2655                             DEBUG_TRIE_EXECUTE_r(
2656                                     PerlIO_printf( Perl_debug_log," - accepting\n"));
2657                             failed = 1;
2658                             break;
2659                         }
2660                     } while(state);
2661                     uc += len;
2662                     if (failed) {
2663                         if (leftmost)
2664                             break;
2665                         if (!state) state = 1;
2666                     }
2667                 }
2668                 if ( aho->states[ state ].wordnum ) {
2669                     U8 *lpos = points[ (pointpos - trie->wordinfo[aho->states[ state ].wordnum].len) % maxlen ];
2670                     if (!leftmost || lpos < leftmost) {
2671                         DEBUG_r(accepted_word=aho->states[ state ].wordnum);
2672                         leftmost = lpos;
2673                     }
2674                 }
2675                 if (leftmost) {
2676                     s = (char*)leftmost;
2677                     DEBUG_TRIE_EXECUTE_r({
2678                         PerlIO_printf(
2679                             Perl_debug_log,"Matches word #%"UVxf" at position %"IVdf". Trying full pattern...\n",
2680                             (UV)accepted_word, (IV)(s - real_start)
2681                         );
2682                     });
2683                     if (reginfo->intuit || regtry(reginfo, &s)) {
2684                         FREETMPS;
2685                         LEAVE;
2686                         goto got_it;
2687                     }
2688                     s = HOPc(s,1);
2689                     DEBUG_TRIE_EXECUTE_r({
2690                         PerlIO_printf( Perl_debug_log,"Pattern failed. Looking for new start point...\n");
2691                     });
2692                 } else {
2693                     DEBUG_TRIE_EXECUTE_r(
2694                         PerlIO_printf( Perl_debug_log,"No match.\n"));
2695                     break;
2696                 }
2697             }
2698             FREETMPS;
2699             LEAVE;
2700         }
2701         break;
2702     default:
2703         Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
2704     }
2705     return 0;
2706   got_it:
2707     return s;
2708 }
2709
2710 /* set RX_SAVED_COPY, RX_SUBBEG etc.
2711  * flags have same meanings as with regexec_flags() */
2712
2713 static void
2714 S_reg_set_capture_string(pTHX_ REGEXP * const rx,
2715                             char *strbeg,
2716                             char *strend,
2717                             SV *sv,
2718                             U32 flags,
2719                             bool utf8_target)
2720 {
2721     struct regexp *const prog = ReANY(rx);
2722
2723     if (flags & REXEC_COPY_STR) {
2724 #ifdef PERL_ANY_COW
2725         if (SvCANCOW(sv)) {
2726             if (DEBUG_C_TEST) {
2727                 PerlIO_printf(Perl_debug_log,
2728                               "Copy on write: regexp capture, type %d\n",
2729                               (int) SvTYPE(sv));
2730             }
2731             /* Create a new COW SV to share the match string and store
2732              * in saved_copy, unless the current COW SV in saved_copy
2733              * is valid and suitable for our purpose */
2734             if ((   prog->saved_copy
2735                  && SvIsCOW(prog->saved_copy)
2736                  && SvPOKp(prog->saved_copy)
2737                  && SvIsCOW(sv)
2738                  && SvPOKp(sv)
2739                  && SvPVX(sv) == SvPVX(prog->saved_copy)))
2740             {
2741                 /* just reuse saved_copy SV */
2742                 if (RXp_MATCH_COPIED(prog)) {
2743                     Safefree(prog->subbeg);
2744                     RXp_MATCH_COPIED_off(prog);
2745                 }
2746             }
2747             else {
2748                 /* create new COW SV to share string */
2749                 RX_MATCH_COPY_FREE(rx);
2750                 prog->saved_copy = sv_setsv_cow(prog->saved_copy, sv);
2751             }
2752             prog->subbeg = (char *)SvPVX_const(prog->saved_copy);
2753             assert (SvPOKp(prog->saved_copy));
2754             prog->sublen  = strend - strbeg;
2755             prog->suboffset = 0;
2756             prog->subcoffset = 0;
2757         } else
2758 #endif
2759         {
2760             SSize_t min = 0;
2761             SSize_t max = strend - strbeg;
2762             SSize_t sublen;
2763
2764             if (    (flags & REXEC_COPY_SKIP_POST)
2765                 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2766                 && !(PL_sawampersand & SAWAMPERSAND_RIGHT)
2767             ) { /* don't copy $' part of string */
2768                 U32 n = 0;
2769                 max = -1;
2770                 /* calculate the right-most part of the string covered
2771                  * by a capture. Due to lookahead, this may be to
2772                  * the right of $&, so we have to scan all captures */
2773                 while (n <= prog->lastparen) {
2774                     if (prog->offs[n].end > max)
2775                         max = prog->offs[n].end;
2776                     n++;
2777                 }
2778                 if (max == -1)
2779                     max = (PL_sawampersand & SAWAMPERSAND_LEFT)
2780                             ? prog->offs[0].start
2781                             : 0;
2782                 assert(max >= 0 && max <= strend - strbeg);
2783             }
2784
2785             if (    (flags & REXEC_COPY_SKIP_PRE)
2786                 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2787                 && !(PL_sawampersand & SAWAMPERSAND_LEFT)
2788             ) { /* don't copy $` part of string */
2789                 U32 n = 0;
2790                 min = max;
2791                 /* calculate the left-most part of the string covered
2792                  * by a capture. Due to lookbehind, this may be to
2793                  * the left of $&, so we have to scan all captures */
2794                 while (min && n <= prog->lastparen) {
2795                     if (   prog->offs[n].start != -1
2796                         && prog->offs[n].start < min)
2797                     {
2798                         min = prog->offs[n].start;
2799                     }
2800                     n++;
2801                 }
2802                 if ((PL_sawampersand & SAWAMPERSAND_RIGHT)
2803                     && min >  prog->offs[0].end
2804                 )
2805                     min = prog->offs[0].end;
2806
2807             }
2808
2809             assert(min >= 0 && min <= max && min <= strend - strbeg);
2810             sublen = max - min;
2811
2812             if (RX_MATCH_COPIED(rx)) {
2813                 if (sublen > prog->sublen)
2814                     prog->subbeg =
2815                             (char*)saferealloc(prog->subbeg, sublen+1);
2816             }
2817             else
2818                 prog->subbeg = (char*)safemalloc(sublen+1);
2819             Copy(strbeg + min, prog->subbeg, sublen, char);
2820             prog->subbeg[sublen] = '\0';
2821             prog->suboffset = min;
2822             prog->sublen = sublen;
2823             RX_MATCH_COPIED_on(rx);
2824         }
2825         prog->subcoffset = prog->suboffset;
2826         if (prog->suboffset && utf8_target) {
2827             /* Convert byte offset to chars.
2828              * XXX ideally should only compute this if @-/@+
2829              * has been seen, a la PL_sawampersand ??? */
2830
2831             /* If there's a direct correspondence between the
2832              * string which we're matching and the original SV,
2833              * then we can use the utf8 len cache associated with
2834              * the SV. In particular, it means that under //g,
2835              * sv_pos_b2u() will use the previously cached
2836              * position to speed up working out the new length of
2837              * subcoffset, rather than counting from the start of
2838              * the string each time. This stops
2839              *   $x = "\x{100}" x 1E6; 1 while $x =~ /(.)/g;
2840              * from going quadratic */
2841             if (SvPOKp(sv) && SvPVX(sv) == strbeg)
2842                 prog->subcoffset = sv_pos_b2u_flags(sv, prog->subcoffset,
2843                                                 SV_GMAGIC|SV_CONST_RETURN);
2844             else
2845                 prog->subcoffset = utf8_length((U8*)strbeg,
2846                                     (U8*)(strbeg+prog->suboffset));
2847         }
2848     }
2849     else {
2850         RX_MATCH_COPY_FREE(rx);
2851         prog->subbeg = strbeg;
2852         prog->suboffset = 0;
2853         prog->subcoffset = 0;
2854         prog->sublen = strend - strbeg;
2855     }
2856 }
2857
2858
2859
2860
2861 /*
2862  - regexec_flags - match a regexp against a string
2863  */
2864 I32
2865 Perl_regexec_flags(pTHX_ REGEXP * const rx, char *stringarg, char *strend,
2866               char *strbeg, SSize_t minend, SV *sv, void *data, U32 flags)
2867 /* stringarg: the point in the string at which to begin matching */
2868 /* strend:    pointer to null at end of string */
2869 /* strbeg:    real beginning of string */
2870 /* minend:    end of match must be >= minend bytes after stringarg. */
2871 /* sv:        SV being matched: only used for utf8 flag, pos() etc; string
2872  *            itself is accessed via the pointers above */
2873 /* data:      May be used for some additional optimizations.
2874               Currently unused. */
2875 /* flags:     For optimizations. See REXEC_* in regexp.h */
2876
2877 {
2878     struct regexp *const prog = ReANY(rx);
2879     char *s;
2880     regnode *c;
2881     char *startpos;
2882     SSize_t minlen;             /* must match at least this many chars */
2883     SSize_t dontbother = 0;     /* how many characters not to try at end */
2884     const bool utf8_target = cBOOL(DO_UTF8(sv));
2885     I32 multiline;
2886     RXi_GET_DECL(prog,progi);
2887     regmatch_info reginfo_buf;  /* create some info to pass to regtry etc */
2888     regmatch_info *const reginfo = &reginfo_buf;
2889     regexp_paren_pair *swap = NULL;
2890     I32 oldsave;
2891     GET_RE_DEBUG_FLAGS_DECL;
2892
2893     PERL_ARGS_ASSERT_REGEXEC_FLAGS;
2894     PERL_UNUSED_ARG(data);
2895
2896     /* Be paranoid... */
2897     if (prog == NULL) {
2898         Perl_croak(aTHX_ "NULL regexp parameter");
2899     }
2900
2901     DEBUG_EXECUTE_r(
2902         debug_start_match(rx, utf8_target, stringarg, strend,
2903         "Matching");
2904     );
2905
2906     startpos = stringarg;
2907
2908     /* set these early as they may be used by the HOP macros below */
2909     reginfo->strbeg = strbeg;
2910     reginfo->strend = strend;
2911     reginfo->is_utf8_target = cBOOL(utf8_target);
2912
2913     if (prog->intflags & PREGf_GPOS_SEEN) {
2914         MAGIC *mg;
2915
2916         /* set reginfo->ganch, the position where \G can match */
2917
2918         reginfo->ganch =
2919             (flags & REXEC_IGNOREPOS)
2920             ? stringarg /* use start pos rather than pos() */
2921             : ((mg = mg_find_mglob(sv)) && mg->mg_len >= 0)
2922               /* Defined pos(): */
2923             ? strbeg + MgBYTEPOS(mg, sv, strbeg, strend-strbeg)
2924             : strbeg; /* pos() not defined; use start of string */
2925
2926         DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
2927             "GPOS ganch set to strbeg[%"IVdf"]\n", (IV)(reginfo->ganch - strbeg)));
2928
2929         /* in the presence of \G, we may need to start looking earlier in
2930          * the string than the suggested start point of stringarg:
2931          * if prog->gofs is set, then that's a known, fixed minimum
2932          * offset, such as
2933          * /..\G/:   gofs = 2
2934          * /ab|c\G/: gofs = 1
2935          * or if the minimum offset isn't known, then we have to go back
2936          * to the start of the string, e.g. /w+\G/
2937          */
2938
2939         if (prog->intflags & PREGf_ANCH_GPOS) {
2940             if (prog->gofs) {
2941                 startpos = HOPBACKc(reginfo->ganch, prog->gofs);
2942                 if (!startpos ||
2943                     ((flags & REXEC_FAIL_ON_UNDERFLOW) && startpos < stringarg))
2944                 {
2945                     DEBUG_r(PerlIO_printf(Perl_debug_log,
2946                             "fail: ganch-gofs before earliest possible start\n"));
2947                     return 0;
2948                 }
2949             }
2950             else
2951                 startpos = reginfo->ganch;
2952         }
2953         else if (prog->gofs) {
2954             startpos = HOPBACKc(startpos, prog->gofs);
2955             if (!startpos)
2956                 startpos = strbeg;
2957         }
2958         else if (prog->intflags & PREGf_GPOS_FLOAT)
2959             startpos = strbeg;
2960     }
2961
2962     minlen = prog->minlen;
2963     if ((startpos + minlen) > strend || startpos < strbeg) {
2964         DEBUG_r(PerlIO_printf(Perl_debug_log,
2965                     "Regex match can't succeed, so not even tried\n"));
2966         return 0;
2967     }
2968
2969     /* at the end of this function, we'll do a LEAVE_SCOPE(oldsave),
2970      * which will call destuctors to reset PL_regmatch_state, free higher
2971      * PL_regmatch_slabs, and clean up regmatch_info_aux and
2972      * regmatch_info_aux_eval */
2973
2974     oldsave = PL_savestack_ix;
2975
2976     s = startpos;
2977
2978     if ((prog->extflags & RXf_USE_INTUIT)
2979         && !(flags & REXEC_CHECKED))
2980     {
2981         s = re_intuit_start(rx, sv, strbeg, startpos, strend,
2982                                     flags, NULL);
2983         if (!s)
2984             return 0;
2985
2986         if (prog->extflags & RXf_CHECK_ALL) {
2987             /* we can match based purely on the result of INTUIT.
2988              * Set up captures etc just for $& and $-[0]
2989              * (an intuit-only match wont have $1,$2,..) */
2990             assert(!prog->nparens);
2991
2992             /* s/// doesn't like it if $& is earlier than where we asked it to
2993              * start searching (which can happen on something like /.\G/) */
2994             if (       (flags & REXEC_FAIL_ON_UNDERFLOW)
2995                     && (s < stringarg))
2996             {
2997                 /* this should only be possible under \G */
2998                 assert(prog->intflags & PREGf_GPOS_SEEN);
2999                 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
3000                     "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3001                 goto phooey;
3002             }
3003
3004             /* match via INTUIT shouldn't have any captures.
3005              * Let @-, @+, $^N know */
3006             prog->lastparen = prog->lastcloseparen = 0;
3007             RX_MATCH_UTF8_set(rx, utf8_target);
3008             prog->offs[0].start = s - strbeg;
3009             prog->offs[0].end = utf8_target
3010                 ? (char*)utf8_hop((U8*)s, prog->minlenret) - strbeg
3011                 : s - strbeg + prog->minlenret;
3012             if ( !(flags & REXEC_NOT_FIRST) )
3013                 S_reg_set_capture_string(aTHX_ rx,
3014                                         strbeg, strend,
3015                                         sv, flags, utf8_target);
3016
3017             return 1;
3018         }
3019     }
3020
3021     multiline = prog->extflags & RXf_PMf_MULTILINE;
3022     
3023     if (strend - s < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
3024         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
3025                               "String too short [regexec_flags]...\n"));
3026         goto phooey;
3027     }
3028     
3029     /* Check validity of program. */
3030     if (UCHARAT(progi->program) != REG_MAGIC) {
3031         Perl_croak(aTHX_ "corrupted regexp program");
3032     }
3033
3034     RX_MATCH_TAINTED_off(rx);
3035     RX_MATCH_UTF8_set(rx, utf8_target);
3036
3037     reginfo->prog = rx;  /* Yes, sorry that this is confusing.  */
3038     reginfo->intuit = 0;
3039     reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
3040     reginfo->warned = FALSE;
3041     reginfo->sv = sv;
3042     reginfo->poscache_maxiter = 0; /* not yet started a countdown */
3043     /* see how far we have to get to not match where we matched before */
3044     reginfo->till = stringarg + minend;
3045
3046     if (prog->extflags & RXf_EVAL_SEEN && SvPADTMP(sv)) {
3047         /* SAVEFREESV, not sv_mortalcopy, as this SV must last until after
3048            S_cleanup_regmatch_info_aux has executed (registered by
3049            SAVEDESTRUCTOR_X below).  S_cleanup_regmatch_info_aux modifies
3050            magic belonging to this SV.
3051            Not newSVsv, either, as it does not COW.
3052         */
3053         reginfo->sv = newSV(0);
3054         SvSetSV_nosteal(reginfo->sv, sv);
3055         SAVEFREESV(reginfo->sv);
3056     }
3057
3058     /* reserve next 2 or 3 slots in PL_regmatch_state:
3059      * slot N+0: may currently be in use: skip it
3060      * slot N+1: use for regmatch_info_aux struct
3061      * slot N+2: use for regmatch_info_aux_eval struct if we have (?{})'s
3062      * slot N+3: ready for use by regmatch()
3063      */
3064
3065     {
3066         regmatch_state *old_regmatch_state;
3067         regmatch_slab  *old_regmatch_slab;
3068         int i, max = (prog->extflags & RXf_EVAL_SEEN) ? 2 : 1;
3069
3070         /* on first ever match, allocate first slab */
3071         if (!PL_regmatch_slab) {
3072             Newx(PL_regmatch_slab, 1, regmatch_slab);
3073             PL_regmatch_slab->prev = NULL;
3074             PL_regmatch_slab->next = NULL;
3075             PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
3076         }
3077
3078         old_regmatch_state = PL_regmatch_state;
3079         old_regmatch_slab  = PL_regmatch_slab;
3080
3081         for (i=0; i <= max; i++) {
3082             if (i == 1)
3083                 reginfo->info_aux = &(PL_regmatch_state->u.info_aux);
3084             else if (i ==2)
3085                 reginfo->info_aux_eval =
3086                 reginfo->info_aux->info_aux_eval =
3087                             &(PL_regmatch_state->u.info_aux_eval);
3088
3089             if (++PL_regmatch_state >  SLAB_LAST(PL_regmatch_slab))
3090                 PL_regmatch_state = S_push_slab(aTHX);
3091         }
3092
3093         /* note initial PL_regmatch_state position; at end of match we'll
3094          * pop back to there and free any higher slabs */
3095
3096         reginfo->info_aux->old_regmatch_state = old_regmatch_state;
3097         reginfo->info_aux->old_regmatch_slab  = old_regmatch_slab;
3098         reginfo->info_aux->poscache = NULL;
3099
3100         SAVEDESTRUCTOR_X(S_cleanup_regmatch_info_aux, reginfo->info_aux);
3101
3102         if ((prog->extflags & RXf_EVAL_SEEN))
3103             S_setup_eval_state(aTHX_ reginfo);
3104         else
3105             reginfo->info_aux_eval = reginfo->info_aux->info_aux_eval = NULL;
3106     }
3107
3108     /* If there is a "must appear" string, look for it. */
3109
3110     if (PL_curpm && (PM_GETRE(PL_curpm) == rx)) {
3111         /* We have to be careful. If the previous successful match
3112            was from this regex we don't want a subsequent partially
3113            successful match to clobber the old results.
3114            So when we detect this possibility we add a swap buffer
3115            to the re, and switch the buffer each match. If we fail,
3116            we switch it back; otherwise we leave it swapped.
3117         */
3118         swap = prog->offs;
3119         /* do we need a save destructor here for eval dies? */
3120         Newxz(prog->offs, (prog->nparens + 1), regexp_paren_pair);
3121         DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
3122             "rex=0x%"UVxf" saving  offs: orig=0x%"UVxf" new=0x%"UVxf"\n",
3123             PTR2UV(prog),
3124             PTR2UV(swap),
3125             PTR2UV(prog->offs)
3126         ));
3127     }
3128
3129     if (prog->recurse_locinput)
3130         Zero(prog->recurse_locinput,prog->nparens + 1, char *);
3131
3132     /* Simplest case: anchored match need be tried only once, or with
3133      * MBOL, only at the beginning of each line.
3134      *
3135      * Note that /.*.../ sets PREGf_IMPLICIT|MBOL, while /.*.../s sets
3136      * PREGf_IMPLICIT|SBOL. The idea is that with /.*.../s, if it doesn't
3137      * match at the start of the string then it won't match anywhere else
3138      * either; while with /.*.../, if it doesn't match at the beginning,
3139      * the earliest it could match is at the start of the next line */
3140
3141     if (prog->intflags & (PREGf_ANCH & ~PREGf_ANCH_GPOS)) {
3142         char *end;
3143
3144         if (regtry(reginfo, &s))
3145             goto got_it;
3146
3147         if (!(prog->intflags & PREGf_ANCH_MBOL))
3148             goto phooey;
3149
3150         /* didn't match at start, try at other newline positions */
3151
3152         if (minlen)
3153             dontbother = minlen - 1;
3154         end = HOP3c(strend, -dontbother, strbeg) - 1;
3155
3156         /* skip to next newline */
3157
3158         while (s <= end) { /* note it could be possible to match at the end of the string */
3159             /* NB: newlines are the same in unicode as they are in latin */
3160             if (*s++ != '\n')
3161                 continue;
3162             if (prog->check_substr || prog->check_utf8) {
3163             /* note that with PREGf_IMPLICIT, intuit can only fail
3164              * or return the start position, so it's of limited utility.
3165              * Nevertheless, I made the decision that the potential for
3166              * quick fail was still worth it - DAPM */
3167                 s = re_intuit_start(rx, sv, strbeg, s, strend, flags, NULL);
3168                 if (!s)
3169                     goto phooey;
3170             }
3171             if (regtry(reginfo, &s))
3172                 goto got_it;
3173         }
3174         goto phooey;
3175     } /* end anchored search */
3176
3177     if (prog->intflags & PREGf_ANCH_GPOS)
3178     {
3179         /* PREGf_ANCH_GPOS should never be true if PREGf_GPOS_SEEN is not true */
3180         assert(prog->intflags & PREGf_GPOS_SEEN);
3181         /* For anchored \G, the only position it can match from is
3182          * (ganch-gofs); we already set startpos to this above; if intuit
3183          * moved us on from there, we can't possibly succeed */
3184         assert(startpos == HOPBACKc(reginfo->ganch, prog->gofs));
3185         if (s == startpos && regtry(reginfo, &s))
3186             goto got_it;
3187         goto phooey;
3188     }
3189
3190     /* Messy cases:  unanchored match. */
3191     if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
3192         /* we have /x+whatever/ */
3193         /* it must be a one character string (XXXX Except is_utf8_pat?) */
3194         char ch;
3195 #ifdef DEBUGGING
3196         int did_match = 0;
3197 #endif
3198         if (utf8_target) {
3199             if (! prog->anchored_utf8) {
3200                 to_utf8_substr(prog);
3201             }
3202             ch = SvPVX_const(prog->anchored_utf8)[0];
3203             REXEC_FBC_SCAN(
3204                 if (*s == ch) {
3205                     DEBUG_EXECUTE_r( did_match = 1 );
3206                     if (regtry(reginfo, &s)) goto got_it;
3207                     s += UTF8SKIP(s);
3208                     while (s < strend && *s == ch)
3209                         s += UTF8SKIP(s);
3210                 }
3211             );
3212
3213         }
3214         else {
3215             if (! prog->anchored_substr) {
3216                 if (! to_byte_substr(prog)) {
3217                     NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3218                 }
3219             }
3220             ch = SvPVX_const(prog->anchored_substr)[0];
3221             REXEC_FBC_SCAN(
3222                 if (*s == ch) {
3223                     DEBUG_EXECUTE_r( did_match = 1 );
3224                     if (regtry(reginfo, &s)) goto got_it;
3225                     s++;
3226                     while (s < strend && *s == ch)
3227                         s++;
3228                 }
3229             );
3230         }
3231         DEBUG_EXECUTE_r(if (!did_match)
3232                 PerlIO_printf(Perl_debug_log,
3233                                   "Did not find anchored character...\n")
3234                );
3235     }
3236     else if (prog->anchored_substr != NULL
3237               || prog->anchored_utf8 != NULL
3238               || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
3239                   && prog->float_max_offset < strend - s)) {
3240         SV *must;
3241         SSize_t back_max;
3242         SSize_t back_min;
3243         char *last;
3244         char *last1;            /* Last position checked before */
3245 #ifdef DEBUGGING
3246         int did_match = 0;
3247 #endif
3248         if (prog->anchored_substr || prog->anchored_utf8) {
3249             if (utf8_target) {
3250                 if (! prog->anchored_utf8) {
3251                     to_utf8_substr(prog);
3252                 }
3253                 must = prog->anchored_utf8;
3254             }
3255             else {
3256                 if (! prog->anchored_substr) {
3257                     if (! to_byte_substr(prog)) {
3258                         NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3259                     }
3260                 }
3261                 must = prog->anchored_substr;
3262             }
3263             back_max = back_min = prog->anchored_offset;
3264         } else {
3265             if (utf8_target) {
3266                 if (! prog->float_utf8) {
3267                     to_utf8_substr(prog);
3268                 }
3269                 must = prog->float_utf8;
3270             }
3271             else {
3272                 if (! prog->float_substr) {
3273                     if (! to_byte_substr(prog)) {
3274                         NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3275                     }
3276                 }
3277                 must = prog->float_substr;
3278             }
3279             back_max = prog->float_max_offset;
3280             back_min = prog->float_min_offset;
3281         }
3282             
3283         if (back_min<0) {
3284             last = strend;
3285         } else {
3286             last = HOP3c(strend,        /* Cannot start after this */
3287                   -(SSize_t)(CHR_SVLEN(must)
3288                          - (SvTAIL(must) != 0) + back_min), strbeg);
3289         }
3290         if (s > reginfo->strbeg)
3291             last1 = HOPc(s, -1);
3292         else
3293             last1 = s - 1;      /* bogus */
3294
3295         /* XXXX check_substr already used to find "s", can optimize if
3296            check_substr==must. */
3297         dontbother = 0;
3298         strend = HOPc(strend, -dontbother);
3299         while ( (s <= last) &&
3300                 (s = fbm_instr((unsigned char*)HOP4c(s, back_min, strbeg,  strend),
3301                                   (unsigned char*)strend, must,
3302                                   multiline ? FBMrf_MULTILINE : 0)) ) {
3303             DEBUG_EXECUTE_r( did_match = 1 );
3304             if (HOPc(s, -back_max) > last1) {
3305                 last1 = HOPc(s, -back_min);
3306                 s = HOPc(s, -back_max);
3307             }
3308             else {
3309                 char * const t = (last1 >= reginfo->strbeg)
3310                                     ? HOPc(last1, 1) : last1 + 1;
3311
3312                 last1 = HOPc(s, -back_min);
3313                 s = t;
3314             }
3315             if (utf8_target) {
3316                 while (s <= last1) {
3317                     if (regtry(reginfo, &s))
3318                         goto got_it;
3319                     if (s >= last1) {
3320                         s++; /* to break out of outer loop */
3321                         break;
3322                     }
3323                     s += UTF8SKIP(s);
3324                 }
3325             }
3326             else {
3327                 while (s <= last1) {
3328                     if (regtry(reginfo, &s))
3329                         goto got_it;
3330                     s++;
3331                 }
3332             }
3333         }
3334         DEBUG_EXECUTE_r(if (!did_match) {
3335             RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
3336                 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
3337             PerlIO_printf(Perl_debug_log, "Did not find %s substr %s%s...\n",
3338                               ((must == prog->anchored_substr || must == prog->anchored_utf8)
3339                                ? "anchored" : "floating"),
3340                 quoted, RE_SV_TAIL(must));
3341         });                 
3342         goto phooey;
3343     }
3344     else if ( (c = progi->regstclass) ) {
3345         if (minlen) {
3346             const OPCODE op = OP(progi->regstclass);
3347             /* don't bother with what can't match */
3348             if (PL_regkind[op] != EXACT && PL_regkind[op] != TRIE)
3349                 strend = HOPc(strend, -(minlen - 1));
3350         }
3351         DEBUG_EXECUTE_r({
3352             SV * const prop = sv_newmortal();
3353             regprop(prog, prop, c, reginfo, NULL);
3354             {
3355                 RE_PV_QUOTED_DECL(quoted,utf8_target,PERL_DEBUG_PAD_ZERO(1),
3356                     s,strend-s,60);
3357                 PerlIO_printf(Perl_debug_log,
3358                     "Matching stclass %.*s against %s (%d bytes)\n",
3359                     (int)SvCUR(prop), SvPVX_const(prop),
3360                      quoted, (int)(strend - s));
3361             }
3362         });
3363         if (find_byclass(prog, c, s, strend, reginfo))
3364             goto got_it;
3365         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Contradicts stclass... [regexec_flags]\n"));
3366     }
3367     else {
3368         dontbother = 0;
3369         if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
3370             /* Trim the end. */
3371             char *last= NULL;
3372             SV* float_real;
3373             STRLEN len;
3374             const char *little;
3375
3376             if (utf8_target) {
3377                 if (! prog->float_utf8) {
3378                     to_utf8_substr(prog);
3379                 }
3380                 float_real = prog->float_utf8;
3381             }
3382             else {
3383                 if (! prog->float_substr) {
3384                     if (! to_byte_substr(prog)) {
3385                         NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3386                     }
3387                 }
3388                 float_real = prog->float_substr;
3389             }
3390
3391             little = SvPV_const(float_real, len);
3392             if (SvTAIL(float_real)) {
3393                     /* This means that float_real contains an artificial \n on
3394                      * the end due to the presence of something like this:
3395                      * /foo$/ where we can match both "foo" and "foo\n" at the
3396                      * end of the string.  So we have to compare the end of the
3397                      * string first against the float_real without the \n and
3398                      * then against the full float_real with the string.  We
3399                      * have to watch out for cases where the string might be
3400                      * smaller than the float_real or the float_real without
3401                      * the \n. */
3402                     char *checkpos= strend - len;
3403                     DEBUG_OPTIMISE_r(
3404                         PerlIO_printf(Perl_debug_log,
3405                             "%sChecking for float_real.%s\n",
3406                             PL_colors[4], PL_colors[5]));
3407                     if (checkpos + 1 < strbeg) {
3408                         /* can't match, even if we remove the trailing \n
3409                          * string is too short to match */
3410                         DEBUG_EXECUTE_r(
3411                             PerlIO_printf(Perl_debug_log,
3412                                 "%sString shorter than required trailing substring, cannot match.%s\n",
3413                                 PL_colors[4], PL_colors[5]));
3414                         goto phooey;
3415                     } else if (memEQ(checkpos + 1, little, len - 1)) {
3416                         /* can match, the end of the string matches without the
3417                          * "\n" */
3418                         last = checkpos + 1;
3419                     } else if (checkpos < strbeg) {
3420                         /* cant match, string is too short when the "\n" is
3421                          * included */
3422                         DEBUG_EXECUTE_r(
3423                             PerlIO_printf(Perl_debug_log,
3424                                 "%sString does not contain required trailing substring, cannot match.%s\n",
3425                                 PL_colors[4], PL_colors[5]));
3426                         goto phooey;
3427                     } else if (!multiline) {
3428                         /* non multiline match, so compare with the "\n" at the
3429                          * end of the string */
3430                         if (memEQ(checkpos, little, len)) {
3431                             last= checkpos;
3432                         } else {
3433                             DEBUG_EXECUTE_r(
3434                                 PerlIO_printf(Perl_debug_log,
3435                                     "%sString does not contain required trailing substring, cannot match.%s\n",
3436                                     PL_colors[4], PL_colors[5]));
3437                             goto phooey;
3438                         }
3439                     } else {
3440                         /* multiline match, so we have to search for a place
3441                          * where the full string is located */
3442                         goto find_last;
3443                     }
3444             } else {
3445                   find_last:
3446                     if (len)
3447                         last = rninstr(s, strend, little, little + len);
3448                     else
3449                         last = strend;  /* matching "$" */
3450             }
3451             if (!last) {
3452                 /* at one point this block contained a comment which was
3453                  * probably incorrect, which said that this was a "should not
3454                  * happen" case.  Even if it was true when it was written I am
3455                  * pretty sure it is not anymore, so I have removed the comment
3456                  * and replaced it with this one. Yves */
3457                 DEBUG_EXECUTE_r(
3458                     PerlIO_printf(Perl_debug_log,
3459                         "%sString does not contain required substring, cannot match.%s\n",
3460                         PL_colors[4], PL_colors[5]
3461                     ));
3462                 goto phooey;
3463             }
3464             dontbother = strend - last + prog->float_min_offset;
3465         }
3466         if (minlen && (dontbother < minlen))
3467             dontbother = minlen - 1;
3468         strend -= dontbother;              /* this one's always in bytes! */
3469         /* We don't know much -- general case. */
3470         if (utf8_target) {
3471             for (;;) {
3472                 if (regtry(reginfo, &s))
3473                     goto got_it;
3474                 if (s >= strend)
3475                     break;
3476                 s += UTF8SKIP(s);
3477             };
3478         }
3479         else {
3480             do {
3481                 if (regtry(reginfo, &s))
3482                     goto got_it;
3483             } while (s++ < strend);
3484         }
3485     }
3486
3487     /* Failure. */
3488     goto phooey;
3489
3490   got_it:
3491     /* s/// doesn't like it if $& is earlier than where we asked it to
3492      * start searching (which can happen on something like /.\G/) */
3493     if (       (flags & REXEC_FAIL_ON_UNDERFLOW)
3494             && (prog->offs[0].start < stringarg - strbeg))
3495     {
3496         /* this should only be possible under \G */
3497         assert(prog->intflags & PREGf_GPOS_SEEN);
3498         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
3499             "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3500         goto phooey;
3501     }
3502
3503     DEBUG_BUFFERS_r(
3504         if (swap)
3505             PerlIO_printf(Perl_debug_log,
3506                 "rex=0x%"UVxf" freeing offs: 0x%"UVxf"\n",
3507                 PTR2UV(prog),
3508                 PTR2UV(swap)
3509             );
3510     );
3511     Safefree(swap);
3512
3513     /* clean up; this will trigger destructors that will free all slabs
3514      * above the current one, and cleanup the regmatch_info_aux
3515      * and regmatch_info_aux_eval sructs */
3516
3517     LEAVE_SCOPE(oldsave);
3518
3519     if (RXp_PAREN_NAMES(prog)) 
3520         (void)hv_iterinit(RXp_PAREN_NAMES(prog));
3521
3522     /* make sure $`, $&, $', and $digit will work later */
3523     if ( !(flags & REXEC_NOT_FIRST) )
3524         S_reg_set_capture_string(aTHX_ rx,
3525                                     strbeg, reginfo->strend,
3526                                     sv, flags, utf8_target);
3527
3528     return 1;
3529
3530   phooey:
3531     DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch failed%s\n",
3532                           PL_colors[4], PL_colors[5]));
3533
3534     /* clean up; this will trigger destructors that will free all slabs
3535      * above the current one, and cleanup the regmatch_info_aux
3536      * and regmatch_info_aux_eval sructs */
3537
3538     LEAVE_SCOPE(oldsave);
3539
3540     if (swap) {
3541         /* we failed :-( roll it back */
3542         DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
3543             "rex=0x%"UVxf" rolling back offs: freeing=0x%"UVxf" restoring=0x%"UVxf"\n",
3544             PTR2UV(prog),
3545             PTR2UV(prog->offs),
3546             PTR2UV(swap)
3547         ));
3548         Safefree(prog->offs);
3549         prog->offs = swap;
3550     }
3551     return 0;
3552 }
3553
3554
3555 /* Set which rex is pointed to by PL_reg_curpm, handling ref counting.
3556  * Do inc before dec, in case old and new rex are the same */
3557 #define SET_reg_curpm(Re2)                          \
3558     if (reginfo->info_aux_eval) {                   \
3559         (void)ReREFCNT_inc(Re2);                    \
3560         ReREFCNT_dec(PM_GETRE(PL_reg_curpm));       \
3561         PM_SETRE((PL_reg_curpm), (Re2));            \
3562     }
3563
3564
3565 /*
3566  - regtry - try match at specific point
3567  */
3568 STATIC bool                     /* 0 failure, 1 success */
3569 S_regtry(pTHX_ regmatch_info *reginfo, char **startposp)
3570 {
3571     CHECKPOINT lastcp;
3572     REGEXP *const rx = reginfo->prog;
3573     regexp *const prog = ReANY(rx);
3574     SSize_t result;
3575     RXi_GET_DECL(prog,progi);
3576     GET_RE_DEBUG_FLAGS_DECL;
3577
3578     PERL_ARGS_ASSERT_REGTRY;
3579
3580     reginfo->cutpoint=NULL;
3581
3582     prog->offs[0].start = *startposp - reginfo->strbeg;
3583     prog->lastparen = 0;
3584     prog->lastcloseparen = 0;
3585
3586     /* XXXX What this code is doing here?!!!  There should be no need
3587        to do this again and again, prog->lastparen should take care of
3588        this!  --ilya*/
3589
3590     /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
3591      * Actually, the code in regcppop() (which Ilya may be meaning by
3592      * prog->lastparen), is not needed at all by the test suite
3593      * (op/regexp, op/pat, op/split), but that code is needed otherwise
3594      * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
3595      * Meanwhile, this code *is* needed for the
3596      * above-mentioned test suite tests to succeed.  The common theme
3597      * on those tests seems to be returning null fields from matches.
3598      * --jhi updated by dapm */
3599 #if 1
3600     if (prog->nparens) {
3601         regexp_paren_pair *pp = prog->offs;
3602         I32 i;
3603         for (i = prog->nparens; i > (I32)prog->lastparen; i--) {
3604             ++pp;
3605             pp->start = -1;
3606             pp->end = -1;
3607         }
3608     }
3609 #endif
3610     REGCP_SET(lastcp);
3611     result = regmatch(reginfo, *startposp, progi->program + 1);
3612     if (result != -1) {
3613         prog->offs[0].end = result;
3614         return 1;
3615     }
3616     if (reginfo->cutpoint)
3617         *startposp= reginfo->cutpoint;
3618     REGCP_UNWIND(lastcp);
3619     return 0;
3620 }
3621
3622
3623 #define sayYES goto yes
3624 #define sayNO goto no
3625 #define sayNO_SILENT goto no_silent
3626
3627 /* we dont use STMT_START/END here because it leads to 
3628    "unreachable code" warnings, which are bogus, but distracting. */
3629 #define CACHEsayNO \
3630     if (ST.cache_mask) \
3631        reginfo->info_aux->poscache[ST.cache_offset] |= ST.cache_mask; \
3632     sayNO
3633
3634 /* this is used to determine how far from the left messages like
3635    'failed...' are printed. It should be set such that messages 
3636    are inline with the regop output that created them.
3637 */
3638 #define REPORT_CODE_OFF 32
3639
3640
3641 #define CHRTEST_UNINIT -1001 /* c1/c2 haven't been calculated yet */
3642 #define CHRTEST_VOID   -1000 /* the c1/c2 "next char" test should be skipped */
3643 #define CHRTEST_NOT_A_CP_1 -999
3644 #define CHRTEST_NOT_A_CP_2 -998
3645
3646 /* grab a new slab and return the first slot in it */
3647
3648 STATIC regmatch_state *
3649 S_push_slab(pTHX)
3650 {
3651 #if PERL_VERSION < 9 && !defined(PERL_CORE)
3652     dMY_CXT;
3653 #endif
3654     regmatch_slab *s = PL_regmatch_slab->next;
3655     if (!s) {
3656         Newx(s, 1, regmatch_slab);
3657         s->prev = PL_regmatch_slab;
3658         s->next = NULL;
3659         PL_regmatch_slab->next = s;
3660     }
3661     PL_regmatch_slab = s;
3662     return SLAB_FIRST(s);
3663 }
3664
3665
3666 /* push a new state then goto it */
3667
3668 #define PUSH_STATE_GOTO(state, node, input) \
3669     pushinput = input; \
3670     scan = node; \
3671     st->resume_state = state; \
3672     goto push_state;
3673
3674 /* push a new state with success backtracking, then goto it */
3675
3676 #define PUSH_YES_STATE_GOTO(state, node, input) \
3677     pushinput = input; \
3678     scan = node; \
3679     st->resume_state = state; \
3680     goto push_yes_state;
3681
3682
3683
3684
3685 /*
3686
3687 regmatch() - main matching routine
3688
3689 This is basically one big switch statement in a loop. We execute an op,
3690 set 'next' to point the next op, and continue. If we come to a point which
3691 we may need to backtrack to on failure such as (A|B|C), we push a
3692 backtrack state onto the backtrack stack. On failure, we pop the top
3693 state, and re-enter the loop at the state indicated. If there are no more
3694 states to pop, we return failure.
3695
3696 Sometimes we also need to backtrack on success; for example /A+/, where
3697 after successfully matching one A, we need to go back and try to
3698 match another one; similarly for lookahead assertions: if the assertion
3699 completes successfully, we backtrack to the state just before the assertion
3700 and then carry on.  In these cases, the pushed state is marked as
3701 'backtrack on success too'. This marking is in fact done by a chain of
3702 pointers, each pointing to the previous 'yes' state. On success, we pop to
3703 the nearest yes state, discarding any intermediate failure-only states.
3704 Sometimes a yes state is pushed just to force some cleanup code to be
3705 called at the end of a successful match or submatch; e.g. (??{$re}) uses
3706 it to free the inner regex.
3707
3708 Note that failure backtracking rewinds the cursor position, while
3709 success backtracking leaves it alone.
3710
3711 A pattern is complete when the END op is executed, while a subpattern
3712 such as (?=foo) is complete when the SUCCESS op is executed. Both of these
3713 ops trigger the "pop to last yes state if any, otherwise return true"
3714 behaviour.
3715
3716 A common convention in this function is to use A and B to refer to the two
3717 subpatterns (or to the first nodes thereof) in patterns like /A*B/: so A is
3718 the subpattern to be matched possibly multiple times, while B is the entire
3719 rest of the pattern. Variable and state names reflect this convention.
3720
3721 The states in the main switch are the union of ops and failure/success of
3722 substates associated with with that op.  For example, IFMATCH is the op
3723 that does lookahead assertions /(?=A)B/ and so the IFMATCH state means
3724 'execute IFMATCH'; while IFMATCH_A is a state saying that we have just
3725 successfully matched A and IFMATCH_A_fail is a state saying that we have
3726 just failed to match A. Resume states always come in pairs. The backtrack
3727 state we push is marked as 'IFMATCH_A', but when that is popped, we resume
3728 at IFMATCH_A or IFMATCH_A_fail, depending on whether we are backtracking
3729 on success or failure.
3730
3731 The struct that holds a backtracking state is actually a big union, with
3732 one variant for each major type of op. The variable st points to the
3733 top-most backtrack struct. To make the code clearer, within each
3734 block of code we #define ST to alias the relevant union.
3735
3736 Here's a concrete example of a (vastly oversimplified) IFMATCH
3737 implementation:
3738
3739     switch (state) {
3740     ....
3741
3742 #define ST st->u.ifmatch
3743
3744     case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3745         ST.foo = ...; // some state we wish to save
3746         ...
3747         // push a yes backtrack state with a resume value of
3748         // IFMATCH_A/IFMATCH_A_fail, then continue execution at the
3749         // first node of A:
3750         PUSH_YES_STATE_GOTO(IFMATCH_A, A, newinput);
3751         // NOTREACHED
3752
3753     case IFMATCH_A: // we have successfully executed A; now continue with B
3754         next = B;
3755         bar = ST.foo; // do something with the preserved value
3756         break;
3757
3758     case IFMATCH_A_fail: // A failed, so the assertion failed
3759         ...;   // do some housekeeping, then ...
3760         sayNO; // propagate the failure
3761
3762 #undef ST
3763
3764     ...
3765     }
3766
3767 For any old-timers reading this who are familiar with the old recursive
3768 approach, the code above is equivalent to:
3769
3770     case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3771     {
3772         int foo = ...
3773         ...
3774         if (regmatch(A)) {
3775             next = B;
3776             bar = foo;
3777             break;
3778         }
3779         ...;   // do some housekeeping, then ...
3780         sayNO; // propagate the failure
3781     }
3782
3783 The topmost backtrack state, pointed to by st, is usually free. If you
3784 want to claim it, populate any ST.foo fields in it with values you wish to
3785 save, then do one of
3786
3787         PUSH_STATE_GOTO(resume_state, node, newinput);
3788         PUSH_YES_STATE_GOTO(resume_state, node, newinput);
3789
3790 which sets that backtrack state's resume value to 'resume_state', pushes a
3791 new free entry to the top of the backtrack stack, then goes to 'node'.
3792 On backtracking, the free slot is popped, and the saved state becomes the
3793 new free state. An ST.foo field in this new top state can be temporarily
3794 accessed to retrieve values, but once the main loop is re-entered, it
3795 becomes available for reuse.
3796
3797 Note that the depth of the backtrack stack constantly increases during the
3798 left-to-right execution of the pattern, rather than going up and down with
3799 the pattern nesting. For example the stack is at its maximum at Z at the
3800 end of the pattern, rather than at X in the following:
3801
3802     /(((X)+)+)+....(Y)+....Z/
3803
3804 The only exceptions to this are lookahead/behind assertions and the cut,
3805 (?>A), which pop all the backtrack states associated with A before
3806 continuing.
3807  
3808 Backtrack state structs are allocated in slabs of about 4K in size.
3809 PL_regmatch_state and st always point to the currently active state,
3810 and PL_regmatch_slab points to the slab currently containing
3811 PL_regmatch_state.  The first time regmatch() is called, the first slab is
3812 allocated, and is never freed until interpreter destruction. When the slab
3813 is full, a new one is allocated and chained to the end. At exit from
3814 regmatch(), slabs allocated since entry are freed.
3815
3816 */
3817  
3818
3819 #define DEBUG_STATE_pp(pp)                                  \
3820     DEBUG_STATE_r({                                         \
3821         DUMP_EXEC_POS(locinput, scan, utf8_target);         \
3822         PerlIO_printf(Perl_debug_log,                       \
3823             "    %*s"pp" %s%s%s%s%s\n",                     \
3824             depth*2, "",                                    \
3825             PL_reg_name[st->resume_state],                  \
3826             ((st==yes_state||st==mark_state) ? "[" : ""),   \
3827             ((st==yes_state) ? "Y" : ""),                   \
3828             ((st==mark_state) ? "M" : ""),                  \
3829             ((st==yes_state||st==mark_state) ? "]" : "")    \
3830         );                                                  \
3831     });
3832
3833
3834 #define REG_NODE_NUM(x) ((x) ? (int)((x)-prog) : -1)
3835
3836 #ifdef DEBUGGING
3837
3838 STATIC void
3839 S_debug_start_match(pTHX_ const REGEXP *prog, const bool utf8_target,
3840     const char *start, const char *end, const char *blurb)
3841 {
3842     const bool utf8_pat = RX_UTF8(prog) ? 1 : 0;
3843
3844     PERL_ARGS_ASSERT_DEBUG_START_MATCH;
3845
3846     if (!PL_colorset)   
3847             reginitcolors();    
3848     {
3849         RE_PV_QUOTED_DECL(s0, utf8_pat, PERL_DEBUG_PAD_ZERO(0), 
3850             RX_PRECOMP_const(prog), RX_PRELEN(prog), 60);   
3851         
3852         RE_PV_QUOTED_DECL(s1, utf8_target, PERL_DEBUG_PAD_ZERO(1),
3853             start, end - start, 60); 
3854         
3855         PerlIO_printf(Perl_debug_log, 
3856             "%s%s REx%s %s against %s\n", 
3857        &nbs