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