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