This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Upgrade to ExtUtils-ParseXS-2.16. There actually are a couple of
[perl5.git] / regexec.c
1 /*    regexec.c
2  */
3
4 /*
5  * "One Ring to rule them all, One Ring to find them..."
6  */
7
8 /* This file contains functions for executing a regular expression.  See
9  * also regcomp.c which funnily enough, contains functions for compiling
10  * a regular expression.
11  *
12  * This file is also copied at build time to ext/re/re_exec.c, where
13  * it's built with -DPERL_EXT_RE_BUILD -DPERL_EXT_RE_DEBUG -DPERL_EXT.
14  * This causes the main functions to be compiled under new names and with
15  * debugging support added, which makes "use re 'debug'" work.
16  */
17
18 /* NOTE: this is derived from Henry Spencer's regexp code, and should not
19  * confused with the original package (see point 3 below).  Thanks, Henry!
20  */
21
22 /* Additional note: this code is very heavily munged from Henry's version
23  * in places.  In some spots I've traded clarity for efficiency, so don't
24  * blame Henry for some of the lack of readability.
25  */
26
27 /* The names of the functions have been changed from regcomp and
28  * regexec to  pregcomp and pregexec in order to avoid conflicts
29  * with the POSIX routines of the same names.
30 */
31
32 #ifdef PERL_EXT_RE_BUILD
33 #include "re_top.h"
34 #endif
35
36 /*
37  * pregcomp and pregexec -- regsub and regerror are not used in perl
38  *
39  *      Copyright (c) 1986 by University of Toronto.
40  *      Written by Henry Spencer.  Not derived from licensed software.
41  *
42  *      Permission is granted to anyone to use this software for any
43  *      purpose on any computer system, and to redistribute it freely,
44  *      subject to the following restrictions:
45  *
46  *      1. The author is not responsible for the consequences of use of
47  *              this software, no matter how awful, even if they arise
48  *              from defects in it.
49  *
50  *      2. The origin of this software must not be misrepresented, either
51  *              by explicit claim or by omission.
52  *
53  *      3. Altered versions must be plainly marked as such, and must not
54  *              be misrepresented as being the original software.
55  *
56  ****    Alterations to Henry's code are...
57  ****
58  ****    Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
59  ****    2000, 2001, 2002, 2003, 2004, 2005, 2006, by Larry Wall and others
60  ****
61  ****    You may distribute under the terms of either the GNU General Public
62  ****    License or the Artistic License, as specified in the README file.
63  *
64  * Beware that some of this code is subtly aware of the way operator
65  * precedence is structured in regular expressions.  Serious changes in
66  * regular-expression syntax might require a total rethink.
67  */
68 #include "EXTERN.h"
69 #define PERL_IN_REGEXEC_C
70 #include "perl.h"
71
72 #ifdef PERL_IN_XSUB_RE
73 #  include "re_comp.h"
74 #else
75 #  include "regcomp.h"
76 #endif
77
78 #define RF_tainted      1               /* tainted information used? */
79 #define RF_warned       2               /* warned about big count? */
80 #define RF_evaled       4               /* Did an EVAL with setting? */
81 #define RF_utf8         8               /* Pattern contains multibyte chars? */
82
83 #define UTF ((PL_reg_flags & RF_utf8) != 0)
84
85 #define RS_init         1               /* eval environment created */
86 #define RS_set          2               /* replsv value is set */
87
88 #ifndef STATIC
89 #define STATIC  static
90 #endif
91
92 #define REGINCLASS(prog,p,c)  (ANYOF_FLAGS(p) ? reginclass(prog,p,c,0,0) : ANYOF_BITMAP_TEST(p,*(c)))
93
94 /*
95  * Forwards.
96  */
97
98 #define CHR_SVLEN(sv) (do_utf8 ? sv_len_utf8(sv) : SvCUR(sv))
99 #define CHR_DIST(a,b) (PL_reg_match_utf8 ? utf8_distance(a,b) : a - b)
100
101 #define HOPc(pos,off) \
102         (char *)(PL_reg_match_utf8 \
103             ? reghop3((U8*)pos, off, (U8*)(off >= 0 ? PL_regeol : PL_bostr)) \
104             : (U8*)(pos + off))
105 #define HOPBACKc(pos, off) \
106         (char*)(PL_reg_match_utf8\
107             ? reghopmaybe3((U8*)pos, -off, (U8*)PL_bostr) \
108             : (pos - off >= PL_bostr)           \
109                 ? (U8*)pos - off                \
110                 : NULL)
111
112 #define HOP3(pos,off,lim) (PL_reg_match_utf8 ? reghop3((U8*)(pos), off, (U8*)(lim)) : (U8*)(pos + off))
113 #define HOP3c(pos,off,lim) ((char*)HOP3(pos,off,lim))
114
115 #define LOAD_UTF8_CHARCLASS(class,str) STMT_START { \
116     if (!CAT2(PL_utf8_,class)) { bool ok; ENTER; save_re_context(); ok=CAT2(is_utf8_,class)((const U8*)str); assert(ok); LEAVE; } } STMT_END
117 #define LOAD_UTF8_CHARCLASS_ALNUM() LOAD_UTF8_CHARCLASS(alnum,"a")
118 #define LOAD_UTF8_CHARCLASS_DIGIT() LOAD_UTF8_CHARCLASS(digit,"0")
119 #define LOAD_UTF8_CHARCLASS_SPACE() LOAD_UTF8_CHARCLASS(space," ")
120 #define LOAD_UTF8_CHARCLASS_MARK()  LOAD_UTF8_CHARCLASS(mark, "\xcd\x86")
121
122 /* TODO: Combine JUMPABLE and HAS_TEXT to cache OP(rn) */
123
124 /* for use after a quantifier and before an EXACT-like node -- japhy */
125 #define JUMPABLE(rn) ( \
126     OP(rn) == OPEN || OP(rn) == CLOSE || OP(rn) == EVAL || \
127     OP(rn) == SUSPEND || OP(rn) == IFMATCH || \
128     OP(rn) == PLUS || OP(rn) == MINMOD || \
129     (PL_regkind[OP(rn)] == CURLY && ARG1(rn) > 0) \
130 )
131
132 #define HAS_TEXT(rn) ( \
133     PL_regkind[OP(rn)] == EXACT || PL_regkind[OP(rn)] == REF \
134 )
135
136 /*
137   Search for mandatory following text node; for lookahead, the text must
138   follow but for lookbehind (rn->flags != 0) we skip to the next step.
139 */
140 #define FIND_NEXT_IMPT(rn) STMT_START { \
141     while (JUMPABLE(rn)) { \
142         const OPCODE type = OP(rn); \
143         if (type == SUSPEND || PL_regkind[type] == CURLY) \
144             rn = NEXTOPER(NEXTOPER(rn)); \
145         else if (type == PLUS) \
146             rn = NEXTOPER(rn); \
147         else if (type == IFMATCH) \
148             rn = (rn->flags == 0) ? NEXTOPER(NEXTOPER(rn)) : rn + ARG(rn); \
149         else rn += NEXT_OFF(rn); \
150     } \
151 } STMT_END 
152
153 static void restore_pos(pTHX_ void *arg);
154
155 STATIC CHECKPOINT
156 S_regcppush(pTHX_ I32 parenfloor)
157 {
158     dVAR;
159     const int retval = PL_savestack_ix;
160 #define REGCP_PAREN_ELEMS 4
161     const int paren_elems_to_push = (PL_regsize - parenfloor) * REGCP_PAREN_ELEMS;
162     int p;
163     GET_RE_DEBUG_FLAGS_DECL;
164
165     if (paren_elems_to_push < 0)
166         Perl_croak(aTHX_ "panic: paren_elems_to_push < 0");
167
168 #define REGCP_OTHER_ELEMS 6
169     SSGROW(paren_elems_to_push + REGCP_OTHER_ELEMS);
170     for (p = PL_regsize; p > parenfloor; p--) {
171 /* REGCP_PARENS_ELEMS are pushed per pairs of parentheses. */
172         SSPUSHINT(PL_regendp[p]);
173         SSPUSHINT(PL_regstartp[p]);
174         SSPUSHPTR(PL_reg_start_tmp[p]);
175         SSPUSHINT(p);
176         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
177           "     saving \\%"UVuf" %"IVdf"(%"IVdf")..%"IVdf"\n",
178                       (UV)p, (IV)PL_regstartp[p],
179                       (IV)(PL_reg_start_tmp[p] - PL_bostr),
180                       (IV)PL_regendp[p]
181         ));
182     }
183 /* REGCP_OTHER_ELEMS are pushed in any case, parentheses or no. */
184     SSPUSHINT(PL_regsize);
185     SSPUSHINT(*PL_reglastparen);
186     SSPUSHINT(*PL_reglastcloseparen);
187     SSPUSHPTR(PL_reginput);
188 #define REGCP_FRAME_ELEMS 2
189 /* REGCP_FRAME_ELEMS are part of the REGCP_OTHER_ELEMS and
190  * are needed for the regexp context stack bookkeeping. */
191     SSPUSHINT(paren_elems_to_push + REGCP_OTHER_ELEMS - REGCP_FRAME_ELEMS);
192     SSPUSHINT(SAVEt_REGCONTEXT); /* Magic cookie. */
193
194     return retval;
195 }
196
197 /* These are needed since we do not localize EVAL nodes: */
198 #define REGCP_SET(cp)                                           \
199     DEBUG_STATE_r(                                              \
200             PerlIO_printf(Perl_debug_log,                       \
201                 "  Setting an EVAL scope, savestack=%"IVdf"\n", \
202                 (IV)PL_savestack_ix));                          \
203     cp = PL_savestack_ix
204
205 #define REGCP_UNWIND(cp)                                        \
206     DEBUG_STATE_r(                                              \
207         if (cp != PL_savestack_ix)                              \
208             PerlIO_printf(Perl_debug_log,                       \
209                 "  Clearing an EVAL scope, savestack=%"IVdf"..%"IVdf"\n", \
210                 (IV)(cp), (IV)PL_savestack_ix));                \
211     regcpblow(cp)
212
213 STATIC char *
214 S_regcppop(pTHX_ const regexp *rex)
215 {
216     dVAR;
217     I32 i;
218     char *input;
219
220     GET_RE_DEBUG_FLAGS_DECL;
221
222     /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
223     i = SSPOPINT;
224     assert(i == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
225     i = SSPOPINT; /* Parentheses elements to pop. */
226     input = (char *) SSPOPPTR;
227     *PL_reglastcloseparen = SSPOPINT;
228     *PL_reglastparen = SSPOPINT;
229     PL_regsize = SSPOPINT;
230
231     /* Now restore the parentheses context. */
232     for (i -= (REGCP_OTHER_ELEMS - REGCP_FRAME_ELEMS);
233          i > 0; i -= REGCP_PAREN_ELEMS) {
234         I32 tmps;
235         U32 paren = (U32)SSPOPINT;
236         PL_reg_start_tmp[paren] = (char *) SSPOPPTR;
237         PL_regstartp[paren] = SSPOPINT;
238         tmps = SSPOPINT;
239         if (paren <= *PL_reglastparen)
240             PL_regendp[paren] = tmps;
241         DEBUG_EXECUTE_r(
242             PerlIO_printf(Perl_debug_log,
243                           "     restoring \\%"UVuf" to %"IVdf"(%"IVdf")..%"IVdf"%s\n",
244                           (UV)paren, (IV)PL_regstartp[paren],
245                           (IV)(PL_reg_start_tmp[paren] - PL_bostr),
246                           (IV)PL_regendp[paren],
247                           (paren > *PL_reglastparen ? "(no)" : ""));
248         );
249     }
250     DEBUG_EXECUTE_r(
251         if (*PL_reglastparen + 1 <= rex->nparens) {
252             PerlIO_printf(Perl_debug_log,
253                           "     restoring \\%"IVdf"..\\%"IVdf" to undef\n",
254                           (IV)(*PL_reglastparen + 1), (IV)rex->nparens);
255         }
256     );
257 #if 1
258     /* It would seem that the similar code in regtry()
259      * already takes care of this, and in fact it is in
260      * a better location to since this code can #if 0-ed out
261      * but the code in regtry() is needed or otherwise tests
262      * requiring null fields (pat.t#187 and split.t#{13,14}
263      * (as of patchlevel 7877)  will fail.  Then again,
264      * this code seems to be necessary or otherwise
265      * building DynaLoader will fail:
266      * "Error: '*' not in typemap in DynaLoader.xs, line 164"
267      * --jhi */
268     for (i = *PL_reglastparen + 1; (U32)i <= rex->nparens; i++) {
269         if (i > PL_regsize)
270             PL_regstartp[i] = -1;
271         PL_regendp[i] = -1;
272     }
273 #endif
274     return input;
275 }
276
277 #define regcpblow(cp) LEAVE_SCOPE(cp)   /* Ignores regcppush()ed data. */
278
279 /*
280  * pregexec and friends
281  */
282
283 #ifndef PERL_IN_XSUB_RE
284 /*
285  - pregexec - match a regexp against a string
286  */
287 I32
288 Perl_pregexec(pTHX_ register regexp *prog, char *stringarg, register char *strend,
289          char *strbeg, I32 minend, SV *screamer, U32 nosave)
290 /* strend: pointer to null at end of string */
291 /* strbeg: real beginning of string */
292 /* minend: end of match must be >=minend after stringarg. */
293 /* nosave: For optimizations. */
294 {
295     return
296         regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
297                       nosave ? 0 : REXEC_COPY_STR);
298 }
299 #endif
300
301 /*
302  * Need to implement the following flags for reg_anch:
303  *
304  * USE_INTUIT_NOML              - Useful to call re_intuit_start() first
305  * USE_INTUIT_ML
306  * INTUIT_AUTORITATIVE_NOML     - Can trust a positive answer
307  * INTUIT_AUTORITATIVE_ML
308  * INTUIT_ONCE_NOML             - Intuit can match in one location only.
309  * INTUIT_ONCE_ML
310  *
311  * Another flag for this function: SECOND_TIME (so that float substrs
312  * with giant delta may be not rechecked).
313  */
314
315 /* Assumptions: if ANCH_GPOS, then strpos is anchored. XXXX Check GPOS logic */
316
317 /* If SCREAM, then SvPVX_const(sv) should be compatible with strpos and strend.
318    Otherwise, only SvCUR(sv) is used to get strbeg. */
319
320 /* XXXX We assume that strpos is strbeg unless sv. */
321
322 /* XXXX Some places assume that there is a fixed substring.
323         An update may be needed if optimizer marks as "INTUITable"
324         RExen without fixed substrings.  Similarly, it is assumed that
325         lengths of all the strings are no more than minlen, thus they
326         cannot come from lookahead.
327         (Or minlen should take into account lookahead.) */
328
329 /* A failure to find a constant substring means that there is no need to make
330    an expensive call to REx engine, thus we celebrate a failure.  Similarly,
331    finding a substring too deep into the string means that less calls to
332    regtry() should be needed.
333
334    REx compiler's optimizer found 4 possible hints:
335         a) Anchored substring;
336         b) Fixed substring;
337         c) Whether we are anchored (beginning-of-line or \G);
338         d) First node (of those at offset 0) which may distingush positions;
339    We use a)b)d) and multiline-part of c), and try to find a position in the
340    string which does not contradict any of them.
341  */
342
343 /* Most of decisions we do here should have been done at compile time.
344    The nodes of the REx which we used for the search should have been
345    deleted from the finite automaton. */
346
347 char *
348 Perl_re_intuit_start(pTHX_ regexp *prog, SV *sv, char *strpos,
349                      char *strend, U32 flags, re_scream_pos_data *data)
350 {
351     dVAR;
352     register I32 start_shift = 0;
353     /* Should be nonnegative! */
354     register I32 end_shift   = 0;
355     register char *s;
356     register SV *check;
357     char *strbeg;
358     char *t;
359     const bool do_utf8 = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
360     I32 ml_anch;
361     register char *other_last = NULL;   /* other substr checked before this */
362     char *check_at = NULL;              /* check substr found at this pos */
363     const I32 multiline = prog->reganch & PMf_MULTILINE;
364 #ifdef DEBUGGING
365     const char * const i_strpos = strpos;
366 #endif
367
368     GET_RE_DEBUG_FLAGS_DECL;
369
370     RX_MATCH_UTF8_set(prog,do_utf8);
371
372     if (prog->reganch & ROPT_UTF8) {
373         PL_reg_flags |= RF_utf8;
374     }
375     DEBUG_EXECUTE_r( 
376         debug_start_match(prog, do_utf8, strpos, strend, 
377             sv ? "Guessing start of match in sv for"
378                : "Guessing start of match in string for");
379               );
380
381     /* CHR_DIST() would be more correct here but it makes things slow. */
382     if (prog->minlen > strend - strpos) {
383         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
384                               "String too short... [re_intuit_start]\n"));
385         goto fail;
386     }
387                 
388     strbeg = (sv && SvPOK(sv)) ? strend - SvCUR(sv) : strpos;
389     PL_regeol = strend;
390     if (do_utf8) {
391         if (!prog->check_utf8 && prog->check_substr)
392             to_utf8_substr(prog);
393         check = prog->check_utf8;
394     } else {
395         if (!prog->check_substr && prog->check_utf8)
396             to_byte_substr(prog);
397         check = prog->check_substr;
398     }
399     if (check == &PL_sv_undef) {
400         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
401                 "Non-utf8 string cannot match utf8 check string\n"));
402         goto fail;
403     }
404     if (prog->reganch & ROPT_ANCH) {    /* Match at beg-of-str or after \n */
405         ml_anch = !( (prog->reganch & ROPT_ANCH_SINGLE)
406                      || ( (prog->reganch & ROPT_ANCH_BOL)
407                           && !multiline ) );    /* Check after \n? */
408
409         if (!ml_anch) {
410           if ( !(prog->reganch & (ROPT_ANCH_GPOS /* Checked by the caller */
411                                   | ROPT_IMPLICIT)) /* not a real BOL */
412                /* SvCUR is not set on references: SvRV and SvPVX_const overlap */
413                && sv && !SvROK(sv)
414                && (strpos != strbeg)) {
415               DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Not at start...\n"));
416               goto fail;
417           }
418           if (prog->check_offset_min == prog->check_offset_max &&
419               !(prog->reganch & ROPT_CANY_SEEN)) {
420             /* Substring at constant offset from beg-of-str... */
421             I32 slen;
422
423             s = HOP3c(strpos, prog->check_offset_min, strend);
424             
425             if (SvTAIL(check)) {
426                 slen = SvCUR(check);    /* >= 1 */
427
428                 if ( strend - s > slen || strend - s < slen - 1
429                      || (strend - s == slen && strend[-1] != '\n')) {
430                     DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "String too long...\n"));
431                     goto fail_finish;
432                 }
433                 /* Now should match s[0..slen-2] */
434                 slen--;
435                 if (slen && (*SvPVX_const(check) != *s
436                              || (slen > 1
437                                  && memNE(SvPVX_const(check), s, slen)))) {
438                   report_neq:
439                     DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "String not equal...\n"));
440                     goto fail_finish;
441                 }
442             }
443             else if (*SvPVX_const(check) != *s
444                      || ((slen = SvCUR(check)) > 1
445                          && memNE(SvPVX_const(check), s, slen)))
446                 goto report_neq;
447             check_at = s;
448             goto success_at_start;
449           }
450         }
451         /* Match is anchored, but substr is not anchored wrt beg-of-str. */
452         s = strpos;
453         start_shift = prog->check_offset_min; /* okay to underestimate on CC */
454         end_shift = prog->check_end_shift;
455         
456         if (!ml_anch) {
457             const I32 end = prog->check_offset_max + CHR_SVLEN(check)
458                                          - (SvTAIL(check) != 0);
459             const I32 eshift = CHR_DIST((U8*)strend, (U8*)s) - end;
460
461             if (end_shift < eshift)
462                 end_shift = eshift;
463         }
464     }
465     else {                              /* Can match at random position */
466         ml_anch = 0;
467         s = strpos;
468         start_shift = prog->check_offset_min;  /* okay to underestimate on CC */
469         end_shift = prog->check_end_shift;
470         
471         /* end shift should be non negative here */
472     }
473
474 #ifdef DEBUGGING        /* 7/99: reports of failure (with the older version) */
475     if (end_shift < 0)
476         Perl_croak(aTHX_ "panic: end_shift: %"IVdf" pattern:\n%s\n ",
477             end_shift,prog->precomp);
478 #endif
479
480   restart:
481     /* Find a possible match in the region s..strend by looking for
482        the "check" substring in the region corrected by start/end_shift. */
483     
484     {
485         I32 srch_start_shift = start_shift;
486         I32 srch_end_shift = end_shift;
487         if (srch_start_shift < 0 && strbeg - s > srch_start_shift) {
488             srch_end_shift -= ((strbeg - s) - srch_start_shift); 
489             srch_start_shift = strbeg - s;
490         }
491     DEBUG_OPTIMISE_r({
492         PerlIO_printf(Perl_debug_log, "Check offset min: %"IVdf" Start shift: %"IVdf" End shift %"IVdf" Real End Shift: %"IVdf"\n",
493             (IV)prog->check_offset_min,
494             (IV)srch_start_shift,
495             (IV)srch_end_shift, 
496             (IV)prog->check_end_shift);
497     });       
498         
499     if (flags & REXEC_SCREAM) {
500         I32 p = -1;                     /* Internal iterator of scream. */
501         I32 * const pp = data ? data->scream_pos : &p;
502
503         if (PL_screamfirst[BmRARE(check)] >= 0
504             || ( BmRARE(check) == '\n'
505                  && (BmPREVIOUS(check) == SvCUR(check) - 1)
506                  && SvTAIL(check) ))
507             s = screaminstr(sv, check,
508                             srch_start_shift + (s - strbeg), srch_end_shift, pp, 0);
509         else
510             goto fail_finish;
511         /* we may be pointing at the wrong string */
512         if (s && RX_MATCH_COPIED(prog))
513             s = strbeg + (s - SvPVX_const(sv));
514         if (data)
515             *data->scream_olds = s;
516     }
517     else {
518         U8* start_point;
519         U8* end_point;
520         if (prog->reganch & ROPT_CANY_SEEN) {
521             start_point= (U8*)(s + srch_start_shift);
522             end_point= (U8*)(strend - srch_end_shift);
523         } else {
524             start_point= HOP3(s, srch_start_shift, srch_start_shift < 0 ? strbeg : strend);
525             end_point= HOP3(strend, -srch_end_shift, strbeg);
526         }
527         DEBUG_OPTIMISE_r({
528             PerlIO_printf(Perl_debug_log, "fbm_instr len=%d str=<%.*s>\n", 
529                 (int)(end_point - start_point),
530                 (int)(end_point - start_point), 
531                 start_point);
532         });
533
534         s = fbm_instr( start_point, end_point,
535                       check, multiline ? FBMrf_MULTILINE : 0);
536     }
537     }
538     /* Update the count-of-usability, remove useless subpatterns,
539         unshift s.  */
540
541     DEBUG_EXECUTE_r({
542         RE_PV_QUOTED_DECL(quoted, do_utf8, PERL_DEBUG_PAD_ZERO(0), 
543             SvPVX_const(check), RE_SV_DUMPLEN(check), 30);
544         PerlIO_printf(Perl_debug_log, "%s %s substr %s%s%s",
545                           (s ? "Found" : "Did not find"),
546             (check == (do_utf8 ? prog->anchored_utf8 : prog->anchored_substr) 
547                 ? "anchored" : "floating"),
548             quoted,
549             RE_SV_TAIL(check),
550             (s ? " at offset " : "...\n") ); 
551     });
552
553     if (!s)
554         goto fail_finish;
555     /* Finish the diagnostic message */
556     DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%ld...\n", (long)(s - i_strpos)) );
557
558     /* XXX dmq: first branch is for positive lookbehind...
559        Our check string is offset from the beginning of the pattern.
560        So we need to do any stclass tests offset forward from that 
561        point. I think. :-(
562      */
563     
564         
565     
566     check_at=s;
567      
568
569     /* Got a candidate.  Check MBOL anchoring, and the *other* substr.
570        Start with the other substr.
571        XXXX no SCREAM optimization yet - and a very coarse implementation
572        XXXX /ttx+/ results in anchored="ttx", floating="x".  floating will
573                 *always* match.  Probably should be marked during compile...
574        Probably it is right to do no SCREAM here...
575      */
576
577     if (do_utf8 ? (prog->float_utf8 && prog->anchored_utf8) 
578                 : (prog->float_substr && prog->anchored_substr)) 
579     {
580         /* Take into account the "other" substring. */
581         /* XXXX May be hopelessly wrong for UTF... */
582         if (!other_last)
583             other_last = strpos;
584         if (check == (do_utf8 ? prog->float_utf8 : prog->float_substr)) {
585           do_other_anchored:
586             {
587                 char * const last = HOP3c(s, -start_shift, strbeg);
588                 char *last1, *last2;
589                 char * const saved_s = s;
590                 SV* must;
591
592                 t = s - prog->check_offset_max;
593                 if (s - strpos > prog->check_offset_max  /* signed-corrected t > strpos */
594                     && (!do_utf8
595                         || ((t = (char*)reghopmaybe3((U8*)s, -(prog->check_offset_max), (U8*)strpos))
596                             && t > strpos)))
597                     NOOP;
598                 else
599                     t = strpos;
600                 t = HOP3c(t, prog->anchored_offset, strend);
601                 if (t < other_last)     /* These positions already checked */
602                     t = other_last;
603                 last2 = last1 = HOP3c(strend, -prog->minlen, strbeg);
604                 if (last < last1)
605                     last1 = last;
606                 /* XXXX It is not documented what units *_offsets are in.  
607                    We assume bytes, but this is clearly wrong. 
608                    Meaning this code needs to be carefully reviewed for errors.
609                    dmq.
610                   */
611  
612                 /* On end-of-str: see comment below. */
613                 must = do_utf8 ? prog->anchored_utf8 : prog->anchored_substr;
614                 if (must == &PL_sv_undef) {
615                     s = (char*)NULL;
616                     DEBUG_r(must = prog->anchored_utf8);        /* for debug */
617                 }
618                 else
619                     s = fbm_instr(
620                         (unsigned char*)t,
621                         HOP3(HOP3(last1, prog->anchored_offset, strend)
622                                 + SvCUR(must), -(SvTAIL(must)!=0), strbeg),
623                         must,
624                         multiline ? FBMrf_MULTILINE : 0
625                     );
626                 DEBUG_EXECUTE_r({
627                     RE_PV_QUOTED_DECL(quoted, do_utf8, PERL_DEBUG_PAD_ZERO(0), 
628                         SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
629                     PerlIO_printf(Perl_debug_log, "%s anchored substr %s%s",
630                         (s ? "Found" : "Contradicts"),
631                         quoted, RE_SV_TAIL(must));
632                 });                 
633                 
634                             
635                 if (!s) {
636                     if (last1 >= last2) {
637                         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
638                                                 ", giving up...\n"));
639                         goto fail_finish;
640                     }
641                     DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
642                         ", trying floating at offset %ld...\n",
643                         (long)(HOP3c(saved_s, 1, strend) - i_strpos)));
644                     other_last = HOP3c(last1, prog->anchored_offset+1, strend);
645                     s = HOP3c(last, 1, strend);
646                     goto restart;
647                 }
648                 else {
649                     DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " at offset %ld...\n",
650                           (long)(s - i_strpos)));
651                     t = HOP3c(s, -prog->anchored_offset, strbeg);
652                     other_last = HOP3c(s, 1, strend);
653                     s = saved_s;
654                     if (t == strpos)
655                         goto try_at_start;
656                     goto try_at_offset;
657                 }
658             }
659         }
660         else {          /* Take into account the floating substring. */
661             char *last, *last1;
662             char * const saved_s = s;
663             SV* must;
664
665             t = HOP3c(s, -start_shift, strbeg);
666             last1 = last =
667                 HOP3c(strend, -prog->minlen + prog->float_min_offset, strbeg);
668             if (CHR_DIST((U8*)last, (U8*)t) > prog->float_max_offset)
669                 last = HOP3c(t, prog->float_max_offset, strend);
670             s = HOP3c(t, prog->float_min_offset, strend);
671             if (s < other_last)
672                 s = other_last;
673  /* XXXX It is not documented what units *_offsets are in.  Assume bytes.  */
674             must = do_utf8 ? prog->float_utf8 : prog->float_substr;
675             /* fbm_instr() takes into account exact value of end-of-str
676                if the check is SvTAIL(ed).  Since false positives are OK,
677                and end-of-str is not later than strend we are OK. */
678             if (must == &PL_sv_undef) {
679                 s = (char*)NULL;
680                 DEBUG_r(must = prog->float_utf8);       /* for debug message */
681             }
682             else
683                 s = fbm_instr((unsigned char*)s,
684                               (unsigned char*)last + SvCUR(must)
685                                   - (SvTAIL(must)!=0),
686                               must, multiline ? FBMrf_MULTILINE : 0);
687             DEBUG_EXECUTE_r({
688                 RE_PV_QUOTED_DECL(quoted, do_utf8, PERL_DEBUG_PAD_ZERO(0), 
689                     SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
690                 PerlIO_printf(Perl_debug_log, "%s floating substr %s%s",
691                     (s ? "Found" : "Contradicts"),
692                     quoted, RE_SV_TAIL(must));
693             });
694             if (!s) {
695                 if (last1 == last) {
696                     DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
697                                             ", giving up...\n"));
698                     goto fail_finish;
699                 }
700                 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
701                     ", trying anchored starting at offset %ld...\n",
702                     (long)(saved_s + 1 - i_strpos)));
703                 other_last = last;
704                 s = HOP3c(t, 1, strend);
705                 goto restart;
706             }
707             else {
708                 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " at offset %ld...\n",
709                       (long)(s - i_strpos)));
710                 other_last = s; /* Fix this later. --Hugo */
711                 s = saved_s;
712                 if (t == strpos)
713                     goto try_at_start;
714                 goto try_at_offset;
715             }
716         }
717     }
718
719     
720     t= (char*)HOP3( s, -prog->check_offset_max, (prog->check_offset_max<0) ? strend : strpos);
721         
722     DEBUG_OPTIMISE_r(
723         PerlIO_printf(Perl_debug_log, 
724             "Check offset min:%"IVdf" max:%"IVdf" S:%"IVdf" t:%"IVdf" D:%"IVdf" end:%"IVdf"\n",
725             (IV)prog->check_offset_min,
726             (IV)prog->check_offset_max,
727             (IV)(s-strpos),
728             (IV)(t-strpos),
729             (IV)(t-s),
730             (IV)(strend-strpos)
731         )
732     );
733
734     if (s - strpos > prog->check_offset_max  /* signed-corrected t > strpos */
735         && (!do_utf8
736             || ((t = (char*)reghopmaybe3((U8*)s, -prog->check_offset_max, (U8*) ((prog->check_offset_max<0) ? strend : strpos)))
737                  && t > strpos))) 
738     {
739         /* Fixed substring is found far enough so that the match
740            cannot start at strpos. */
741       try_at_offset:
742         if (ml_anch && t[-1] != '\n') {
743             /* Eventually fbm_*() should handle this, but often
744                anchored_offset is not 0, so this check will not be wasted. */
745             /* XXXX In the code below we prefer to look for "^" even in
746                presence of anchored substrings.  And we search even
747                beyond the found float position.  These pessimizations
748                are historical artefacts only.  */
749           find_anchor:
750             while (t < strend - prog->minlen) {
751                 if (*t == '\n') {
752                     if (t < check_at - prog->check_offset_min) {
753                         if (do_utf8 ? prog->anchored_utf8 : prog->anchored_substr) {
754                             /* Since we moved from the found position,
755                                we definitely contradict the found anchored
756                                substr.  Due to the above check we do not
757                                contradict "check" substr.
758                                Thus we can arrive here only if check substr
759                                is float.  Redo checking for "other"=="fixed".
760                              */
761                             strpos = t + 1;                     
762                             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Found /%s^%s/m at offset %ld, rescanning for anchored from offset %ld...\n",
763                                 PL_colors[0], PL_colors[1], (long)(strpos - i_strpos), (long)(strpos - i_strpos + prog->anchored_offset)));
764                             goto do_other_anchored;
765                         }
766                         /* We don't contradict the found floating substring. */
767                         /* XXXX Why not check for STCLASS? */
768                         s = t + 1;
769                         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Found /%s^%s/m at offset %ld...\n",
770                             PL_colors[0], PL_colors[1], (long)(s - i_strpos)));
771                         goto set_useful;
772                     }
773                     /* Position contradicts check-string */
774                     /* XXXX probably better to look for check-string
775                        than for "\n", so one should lower the limit for t? */
776                     DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Found /%s^%s/m, restarting lookup for check-string at offset %ld...\n",
777                         PL_colors[0], PL_colors[1], (long)(t + 1 - i_strpos)));
778                     other_last = strpos = s = t + 1;
779                     goto restart;
780                 }
781                 t++;
782             }
783             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Did not find /%s^%s/m...\n",
784                         PL_colors[0], PL_colors[1]));
785             goto fail_finish;
786         }
787         else {
788             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Starting position does not contradict /%s^%s/m...\n",
789                         PL_colors[0], PL_colors[1]));
790         }
791         s = t;
792       set_useful:
793         ++BmUSEFUL(do_utf8 ? prog->check_utf8 : prog->check_substr);    /* hooray/5 */
794     }
795     else {
796         /* The found string does not prohibit matching at strpos,
797            - no optimization of calling REx engine can be performed,
798            unless it was an MBOL and we are not after MBOL,
799            or a future STCLASS check will fail this. */
800       try_at_start:
801         /* Even in this situation we may use MBOL flag if strpos is offset
802            wrt the start of the string. */
803         if (ml_anch && sv && !SvROK(sv) /* See prev comment on SvROK */
804             && (strpos != strbeg) && strpos[-1] != '\n'
805             /* May be due to an implicit anchor of m{.*foo}  */
806             && !(prog->reganch & ROPT_IMPLICIT))
807         {
808             t = strpos;
809             goto find_anchor;
810         }
811         DEBUG_EXECUTE_r( if (ml_anch)
812             PerlIO_printf(Perl_debug_log, "Position at offset %ld does not contradict /%s^%s/m...\n",
813                         (long)(strpos - i_strpos), PL_colors[0], PL_colors[1]);
814         );
815       success_at_start:
816         if (!(prog->reganch & ROPT_NAUGHTY)     /* XXXX If strpos moved? */
817             && (do_utf8 ? (
818                 prog->check_utf8                /* Could be deleted already */
819                 && --BmUSEFUL(prog->check_utf8) < 0
820                 && (prog->check_utf8 == prog->float_utf8)
821             ) : (
822                 prog->check_substr              /* Could be deleted already */
823                 && --BmUSEFUL(prog->check_substr) < 0
824                 && (prog->check_substr == prog->float_substr)
825             )))
826         {
827             /* If flags & SOMETHING - do not do it many times on the same match */
828             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "... Disabling check substring...\n"));
829             SvREFCNT_dec(do_utf8 ? prog->check_utf8 : prog->check_substr);
830             if (do_utf8 ? prog->check_substr : prog->check_utf8)
831                 SvREFCNT_dec(do_utf8 ? prog->check_substr : prog->check_utf8);
832             prog->check_substr = prog->check_utf8 = NULL;       /* disable */
833             prog->float_substr = prog->float_utf8 = NULL;       /* clear */
834             check = NULL;                       /* abort */
835             s = strpos;
836             /* XXXX This is a remnant of the old implementation.  It
837                     looks wasteful, since now INTUIT can use many
838                     other heuristics. */
839             prog->reganch &= ~RE_USE_INTUIT;
840         }
841         else
842             s = strpos;
843     }
844
845     /* Last resort... */
846     /* XXXX BmUSEFUL already changed, maybe multiple change is meaningful... */
847     /* trie stclasses are too expensive to use here, we are better off to
848        leave it to regmatch itself */
849     if (prog->regstclass && PL_regkind[OP(prog->regstclass)]!=TRIE) {
850         /* minlen == 0 is possible if regstclass is \b or \B,
851            and the fixed substr is ''$.
852            Since minlen is already taken into account, s+1 is before strend;
853            accidentally, minlen >= 1 guaranties no false positives at s + 1
854            even for \b or \B.  But (minlen? 1 : 0) below assumes that
855            regstclass does not come from lookahead...  */
856         /* If regstclass takes bytelength more than 1: If charlength==1, OK.
857            This leaves EXACTF only, which is dealt with in find_byclass().  */
858         const U8* const str = (U8*)STRING(prog->regstclass);
859         const int cl_l = (PL_regkind[OP(prog->regstclass)] == EXACT
860                     ? CHR_DIST(str+STR_LEN(prog->regstclass), str)
861                     : 1);
862         char * endpos;
863         if (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
864             endpos= HOP3c(s, (prog->minlen ? cl_l : 0), strend);
865         else if (prog->float_substr || prog->float_utf8)
866             endpos= HOP3c(HOP3c(check_at, -start_shift, strbeg), cl_l, strend);
867         else 
868             endpos= strend;
869                     
870         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "start_shift: %"IVdf" check_at: %d s: %d endpos: %d\n",
871                       start_shift,check_at-strbeg,s-strbeg,endpos-strbeg));
872         
873         t = s;
874         s = find_byclass(prog, prog->regstclass, s, endpos, NULL);
875         if (!s) {
876 #ifdef DEBUGGING
877             const char *what = NULL;
878 #endif
879             if (endpos == strend) {
880                 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
881                                 "Could not match STCLASS...\n") );
882                 goto fail;
883             }
884             DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
885                                    "This position contradicts STCLASS...\n") );
886             if ((prog->reganch & ROPT_ANCH) && !ml_anch)
887                 goto fail;
888             /* Contradict one of substrings */
889             if (prog->anchored_substr || prog->anchored_utf8) {
890                 if ((do_utf8 ? prog->anchored_utf8 : prog->anchored_substr) == check) {
891                     DEBUG_EXECUTE_r( what = "anchored" );
892                   hop_and_restart:
893                     s = HOP3c(t, 1, strend);
894                     if (s + start_shift + end_shift > strend) {
895                         /* XXXX Should be taken into account earlier? */
896                         DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
897                                                "Could not match STCLASS...\n") );
898                         goto fail;
899                     }
900                     if (!check)
901                         goto giveup;
902                     DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
903                                 "Looking for %s substr starting at offset %ld...\n",
904                                  what, (long)(s + start_shift - i_strpos)) );
905                     goto restart;
906                 }
907                 /* Have both, check_string is floating */
908                 if (t + start_shift >= check_at) /* Contradicts floating=check */
909                     goto retry_floating_check;
910                 /* Recheck anchored substring, but not floating... */
911                 s = check_at;
912                 if (!check)
913                     goto giveup;
914                 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
915                           "Looking for anchored substr starting at offset %ld...\n",
916                           (long)(other_last - i_strpos)) );
917                 goto do_other_anchored;
918             }
919             /* Another way we could have checked stclass at the
920                current position only: */
921             if (ml_anch) {
922                 s = t = t + 1;
923                 if (!check)
924                     goto giveup;
925                 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
926                           "Looking for /%s^%s/m starting at offset %ld...\n",
927                           PL_colors[0], PL_colors[1], (long)(t - i_strpos)) );
928                 goto try_at_offset;
929             }
930             if (!(do_utf8 ? prog->float_utf8 : prog->float_substr))     /* Could have been deleted */
931                 goto fail;
932             /* Check is floating subtring. */
933           retry_floating_check:
934             t = check_at - start_shift;
935             DEBUG_EXECUTE_r( what = "floating" );
936             goto hop_and_restart;
937         }
938         if (t != s) {
939             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
940                         "By STCLASS: moving %ld --> %ld\n",
941                                   (long)(t - i_strpos), (long)(s - i_strpos))
942                    );
943         }
944         else {
945             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
946                                   "Does not contradict STCLASS...\n"); 
947                    );
948         }
949     }
950   giveup:
951     DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%s%s:%s match at offset %ld\n",
952                           PL_colors[4], (check ? "Guessed" : "Giving up"),
953                           PL_colors[5], (long)(s - i_strpos)) );
954     return s;
955
956   fail_finish:                          /* Substring not found */
957     if (prog->check_substr || prog->check_utf8)         /* could be removed already */
958         BmUSEFUL(do_utf8 ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
959   fail:
960     DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch rejected by optimizer%s\n",
961                           PL_colors[4], PL_colors[5]));
962     return NULL;
963 }
964
965
966
967 #define REXEC_TRIE_READ_CHAR(trie_type, trie, uc, uscan, len, uvc, charid,  \
968 foldlen, foldbuf, uniflags) STMT_START {                                    \
969     switch (trie_type) {                                                    \
970     case trie_utf8_fold:                                                    \
971         if ( foldlen>0 ) {                                                  \
972             uvc = utf8n_to_uvuni( uscan, UTF8_MAXLEN, &len, uniflags );     \
973             foldlen -= len;                                                 \
974             uscan += len;                                                   \
975             len=0;                                                          \
976         } else {                                                            \
977             uvc = utf8n_to_uvuni( (U8*)uc, UTF8_MAXLEN, &len, uniflags );   \
978             uvc = to_uni_fold( uvc, foldbuf, &foldlen );                    \
979             foldlen -= UNISKIP( uvc );                                      \
980             uscan = foldbuf + UNISKIP( uvc );                               \
981         }                                                                   \
982         break;                                                              \
983     case trie_utf8:                                                         \
984         uvc = utf8n_to_uvuni( (U8*)uc, UTF8_MAXLEN, &len, uniflags );       \
985         break;                                                              \
986     case trie_plain:                                                        \
987         uvc = (UV)*uc;                                                      \
988         len = 1;                                                            \
989     }                                                                       \
990                                                                             \
991     if (uvc < 256) {                                                        \
992         charid = trie->charmap[ uvc ];                                      \
993     }                                                                       \
994     else {                                                                  \
995         charid = 0;                                                         \
996         if (trie->widecharmap) {                                            \
997             SV** const svpp = hv_fetch(trie->widecharmap,                   \
998                         (char*)&uvc, sizeof(UV), 0);                        \
999             if (svpp)                                                       \
1000                 charid = (U16)SvIV(*svpp);                                  \
1001         }                                                                   \
1002     }                                                                       \
1003 } STMT_END
1004
1005 #define REXEC_FBC_EXACTISH_CHECK(CoNd)                  \
1006     if ( (CoNd)                                        \
1007          && (ln == len ||                              \
1008              ibcmp_utf8(s, NULL, 0,  do_utf8,          \
1009                         m, NULL, ln, (bool)UTF))       \
1010          && (!reginfo || regtry(reginfo, s)) )         \
1011         goto got_it;                                   \
1012     else {                                             \
1013          U8 foldbuf[UTF8_MAXBYTES_CASE+1];             \
1014          uvchr_to_utf8(tmpbuf, c);                     \
1015          f = to_utf8_fold(tmpbuf, foldbuf, &foldlen);  \
1016          if ( f != c                                   \
1017               && (f == c1 || f == c2)                  \
1018               && (ln == foldlen ||                     \
1019                   !ibcmp_utf8((char *) foldbuf,        \
1020                               NULL, foldlen, do_utf8,  \
1021                               m,                       \
1022                               NULL, ln, (bool)UTF))    \
1023               && (!reginfo || regtry(reginfo, s)) )    \
1024               goto got_it;                             \
1025     }                                                  \
1026     s += len
1027
1028 #define REXEC_FBC_EXACTISH_SCAN(CoNd)                     \
1029 STMT_START {                                              \
1030     while (s <= e) {                                      \
1031         if ( (CoNd)                                       \
1032              && (ln == 1 || !(OP(c) == EXACTF             \
1033                               ? ibcmp(s, m, ln)           \
1034                               : ibcmp_locale(s, m, ln)))  \
1035              && (!reginfo || regtry(reginfo, s)) )        \
1036             goto got_it;                                  \
1037         s++;                                              \
1038     }                                                     \
1039 } STMT_END
1040
1041 #define REXEC_FBC_UTF8_SCAN(CoDe)                     \
1042 STMT_START {                                          \
1043     while (s + (uskip = UTF8SKIP(s)) <= strend) {     \
1044         CoDe                                          \
1045         s += uskip;                                   \
1046     }                                                 \
1047 } STMT_END
1048
1049 #define REXEC_FBC_SCAN(CoDe)                          \
1050 STMT_START {                                          \
1051     while (s < strend) {                              \
1052         CoDe                                          \
1053         s++;                                          \
1054     }                                                 \
1055 } STMT_END
1056
1057 #define REXEC_FBC_UTF8_CLASS_SCAN(CoNd)               \
1058 REXEC_FBC_UTF8_SCAN(                                  \
1059     if (CoNd) {                                       \
1060         if (tmp && (!reginfo || regtry(reginfo, s)))  \
1061             goto got_it;                              \
1062         else                                          \
1063             tmp = doevery;                            \
1064     }                                                 \
1065     else                                              \
1066         tmp = 1;                                      \
1067 )
1068
1069 #define REXEC_FBC_CLASS_SCAN(CoNd)                    \
1070 REXEC_FBC_SCAN(                                       \
1071     if (CoNd) {                                       \
1072         if (tmp && (!reginfo || regtry(reginfo, s)))  \
1073             goto got_it;                              \
1074         else                                          \
1075             tmp = doevery;                            \
1076     }                                                 \
1077     else                                              \
1078         tmp = 1;                                      \
1079 )
1080
1081 #define REXEC_FBC_TRYIT               \
1082 if ((!reginfo || regtry(reginfo, s))) \
1083     goto got_it
1084
1085 #define REXEC_FBC_CSCAN_PRELOAD(UtFpReLoAd,CoNdUtF8,CoNd)      \
1086     if (do_utf8) {                                             \
1087         UtFpReLoAd;                                            \
1088         REXEC_FBC_UTF8_CLASS_SCAN(CoNdUtF8);                   \
1089     }                                                          \
1090     else {                                                     \
1091         REXEC_FBC_CLASS_SCAN(CoNd);                            \
1092     }                                                          \
1093     break
1094
1095 #define REXEC_FBC_CSCAN_TAINT(CoNdUtF8,CoNd)                   \
1096     PL_reg_flags |= RF_tainted;                                \
1097     if (do_utf8) {                                             \
1098         REXEC_FBC_UTF8_CLASS_SCAN(CoNdUtF8);                   \
1099     }                                                          \
1100     else {                                                     \
1101         REXEC_FBC_CLASS_SCAN(CoNd);                            \
1102     }                                                          \
1103     break
1104
1105 #define DUMP_EXEC_POS(li,s,doutf8) \
1106     dump_exec_pos(li,s,(PL_regeol),(PL_bostr),(PL_reg_starttry),doutf8)
1107
1108 /* We know what class REx starts with.  Try to find this position... */
1109 /* if reginfo is NULL, its a dryrun */
1110 /* annoyingly all the vars in this routine have different names from their counterparts
1111    in regmatch. /grrr */
1112
1113 STATIC char *
1114 S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s, 
1115     const char *strend, const regmatch_info *reginfo)
1116 {
1117         dVAR;
1118         const I32 doevery = (prog->reganch & ROPT_SKIP) == 0;
1119         char *m;
1120         STRLEN ln;
1121         STRLEN lnc;
1122         register STRLEN uskip;
1123         unsigned int c1;
1124         unsigned int c2;
1125         char *e;
1126         register I32 tmp = 1;   /* Scratch variable? */
1127         register const bool do_utf8 = PL_reg_match_utf8;
1128
1129         /* We know what class it must start with. */
1130         switch (OP(c)) {
1131         case ANYOF:
1132             if (do_utf8) {
1133                  REXEC_FBC_UTF8_CLASS_SCAN((ANYOF_FLAGS(c) & ANYOF_UNICODE) ||
1134                           !UTF8_IS_INVARIANT((U8)s[0]) ?
1135                           reginclass(prog, c, (U8*)s, 0, do_utf8) :
1136                           REGINCLASS(prog, c, (U8*)s));
1137             }
1138             else {
1139                  while (s < strend) {
1140                       STRLEN skip = 1;
1141
1142                       if (REGINCLASS(prog, c, (U8*)s) ||
1143                           (ANYOF_FOLD_SHARP_S(c, s, strend) &&
1144                            /* The assignment of 2 is intentional:
1145                             * for the folded sharp s, the skip is 2. */
1146                            (skip = SHARP_S_SKIP))) {
1147                            if (tmp && (!reginfo || regtry(reginfo, s)))
1148                                 goto got_it;
1149                            else
1150                                 tmp = doevery;
1151                       }
1152                       else 
1153                            tmp = 1;
1154                       s += skip;
1155                  }
1156             }
1157             break;
1158         case CANY:
1159             REXEC_FBC_SCAN(
1160                 if (tmp && (!reginfo || regtry(reginfo, s)))
1161                     goto got_it;
1162                 else
1163                     tmp = doevery;
1164             );
1165             break;
1166         case EXACTF:
1167             m   = STRING(c);
1168             ln  = STR_LEN(c);   /* length to match in octets/bytes */
1169             lnc = (I32) ln;     /* length to match in characters */
1170             if (UTF) {
1171                 STRLEN ulen1, ulen2;
1172                 U8 *sm = (U8 *) m;
1173                 U8 tmpbuf1[UTF8_MAXBYTES_CASE+1];
1174                 U8 tmpbuf2[UTF8_MAXBYTES_CASE+1];
1175                 const U32 uniflags = UTF8_ALLOW_DEFAULT;
1176
1177                 to_utf8_lower((U8*)m, tmpbuf1, &ulen1);
1178                 to_utf8_upper((U8*)m, tmpbuf2, &ulen2);
1179
1180                 c1 = utf8n_to_uvchr(tmpbuf1, UTF8_MAXBYTES_CASE, 
1181                                     0, uniflags);
1182                 c2 = utf8n_to_uvchr(tmpbuf2, UTF8_MAXBYTES_CASE,
1183                                     0, uniflags);
1184                 lnc = 0;
1185                 while (sm < ((U8 *) m + ln)) {
1186                     lnc++;
1187                     sm += UTF8SKIP(sm);
1188                 }
1189             }
1190             else {
1191                 c1 = *(U8*)m;
1192                 c2 = PL_fold[c1];
1193             }
1194             goto do_exactf;
1195         case EXACTFL:
1196             m   = STRING(c);
1197             ln  = STR_LEN(c);
1198             lnc = (I32) ln;
1199             c1 = *(U8*)m;
1200             c2 = PL_fold_locale[c1];
1201           do_exactf:
1202             e = HOP3c(strend, -((I32)lnc), s);
1203
1204             if (!reginfo && e < s)
1205                 e = s;                  /* Due to minlen logic of intuit() */
1206
1207             /* The idea in the EXACTF* cases is to first find the
1208              * first character of the EXACTF* node and then, if
1209              * necessary, case-insensitively compare the full
1210              * text of the node.  The c1 and c2 are the first
1211              * characters (though in Unicode it gets a bit
1212              * more complicated because there are more cases
1213              * than just upper and lower: one needs to use
1214              * the so-called folding case for case-insensitive
1215              * matching (called "loose matching" in Unicode).
1216              * ibcmp_utf8() will do just that. */
1217
1218             if (do_utf8) {
1219                 UV c, f;
1220                 U8 tmpbuf [UTF8_MAXBYTES+1];
1221                 STRLEN len, foldlen;
1222                 const U32 uniflags = UTF8_ALLOW_DEFAULT;
1223                 if (c1 == c2) {
1224                     /* Upper and lower of 1st char are equal -
1225                      * probably not a "letter". */
1226                     while (s <= e) {
1227                         c = utf8n_to_uvchr((U8*)s, UTF8_MAXBYTES, &len,
1228                                            uniflags);
1229                         REXEC_FBC_EXACTISH_CHECK(c == c1);
1230                     }
1231                 }
1232                 else {
1233                     while (s <= e) {
1234                       c = utf8n_to_uvchr((U8*)s, UTF8_MAXBYTES, &len,
1235                                            uniflags);
1236
1237                         /* Handle some of the three Greek sigmas cases.
1238                          * Note that not all the possible combinations
1239                          * are handled here: some of them are handled
1240                          * by the standard folding rules, and some of
1241                          * them (the character class or ANYOF cases)
1242                          * are handled during compiletime in
1243                          * regexec.c:S_regclass(). */
1244                         if (c == (UV)UNICODE_GREEK_CAPITAL_LETTER_SIGMA ||
1245                             c == (UV)UNICODE_GREEK_SMALL_LETTER_FINAL_SIGMA)
1246                             c = (UV)UNICODE_GREEK_SMALL_LETTER_SIGMA;
1247
1248                         REXEC_FBC_EXACTISH_CHECK(c == c1 || c == c2);
1249                     }
1250                 }
1251             }
1252             else {
1253                 if (c1 == c2)
1254                     REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1);
1255                 else
1256                     REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1 || *(U8*)s == c2);
1257             }
1258             break;
1259         case BOUNDL:
1260             PL_reg_flags |= RF_tainted;
1261             /* FALL THROUGH */
1262         case BOUND:
1263             if (do_utf8) {
1264                 if (s == PL_bostr)
1265                     tmp = '\n';
1266                 else {
1267                     U8 * const r = reghop3((U8*)s, -1, (U8*)PL_bostr);
1268                     tmp = utf8n_to_uvchr(r, UTF8SKIP(r), 0, UTF8_ALLOW_DEFAULT);
1269                 }
1270                 tmp = ((OP(c) == BOUND ?
1271                         isALNUM_uni(tmp) : isALNUM_LC_uvchr(UNI_TO_NATIVE(tmp))) != 0);
1272                 LOAD_UTF8_CHARCLASS_ALNUM();
1273                 REXEC_FBC_UTF8_SCAN(
1274                     if (tmp == !(OP(c) == BOUND ?
1275                                  (bool)swash_fetch(PL_utf8_alnum, (U8*)s, do_utf8) :
1276                                  isALNUM_LC_utf8((U8*)s)))
1277                     {
1278                         tmp = !tmp;
1279                         REXEC_FBC_TRYIT;
1280                 }
1281                 );
1282             }
1283             else {
1284                 tmp = (s != PL_bostr) ? UCHARAT(s - 1) : '\n';
1285                 tmp = ((OP(c) == BOUND ? isALNUM(tmp) : isALNUM_LC(tmp)) != 0);
1286                 REXEC_FBC_SCAN(
1287                     if (tmp ==
1288                         !(OP(c) == BOUND ? isALNUM(*s) : isALNUM_LC(*s))) {
1289                         tmp = !tmp;
1290                         REXEC_FBC_TRYIT;
1291                 }
1292                 );
1293             }
1294             if ((!prog->minlen && tmp) && (!reginfo || regtry(reginfo, s)))
1295                 goto got_it;
1296             break;
1297         case NBOUNDL:
1298             PL_reg_flags |= RF_tainted;
1299             /* FALL THROUGH */
1300         case NBOUND:
1301             if (do_utf8) {
1302                 if (s == PL_bostr)
1303                     tmp = '\n';
1304                 else {
1305                     U8 * const r = reghop3((U8*)s, -1, (U8*)PL_bostr);
1306                     tmp = utf8n_to_uvchr(r, UTF8SKIP(r), 0, UTF8_ALLOW_DEFAULT);
1307                 }
1308                 tmp = ((OP(c) == NBOUND ?
1309                         isALNUM_uni(tmp) : isALNUM_LC_uvchr(UNI_TO_NATIVE(tmp))) != 0);
1310                 LOAD_UTF8_CHARCLASS_ALNUM();
1311                 REXEC_FBC_UTF8_SCAN(
1312                     if (tmp == !(OP(c) == NBOUND ?
1313                                  (bool)swash_fetch(PL_utf8_alnum, (U8*)s, do_utf8) :
1314                                  isALNUM_LC_utf8((U8*)s)))
1315                         tmp = !tmp;
1316                     else REXEC_FBC_TRYIT;
1317                 );
1318             }
1319             else {
1320                 tmp = (s != PL_bostr) ? UCHARAT(s - 1) : '\n';
1321                 tmp = ((OP(c) == NBOUND ?
1322                         isALNUM(tmp) : isALNUM_LC(tmp)) != 0);
1323                 REXEC_FBC_SCAN(
1324                     if (tmp ==
1325                         !(OP(c) == NBOUND ? isALNUM(*s) : isALNUM_LC(*s)))
1326                         tmp = !tmp;
1327                     else REXEC_FBC_TRYIT;
1328                 );
1329             }
1330             if ((!prog->minlen && !tmp) && (!reginfo || regtry(reginfo, s)))
1331                 goto got_it;
1332             break;
1333         case ALNUM:
1334             REXEC_FBC_CSCAN_PRELOAD(
1335                 LOAD_UTF8_CHARCLASS_ALNUM(),
1336                 swash_fetch(PL_utf8_alnum, (U8*)s, do_utf8),
1337                 isALNUM(*s)
1338             );
1339         case ALNUML:
1340             REXEC_FBC_CSCAN_TAINT(
1341                 isALNUM_LC_utf8((U8*)s),
1342                 isALNUM_LC(*s)
1343             );
1344         case NALNUM:
1345             REXEC_FBC_CSCAN_PRELOAD(
1346                 LOAD_UTF8_CHARCLASS_ALNUM(),
1347                 !swash_fetch(PL_utf8_alnum, (U8*)s, do_utf8),
1348                 !isALNUM(*s)
1349             );
1350         case NALNUML:
1351             REXEC_FBC_CSCAN_TAINT(
1352                 !isALNUM_LC_utf8((U8*)s),
1353                 !isALNUM_LC(*s)
1354             );
1355         case SPACE:
1356             REXEC_FBC_CSCAN_PRELOAD(
1357                 LOAD_UTF8_CHARCLASS_SPACE(),
1358                 *s == ' ' || swash_fetch(PL_utf8_space,(U8*)s, do_utf8),
1359                 isSPACE(*s)
1360             );
1361         case SPACEL:
1362             REXEC_FBC_CSCAN_TAINT(
1363                 *s == ' ' || isSPACE_LC_utf8((U8*)s),
1364                 isSPACE_LC(*s)
1365             );
1366         case NSPACE:
1367             REXEC_FBC_CSCAN_PRELOAD(
1368                 LOAD_UTF8_CHARCLASS_SPACE(),
1369                 !(*s == ' ' || swash_fetch(PL_utf8_space,(U8*)s, do_utf8)),
1370                 !isSPACE(*s)
1371             );
1372         case NSPACEL:
1373             REXEC_FBC_CSCAN_TAINT(
1374                 !(*s == ' ' || isSPACE_LC_utf8((U8*)s)),
1375                 !isSPACE_LC(*s)
1376             );
1377         case DIGIT:
1378             REXEC_FBC_CSCAN_PRELOAD(
1379                 LOAD_UTF8_CHARCLASS_DIGIT(),
1380                 swash_fetch(PL_utf8_digit,(U8*)s, do_utf8),
1381                 isDIGIT(*s)
1382             );
1383         case DIGITL:
1384             REXEC_FBC_CSCAN_TAINT(
1385                 isDIGIT_LC_utf8((U8*)s),
1386                 isDIGIT_LC(*s)
1387             );
1388         case NDIGIT:
1389             REXEC_FBC_CSCAN_PRELOAD(
1390                 LOAD_UTF8_CHARCLASS_DIGIT(),
1391                 !swash_fetch(PL_utf8_digit,(U8*)s, do_utf8),
1392                 !isDIGIT(*s)
1393             );
1394         case NDIGITL:
1395             REXEC_FBC_CSCAN_TAINT(
1396                 !isDIGIT_LC_utf8((U8*)s),
1397                 !isDIGIT_LC(*s)
1398             );
1399         case AHOCORASICKC:
1400         case AHOCORASICK: 
1401             {
1402                 const enum { trie_plain, trie_utf8, trie_utf8_fold }
1403                     trie_type = do_utf8 ?
1404                           (c->flags == EXACT ? trie_utf8 : trie_utf8_fold)
1405                         : trie_plain;
1406                 /* what trie are we using right now */
1407                 reg_ac_data *aho
1408                     = (reg_ac_data*)prog->data->data[ ARG( c ) ];
1409                 reg_trie_data *trie=aho->trie;
1410
1411                 const char *last_start = strend - trie->minlen;
1412 #ifdef DEBUGGING
1413                 const char *real_start = s;
1414 #endif
1415                 STRLEN maxlen = trie->maxlen;
1416                 SV *sv_points;
1417                 U8 **points; /* map of where we were in the input string
1418                                 when reading a given char. For ASCII this
1419                                 is unnecessary overhead as the relationship
1420                                 is always 1:1, but for unicode, especially
1421                                 case folded unicode this is not true. */
1422                 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1423                 U8 *bitmap=NULL;
1424
1425
1426                 GET_RE_DEBUG_FLAGS_DECL;
1427
1428                 /* We can't just allocate points here. We need to wrap it in
1429                  * an SV so it gets freed properly if there is a croak while
1430                  * running the match */
1431                 ENTER;
1432                 SAVETMPS;
1433                 sv_points=newSV(maxlen * sizeof(U8 *));
1434                 SvCUR_set(sv_points,
1435                     maxlen * sizeof(U8 *));
1436                 SvPOK_on(sv_points);
1437                 sv_2mortal(sv_points);
1438                 points=(U8**)SvPV_nolen(sv_points );
1439                 if ( trie_type != trie_utf8_fold 
1440                      && (trie->bitmap || OP(c)==AHOCORASICKC) ) 
1441                 {
1442                     if (trie->bitmap) 
1443                         bitmap=(U8*)trie->bitmap;
1444                     else
1445                         bitmap=(U8*)ANYOF_BITMAP(c);
1446                 }
1447                 /* this is the Aho-Corasick algorithm modified a touch
1448                    to include special handling for long "unknown char" 
1449                    sequences. The basic idea being that we use AC as long
1450                    as we are dealing with a possible matching char, when
1451                    we encounter an unknown char (and we have not encountered
1452                    an accepting state) we scan forward until we find a legal 
1453                    starting char. 
1454                    AC matching is basically that of trie matching, except
1455                    that when we encounter a failing transition, we fall back
1456                    to the current states "fail state", and try the current char 
1457                    again, a process we repeat until we reach the root state, 
1458                    state 1, or a legal transition. If we fail on the root state 
1459                    then we can either terminate if we have reached an accepting 
1460                    state previously, or restart the entire process from the beginning 
1461                    if we have not.
1462
1463                  */
1464                 while (s <= last_start) {
1465                     const U32 uniflags = UTF8_ALLOW_DEFAULT;
1466                     U8 *uc = (U8*)s;
1467                     U16 charid = 0;
1468                     U32 base = 1;
1469                     U32 state = 1;
1470                     UV uvc = 0;
1471                     STRLEN len = 0;
1472                     STRLEN foldlen = 0;
1473                     U8 *uscan = (U8*)NULL;
1474                     U8 *leftmost = NULL;
1475 #ifdef DEBUGGING                    
1476                     U32 accepted_word= 0;
1477 #endif
1478                     U32 pointpos = 0;
1479
1480                     while ( state && uc <= (U8*)strend ) {
1481                         int failed=0;
1482                         U32 word = aho->states[ state ].wordnum;
1483
1484                         if( state==1 ) {
1485                             if ( bitmap ) {
1486                                 DEBUG_TRIE_EXECUTE_r(
1487                                     if ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
1488                                         dump_exec_pos( (char *)uc, c, strend, real_start, 
1489                                             (char *)uc, do_utf8 );
1490                                         PerlIO_printf( Perl_debug_log,
1491                                             " Scanning for legal start char...\n");
1492                                     }
1493                                 );            
1494                                 while ( uc <= (U8*)last_start  && !BITMAP_TEST(bitmap,*uc) ) {
1495                                     uc++;
1496                                 }
1497                                 s= (char *)uc;
1498                             }
1499                             if (uc >(U8*)last_start) break;
1500                         }
1501                                             
1502                         if ( word ) {
1503                             U8 *lpos= points[ (pointpos - trie->wordlen[word-1] ) % maxlen ];
1504                             if (!leftmost || lpos < leftmost) {
1505                                 DEBUG_r(accepted_word=word);
1506                                 leftmost= lpos;
1507                             }
1508                             if (base==0) break;
1509                             
1510                         }
1511                         points[pointpos++ % maxlen]= uc;
1512                         REXEC_TRIE_READ_CHAR(trie_type, trie, uc, uscan, len,
1513                             uvc, charid, foldlen, foldbuf, uniflags);
1514                         DEBUG_TRIE_EXECUTE_r({
1515                             dump_exec_pos( (char *)uc, c, strend, real_start, 
1516                                 s,   do_utf8 );
1517                             PerlIO_printf(Perl_debug_log,
1518                                 " Charid:%3u CP:%4"UVxf" ",
1519                                  charid, uvc);
1520                         });
1521
1522                         do {
1523 #ifdef DEBUGGING
1524                             word = aho->states[ state ].wordnum;
1525 #endif
1526                             base = aho->states[ state ].trans.base;
1527
1528                             DEBUG_TRIE_EXECUTE_r({
1529                                 if (failed) 
1530                                     dump_exec_pos( (char *)uc, c, strend, real_start, 
1531                                         s,   do_utf8 );
1532                                 PerlIO_printf( Perl_debug_log,
1533                                     "%sState: %4"UVxf", word=%"UVxf,
1534                                     failed ? " Fail transition to " : "",
1535                                     (UV)state, (UV)word);
1536                             });
1537                             if ( base ) {
1538                                 U32 tmp;
1539                                 if (charid &&
1540                                      (base + charid > trie->uniquecharcount )
1541                                      && (base + charid - 1 - trie->uniquecharcount
1542                                             < trie->lasttrans)
1543                                      && trie->trans[base + charid - 1 -
1544                                             trie->uniquecharcount].check == state
1545                                      && (tmp=trie->trans[base + charid - 1 -
1546                                         trie->uniquecharcount ].next))
1547                                 {
1548                                     DEBUG_TRIE_EXECUTE_r(
1549                                         PerlIO_printf( Perl_debug_log," - legal\n"));
1550                                     state = tmp;
1551                                     break;
1552                                 }
1553                                 else {
1554                                     DEBUG_TRIE_EXECUTE_r(
1555                                         PerlIO_printf( Perl_debug_log," - fail\n"));
1556                                     failed = 1;
1557                                     state = aho->fail[state];
1558                                 }
1559                             }
1560                             else {
1561                                 /* we must be accepting here */
1562                                 DEBUG_TRIE_EXECUTE_r(
1563                                         PerlIO_printf( Perl_debug_log," - accepting\n"));
1564                                 failed = 1;
1565                                 break;
1566                             }
1567                         } while(state);
1568                         uc += len;
1569                         if (failed) {
1570                             if (leftmost)
1571                                 break;
1572                             if (!state) state = 1;
1573                         }
1574                     }
1575                     if ( aho->states[ state ].wordnum ) {
1576                         U8 *lpos = points[ (pointpos - trie->wordlen[aho->states[ state ].wordnum-1]) % maxlen ];
1577                         if (!leftmost || lpos < leftmost) {
1578                             DEBUG_r(accepted_word=aho->states[ state ].wordnum);
1579                             leftmost = lpos;
1580                         }
1581                     }
1582                     if (leftmost) {
1583                         s = (char*)leftmost;
1584                         DEBUG_TRIE_EXECUTE_r({
1585                             PerlIO_printf( 
1586                                 Perl_debug_log,"Matches word #%"UVxf" at position %d. Trying full pattern...\n",
1587                                 (UV)accepted_word, s - real_start
1588                             );
1589                         });
1590                         if (!reginfo || regtry(reginfo, s)) {
1591                             FREETMPS;
1592                             LEAVE;
1593                             goto got_it;
1594                         }
1595                         s = HOPc(s,1);
1596                         DEBUG_TRIE_EXECUTE_r({
1597                             PerlIO_printf( Perl_debug_log,"Pattern failed. Looking for new start point...\n");
1598                         });
1599                     } else {
1600                         DEBUG_TRIE_EXECUTE_r(
1601                             PerlIO_printf( Perl_debug_log,"No match.\n"));
1602                         break;
1603                     }
1604                 }
1605                 FREETMPS;
1606                 LEAVE;
1607             }
1608             break;
1609         default:
1610             Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
1611             break;
1612         }
1613         return 0;
1614       got_it:
1615         return s;
1616 }
1617
1618 /*
1619  - regexec_flags - match a regexp against a string
1620  */
1621 I32
1622 Perl_regexec_flags(pTHX_ register regexp *prog, char *stringarg, register char *strend,
1623               char *strbeg, I32 minend, SV *sv, void *data, U32 flags)
1624 /* strend: pointer to null at end of string */
1625 /* strbeg: real beginning of string */
1626 /* minend: end of match must be >=minend after stringarg. */
1627 /* data: May be used for some additional optimizations. */
1628 /* nosave: For optimizations. */
1629 {
1630     dVAR;
1631     register char *s;
1632     register regnode *c;
1633     register char *startpos = stringarg;
1634     I32 minlen;         /* must match at least this many chars */
1635     I32 dontbother = 0; /* how many characters not to try at end */
1636     I32 end_shift = 0;                  /* Same for the end. */         /* CC */
1637     I32 scream_pos = -1;                /* Internal iterator of scream. */
1638     char *scream_olds = NULL;
1639     SV* const oreplsv = GvSV(PL_replgv);
1640     const bool do_utf8 = DO_UTF8(sv);
1641     I32 multiline;
1642
1643     regmatch_info reginfo;  /* create some info to pass to regtry etc */
1644
1645     GET_RE_DEBUG_FLAGS_DECL;
1646
1647     PERL_UNUSED_ARG(data);
1648
1649     /* Be paranoid... */
1650     if (prog == NULL || startpos == NULL) {
1651         Perl_croak(aTHX_ "NULL regexp parameter");
1652         return 0;
1653     }
1654
1655     multiline = prog->reganch & PMf_MULTILINE;
1656     reginfo.prog = prog;
1657
1658     RX_MATCH_UTF8_set(prog, do_utf8);
1659     DEBUG_EXECUTE_r( 
1660         debug_start_match(prog, do_utf8, startpos, strend, 
1661         "Matching");
1662     );
1663
1664     minlen = prog->minlen;
1665     
1666     if (strend - startpos < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
1667         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1668                               "String too short [regexec_flags]...\n"));
1669         goto phooey;
1670     }
1671
1672     
1673     /* Check validity of program. */
1674     if (UCHARAT(prog->program) != REG_MAGIC) {
1675         Perl_croak(aTHX_ "corrupted regexp program");
1676     }
1677
1678     PL_reg_flags = 0;
1679     PL_reg_eval_set = 0;
1680     PL_reg_maxiter = 0;
1681
1682     if (prog->reganch & ROPT_UTF8)
1683         PL_reg_flags |= RF_utf8;
1684
1685     /* Mark beginning of line for ^ and lookbehind. */
1686     reginfo.bol = startpos; /* XXX not used ??? */
1687     PL_bostr  = strbeg;
1688     reginfo.sv = sv;
1689
1690     /* Mark end of line for $ (and such) */
1691     PL_regeol = strend;
1692
1693     /* see how far we have to get to not match where we matched before */
1694     reginfo.till = startpos+minend;
1695
1696     /* If there is a "must appear" string, look for it. */
1697     s = startpos;
1698
1699     if (prog->reganch & ROPT_GPOS_SEEN) { /* Need to set reginfo->ganch */
1700         MAGIC *mg;
1701
1702         if (flags & REXEC_IGNOREPOS)    /* Means: check only at start */
1703             reginfo.ganch = startpos;
1704         else if (sv && SvTYPE(sv) >= SVt_PVMG
1705                   && SvMAGIC(sv)
1706                   && (mg = mg_find(sv, PERL_MAGIC_regex_global))
1707                   && mg->mg_len >= 0) {
1708             reginfo.ganch = strbeg + mg->mg_len;        /* Defined pos() */
1709             if (prog->reganch & ROPT_ANCH_GPOS) {
1710                 if (s > reginfo.ganch)
1711                     goto phooey;
1712                 s = reginfo.ganch;
1713             }
1714         }
1715         else                            /* pos() not defined */
1716             reginfo.ganch = strbeg;
1717     }
1718
1719     if (!(flags & REXEC_CHECKED) && (prog->check_substr != NULL || prog->check_utf8 != NULL)) {
1720         re_scream_pos_data d;
1721
1722         d.scream_olds = &scream_olds;
1723         d.scream_pos = &scream_pos;
1724         s = re_intuit_start(prog, sv, s, strend, flags, &d);
1725         if (!s) {
1726             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Not present...\n"));
1727             goto phooey;        /* not present */
1728         }
1729     }
1730
1731
1732
1733     /* Simplest case:  anchored match need be tried only once. */
1734     /*  [unless only anchor is BOL and multiline is set] */
1735     if (prog->reganch & (ROPT_ANCH & ~ROPT_ANCH_GPOS)) {
1736         if (s == startpos && regtry(&reginfo, startpos))
1737             goto got_it;
1738         else if (multiline || (prog->reganch & ROPT_IMPLICIT)
1739                  || (prog->reganch & ROPT_ANCH_MBOL)) /* XXXX SBOL? */
1740         {
1741             char *end;
1742
1743             if (minlen)
1744                 dontbother = minlen - 1;
1745             end = HOP3c(strend, -dontbother, strbeg) - 1;
1746             /* for multiline we only have to try after newlines */
1747             if (prog->check_substr || prog->check_utf8) {
1748                 if (s == startpos)
1749                     goto after_try;
1750                 while (1) {
1751                     if (regtry(&reginfo, s))
1752                         goto got_it;
1753                   after_try:
1754                     if (s >= end)
1755                         goto phooey;
1756                     if (prog->reganch & RE_USE_INTUIT) {
1757                         s = re_intuit_start(prog, sv, s + 1, strend, flags, NULL);
1758                         if (!s)
1759                             goto phooey;
1760                     }
1761                     else
1762                         s++;
1763                 }               
1764             } else {
1765                 if (s > startpos)
1766                     s--;
1767                 while (s < end) {
1768                     if (*s++ == '\n') { /* don't need PL_utf8skip here */
1769                         if (regtry(&reginfo, s))
1770                             goto got_it;
1771                     }
1772                 }               
1773             }
1774         }
1775         goto phooey;
1776     } else if (prog->reganch & ROPT_ANCH_GPOS) {
1777         if (regtry(&reginfo, reginfo.ganch))
1778             goto got_it;
1779         goto phooey;
1780     }
1781
1782     /* Messy cases:  unanchored match. */
1783     if ((prog->anchored_substr || prog->anchored_utf8) && prog->reganch & ROPT_SKIP) {
1784         /* we have /x+whatever/ */
1785         /* it must be a one character string (XXXX Except UTF?) */
1786         char ch;
1787 #ifdef DEBUGGING
1788         int did_match = 0;
1789 #endif
1790         if (!(do_utf8 ? prog->anchored_utf8 : prog->anchored_substr))
1791             do_utf8 ? to_utf8_substr(prog) : to_byte_substr(prog);
1792         ch = SvPVX_const(do_utf8 ? prog->anchored_utf8 : prog->anchored_substr)[0];
1793
1794         if (do_utf8) {
1795             REXEC_FBC_SCAN(
1796                 if (*s == ch) {
1797                     DEBUG_EXECUTE_r( did_match = 1 );
1798                     if (regtry(&reginfo, s)) goto got_it;
1799                     s += UTF8SKIP(s);
1800                     while (s < strend && *s == ch)
1801                         s += UTF8SKIP(s);
1802                 }
1803             );
1804         }
1805         else {
1806             REXEC_FBC_SCAN(
1807                 if (*s == ch) {
1808                     DEBUG_EXECUTE_r( did_match = 1 );
1809                     if (regtry(&reginfo, s)) goto got_it;
1810                     s++;
1811                     while (s < strend && *s == ch)
1812                         s++;
1813                 }
1814             );
1815         }
1816         DEBUG_EXECUTE_r(if (!did_match)
1817                 PerlIO_printf(Perl_debug_log,
1818                                   "Did not find anchored character...\n")
1819                );
1820     }
1821     else if (prog->anchored_substr != NULL
1822               || prog->anchored_utf8 != NULL
1823               || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
1824                   && prog->float_max_offset < strend - s)) {
1825         SV *must;
1826         I32 back_max;
1827         I32 back_min;
1828         char *last;
1829         char *last1;            /* Last position checked before */
1830 #ifdef DEBUGGING
1831         int did_match = 0;
1832 #endif
1833         if (prog->anchored_substr || prog->anchored_utf8) {
1834             if (!(do_utf8 ? prog->anchored_utf8 : prog->anchored_substr))
1835                 do_utf8 ? to_utf8_substr(prog) : to_byte_substr(prog);
1836             must = do_utf8 ? prog->anchored_utf8 : prog->anchored_substr;
1837             back_max = back_min = prog->anchored_offset;
1838         } else {
1839             if (!(do_utf8 ? prog->float_utf8 : prog->float_substr))
1840                 do_utf8 ? to_utf8_substr(prog) : to_byte_substr(prog);
1841             must = do_utf8 ? prog->float_utf8 : prog->float_substr;
1842             back_max = prog->float_max_offset;
1843             back_min = prog->float_min_offset;
1844         }
1845         
1846             
1847         if (must == &PL_sv_undef)
1848             /* could not downgrade utf8 check substring, so must fail */
1849             goto phooey;
1850
1851         if (back_min<0) {
1852             last = strend;
1853         } else {
1854             last = HOP3c(strend,        /* Cannot start after this */
1855                   -(I32)(CHR_SVLEN(must)
1856                          - (SvTAIL(must) != 0) + back_min), strbeg);
1857         }
1858         if (s > PL_bostr)
1859             last1 = HOPc(s, -1);
1860         else
1861             last1 = s - 1;      /* bogus */
1862
1863         /* XXXX check_substr already used to find "s", can optimize if
1864            check_substr==must. */
1865         scream_pos = -1;
1866         dontbother = end_shift;
1867         strend = HOPc(strend, -dontbother);
1868         while ( (s <= last) &&
1869                 ((flags & REXEC_SCREAM)
1870                  ? (s = screaminstr(sv, must, HOP3c(s, back_min, (back_min<0 ? strbeg : strend)) - strbeg,
1871                                     end_shift, &scream_pos, 0))
1872                  : (s = fbm_instr((unsigned char*)HOP3(s, back_min, (back_min<0 ? strbeg : strend)),
1873                                   (unsigned char*)strend, must,
1874                                   multiline ? FBMrf_MULTILINE : 0))) ) {
1875             /* we may be pointing at the wrong string */
1876             if ((flags & REXEC_SCREAM) && RX_MATCH_COPIED(prog))
1877                 s = strbeg + (s - SvPVX_const(sv));
1878             DEBUG_EXECUTE_r( did_match = 1 );
1879             if (HOPc(s, -back_max) > last1) {
1880                 last1 = HOPc(s, -back_min);
1881                 s = HOPc(s, -back_max);
1882             }
1883             else {
1884                 char * const t = (last1 >= PL_bostr) ? HOPc(last1, 1) : last1 + 1;
1885
1886                 last1 = HOPc(s, -back_min);
1887                 s = t;
1888             }
1889             if (do_utf8) {
1890                 while (s <= last1) {
1891                     if (regtry(&reginfo, s))
1892                         goto got_it;
1893                     s += UTF8SKIP(s);
1894                 }
1895             }
1896             else {
1897                 while (s <= last1) {
1898                     if (regtry(&reginfo, s))
1899                         goto got_it;
1900                     s++;
1901                 }
1902             }
1903         }
1904         DEBUG_EXECUTE_r(if (!did_match) {
1905             RE_PV_QUOTED_DECL(quoted, do_utf8, PERL_DEBUG_PAD_ZERO(0), 
1906                 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
1907             PerlIO_printf(Perl_debug_log, "Did not find %s substr %s%s...\n",
1908                               ((must == prog->anchored_substr || must == prog->anchored_utf8)
1909                                ? "anchored" : "floating"),
1910                 quoted, RE_SV_TAIL(must));
1911         });                 
1912         goto phooey;
1913     }
1914     else if ( (c = prog->regstclass) ) {
1915         if (minlen) {
1916             const OPCODE op = OP(prog->regstclass);
1917             /* don't bother with what can't match */
1918             if (PL_regkind[op] != EXACT && op != CANY && PL_regkind[op] != TRIE)
1919                 strend = HOPc(strend, -(minlen - 1));
1920         }
1921         DEBUG_EXECUTE_r({
1922             SV * const prop = sv_newmortal();
1923             regprop(prog, prop, c);
1924             {
1925                 RE_PV_QUOTED_DECL(quoted,UTF,PERL_DEBUG_PAD_ZERO(1),
1926                     s,strend-s,60);
1927                 PerlIO_printf(Perl_debug_log,
1928                     "Matching stclass %.*s against %s (%d chars)\n",
1929                     (int)SvCUR(prop), SvPVX_const(prop),
1930                      quoted, (int)(strend - s));
1931             }
1932         });
1933         if (find_byclass(prog, c, s, strend, &reginfo))
1934             goto got_it;
1935         DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Contradicts stclass... [regexec_flags]\n"));
1936     }
1937     else {
1938         dontbother = 0;
1939         if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
1940             /* Trim the end. */
1941             char *last;
1942             SV* float_real;
1943
1944             if (!(do_utf8 ? prog->float_utf8 : prog->float_substr))
1945                 do_utf8 ? to_utf8_substr(prog) : to_byte_substr(prog);
1946             float_real = do_utf8 ? prog->float_utf8 : prog->float_substr;
1947
1948             if (flags & REXEC_SCREAM) {
1949                 last = screaminstr(sv, float_real, s - strbeg,
1950                                    end_shift, &scream_pos, 1); /* last one */
1951                 if (!last)
1952                     last = scream_olds; /* Only one occurrence. */
1953                 /* we may be pointing at the wrong string */
1954                 else if (RX_MATCH_COPIED(prog))
1955                     s = strbeg + (s - SvPVX_const(sv));
1956             }
1957             else {
1958                 STRLEN len;
1959                 const char * const little = SvPV_const(float_real, len);
1960
1961                 if (SvTAIL(float_real)) {
1962                     if (memEQ(strend - len + 1, little, len - 1))
1963                         last = strend - len + 1;
1964                     else if (!multiline)
1965                         last = memEQ(strend - len, little, len)
1966                             ? strend - len : NULL;
1967                     else
1968                         goto find_last;
1969                 } else {
1970                   find_last:
1971                     if (len)
1972                         last = rninstr(s, strend, little, little + len);
1973                     else
1974                         last = strend;  /* matching "$" */
1975                 }
1976             }
1977             if (last == NULL) {
1978                 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1979                                       "%sCan't trim the tail, match fails (should not happen)%s\n",
1980                                       PL_colors[4], PL_colors[5]));
1981                 goto phooey; /* Should not happen! */
1982             }
1983             dontbother = strend - last + prog->float_min_offset;
1984         }
1985         if (minlen && (dontbother < minlen))
1986             dontbother = minlen - 1;
1987         strend -= dontbother;              /* this one's always in bytes! */
1988         /* We don't know much -- general case. */
1989         if (do_utf8) {
1990             for (;;) {
1991                 if (regtry(&reginfo, s))
1992                     goto got_it;
1993                 if (s >= strend)
1994                     break;
1995                 s += UTF8SKIP(s);
1996             };
1997         }
1998         else {
1999             do {
2000                 if (regtry(&reginfo, s))
2001                     goto got_it;
2002             } while (s++ < strend);
2003         }
2004     }
2005
2006     /* Failure. */
2007     goto phooey;
2008
2009 got_it:
2010     RX_MATCH_TAINTED_set(prog, PL_reg_flags & RF_tainted);
2011
2012     if (PL_reg_eval_set) {
2013         /* Preserve the current value of $^R */
2014         if (oreplsv != GvSV(PL_replgv))
2015             sv_setsv(oreplsv, GvSV(PL_replgv));/* So that when GvSV(replgv) is
2016                                                   restored, the value remains
2017                                                   the same. */
2018         restore_pos(aTHX_ prog);
2019     }
2020
2021     /* make sure $`, $&, $', and $digit will work later */
2022     if ( !(flags & REXEC_NOT_FIRST) ) {
2023         RX_MATCH_COPY_FREE(prog);
2024         if (flags & REXEC_COPY_STR) {
2025             const I32 i = PL_regeol - startpos + (stringarg - strbeg);
2026 #ifdef PERL_OLD_COPY_ON_WRITE
2027             if ((SvIsCOW(sv)
2028                  || (SvFLAGS(sv) & CAN_COW_MASK) == CAN_COW_FLAGS)) {
2029                 if (DEBUG_C_TEST) {
2030                     PerlIO_printf(Perl_debug_log,
2031                                   "Copy on write: regexp capture, type %d\n",
2032                                   (int) SvTYPE(sv));
2033                 }
2034                 prog->saved_copy = sv_setsv_cow(prog->saved_copy, sv);
2035                 prog->subbeg = (char *)SvPVX_const(prog->saved_copy);
2036                 assert (SvPOKp(prog->saved_copy));
2037             } else
2038 #endif
2039             {
2040                 RX_MATCH_COPIED_on(prog);
2041                 s = savepvn(strbeg, i);
2042                 prog->subbeg = s;
2043             }
2044             prog->sublen = i;
2045         }
2046         else {
2047             prog->subbeg = strbeg;
2048             prog->sublen = PL_regeol - strbeg;  /* strend may have been modified */
2049         }
2050     }
2051
2052     return 1;
2053
2054 phooey:
2055     DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch failed%s\n",
2056                           PL_colors[4], PL_colors[5]));
2057     if (PL_reg_eval_set)
2058         restore_pos(aTHX_ prog);
2059     return 0;
2060 }
2061
2062 /*
2063  - regtry - try match at specific point
2064  */
2065 STATIC I32                      /* 0 failure, 1 success */
2066 S_regtry(pTHX_ const regmatch_info *reginfo, char *startpos)
2067 {
2068     dVAR;
2069     register I32 *sp;
2070     register I32 *ep;
2071     CHECKPOINT lastcp;
2072     regexp *prog = reginfo->prog;
2073     GET_RE_DEBUG_FLAGS_DECL;
2074
2075 #ifdef DEBUGGING
2076     PL_regindent = 0;   /* XXXX Not good when matches are reenterable... */
2077 #endif
2078     if ((prog->reganch & ROPT_EVAL_SEEN) && !PL_reg_eval_set) {
2079         MAGIC *mg;
2080
2081         PL_reg_eval_set = RS_init;
2082         DEBUG_EXECUTE_r(DEBUG_s(
2083             PerlIO_printf(Perl_debug_log, "  setting stack tmpbase at %"IVdf"\n",
2084                           (IV)(PL_stack_sp - PL_stack_base));
2085             ));
2086         SAVEI32(cxstack[cxstack_ix].blk_oldsp);
2087         cxstack[cxstack_ix].blk_oldsp = PL_stack_sp - PL_stack_base;
2088         /* Otherwise OP_NEXTSTATE will free whatever on stack now.  */
2089         SAVETMPS;
2090         /* Apparently this is not needed, judging by wantarray. */
2091         /* SAVEI8(cxstack[cxstack_ix].blk_gimme);
2092            cxstack[cxstack_ix].blk_gimme = G_SCALAR; */
2093
2094         if (reginfo->sv) {
2095             /* Make $_ available to executed code. */
2096             if (reginfo->sv != DEFSV) {
2097                 SAVE_DEFSV;
2098                 DEFSV = reginfo->sv;
2099             }
2100         
2101             if (!(SvTYPE(reginfo->sv) >= SVt_PVMG && SvMAGIC(reginfo->sv)
2102                   && (mg = mg_find(reginfo->sv, PERL_MAGIC_regex_global)))) {
2103                 /* prepare for quick setting of pos */
2104 #ifdef PERL_OLD_COPY_ON_WRITE
2105                 if (SvIsCOW(sv))
2106                     sv_force_normal_flags(sv, 0);
2107 #endif
2108                 mg = sv_magicext(reginfo->sv, NULL, PERL_MAGIC_regex_global,
2109                                  &PL_vtbl_mglob, NULL, 0);
2110                 mg->mg_len = -1;
2111             }
2112             PL_reg_magic    = mg;
2113             PL_reg_oldpos   = mg->mg_len;
2114             SAVEDESTRUCTOR_X(restore_pos, prog);
2115         }
2116         if (!PL_reg_curpm) {
2117             Newxz(PL_reg_curpm, 1, PMOP);
2118 #ifdef USE_ITHREADS
2119             {
2120                 SV* const repointer = newSViv(0);
2121                 /* so we know which PL_regex_padav element is PL_reg_curpm */
2122                 SvFLAGS(repointer) |= SVf_BREAK;
2123                 av_push(PL_regex_padav,repointer);
2124                 PL_reg_curpm->op_pmoffset = av_len(PL_regex_padav);
2125                 PL_regex_pad = AvARRAY(PL_regex_padav);
2126             }
2127 #endif      
2128         }
2129         PM_SETRE(PL_reg_curpm, prog);
2130         PL_reg_oldcurpm = PL_curpm;
2131         PL_curpm = PL_reg_curpm;
2132         if (RX_MATCH_COPIED(prog)) {
2133             /*  Here is a serious problem: we cannot rewrite subbeg,
2134                 since it may be needed if this match fails.  Thus
2135                 $` inside (?{}) could fail... */
2136             PL_reg_oldsaved = prog->subbeg;
2137             PL_reg_oldsavedlen = prog->sublen;
2138 #ifdef PERL_OLD_COPY_ON_WRITE
2139             PL_nrs = prog->saved_copy;
2140 #endif
2141             RX_MATCH_COPIED_off(prog);
2142         }
2143         else
2144             PL_reg_oldsaved = NULL;
2145         prog->subbeg = PL_bostr;
2146         prog->sublen = PL_regeol - PL_bostr; /* strend may have been modified */
2147     }
2148     prog->startp[0] = startpos - PL_bostr;
2149     PL_reginput = startpos;
2150     PL_regstartp = prog->startp;
2151     PL_regendp = prog->endp;
2152     PL_reglastparen = &prog->lastparen;
2153     PL_reglastcloseparen = &prog->lastcloseparen;
2154     prog->lastparen = 0;
2155     prog->lastcloseparen = 0;
2156     PL_regsize = 0;
2157     DEBUG_EXECUTE_r(PL_reg_starttry = startpos);
2158     if (PL_reg_start_tmpl <= prog->nparens) {
2159         PL_reg_start_tmpl = prog->nparens*3/2 + 3;
2160         if(PL_reg_start_tmp)
2161             Renew(PL_reg_start_tmp, PL_reg_start_tmpl, char*);
2162         else
2163             Newx(PL_reg_start_tmp, PL_reg_start_tmpl, char*);
2164     }
2165
2166     /* XXXX What this code is doing here?!!!  There should be no need
2167        to do this again and again, PL_reglastparen should take care of
2168        this!  --ilya*/
2169
2170     /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
2171      * Actually, the code in regcppop() (which Ilya may be meaning by
2172      * PL_reglastparen), is not needed at all by the test suite
2173      * (op/regexp, op/pat, op/split), but that code is needed, oddly
2174      * enough, for building DynaLoader, or otherwise this
2175      * "Error: '*' not in typemap in DynaLoader.xs, line 164"
2176      * will happen.  Meanwhile, this code *is* needed for the
2177      * above-mentioned test suite tests to succeed.  The common theme
2178      * on those tests seems to be returning null fields from matches.
2179      * --jhi */
2180 #if 1
2181     sp = prog->startp;
2182     ep = prog->endp;
2183     if (prog->nparens) {
2184         register I32 i;
2185         for (i = prog->nparens; i > (I32)*PL_reglastparen; i--) {
2186             *++sp = -1;
2187             *++ep = -1;
2188         }
2189     }
2190 #endif
2191     REGCP_SET(lastcp);
2192     if (regmatch(reginfo, prog->program + 1)) {
2193         prog->endp[0] = PL_reginput - PL_bostr;
2194         return 1;
2195     }
2196     REGCP_UNWIND(lastcp);
2197     return 0;
2198 }
2199
2200
2201 #define sayYES goto yes
2202 #define sayNO goto no
2203 #define sayNO_ANYOF goto no_anyof
2204 #define sayYES_FINAL goto yes_final
2205 #define sayNO_FINAL  goto no_final
2206 #define sayNO_SILENT goto do_no
2207 #define saySAME(x) if (x) goto yes; else goto no
2208
2209 #define CACHEsayNO STMT_START { \
2210     if (st->u.whilem.cache_offset | st->u.whilem.cache_bit) \
2211        PL_reg_poscache[st->u.whilem.cache_offset] |= \
2212             (1<<st->u.whilem.cache_bit); \
2213     sayNO; \
2214 } STMT_END
2215
2216
2217 /* this is used to determine how far from the left messages like
2218    'failed...' are printed. Currently 29 makes these messages line
2219    up with the opcode they refer to. Earlier perls used 25 which
2220    left these messages outdented making reviewing a debug output
2221    quite difficult.
2222 */
2223 #define REPORT_CODE_OFF 29
2224
2225
2226 /* Make sure there is a test for this +1 options in re_tests */
2227 #define TRIE_INITAL_ACCEPT_BUFFLEN 4;
2228
2229 #define CHRTEST_UNINIT -1001 /* c1/c2 haven't been calculated yet */
2230 #define CHRTEST_VOID   -1000 /* the c1/c2 "next char" test should be skipped */
2231
2232 #define SLAB_FIRST(s) (&(s)->states[0])
2233 #define SLAB_LAST(s)  (&(s)->states[PERL_REGMATCH_SLAB_SLOTS-1])
2234
2235 /* grab a new slab and return the first slot in it */
2236
2237 STATIC regmatch_state *
2238 S_push_slab(pTHX)
2239 {
2240 #if PERL_VERSION < 9
2241     dMY_CXT;
2242 #endif
2243     regmatch_slab *s = PL_regmatch_slab->next;
2244     if (!s) {
2245         Newx(s, 1, regmatch_slab);
2246         s->prev = PL_regmatch_slab;
2247         s->next = NULL;
2248         PL_regmatch_slab->next = s;
2249     }
2250     PL_regmatch_slab = s;
2251     return SLAB_FIRST(s);
2252 }
2253
2254 /* simulate a recursive call to regmatch */
2255
2256 #define REGMATCH(ns, where) \
2257     st->scan = scan; \
2258     scan = (ns); \
2259     st->resume_state = resume_##where; \
2260     goto start_recurse; \
2261     resume_point_##where:
2262
2263 /* push a new state then goto it */
2264
2265 #define PUSH_STATE_GOTO(state, node) \
2266     scan = node; \
2267     st->resume_state = state; \
2268     goto push_state;
2269
2270 /* push a new state with success backtracking, then goto it */
2271
2272 #define PUSH_YES_STATE_GOTO(state, node) \
2273     scan = node; \
2274     st->resume_state = state; \
2275     goto push_yes_state;
2276
2277
2278
2279 /*
2280  - regmatch - main matching routine
2281  *
2282  * Conceptually the strategy is simple:  check to see whether the current
2283  * node matches, call self recursively to see whether the rest matches,
2284  * and then act accordingly.  In practice we make some effort to avoid
2285  * recursion, in particular by going through "ordinary" nodes (that don't
2286  * need to know whether the rest of the match failed) by a loop instead of
2287  * by recursion.
2288  */
2289 /* [lwall] I've hoisted the register declarations to the outer block in order to
2290  * maybe save a little bit of pushing and popping on the stack.  It also takes
2291  * advantage of machines that use a register save mask on subroutine entry.
2292  *
2293  * This function used to be heavily recursive, but since this had the
2294  * effect of blowing the CPU stack on complex regexes, it has been
2295  * restructured to be iterative, and to save state onto the heap rather
2296  * than the stack. Essentially whereever regmatch() used to be called, it
2297  * pushes the current state, notes where to return, then jumps back into
2298  * the main loop.
2299  *
2300  * Originally the structure of this function used to look something like
2301
2302     S_regmatch() {
2303         int a = 1, b = 2;
2304         ...
2305         while (scan != NULL) {
2306             a++; // do stuff with a and b
2307             ...
2308             switch (OP(scan)) {
2309                 case FOO: {
2310                     int local = 3;
2311                     ...
2312                     if (regmatch(...))  // recurse
2313                         goto yes;
2314                 }
2315                 ...
2316             }
2317         }
2318         yes:
2319         return 1;
2320     }
2321
2322  * Now it looks something like this:
2323
2324     typedef struct {
2325         int a, b, local;
2326         int resume_state;
2327     } regmatch_state;
2328
2329     S_regmatch() {
2330         regmatch_state *st = new();
2331         int depth=0;
2332         st->a++; // do stuff with a and b
2333         ...
2334         while (scan != NULL) {
2335             ...
2336             switch (OP(scan)) {
2337                 case FOO: {
2338                     st->local = 3;
2339                     ...
2340                     st->scan = scan;
2341                     scan = ...;
2342                     st->resume_state = resume_FOO;
2343                     goto start_recurse; // recurse
2344
2345                     resume_point_FOO:
2346                     if (result)
2347                         goto yes;
2348                 }
2349                 ...
2350             }
2351           start_recurse:
2352             st = new(); push a new state
2353             st->a = 1; st->b = 2;
2354             depth++;
2355         }
2356       yes:
2357         result = 1;
2358         if (depth--) {
2359             st = pop();
2360             switch (resume_state) {
2361             case resume_FOO:
2362                 goto resume_point_FOO;
2363             ...
2364             }
2365         }
2366         return result
2367     }
2368             
2369  * WARNING: this means that any line in this function that contains a
2370  * REGMATCH() or TRYPAREN() is actually simulating a recursive call to
2371  * regmatch() using gotos instead. Thus the values of any local variables
2372  * not saved in the regmatch_state structure will have been lost when
2373  * execution resumes on the next line .
2374  *
2375  * States (ie the st pointer) are allocated in slabs of about 4K in size.
2376  * PL_regmatch_state always points to the currently active state, and
2377  * PL_regmatch_slab points to the slab currently containing PL_regmatch_state.
2378  * The first time regmatch is called, the first slab is allocated, and is
2379  * never freed until interpreter desctruction. When the slab is full,
2380  * a new one is allocated chained to the end. At exit from regmatch, slabs
2381  * allocated since entry are freed.
2382  */
2383  
2384 /* *** every FOO_fail should = FOO+1 */
2385 #define TRIE_next              (REGNODE_MAX+1)
2386 #define TRIE_next_fail         (REGNODE_MAX+2)
2387 #define EVAL_A                 (REGNODE_MAX+3)
2388 #define EVAL_A_fail            (REGNODE_MAX+4)
2389 #define resume_CURLYX          (REGNODE_MAX+5)
2390 #define resume_WHILEM1         (REGNODE_MAX+6)
2391 #define resume_WHILEM2         (REGNODE_MAX+7)
2392 #define resume_WHILEM3         (REGNODE_MAX+8)
2393 #define resume_WHILEM4         (REGNODE_MAX+9)
2394 #define resume_WHILEM5         (REGNODE_MAX+10)
2395 #define resume_WHILEM6         (REGNODE_MAX+11)
2396 #define BRANCH_next            (REGNODE_MAX+12)
2397 #define BRANCH_next_fail       (REGNODE_MAX+13)
2398 #define CURLYM_A               (REGNODE_MAX+14)
2399 #define CURLYM_A_fail          (REGNODE_MAX+15)
2400 #define CURLYM_B               (REGNODE_MAX+16)
2401 #define CURLYM_B_fail          (REGNODE_MAX+17)
2402 #define IFMATCH_A              (REGNODE_MAX+18)
2403 #define IFMATCH_A_fail         (REGNODE_MAX+19)
2404 #define CURLY_B_min_known      (REGNODE_MAX+20)
2405 #define CURLY_B_min_known_fail (REGNODE_MAX+21)
2406 #define CURLY_B_min            (REGNODE_MAX+22)
2407 #define CURLY_B_min_fail       (REGNODE_MAX+23)
2408 #define CURLY_B_max            (REGNODE_MAX+24)
2409 #define CURLY_B_max_fail       (REGNODE_MAX+25)
2410
2411
2412 #define REG_NODE_NUM(x) ((x) ? (int)((x)-prog) : -1)
2413
2414 #ifdef DEBUGGING
2415 STATIC void
2416 S_debug_start_match(pTHX_ const regexp *prog, const bool do_utf8, 
2417     const char *start, const char *end, const char *blurb)
2418 {
2419     const bool utf8_pat= prog->reganch & ROPT_UTF8 ? 1 : 0;
2420     if (!PL_colorset)   
2421             reginitcolors();    
2422     {
2423         RE_PV_QUOTED_DECL(s0, utf8_pat, PERL_DEBUG_PAD_ZERO(0), 
2424             prog->precomp, prog->prelen, 60);   
2425         
2426         RE_PV_QUOTED_DECL(s1, do_utf8, PERL_DEBUG_PAD_ZERO(1), 
2427             start, end - start, 60); 
2428         
2429         PerlIO_printf(Perl_debug_log, 
2430             "%s%s REx%s %s against %s\n", 
2431                        PL_colors[4], blurb, PL_colors[5], s0, s1); 
2432         
2433         if (do_utf8||utf8_pat) 
2434             PerlIO_printf(Perl_debug_log, "UTF-8 %s%s%s...\n",
2435                 utf8_pat ? "pattern" : "",
2436                 utf8_pat && do_utf8 ? " and " : "",
2437                 do_utf8 ? "string" : ""
2438             ); 
2439     }
2440 }
2441
2442 STATIC void
2443 S_dump_exec_pos(pTHX_ const char *locinput, 
2444                       const regnode *scan, 
2445                       const char *loc_regeol, 
2446                       const char *loc_bostr, 
2447                       const char *loc_reg_starttry,
2448                       const bool do_utf8)
2449 {
2450     const int docolor = *PL_colors[0] || *PL_colors[2] || *PL_colors[4];
2451     const int taill = (docolor ? 10 : 7); /* 3 chars for "> <" */
2452     int l = (loc_regeol - locinput) > taill ? taill : (loc_regeol - locinput);
2453     /* The part of the string before starttry has one color
2454        (pref0_len chars), between starttry and current
2455        position another one (pref_len - pref0_len chars),
2456        after the current position the third one.
2457        We assume that pref0_len <= pref_len, otherwise we
2458        decrease pref0_len.  */
2459     int pref_len = (locinput - loc_bostr) > (5 + taill) - l
2460         ? (5 + taill) - l : locinput - loc_bostr;
2461     int pref0_len;
2462
2463     while (do_utf8 && UTF8_IS_CONTINUATION(*(U8*)(locinput - pref_len)))
2464         pref_len++;
2465     pref0_len = pref_len  - (locinput - loc_reg_starttry);
2466     if (l + pref_len < (5 + taill) && l < loc_regeol - locinput)
2467         l = ( loc_regeol - locinput > (5 + taill) - pref_len
2468               ? (5 + taill) - pref_len : loc_regeol - locinput);
2469     while (do_utf8 && UTF8_IS_CONTINUATION(*(U8*)(locinput + l)))
2470         l--;
2471     if (pref0_len < 0)
2472         pref0_len = 0;
2473     if (pref0_len > pref_len)
2474         pref0_len = pref_len;
2475     {
2476         const int is_uni = (do_utf8 && OP(scan) != CANY) ? 1 : 0;
2477
2478         RE_PV_COLOR_DECL(s0,len0,is_uni,PERL_DEBUG_PAD(0),
2479             (locinput - pref_len),pref0_len, 60, 4, 5);
2480         
2481         RE_PV_COLOR_DECL(s1,len1,is_uni,PERL_DEBUG_PAD(1),
2482                     (locinput - pref_len + pref0_len),
2483                     pref_len - pref0_len, 60, 2, 3);
2484         
2485         RE_PV_COLOR_DECL(s2,len2,is_uni,PERL_DEBUG_PAD(2),
2486                     locinput, loc_regeol - locinput, 10, 0, 1);
2487
2488         const STRLEN tlen=len0+len1+len2;
2489         PerlIO_printf(Perl_debug_log,
2490                     "%4"IVdf" <%.*s%.*s%s%.*s>%*s|",
2491                     (IV)(locinput - loc_bostr),
2492                     len0, s0,
2493                     len1, s1,
2494                     (docolor ? "" : "> <"),
2495                     len2, s2,
2496                     tlen > 19 ? 0 :  19 - tlen,
2497                     "");
2498     }
2499 }
2500
2501 #endif
2502
2503 STATIC I32                      /* 0 failure, 1 success */
2504 S_regmatch(pTHX_ const regmatch_info *reginfo, regnode *prog)
2505 {
2506 #if PERL_VERSION < 9
2507     dMY_CXT;
2508 #endif
2509     dVAR;
2510     register const bool do_utf8 = PL_reg_match_utf8;
2511     const U32 uniflags = UTF8_ALLOW_DEFAULT;
2512
2513     regexp *rex = reginfo->prog;
2514
2515     regmatch_slab  *orig_slab;
2516     regmatch_state *orig_state;
2517
2518     /* the current state. This is a cached copy of PL_regmatch_state */
2519     register regmatch_state *st;
2520
2521     /* cache heavy used fields of st in registers */
2522     register regnode *scan;
2523     register regnode *next;
2524     register I32 n = 0; /* initialize to shut up compiler warning */
2525     register char *locinput = PL_reginput;
2526
2527     /* these variables are NOT saved during a recusive RFEGMATCH: */
2528     register I32 nextchr;   /* is always set to UCHARAT(locinput) */
2529     bool result = 0;        /* return value of S_regmatch */
2530     int depth = 0;          /* depth of recursion */
2531     regmatch_state *yes_state = NULL; /* state to pop to on success of
2532                                                             subpattern */
2533     U32 state_num;
2534     
2535     I32 parenfloor = 0;
2536
2537 #ifdef DEBUGGING
2538     GET_RE_DEBUG_FLAGS_DECL;
2539     PL_regindent++;
2540 #endif
2541
2542     /* on first ever call to regmatch, allocate first slab */
2543     if (!PL_regmatch_slab) {
2544         Newx(PL_regmatch_slab, 1, regmatch_slab);
2545         PL_regmatch_slab->prev = NULL;
2546         PL_regmatch_slab->next = NULL;
2547         PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
2548     }
2549
2550     /* remember current high-water mark for exit */
2551     /* XXX this should be done with SAVE* instead */
2552     orig_slab  = PL_regmatch_slab;
2553     orig_state = PL_regmatch_state;
2554
2555     /* grab next free state slot */
2556     st = ++PL_regmatch_state;
2557     if (st >  SLAB_LAST(PL_regmatch_slab))
2558         st = PL_regmatch_state = S_push_slab(aTHX);
2559
2560     st->minmod = 0;
2561     st->sw = 0;
2562     st->logical = 0;
2563     st->cc = NULL;
2564
2565     /* Note that nextchr is a byte even in UTF */
2566     nextchr = UCHARAT(locinput);
2567     scan = prog;
2568     while (scan != NULL) {
2569
2570         DEBUG_EXECUTE_r( {
2571             SV * const prop = sv_newmortal();
2572             regnode *rnext=regnext(scan);
2573             DUMP_EXEC_POS( locinput, scan, do_utf8 );
2574             regprop(rex, prop, scan);
2575             
2576             PerlIO_printf(Perl_debug_log,
2577                     "%3"IVdf":%*s%s(%"IVdf")\n",
2578                     (IV)(scan - rex->program), PL_regindent*2, "",
2579                     SvPVX_const(prop),
2580                     (PL_regkind[OP(scan)] == END || !rnext) ? 
2581                         0 : (IV)(rnext - rex->program));
2582         });
2583
2584         next = scan + NEXT_OFF(scan);
2585         if (next == scan)
2586             next = NULL;
2587         state_num = OP(scan);
2588
2589       reenter_switch:
2590         switch (state_num) {
2591         case BOL:
2592             if (locinput == PL_bostr)
2593             {
2594                 /* reginfo->till = reginfo->bol; */
2595                 break;
2596             }
2597             sayNO;
2598         case MBOL:
2599             if (locinput == PL_bostr ||
2600                 ((nextchr || locinput < PL_regeol) && locinput[-1] == '\n'))
2601             {
2602                 break;
2603             }
2604             sayNO;
2605         case SBOL:
2606             if (locinput == PL_bostr)
2607                 break;
2608             sayNO;
2609         case GPOS:
2610             if (locinput == reginfo->ganch)
2611                 break;
2612             sayNO;
2613         case EOL:
2614                 goto seol;
2615         case MEOL:
2616             if ((nextchr || locinput < PL_regeol) && nextchr != '\n')
2617                 sayNO;
2618             break;
2619         case SEOL:
2620           seol:
2621             if ((nextchr || locinput < PL_regeol) && nextchr != '\n')
2622                 sayNO;
2623             if (PL_regeol - locinput > 1)
2624                 sayNO;
2625             break;
2626         case EOS:
2627             if (PL_regeol != locinput)
2628                 sayNO;
2629             break;
2630         case SANY:
2631             if (!nextchr && locinput >= PL_regeol)
2632                 sayNO;
2633             if (do_utf8) {
2634                 locinput += PL_utf8skip[nextchr];
2635                 if (locinput > PL_regeol)
2636                     sayNO;
2637                 nextchr = UCHARAT(locinput);
2638             }
2639             else
2640                 nextchr = UCHARAT(++locinput);
2641             break;
2642         case CANY:
2643             if (!nextchr && locinput >= PL_regeol)
2644                 sayNO;
2645             nextchr = UCHARAT(++locinput);
2646             break;
2647         case REG_ANY:
2648             if ((!nextchr && locinput >= PL_regeol) || nextchr == '\n')
2649                 sayNO;
2650             if (do_utf8) {
2651                 locinput += PL_utf8skip[nextchr];
2652                 if (locinput > PL_regeol)
2653                     sayNO;
2654                 nextchr = UCHARAT(locinput);
2655             }
2656             else
2657                 nextchr = UCHARAT(++locinput);
2658             break;
2659
2660 #undef  ST
2661 #define ST st->u.trie
2662         case TRIEC:
2663             /* In this case the charclass data is available inline so
2664                we can fail fast without a lot of extra overhead. 
2665              */
2666             if (scan->flags == EXACT || !do_utf8) {
2667                 if(!ANYOF_BITMAP_TEST(scan, *locinput)) {
2668                     DEBUG_EXECUTE_r(
2669                         PerlIO_printf(Perl_debug_log,
2670                                   "%*s  %sfailed to match trie start class...%s\n",
2671                                   REPORT_CODE_OFF+PL_regindent*2, "", PL_colors[4], PL_colors[5])
2672                     );
2673                     sayNO_SILENT;
2674                     /* NOTREACHED */
2675                 }                       
2676             }
2677             /* FALL THROUGH */
2678         case TRIE:
2679             {
2680                 /* what type of TRIE am I? (utf8 makes this contextual) */
2681                 const enum { trie_plain, trie_utf8, trie_utf8_fold }
2682                     trie_type = do_utf8 ?
2683                           (scan->flags == EXACT ? trie_utf8 : trie_utf8_fold)
2684                         : trie_plain;
2685
2686                 /* what trie are we using right now */
2687                 reg_trie_data * const trie
2688                     = (reg_trie_data*)rex->data->data[ ARG( scan ) ];
2689                 U32 state = trie->startstate;
2690
2691                 if (trie->bitmap && trie_type != trie_utf8_fold &&
2692                     !TRIE_BITMAP_TEST(trie,*locinput)
2693                 ) {
2694                     if (trie->states[ state ].wordnum) {
2695                          DEBUG_EXECUTE_r(
2696                             PerlIO_printf(Perl_debug_log,
2697                                           "%*s  %smatched empty string...%s\n",
2698                                           REPORT_CODE_OFF+PL_regindent*2, "", PL_colors[4], PL_colors[5])
2699                         );
2700                         break;
2701                     } else {
2702                         DEBUG_EXECUTE_r(
2703                             PerlIO_printf(Perl_debug_log,
2704                                           "%*s  %sfailed to match trie start class...%s\n",
2705                                           REPORT_CODE_OFF+PL_regindent*2, "", PL_colors[4], PL_colors[5])
2706                         );
2707                         sayNO_SILENT;
2708                    }
2709                 }
2710
2711             { 
2712                 U8 *uc = ( U8* )locinput;
2713
2714                 STRLEN len = 0;
2715                 STRLEN foldlen = 0;
2716                 U8 *uscan = (U8*)NULL;
2717                 STRLEN bufflen=0;
2718                 SV *sv_accept_buff = NULL;
2719                 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
2720
2721                 ST.accepted = 0; /* how many accepting states we have seen */
2722                 ST.B = next;
2723                 ST.jump = trie->jump;
2724                 
2725 #ifdef DEBUGGING
2726                 ST.me = scan;
2727 #endif
2728                 
2729                 
2730
2731                 /*
2732                    traverse the TRIE keeping track of all accepting states
2733                    we transition through until we get to a failing node.
2734                 */
2735
2736                 while ( state && uc <= (U8*)PL_regeol ) {
2737                     U32 base = trie->states[ state ].trans.base;
2738                     UV uvc;
2739                     U16 charid;
2740                     /* We use charid to hold the wordnum as we don't use it
2741                        for charid until after we have done the wordnum logic. 
2742                        We define an alias just so that the wordnum logic reads
2743                        more naturally. */
2744
2745 #define got_wordnum charid
2746                     got_wordnum = trie->states[ state ].wordnum;
2747
2748                     if ( got_wordnum ) {
2749                         if ( ! ST.accepted ) {
2750                             ENTER;
2751                             SAVETMPS;
2752                             bufflen = TRIE_INITAL_ACCEPT_BUFFLEN;
2753                             sv_accept_buff=newSV(bufflen *
2754                                             sizeof(reg_trie_accepted) - 1);
2755                             SvCUR_set(sv_accept_buff, 0);
2756                             SvPOK_on(sv_accept_buff);
2757                             sv_2mortal(sv_accept_buff);
2758                             SAVETMPS;
2759                             ST.accept_buff =
2760                                 (reg_trie_accepted*)SvPV_nolen(sv_accept_buff );
2761                         }
2762                         do {
2763                             if (ST.accepted >= bufflen) {
2764                                 bufflen *= 2;
2765                                 ST.accept_buff =(reg_trie_accepted*)
2766                                     SvGROW(sv_accept_buff,
2767                                         bufflen * sizeof(reg_trie_accepted));
2768                             }
2769                             SvCUR_set(sv_accept_buff,SvCUR(sv_accept_buff)
2770                                 + sizeof(reg_trie_accepted));
2771
2772
2773                             ST.accept_buff[ST.accepted].wordnum = got_wordnum;
2774                             ST.accept_buff[ST.accepted].endpos = uc;
2775                             ++ST.accepted;
2776                         } while (trie->nextword && (got_wordnum= trie->nextword[got_wordnum]));
2777                     }
2778 #undef got_wordnum 
2779
2780                     DEBUG_TRIE_EXECUTE_r({
2781                                 DUMP_EXEC_POS( (char *)uc, scan, do_utf8 );
2782                                 PerlIO_printf( Perl_debug_log,
2783                                     "%*s  %sState: %4"UVxf" Accepted: %4"UVxf" ",
2784                                     2+PL_regindent * 2, "", PL_colors[4],
2785                                     (UV)state, (UV)ST.accepted );
2786                     });
2787
2788                     if ( base ) {
2789                         REXEC_TRIE_READ_CHAR(trie_type, trie, uc, uscan, len,
2790                             uvc, charid, foldlen, foldbuf, uniflags);
2791
2792                         if (charid &&
2793                              (base + charid > trie->uniquecharcount )
2794                              && (base + charid - 1 - trie->uniquecharcount
2795                                     < trie->lasttrans)
2796                              && trie->trans[base + charid - 1 -
2797                                     trie->uniquecharcount].check == state)
2798                         {
2799                             state = trie->trans[base + charid - 1 -
2800                                 trie->uniquecharcount ].next;
2801                         }
2802                         else {
2803                             state = 0;
2804                         }
2805                         uc += len;
2806
2807                     }
2808                     else {
2809                         state = 0;
2810                     }
2811                     DEBUG_TRIE_EXECUTE_r(
2812                         PerlIO_printf( Perl_debug_log,
2813                             "Charid:%3x CP:%4"UVxf" After State: %4"UVxf"%s\n",
2814                             charid, uvc, (UV)state, PL_colors[5] );
2815                     );
2816                 }
2817                 if (!ST.accepted )
2818                    sayNO;
2819
2820                 DEBUG_EXECUTE_r(
2821                     PerlIO_printf( Perl_debug_log,
2822                         "%*s  %sgot %"IVdf" possible matches%s\n",
2823                         REPORT_CODE_OFF + PL_regindent * 2, "",
2824                         PL_colors[4], (IV)ST.accepted, PL_colors[5] );
2825                 );
2826             }}
2827
2828             /* FALL THROUGH */
2829
2830         case TRIE_next_fail: /* we failed - try next alterative */
2831
2832             if ( ST.accepted == 1 ) {
2833                 /* only one choice left - just continue */
2834                 DEBUG_EXECUTE_r({
2835                     reg_trie_data * const trie
2836                         = (reg_trie_data*)rex->data->data[ ARG(ST.me) ];
2837                     SV ** const tmp = RX_DEBUG(reginfo->prog)
2838                                     ? av_fetch( trie->words, ST.accept_buff[ 0 ].wordnum-1, 0 )
2839                                     : NULL;
2840                     PerlIO_printf( Perl_debug_log,
2841                         "%*s  %sonly one match left: #%d <%s>%s\n",
2842                         REPORT_CODE_OFF+PL_regindent*2, "", PL_colors[4],
2843                         ST.accept_buff[ 0 ].wordnum,
2844                         tmp ? SvPV_nolen_const( *tmp ) : "not compiled under -Dr",
2845                         PL_colors[5] );
2846                 });
2847                 PL_reginput = (char *)ST.accept_buff[ 0 ].endpos;
2848                 /* in this case we free tmps/leave before we call regmatch
2849                    as we wont be using accept_buff again. */
2850                 FREETMPS;
2851                 LEAVE;
2852                 locinput = PL_reginput;
2853                 nextchr = UCHARAT(locinput);
2854                 
2855                 if ( !ST.jump ) 
2856                     scan = ST.B;
2857                 else
2858                     scan = ST.B - ST.jump[ST.accept_buff[0].wordnum];
2859                 
2860                 continue; /* execute rest of RE */
2861             }
2862
2863             if (!ST.accepted-- ) {
2864                 FREETMPS;
2865                 LEAVE;
2866                 sayNO;
2867             }
2868
2869             /*
2870                There are at least two accepting states left.  Presumably
2871                the number of accepting states is going to be low,
2872                typically two. So we simply scan through to find the one
2873                with lowest wordnum.  Once we find it, we swap the last
2874                state into its place and decrement the size. We then try to
2875                match the rest of the pattern at the point where the word
2876                ends. If we succeed, control just continues along the
2877                regex; if we fail we return here to try the next accepting
2878                state
2879              */
2880
2881             {
2882                 U32 best = 0;
2883                 U32 cur;
2884                 for( cur = 1 ; cur <= ST.accepted ; cur++ ) {
2885                     DEBUG_TRIE_EXECUTE_r(
2886                         PerlIO_printf( Perl_debug_log,
2887                             "%*s  %sgot %"IVdf" (%d) as best, looking at %"IVdf" (%d)%s\n",
2888                             REPORT_CODE_OFF + PL_regindent * 2, "", PL_colors[4],
2889                             (IV)best, ST.accept_buff[ best ].wordnum, (IV)cur,
2890                             ST.accept_buff[ cur ].wordnum, PL_colors[5] );
2891                     );
2892
2893                     if (ST.accept_buff[cur].wordnum <
2894                             ST.accept_buff[best].wordnum)
2895                         best = cur;
2896                 }
2897
2898                 DEBUG_EXECUTE_r({
2899                     reg_trie_data * const trie
2900                         = (reg_trie_data*)rex->data->data[ ARG(ST.me) ];
2901                     SV ** const tmp = RX_DEBUG(reginfo->prog)
2902                                 ? av_fetch( trie->words, ST.accept_buff[ best ].wordnum - 1, 0 )
2903                                 : NULL;
2904                     PerlIO_printf( Perl_debug_log, "%*s  %strying alternation #%d <%s> at node #%d %s\n",
2905                         REPORT_CODE_OFF+PL_regindent*2, "", PL_colors[4],
2906                         ST.accept_buff[best].wordnum,
2907                         tmp ? SvPV_nolen_const( *tmp ) : "not compiled under -Dr", REG_NODE_NUM(scan),
2908                         PL_colors[5] );
2909                 });
2910
2911                 if ( best<ST.accepted ) {
2912                     reg_trie_accepted tmp = ST.accept_buff[ best ];
2913                     ST.accept_buff[ best ] = ST.accept_buff[ ST.accepted ];
2914                     ST.accept_buff[ ST.accepted ] = tmp;
2915                     best = ST.accepted;
2916                 }
2917                 PL_reginput = (char *)ST.accept_buff[ best ].endpos;
2918                 if ( !ST.jump ) {
2919                     PUSH_STATE_GOTO(TRIE_next, ST.B);
2920                     /* NOTREACHED */
2921                 } else {
2922                     PUSH_STATE_GOTO(TRIE_next, ST.B - ST.jump[ST.accept_buff[best].wordnum]);
2923                     /* NOTREACHED */
2924                 }
2925                 /* NOTREACHED */
2926             }
2927             /* NOTREACHED */
2928
2929 #undef  ST
2930
2931         case EXACT: {
2932             char *s = STRING(scan);
2933             st->ln = STR_LEN(scan);
2934             if (do_utf8 != UTF) {
2935                 /* The target and the pattern have differing utf8ness. */
2936                 char *l = locinput;
2937                 const char * const e = s + st->ln;
2938
2939                 if (do_utf8) {
2940                     /* The target is utf8, the pattern is not utf8. */
2941                     while (s < e) {
2942                         STRLEN ulen;
2943                         if (l >= PL_regeol)
2944                              sayNO;
2945                         if (NATIVE_TO_UNI(*(U8*)s) !=
2946                             utf8n_to_uvuni((U8*)l, UTF8_MAXBYTES, &ulen,
2947                                             uniflags))
2948                              sayNO;
2949                         l += ulen;
2950                         s ++;
2951                     }
2952                 }
2953                 else {
2954                     /* The target is not utf8, the pattern is utf8. */
2955                     while (s < e) {
2956                         STRLEN ulen;
2957                         if (l >= PL_regeol)
2958                             sayNO;
2959                         if (NATIVE_TO_UNI(*((U8*)l)) !=
2960                             utf8n_to_uvuni((U8*)s, UTF8_MAXBYTES, &ulen,
2961                                            uniflags))
2962                             sayNO;
2963                         s += ulen;
2964                         l ++;
2965                     }
2966                 }
2967                 locinput = l;
2968                 nextchr = UCHARAT(locinput);
2969                 break;
2970             }
2971             /* The target and the pattern have the same utf8ness. */
2972             /* Inline the first character, for speed. */
2973             if (UCHARAT(s) != nextchr)
2974                 sayNO;
2975             if (PL_regeol - locinput < st->ln)
2976                 sayNO;
2977             if (st->ln > 1 && memNE(s, locinput, st->ln))
2978                 sayNO;
2979             locinput += st->ln;
2980             nextchr = UCHARAT(locinput);
2981             break;
2982             }
2983         case EXACTFL:
2984             PL_reg_flags |= RF_tainted;
2985             /* FALL THROUGH */
2986         case EXACTF: {
2987             char * const s = STRING(scan);
2988             st->ln = STR_LEN(scan);
2989
2990             if (do_utf8 || UTF) {
2991               /* Either target or the pattern are utf8. */
2992                 const char * const l = locinput;
2993                 char *e = PL_regeol;
2994
2995                 if (ibcmp_utf8(s, 0,  st->ln, (bool)UTF,
2996                                l, &e, 0,  do_utf8)) {
2997                      /* One more case for the sharp s:
2998                       * pack("U0U*", 0xDF) =~ /ss/i,
2999                       * the 0xC3 0x9F are the UTF-8
3000                       * byte sequence for the U+00DF. */
3001                      if (!(do_utf8 &&
3002                            toLOWER(s[0]) == 's' &&
3003                            st->ln >= 2 &&
3004                            toLOWER(s[1]) == 's' &&
3005                            (U8)l[0] == 0xC3 &&
3006                            e - l >= 2 &&
3007                            (U8)l[1] == 0x9F))
3008                           sayNO;
3009                 }
3010                 locinput = e;
3011                 nextchr = UCHARAT(locinput);
3012                 break;
3013             }
3014
3015             /* Neither the target and the pattern are utf8. */
3016
3017             /* Inline the first character, for speed. */
3018             if (UCHARAT(s) != nextchr &&
3019                 UCHARAT(s) != ((OP(scan) == EXACTF)
3020                                ? PL_fold : PL_fold_locale)[nextchr])
3021                 sayNO;
3022             if (PL_regeol - locinput < st->ln)
3023                 sayNO;
3024             if (st->ln > 1 && (OP(scan) == EXACTF
3025                            ? ibcmp(s, locinput, st->ln)
3026                            : ibcmp_locale(s, locinput, st->ln)))
3027                 sayNO;
3028             locinput += st->ln;
3029             nextchr = UCHARAT(locinput);
3030             break;
3031             }
3032         case ANYOF:
3033             if (do_utf8) {
3034                 STRLEN inclasslen = PL_regeol - locinput;
3035
3036                 if (!reginclass(rex, scan, (U8*)locinput, &inclasslen, do_utf8))
3037                     sayNO_ANYOF;
3038                 if (locinput >= PL_regeol)
3039                     sayNO;
3040                 locinput += inclasslen ? inclasslen : UTF8SKIP(locinput);
3041                 nextchr = UCHARAT(locinput);
3042                 break;
3043             }
3044             else {
3045                 if (nextchr < 0)
3046                     nextchr = UCHARAT(locinput);
3047                 if (!REGINCLASS(rex, scan, (U8*)locinput))
3048                     sayNO_ANYOF;
3049                 if (!nextchr && locinput >= PL_regeol)
3050                     sayNO;
3051                 nextchr = UCHARAT(++locinput);
3052                 break;
3053             }
3054         no_anyof:
3055             /* If we might have the case of the German sharp s
3056              * in a casefolding Unicode character class. */
3057
3058             if (ANYOF_FOLD_SHARP_S(scan, locinput, PL_regeol)) {
3059                  locinput += SHARP_S_SKIP;
3060                  nextchr = UCHARAT(locinput);
3061             }
3062             else
3063                  sayNO;
3064             break;
3065         case ALNUML:
3066             PL_reg_flags |= RF_tainted;
3067             /* FALL THROUGH */
3068         case ALNUM:
3069             if (!nextchr)
3070                 sayNO;
3071             if (do_utf8) {
3072                 LOAD_UTF8_CHARCLASS_ALNUM();
3073                 if (!(OP(scan) == ALNUM
3074                       ? (bool)swash_fetch(PL_utf8_alnum, (U8*)locinput, do_utf8)
3075                       : isALNUM_LC_utf8((U8*)locinput)))
3076                 {
3077                     sayNO;
3078                 }
3079                 locinput += PL_utf8skip[nextchr];
3080                 nextchr = UCHARAT(locinput);
3081                 break;
3082             }
3083             if (!(OP(scan) == ALNUM
3084                   ? isALNUM(nextchr) : isALNUM_LC(nextchr)))
3085                 sayNO;
3086             nextchr = UCHARAT(++locinput);
3087             break;
3088         case NALNUML:
3089             PL_reg_flags |= RF_tainted;
3090             /* FALL THROUGH */
3091         case NALNUM:
3092             if (!nextchr && locinput >= PL_regeol)
3093                 sayNO;
3094             if (do_utf8) {
3095                 LOAD_UTF8_CHARCLASS_ALNUM();
3096                 if (OP(scan) == NALNUM
3097                     ? (bool)swash_fetch(PL_utf8_alnum, (U8*)locinput, do_utf8)
3098                     : isALNUM_LC_utf8((U8*)locinput))
3099                 {
3100                     sayNO;
3101                 }
3102                 locinput += PL_utf8skip[nextchr];
3103                 nextchr = UCHARAT(locinput);
3104                 break;
3105             }
3106             if (OP(scan) == NALNUM
3107                 ? isALNUM(nextchr) : isALNUM_LC(nextchr))
3108                 sayNO;
3109             nextchr = UCHARAT(++locinput);
3110             break;
3111         case BOUNDL:
3112         case NBOUNDL:
3113             PL_reg_flags |= RF_tainted;
3114             /* FALL THROUGH */
3115         case BOUND:
3116         case NBOUND:
3117             /* was last char in word? */
3118             if (do_utf8) {
3119                 if (locinput == PL_bostr)
3120                     st->ln = '\n';
3121                 else {
3122                     const U8 * const r = reghop3((U8*)locinput, -1, (U8*)PL_bostr);
3123                 
3124                     st->ln = utf8n_to_uvchr(r, UTF8SKIP(r), 0, uniflags);
3125                 }
3126                 if (OP(scan) == BOUND || OP(scan) == NBOUND) {
3127                     st->ln = isALNUM_uni(st->ln);
3128                     LOAD_UTF8_CHARCLASS_ALNUM();
3129                     n = swash_fetch(PL_utf8_alnum, (U8*)locinput, do_utf8);
3130                 }
3131                 else {
3132                     st->ln = isALNUM_LC_uvchr(UNI_TO_NATIVE(st->ln));
3133                     n = isALNUM_LC_utf8((U8*)locinput);
3134                 }
3135             }
3136             else {
3137                 st->ln = (locinput != PL_bostr) ?
3138                     UCHARAT(locinput - 1) : '\n';
3139                 if (OP(scan) == BOUND || OP(scan) == NBOUND) {
3140                     st->ln = isALNUM(st->ln);
3141                     n = isALNUM(nextchr);
3142                 }
3143                 else {
3144                     st->ln = isALNUM_LC(st->ln);
3145                     n = isALNUM_LC(nextchr);
3146                 }
3147             }
3148             if (((!st->ln) == (!n)) == (OP(scan) == BOUND ||
3149                                     OP(scan) == BOUNDL))
3150                     sayNO;
3151             break;
3152         case SPACEL:
3153             PL_reg_flags |= RF_tainted;
3154             /* FALL THROUGH */
3155         case SPACE:
3156             if (!nextchr)
3157                 sayNO;
3158             if (do_utf8) {
3159                 if (UTF8_IS_CONTINUED(nextchr)) {
3160                     LOAD_UTF8_CHARCLASS_SPACE();
3161                     if (!(OP(scan) == SPACE
3162                           ? (bool)swash_fetch(PL_utf8_space, (U8*)locinput, do_utf8)
3163                           : isSPACE_LC_utf8((U8*)locinput)))
3164                     {
3165                         sayNO;
3166                     }
3167                     locinput += PL_utf8skip[nextchr];
3168                     nextchr = UCHARAT(locinput);
3169                     break;
3170                 }
3171                 if (!(OP(scan) == SPACE
3172                       ? isSPACE(nextchr) : isSPACE_LC(nextchr)))
3173                     sayNO;
3174                 nextchr = UCHARAT(++locinput);
3175             }
3176             else {
3177                 if (!(OP(scan) == SPACE
3178                       ? isSPACE(nextchr) : isSPACE_LC(nextchr)))
3179                     sayNO;
3180                 nextchr = UCHARAT(++locinput);
3181             }
3182             break;
3183         case NSPACEL:
3184             PL_reg_flags |= RF_tainted;
3185             /* FALL THROUGH */
3186         case NSPACE:
3187             if (!nextchr && locinput >= PL_regeol)
3188                 sayNO;
3189             if (do_utf8) {
3190                 LOAD_UTF8_CHARCLASS_SPACE();
3191                 if (OP(scan) == NSPACE
3192                     ? (bool)swash_fetch(PL_utf8_space, (U8*)locinput, do_utf8)
3193                     : isSPACE_LC_utf8((U8*)locinput))
3194                 {
3195                     sayNO;
3196                 }
3197                 locinput += PL_utf8skip[nextchr];
3198                 nextchr = UCHARAT(locinput);
3199                 break;
3200             }
3201             if (OP(scan) == NSPACE
3202                 ? isSPACE(nextchr) : isSPACE_LC(nextchr))
3203                 sayNO;
3204             nextchr = UCHARAT(++locinput);
3205             break;
3206         case DIGITL:
3207             PL_reg_flags |= RF_tainted;
3208             /* FALL THROUGH */
3209         case DIGIT:
3210             if (!nextchr)
3211                 sayNO;
3212             if (do_utf8) {
3213                 LOAD_UTF8_CHARCLASS_DIGIT();
3214                 if (!(OP(scan) == DIGIT
3215                       ? (bool)swash_fetch(PL_utf8_digit, (U8*)locinput, do_utf8)
3216                       : isDIGIT_LC_utf8((U8*)locinput)))
3217                 {
3218                     sayNO;
3219                 }
3220                 locinput += PL_utf8skip[nextchr];
3221                 nextchr = UCHARAT(locinput);
3222                 break;
3223             }
3224             if (!(OP(scan) == DIGIT
3225                   ? isDIGIT(nextchr) : isDIGIT_LC(nextchr)))
3226                 sayNO;
3227             nextchr = UCHARAT(++locinput);
3228             break;
3229         case NDIGITL:
3230             PL_reg_flags |= RF_tainted;
3231             /* FALL THROUGH */
3232         case NDIGIT:
3233             if (!nextchr && locinput >= PL_regeol)
3234                 sayNO;
3235             if (do_utf8) {
3236                 LOAD_UTF8_CHARCLASS_DIGIT();
3237                 if (OP(scan) == NDIGIT
3238                     ? (bool)swash_fetch(PL_utf8_digit, (U8*)locinput, do_utf8)
3239                     : isDIGIT_LC_utf8((U8*)locinput))
3240                 {
3241                     sayNO;
3242                 }
3243                 locinput += PL_utf8skip[nextchr];
3244                 nextchr = UCHARAT(locinput);
3245                 break;
3246             }
3247             if (OP(scan) == NDIGIT
3248                 ? isDIGIT(nextchr) : isDIGIT_LC(nextchr))
3249                 sayNO;
3250             nextchr = UCHARAT(++locinput);
3251             break;
3252         case CLUMP:
3253             if (locinput >= PL_regeol)
3254                 sayNO;
3255             if  (do_utf8) {
3256                 LOAD_UTF8_CHARCLASS_MARK();
3257                 if (swash_fetch(PL_utf8_mark,(U8*)locinput, do_utf8))
3258                     sayNO;
3259                 locinput += PL_utf8skip[nextchr];
3260                 while (locinput < PL_regeol &&
3261                        swash_fetch(PL_utf8_mark,(U8*)locinput, do_utf8))
3262                     locinput += UTF8SKIP(locinput);
3263                 if (locinput > PL_regeol)
3264                     sayNO;
3265             } 
3266             else
3267                locinput++;
3268             nextchr = UCHARAT(locinput);
3269             break;
3270         case REFFL:
3271             PL_reg_flags |= RF_tainted;
3272             /* FALL THROUGH */
3273         case REF:
3274         case REFF: {
3275             char *s;
3276             n = ARG(scan);  /* which paren pair */
3277             st->ln = PL_regstartp[n];
3278             PL_reg_leftiter = PL_reg_maxiter;           /* Void cache */
3279             if ((I32)*PL_reglastparen < n || st->ln == -1)
3280                 sayNO;                  /* Do not match unless seen CLOSEn. */
3281             if (st->ln == PL_regendp[n])
3282                 break;
3283
3284             s = PL_bostr + st->ln;
3285             if (do_utf8 && OP(scan) != REF) {   /* REF can do byte comparison */
3286                 char *l = locinput;
3287                 const char *e = PL_bostr + PL_regendp[n];
3288                 /*
3289                  * Note that we can't do the "other character" lookup trick as
3290                  * in the 8-bit case (no pun intended) because in Unicode we
3291                  * have to map both upper and title case to lower case.
3292                  */
3293                 if (OP(scan) == REFF) {
3294                     while (s < e) {
3295                         STRLEN ulen1, ulen2;
3296                         U8 tmpbuf1[UTF8_MAXBYTES_CASE+1];
3297                         U8 tmpbuf2[UTF8_MAXBYTES_CASE+1];
3298
3299                         if (l >= PL_regeol)
3300                             sayNO;
3301                         toLOWER_utf8((U8*)s, tmpbuf1, &ulen1);
3302                         toLOWER_utf8((U8*)l, tmpbuf2, &ulen2);
3303                         if (ulen1 != ulen2 || memNE((char *)tmpbuf1, (char *)tmpbuf2, ulen1))
3304                             sayNO;
3305                         s += ulen1;
3306                         l += ulen2;
3307                     }
3308                 }
3309                 locinput = l;
3310                 nextchr = UCHARAT(locinput);
3311                 break;
3312             }
3313
3314             /* Inline the first character, for speed. */
3315             if (UCHARAT(s) != nextchr &&
3316                 (OP(scan) == REF ||
3317                  (UCHARAT(s) != ((OP(scan) == REFF
3318                                   ? PL_fold : PL_fold_locale)[nextchr]))))
3319                 sayNO;
3320             st->ln = PL_regendp[n] - st->ln;
3321             if (locinput + st->ln > PL_regeol)
3322                 sayNO;
3323             if (st->ln > 1 && (OP(scan) == REF
3324                            ? memNE(s, locinput, st->ln)
3325                            : (OP(scan) == REFF
3326                               ? ibcmp(s, locinput, st->ln)
3327                               : ibcmp_locale(s, locinput, st->ln))))
3328                 sayNO;
3329             locinput += st->ln;
3330             nextchr = UCHARAT(locinput);
3331             break;
3332             }
3333
3334         case NOTHING:
3335         case TAIL:
3336             break;
3337         case BACK:
3338             break;
3339
3340 #undef  ST
3341 #define ST st->u.eval
3342
3343         case EVAL:  /*   /(?{A})B/   /(??{A})B/  and /(?(?{A})X|Y)B/   */
3344         {
3345             SV *ret;
3346             {
3347                 /* execute the code in the {...} */
3348                 dSP;
3349                 SV ** const before = SP;
3350                 OP_4tree * const oop = PL_op;
3351                 COP * const ocurcop = PL_curcop;
3352                 PAD *old_comppad;
3353             
3354                 n = ARG(scan);
3355                 PL_op = (OP_4tree*)rex->data->data[n];
3356                 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log, "  re_eval 0x%"UVxf"\n", PTR2UV(PL_op)) );
3357                 PAD_SAVE_LOCAL(old_comppad, (PAD*)rex->data->data[n + 2]);
3358                 PL_regendp[0] = PL_reg_magic->mg_len = locinput - PL_bostr;
3359
3360                 CALLRUNOPS(aTHX);                       /* Scalar context. */
3361                 SPAGAIN;
3362                 if (SP == before)
3363                     ret = &PL_sv_undef;   /* protect against empty (?{}) blocks. */
3364                 else {
3365                     ret = POPs;
3366                     PUTBACK;
3367                 }
3368
3369                 PL_op = oop;
3370                 PAD_RESTORE_LOCAL(old_comppad);
3371                 PL_curcop = ocurcop;
3372                 if (!st->logical) {
3373                     /* /(?{...})/ */
3374                     sv_setsv(save_scalar(PL_replgv), ret);
3375                     break;
3376                 }
3377             }
3378             if (st->logical == 2) { /* Postponed subexpression: /(??{...})/ */
3379                 regexp *re;
3380                 {
3381                     /* extract RE object from returned value; compiling if
3382                      * necessary */
3383
3384                     MAGIC *mg = NULL;
3385                     const SV *sv;
3386                     if(SvROK(ret) && SvSMAGICAL(sv = SvRV(ret)))
3387                         mg = mg_find(sv, PERL_MAGIC_qr);
3388                     else if (SvSMAGICAL(ret)) {
3389                         if (SvGMAGICAL(ret))
3390                             sv_unmagic(ret, PERL_MAGIC_qr);
3391                         else
3392                             mg = mg_find(ret, PERL_MAGIC_qr);
3393                     }
3394
3395                     if (mg) {
3396                         re = (regexp *)mg->mg_obj;
3397                         (void)ReREFCNT_inc(re);
3398                     }
3399                     else {
3400                         STRLEN len;
3401                         const char * const t = SvPV_const(ret, len);
3402                         PMOP pm;
3403                         const I32 osize = PL_regsize;
3404
3405                         Zero(&pm, 1, PMOP);
3406                         if (DO_UTF8(ret)) pm.op_pmdynflags |= PMdf_DYN_UTF8;
3407                         re = CALLREGCOMP(aTHX_ (char*)t, (char*)t + len, &pm);
3408                         if (!(SvFLAGS(ret)
3409                               & (SVs_TEMP | SVs_PADTMP | SVf_READONLY
3410                                 | SVs_GMG)))
3411                             sv_magic(ret,(SV*)ReREFCNT_inc(re),
3412                                         PERL_MAGIC_qr,0,0);
3413                         PL_regsize = osize;
3414                     }
3415                 }
3416
3417                 /* run the pattern returned from (??{...}) */
3418                 ST.cp = regcppush(0);   /* Save *all* the positions. */
3419                 REGCP_SET(ST.lastcp);
3420                 *PL_reglastparen = 0;
3421                 *PL_reglastcloseparen = 0;
3422                 PL_reginput = locinput;
3423
3424                 /* XXXX This is too dramatic a measure... */
3425                 PL_reg_maxiter = 0;
3426
3427                 st->logical = 0;
3428                 ST.toggleutf = ((PL_reg_flags & RF_utf8) != 0) ^
3429                             ((re->reganch & ROPT_UTF8) != 0);
3430                 if (ST.toggleutf) PL_reg_flags ^= RF_utf8;
3431                 ST.prev_rex = rex;
3432                 rex = re;
3433
3434                 ST.B = next;
3435                 DEBUG_EXECUTE_r(
3436                     debug_start_match(re, do_utf8, locinput, PL_regeol, 
3437                         "Matching embedded");
3438                     );
3439                 /* now continue  from first node in postoned RE */
3440                 PUSH_YES_STATE_GOTO(EVAL_A, re->program + 1);
3441                 /* NOTREACHED */
3442             }
3443             /* /(?(?{...})X|Y)/ */
3444             st->sw = SvTRUE(ret);
3445             st->logical = 0;
3446             break;
3447         }
3448
3449         case EVAL_A: /* successfully ran inner rex (??{rex}) */
3450             if (ST.toggleutf)
3451                 PL_reg_flags ^= RF_utf8;
3452             ReREFCNT_dec(rex);
3453             rex = ST.prev_rex;
3454             /* XXXX This is too dramatic a measure... */
3455             PL_reg_maxiter = 0;
3456             /* Restore parens of the caller without popping the
3457              * savestack */
3458             {
3459                 const I32 tmp = PL_savestack_ix;
3460                 PL_savestack_ix = ST.lastcp;
3461                 regcppop(rex);
3462                 PL_savestack_ix = tmp;
3463             }
3464             PL_reginput = locinput;
3465              /* continue at the node following the (??{...}) */
3466             scan = ST.B;
3467             continue;
3468         case EVAL_A_fail: /* unsuccessfully ran inner rex (??{rex}) */
3469             /* Restore state to the outer re then re-throw the failure */
3470             if (ST.toggleutf)
3471                 PL_reg_flags ^= RF_utf8;
3472             ReREFCNT_dec(rex);
3473             rex = ST.prev_rex;
3474
3475             /* XXXX This is too dramatic a measure... */
3476             PL_reg_maxiter = 0;
3477
3478             PL_reginput = locinput;
3479             REGCP_UNWIND(ST.lastcp);
3480             regcppop(rex);
3481             sayNO_SILENT;
3482
3483 #undef ST
3484
3485         case OPEN:
3486             n = ARG(scan);  /* which paren pair */
3487             PL_reg_start_tmp[n] = locinput;
3488             if (n > PL_regsize)
3489                 PL_regsize = n;
3490             break;
3491         case CLOSE:
3492             n = ARG(scan);  /* which paren pair */
3493             PL_regstartp[n] = PL_reg_start_tmp[n] - PL_bostr;
3494             PL_regendp[n] = locinput - PL_bostr;
3495             if (n > (I32)*PL_reglastparen)
3496                 *PL_reglastparen = n;
3497             *PL_reglastcloseparen = n;
3498             break;
3499         case GROUPP:
3500             n = ARG(scan);  /* which paren pair */
3501             st->sw = ((I32)*PL_reglastparen >= n && PL_regendp[n] != -1);
3502             break;
3503         case IFTHEN:
3504             PL_reg_leftiter = PL_reg_maxiter;           /* Void cache */
3505             if (st->sw)
3506                 next = NEXTOPER(NEXTOPER(scan));
3507             else {
3508                 next = scan + ARG(scan);
3509                 if (OP(next) == IFTHEN) /* Fake one. */
3510                     next = NEXTOPER(NEXTOPER(next));
3511             }
3512             break;
3513         case LOGICAL:
3514             st->logical = scan->flags;
3515             break;
3516 /*******************************************************************
3517  cc points to the regmatch_state associated with the most recent CURLYX.
3518  This struct contains info about the innermost (...)* loop (an
3519  "infoblock"), and a pointer to the next outer cc.
3520
3521  Here is how Y(A)*Z is processed (if it is compiled into CURLYX/WHILEM):
3522
3523    1) After matching Y, regnode for CURLYX is processed;
3524
3525    2) This regnode populates cc, and calls regmatch() recursively
3526       with the starting point at WHILEM node;
3527
3528    3) Each hit of WHILEM node tries to match A and Z (in the order
3529       depending on the current iteration, min/max of {min,max} and
3530       greediness).  The information about where are nodes for "A"
3531       and "Z" is read from cc, as is info on how many times "A"
3532       was already matched, and greediness.
3533
3534    4) After A matches, the same WHILEM node is hit again.
3535
3536    5) Each time WHILEM is hit, cc is the infoblock created by CURLYX
3537       of the same pair.  Thus when WHILEM tries to match Z, it temporarily
3538       resets cc, since this Y(A)*Z can be a part of some other loop:
3539       as in (Y(A)*Z)*.  If Z matches, the automaton will hit the WHILEM node
3540       of the external loop.
3541
3542  Currently present infoblocks form a tree with a stem formed by st->cc
3543  and whatever it mentions via ->next, and additional attached trees
3544  corresponding to temporarily unset infoblocks as in "5" above.
3545
3546  In the following picture, infoblocks for outer loop of
3547  (Y(A)*?Z)*?T are denoted O, for inner I.  NULL starting block
3548  is denoted by x.  The matched string is YAAZYAZT.  Temporarily postponed
3549  infoblocks are drawn below the "reset" infoblock.
3550
3551  In fact in the picture below we do not show failed matches for Z and T
3552  by WHILEM blocks.  [We illustrate minimal matches, since for them it is
3553  more obvious *why* one needs to *temporary* unset infoblocks.]
3554
3555   Matched       REx position    InfoBlocks      Comment
3556                 (Y(A)*?Z)*?T    x
3557                 Y(A)*?Z)*?T     x <- O
3558   Y             (A)*?Z)*?T      x <- O
3559   Y             A)*?Z)*?T       x <- O <- I
3560   YA            )*?Z)*?T        x <- O <- I
3561   YA            A)*?Z)*?T       x <- O <- I
3562   YAA           )*?Z)*?T        x <- O <- I
3563   YAA           Z)*?T           x <- O          # Temporary unset I
3564                                      I
3565
3566   YAAZ          Y(A)*?Z)*?T     x <- O
3567                                      I
3568
3569   YAAZY         (A)*?Z)*?T      x <- O
3570                                      I
3571
3572   YAAZY         A)*?Z)*?T       x <- O <- I
3573                                      I
3574
3575   YAAZYA        )*?Z)*?T        x <- O <- I     
3576                                      I
3577
3578   YAAZYA        Z)*?T           x <- O          # Temporary unset I
3579                                      I,I
3580
3581   YAAZYAZ       )*?T            x <- O
3582                                      I,I
3583
3584   YAAZYAZ       T               x               # Temporary unset O
3585                                 O
3586                                 I,I
3587
3588   YAAZYAZT                      x
3589                                 O
3590                                 I,I
3591  *******************************************************************/
3592
3593         case CURLYX: {
3594                 /* No need to save/restore up to this paren */
3595                 parenfloor = scan->flags;
3596                 
3597                 /* Dave says:
3598                    
3599                    CURLYX and WHILEM are always paired: they're the moral
3600                    equivalent of pp_enteriter anbd pp_iter.
3601
3602                    The only time next could be null is if the node tree is
3603                    corrupt. This was mentioned on p5p a few days ago.
3604
3605                    See http://www.xray.mpe.mpg.de/mailing-lists/perl5-porters/2006-04/msg00556.html
3606                    So we'll assert that this is true:
3607                 */
3608                 assert(next);
3609                 if (OP(PREVOPER(next)) == NOTHING) /* LONGJMP */
3610                     next += ARG(next);
3611                 /* XXXX Probably it is better to teach regpush to support
3612                    parenfloor > PL_regsize... */
3613                 if (parenfloor > (I32)*PL_reglastparen)
3614                     parenfloor = *PL_reglastparen; /* Pessimization... */
3615
3616                 st->u.curlyx.cp = PL_savestack_ix;
3617                 st->u.curlyx.outercc = st->cc;
3618                 st->cc = st;
3619                 /* these fields contain the state of the current curly.
3620                  * they are accessed by subsequent WHILEMs;
3621                  * cur and lastloc are also updated by WHILEM */
3622                 st->u.curlyx.parenfloor = parenfloor;
3623                 st->u.curlyx.cur = -1; /* this will be updated by WHILEM */
3624                 st->u.curlyx.min = ARG1(scan);
3625                 st->u.curlyx.max  = ARG2(scan);
3626                 st->u.curlyx.scan = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
3627                 st->u.curlyx.lastloc = 0;
3628                 /* st->next and st->minmod are also read by WHILEM */
3629
3630                 PL_reginput = locinput;
3631                 REGMATCH(PREVOPER(next), CURLYX); /* start on the WHILEM */
3632                 /*** all unsaved local vars undefined at this point */
3633                 regcpblow(st->u.curlyx.cp);
3634                 st->cc = st->u.curlyx.outercc;
3635                 saySAME(result);
3636             }
3637             /* NOTREACHED */
3638         case WHILEM: {
3639                 /*
3640                  * This is really hard to understand, because after we match
3641                  * what we're trying to match, we must make sure the rest of
3642                  * the REx is going to match for sure, and to do that we have
3643                  * to go back UP the parse tree by recursing ever deeper.  And
3644                  * if it fails, we have to reset our parent's current state
3645                  * that we can try again after backing off.
3646                  */
3647
3648                 /* Dave says:
3649
3650                    st->cc gets initialised by CURLYX ready for use by WHILEM.
3651                    So again, unless somethings been corrupted, st->cc cannot
3652                    be null at that point in WHILEM.
3653                    
3654                    See http://www.xray.mpe.mpg.de/mailing-lists/perl5-porters/2006-04/msg00556.html
3655                    So we'll assert that this is true:
3656                 */
3657                 assert(st->cc);
3658                 st->u.whilem.lastloc = st->cc->u.curlyx.lastloc; /* Detection of 0-len. */
3659                 st->u.whilem.cache_offset = 0;
3660                 st->u.whilem.cache_bit = 0;
3661                 
3662                 n = st->cc->u.curlyx.cur + 1; /* how many we know we matched */
3663                 PL_reginput = locinput;
3664
3665                 DEBUG_EXECUTE_r(
3666                     PerlIO_printf(Perl_debug_log,
3667                                   "%*s  %ld out of %ld..%ld  cc=%"UVxf"\n",
3668                                   REPORT_CODE_OFF+PL_regindent*2, "",
3669                                   (long)n, (long)st->cc->u.curlyx.min,
3670                                   (long)st->cc->u.curlyx.max, PTR2UV(st->cc))
3671                     );
3672
3673                 /* If degenerate scan matches "", assume scan done. */
3674
3675                 if (locinput == st->cc->u.curlyx.lastloc && n >= st->cc->u.curlyx.min) {
3676                     st->u.whilem.savecc = st->cc;
3677                     st->cc = st->cc->u.curlyx.outercc;
3678                     if (st->cc)
3679                         st->ln = st->cc->u.curlyx.cur;
3680                     DEBUG_EXECUTE_r(
3681                         PerlIO_printf(Perl_debug_log,
3682                            "%*s  empty match detected, try continuation...\n",
3683                            REPORT_CODE_OFF+PL_regindent*2, "")
3684                         );
3685                     REGMATCH(st->u.whilem.savecc->next, WHILEM1);
3686                     /*** all unsaved local vars undefined at this point */
3687                     st->cc = st->u.whilem.savecc;
3688                     if (result)
3689                         sayYES;
3690                     if (st->cc->u.curlyx.outercc)
3691                         st->cc->u.curlyx.outercc->u.curlyx.cur = st->ln;
3692                     sayNO;
3693                 }
3694
3695                 /* First just match a string of min scans. */
3696
3697                 if (n < st->cc->u.curlyx.min) {
3698                     st->cc->u.curlyx.cur = n;
3699                     st->cc->u.curlyx.lastloc = locinput;
3700                     REGMATCH(st->cc->u.curlyx.scan, WHILEM2);
3701                     /*** all unsaved local vars undefined at this point */
3702                     if (result)
3703                         sayYES;
3704                     st->cc->u.curlyx.cur = n - 1;
3705                     st->cc->u.curlyx.lastloc = st->u.whilem.lastloc;
3706                     sayNO;
3707                 }
3708
3709                 if (scan->flags) {
3710                     /* Check whether we already were at this position.
3711                         Postpone detection until we know the match is not
3712                         *that* much linear. */
3713                 if (!PL_reg_maxiter) {
3714                     PL_reg_maxiter = (PL_regeol - PL_bostr + 1) * (scan->flags>>4);
3715                     /* possible overflow for long strings and many CURLYX's */
3716                     if (PL_reg_maxiter < 0)
3717                         PL_reg_maxiter = I32_MAX;
3718                     PL_reg_leftiter = PL_reg_maxiter;
3719                 }
3720                 if (PL_reg_leftiter-- == 0) {
3721                     const I32 size = (PL_reg_maxiter + 7)/8;
3722                     if (PL_reg_poscache) {
3723                         if ((I32)PL_reg_poscache_size < size) {
3724                             Renew(PL_reg_poscache, size, char);
3725                             PL_reg_poscache_size = size;
3726                         }
3727                         Zero(PL_reg_poscache, size, char);
3728                     }
3729                     else {
3730                         PL_reg_poscache_size = size;
3731                         Newxz(PL_reg_poscache, size, char);
3732                     }
3733                     DEBUG_EXECUTE_r(
3734                         PerlIO_printf(Perl_debug_log,
3735               "%sDetected a super-linear match, switching on caching%s...\n",
3736                                       PL_colors[4], PL_colors[5])
3737                         );
3738                 }
3739                 if (PL_reg_leftiter < 0) {
3740                     st->u.whilem.cache_offset = locinput - PL_bostr;
3741
3742                     st->u.whilem.cache_offset = (scan->flags & 0xf) - 1
3743                             + st->u.whilem.cache_offset * (scan->flags>>4);
3744                     st->u.whilem.cache_bit = st->u.whilem.cache_offset % 8;
3745                     st->u.whilem.cache_offset /= 8;
3746                     if (PL_reg_poscache[st->u.whilem.cache_offset] & (1<<st->u.whilem.cache_bit)) {
3747                     DEBUG_EXECUTE_r(
3748                         PerlIO_printf(Perl_debug_log,
3749                                       "%*s  already tried at this position...\n",
3750                                       REPORT_CODE_OFF+PL_regindent*2, "")
3751                         );
3752                         sayNO; /* cache records failure */
3753                     }
3754                 }
3755                 }
3756
3757                 /* Prefer next over scan for minimal matching. */
3758
3759                 if (st->cc->minmod) {
3760                     st->u.whilem.savecc = st->cc;
3761                     st->cc = st->cc->u.curlyx.outercc;
3762                     if (st->cc)
3763                         st->ln = st->cc->u.curlyx.cur;
3764                     st->u.whilem.cp = regcppush(st->u.whilem.savecc->u.curlyx.parenfloor);
3765                     REGCP_SET(st->u.whilem.lastcp);
3766                     REGMATCH(st->u.whilem.savecc->next, WHILEM3);
3767                     /*** all unsaved local vars undefined at this point */
3768                     st->cc = st->u.whilem.savecc;
3769                     if (result) {
3770                         regcpblow(st->u.whilem.cp);
3771                         sayYES; /* All done. */
3772                     }
3773                     REGCP_UNWIND(st->u.whilem.lastcp);
3774                     regcppop(rex);
3775                     if (st->cc->u.curlyx.outercc)
3776                         st->cc->u.curlyx.outercc->u.curlyx.cur = st->ln;
3777
3778                     if (n >= st->cc->u.curlyx.max) { /* Maximum greed exceeded? */
3779                         if (ckWARN(WARN_REGEXP) && n >= REG_INFTY
3780                             && !(PL_reg_flags & RF_warned)) {
3781                             PL_reg_flags |= RF_warned;
3782                             Perl_warner(aTHX_ packWARN(WARN_REGEXP), "%s limit (%d) exceeded",
3783                                  "Complex regular subexpression recursion",
3784                                  REG_INFTY - 1);
3785                         }
3786                         CACHEsayNO;
3787                     }
3788
3789                     DEBUG_EXECUTE_r(
3790                         PerlIO_printf(Perl_debug_log,
3791                                       "%*s  trying longer...\n",
3792                                       REPORT_CODE_OFF+PL_regindent*2, "")
3793                         );
3794                     /* Try scanning more and see if it helps. */
3795                     PL_reginput = locinput;
3796                     st->cc->u.curlyx.cur = n;
3797                     st->cc->u.curlyx.lastloc = locinput;
3798                     st->u.whilem.cp = regcppush(st->cc->u.curlyx.parenfloor);
3799                     REGCP_SET(st->u.whilem.lastcp);
3800                     REGMATCH(st->cc->u.curlyx.scan, WHILEM4);
3801                     /*** all unsaved local vars undefined at this point */
3802                     if (result) {
3803                         regcpblow(st->u.whilem.cp);
3804                         sayYES;
3805                     }
3806                     REGCP_UNWIND(st->u.whilem.lastcp);
3807                     regcppop(rex);
3808                     st->cc->u.curlyx.cur = n - 1;
3809                     st->cc->u.curlyx.lastloc = st->u.whilem.lastloc;
3810                     CACHEsayNO;
3811                 }
3812
3813                 /* Prefer scan over next for maximal matching. */
3814
3815                 if (n < st->cc->u.curlyx.max) { /* More greed allowed? */
3816                     st->u.whilem.cp = regcppush(st->cc->u.curlyx.parenfloor);
3817                     st->cc->u.curlyx.cur = n;
3818                     st->cc->u.curlyx.lastloc = locinput;
3819                     REGCP_SET(st->u.whilem.lastcp);
3820                     REGMATCH(st->cc->u.curlyx.scan, WHILEM5);
3821                     /*** all unsaved local vars undefined at this point */
3822                     if (result) {
3823                         regcpblow(st->u.whilem.cp);
3824                         sayYES;
3825                     }
3826                     REGCP_UNWIND(st->u.whilem.lastcp);
3827                     regcppop(rex);      /* Restore some previous $<digit>s? */
3828                     PL_reginput = locinput;
3829                     DEBUG_EXECUTE_r(
3830                         PerlIO_printf(Perl_debug_log,
3831                                       "%*s  failed, try continuation...\n",
3832                                       REPORT_CODE_OFF+PL_regindent*2, "")
3833                         );
3834                 }
3835                 if (ckWARN(WARN_REGEXP) && n >= REG_INFTY
3836                         && !(PL_reg_flags & RF_warned)) {
3837                     PL_reg_flags |= RF_warned;
3838                     Perl_warner(aTHX_ packWARN(WARN_REGEXP), "%s limit (%d) exceeded",
3839                          "Complex regular subexpression recursion",
3840                          REG_INFTY - 1);
3841                 }
3842
3843                 /* Failed deeper matches of scan, so see if this one works. */
3844                 st->u.whilem.savecc = st->cc;
3845                 st->cc = st->cc->u.curlyx.outercc;
3846                 if (st->cc)
3847                     st->ln = st->cc->u.curlyx.cur;
3848                 REGMATCH(st->u.whilem.savecc->next, WHILEM6);
3849                 /*** all unsaved local vars undefined at this point */
3850                 st->cc = st->u.whilem.savecc;
3851                 if (result)
3852                     sayYES;
3853                 if (st->cc->u.curlyx.outercc)
3854                     st->cc->u.curlyx.outercc->u.curlyx.cur = st->ln;
3855                 st->cc->u.curlyx.cur = n - 1;
3856                 st->cc->u.curlyx.lastloc = st->u.whilem.lastloc;
3857                 CACHEsayNO;
3858             }
3859             /* NOTREACHED */
3860
3861 #undef  ST
3862 #define ST st->u.branch
3863
3864         case BRANCHJ:       /*  /(...|A|...)/ with long next pointer */
3865             next = scan + ARG(scan);
3866             if (next == scan)
3867                 next = NULL;
3868             scan = NEXTOPER(scan);
3869             /* FALL THROUGH */
3870
3871         case BRANCH:        /*  /(...|A|...)/ */
3872             scan = NEXTOPER(scan); /* scan now points to inner node */
3873             if (!next || (OP(next) != BRANCH && OP(next) != BRANCHJ))
3874                 /* last branch; skip state push and jump direct to node */
3875                 continue;
3876             ST.lastparen = *PL_reglastparen;
3877             ST.next_branch = next;
3878             REGCP_SET(ST.cp);
3879             PL_reginput = locinput;
3880
3881             /* Now go into the branch */
3882             PUSH_STATE_GOTO(BRANCH_next, scan);
3883             /* NOTREACHED */
3884
3885         case BRANCH_next_fail: /* that branch failed; try the next, if any */
3886             REGCP_UNWIND(ST.cp);
3887             for (n = *PL_reglastparen; n > ST.lastparen; n--)
3888                 PL_regendp[n] = -1;
3889             *PL_reglastparen = n;
3890             scan = ST.next_branch;
3891             /* no more branches? */
3892             if (!scan || (OP(scan) != BRANCH && OP(scan) != BRANCHJ))
3893                 sayNO;
3894             continue; /* execute next BRANCH[J] op */
3895             /* NOTREACHED */
3896     
3897         case MINMOD:
3898             st->minmod = 1;
3899             break;
3900
3901 #undef  ST
3902 #define ST st->u.curlym
3903
3904         case CURLYM:    /* /A{m,n}B/ where A is fixed-length */
3905
3906             /* This is an optimisation of CURLYX that enables us to push
3907              * only a single backtracking state, no matter now many matches
3908              * there are in {m,n}. It relies on the pattern being constant
3909              * length, with no parens to influence future backrefs
3910              */
3911
3912             ST.me = scan;
3913             scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
3914
3915             /* if paren positive, emulate an OPEN/CLOSE around A */
3916             if (ST.me->flags) {
3917                 I32 paren = ST.me->flags;
3918                 if (paren > PL_regsize)
3919                     PL_regsize = paren;
3920                 if (paren > (I32)*PL_reglastparen)
3921                     *PL_reglastparen = paren;
3922                 scan += NEXT_OFF(scan); /* Skip former OPEN. */
3923             }
3924             ST.A = scan;
3925             ST.B = next;
3926             ST.alen = 0;
3927             ST.count = 0;
3928             ST.minmod = st->minmod;
3929             st->minmod = 0;
3930             ST.c1 = CHRTEST_UNINIT;
3931             REGCP_SET(ST.cp);
3932
3933             if (!(ST.minmod ? ARG1(ST.me) : ARG2(ST.me))) /* min/max */
3934                 goto curlym_do_B;
3935
3936           curlym_do_A: /* execute the A in /A{m,n}B/  */
3937             PL_reginput = locinput;
3938             PUSH_YES_STATE_GOTO(CURLYM_A, ST.A); /* match A */
3939             /* NOTREACHED */
3940
3941         case CURLYM_A: /* we've just matched an A */
3942             locinput = st->locinput;
3943             nextchr = UCHARAT(locinput);
3944
3945             ST.count++;
3946             /* after first match, determine A's length: u.curlym.alen */
3947             if (ST.count == 1) {
3948                 if (PL_reg_match_utf8) {
3949                     char *s = locinput;
3950                     while (s < PL_reginput) {
3951                         ST.alen++;
3952                         s += UTF8SKIP(s);
3953                     }
3954                 }
3955                 else {
3956                     ST.alen = PL_reginput - locinput;
3957                 }
3958                 if (ST.alen == 0)
3959                     ST.count = ST.minmod ? ARG1(ST.me) : ARG2(ST.me);
3960             }
3961             DEBUG_EXECUTE_r(
3962                 PerlIO_printf(Perl_debug_log,
3963                           "%*s  CURLYM now matched %"IVdf" times, len=%"IVdf"...\n",
3964                           (int)(REPORT_CODE_OFF+(PL_regindent*2)), "",
3965                           (IV) ST.count, (IV)ST.alen)
3966             );
3967
3968             locinput = PL_reginput;
3969             if (ST.count < (ST.minmod ? ARG1(ST.me) : ARG2(ST.me)))
3970                 goto curlym_do_A; /* try to match another A */
3971             goto curlym_do_B; /* try to match B */
3972
3973         case CURLYM_A_fail: /* just failed to match an A */
3974             REGCP_UNWIND(ST.cp);
3975             if (ST.minmod || ST.count < ARG1(ST.me) /* min*/ )
3976                 sayNO;
3977
3978           curlym_do_B: /* execute the B in /A{m,n}B/  */
3979             PL_reginput = locinput;
3980             if (ST.c1 == CHRTEST_UNINIT) {
3981                 /* calculate c1 and c2 for possible match of 1st char
3982                  * following curly */
3983                 ST.c1 = ST.c2 = CHRTEST_VOID;
3984                 if (HAS_TEXT(ST.B) || JUMPABLE(ST.B)) {
3985                     regnode *text_node = ST.B;
3986                     if (! HAS_TEXT(text_node))
3987                         FIND_NEXT_IMPT(text_node);
3988                     if (HAS_TEXT(text_node)
3989                         && PL_regkind[OP(text_node)] != REF)
3990                     {
3991                         ST.c1 = (U8)*STRING(text_node);
3992                         ST.c2 =
3993                             (OP(text_node) == EXACTF || OP(text_node) == REFF)
3994                             ? PL_fold[ST.c1]
3995                             : (OP(text_node) == EXACTFL || OP(text_node) == REFFL)
3996                                 ? PL_fold_locale[ST.c1]
3997                                 : ST.c1;
3998                     }
3999                 }
4000             }
4001
4002             DEBUG_EXECUTE_r(
4003                 PerlIO_printf(Perl_debug_log,
4004                     "%*s  CURLYM trying tail with matches=%"IVdf"...\n",
4005                     (int)(REPORT_CODE_OFF+(PL_regindent*2)),
4006                     "", (IV)ST.count)
4007                 );
4008             if (ST.c1 != CHRTEST_VOID
4009                     && UCHARAT(PL_reginput) != ST.c1
4010                     && UCHARAT(PL_reginput) != ST.c2)
4011             {
4012                 /* simulate B failing */
4013                 state_num = CURLYM_B_fail;
4014                 goto reenter_switch;
4015             }
4016
4017             if (ST.me->flags) {
4018                 /* mark current A as captured */
4019                 I32 paren = ST.me->flags;
4020                 if (ST.count) {
4021                     PL_regstartp[paren]
4022                         = HOPc(PL_reginput, -ST.alen) - PL_bostr;
4023                     PL_regendp[paren] = PL_reginput - PL_bostr;
4024                 }
4025                 else
4026                     PL_regendp[paren] = -1;
4027             }
4028             PUSH_STATE_GOTO(CURLYM_B, ST.B); /* match B */
4029             /* NOTREACHED */
4030
4031         case CURLYM_B_fail: /* just failed to match a B */
4032             REGCP_UNWIND(ST.cp);
4033             if (ST.minmod) {
4034                 if (ST.count == ARG2(ST.me) /* max */)
4035                     sayNO;
4036                 goto curlym_do_A; /* try to match a further A */
4037             }
4038             /* backtrack one A */
4039             if (ST.count == ARG1(ST.me) /* min */)
4040                 sayNO;
4041             ST.count--;
4042             locinput = HOPc(locinput, -ST.alen);
4043             goto curlym_do_B; /* try to match B */
4044
4045 #undef ST
4046 #define ST st->u.curly
4047
4048 #define CURLY_SETPAREN(paren, success) \
4049     if (paren) { \
4050         if (success) { \
4051             PL_regstartp[paren] = HOPc(locinput, -1) - PL_bostr; \
4052             PL_regendp[paren] = locinput - PL_bostr; \
4053         } \
4054         else \
4055             PL_regendp[paren] = -1; \
4056     }
4057
4058         case STAR:              /*  /A*B/ where A is width 1 */
4059             ST.paren = 0;
4060             ST.min = 0;
4061             ST.max = REG_INFTY;
4062             scan = NEXTOPER(scan);
4063             goto repeat;
4064         case PLUS:              /*  /A+B/ where A is width 1 */
4065             ST.paren = 0;
4066             ST.min = 1;
4067             ST.max = REG_INFTY;
4068             scan = NEXTOPER(scan);
4069             goto repeat;
4070         case CURLYN:            /*  /(A){m,n}B/ where A is width 1 */
4071             ST.paren = scan->flags;     /* Which paren to set */
4072             if (ST.paren > PL_regsize)
4073                 PL_regsize = ST.paren;
4074             if (ST.paren > (I32)*PL_reglastparen)
4075                 *PL_reglastparen = ST.paren;
4076             ST.min = ARG1(scan);  /* min to match */
4077             ST.max = ARG2(scan);  /* max to match */
4078             scan = regnext(NEXTOPER(scan) + NODE_STEP_REGNODE);
4079             goto repeat;
4080         case CURLY:             /*  /A{m,n}B/ where A is width 1 */
4081             ST.paren = 0;
4082             ST.min = ARG1(scan);  /* min to match */
4083             ST.max = ARG2(scan);  /* max to match */
4084             scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
4085           repeat:
4086             /*
4087             * Lookahead to avoid useless match attempts
4088             * when we know what character comes next.
4089             *
4090             * Used to only do .*x and .*?x, but now it allows
4091             * for )'s, ('s and (?{ ... })'s to be in the way
4092             * of the quantifier and the EXACT-like node.  -- japhy
4093             */
4094
4095             if (ST.min > ST.max) /* XXX make this a compile-time check? */
4096                 sayNO;
4097             if (HAS_TEXT(next) || JUMPABLE(next)) {
4098                 U8 *s;
4099                 regnode *text_node = next;
4100
4101                 if (! HAS_TEXT(text_node)) 
4102                     FIND_NEXT_IMPT(text_node);
4103
4104                 if (! HAS_TEXT(text_node))
4105                     ST.c1 = ST.c2 = CHRTEST_VOID;
4106                 else {
4107                     if (PL_regkind[OP(text_node)] == REF) {
4108                         ST.c1 = ST.c2 = CHRTEST_VOID;
4109                         goto assume_ok_easy;
4110                     }
4111                     else
4112                         s = (U8*)STRING(text_node);
4113
4114                     if (!UTF) {
4115                         ST.c2 = ST.c1 = *s;
4116                         if (OP(text_node) == EXACTF || OP(text_node) == REFF)
4117                             ST.c2 = PL_fold[ST.c1];
4118                         else if (OP(text_node) == EXACTFL || OP(text_node) == REFFL)
4119                             ST.c2 = PL_fold_locale[ST.c1];
4120                     }
4121                     else { /* UTF */
4122                         if (OP(text_node) == EXACTF || OP(text_node) == REFF) {
4123                              STRLEN ulen1, ulen2;
4124                              U8 tmpbuf1[UTF8_MAXBYTES_CASE+1];
4125                              U8 tmpbuf2[UTF8_MAXBYTES_CASE+1];
4126
4127                              to_utf8_lower((U8*)s, tmpbuf1, &ulen1);
4128                              to_utf8_upper((U8*)s, tmpbuf2, &ulen2);
4129 #ifdef EBCDIC
4130                              ST.c1 = utf8n_to_uvchr(tmpbuf1, UTF8_MAXLEN, 0,
4131                                                     ckWARN(WARN_UTF8) ?
4132                                                     0 : UTF8_ALLOW_ANY);
4133                              ST.c2 = utf8n_to_uvchr(tmpbuf2, UTF8_MAXLEN, 0,
4134                                                     ckWARN(WARN_UTF8) ?
4135                                                     0 : UTF8_ALLOW_ANY);
4136 #else
4137                              ST.c1 = utf8n_to_uvuni(tmpbuf1, UTF8_MAXBYTES, 0,
4138                                                     uniflags);
4139                              ST.c2 = utf8n_to_uvuni(tmpbuf2, UTF8_MAXBYTES, 0,
4140                                                     uniflags);
4141 #endif
4142                         }
4143                         else {
4144                             ST.c2 = ST.c1 = utf8n_to_uvchr(s, UTF8_MAXBYTES, 0,
4145                                                      uniflags);
4146                         }
4147                     }
4148                 }
4149             }
4150             else
4151                 ST.c1 = ST.c2 = CHRTEST_VOID;
4152         assume_ok_easy:
4153
4154             ST.A = scan;
4155             ST.B = next;
4156             PL_reginput = locinput;
4157             if (st->minmod) {
4158                 st->minmod = 0;
4159                 if (ST.min && regrepeat(rex, ST.A, ST.min) < ST.min)
4160                     sayNO;
4161                 ST.count = ST.min;
4162                 locinput = PL_reginput;
4163                 REGCP_SET(ST.cp);
4164                 if (ST.c1 == CHRTEST_VOID)
4165                     goto curly_try_B_min;
4166
4167                 ST.oldloc = locinput;
4168
4169                 /* set ST.maxpos to the furthest point along the
4170                  * string that could possibly match */
4171                 if  (ST.max == REG_INFTY) {
4172                     ST.maxpos = PL_regeol - 1;
4173                     if (do_utf8)
4174                         while (UTF8_IS_CONTINUATION(*(U8*)ST.maxpos))
4175                             ST.maxpos--;
4176                 }
4177                 else if (do_utf8) {
4178                     int m = ST.max - ST.min;
4179                     for (ST.maxpos = locinput;
4180                          m >0 && ST.maxpos + UTF8SKIP(ST.maxpos) <= PL_regeol; m--)
4181                         ST.maxpos += UTF8SKIP(ST.maxpos);
4182                 }
4183                 else {
4184                     ST.maxpos = locinput + ST.max - ST.min;
4185                     if (ST.maxpos >= PL_regeol)
4186                         ST.maxpos = PL_regeol - 1;
4187                 }
4188                 goto curly_try_B_min_known;
4189
4190             }
4191             else {
4192                 ST.count = regrepeat(rex, ST.A, ST.max);
4193                 locinput = PL_reginput;
4194                 if (ST.count < ST.min)
4195                     sayNO;
4196                 if ((ST.count > ST.min)
4197                     && (PL_regkind[OP(ST.B)] == EOL) && (OP(ST.B) != MEOL))
4198                 {
4199                     /* A{m,n} must come at the end of the string, there's
4200                      * no point in backing off ... */
4201                     ST.min = ST.count;
4202                     /* ...except that $ and \Z can match before *and* after
4203                        newline at the end.  Consider "\n\n" =~ /\n+\Z\n/.
4204                        We may back off by one in this case. */
4205                     if (UCHARAT(PL_reginput - 1) == '\n' && OP(ST.B) != EOS)
4206                         ST.min--;
4207                 }
4208                 REGCP_SET(ST.cp);
4209                 goto curly_try_B_max;
4210             }
4211             /* NOTREACHED */
4212
4213
4214         case CURLY_B_min_known_fail:
4215             /* failed to find B in a non-greedy match where c1,c2 valid */
4216             if (ST.paren && ST.count)
4217                 PL_regendp[ST.paren] = -1;
4218
4219             PL_reginput = locinput;     /* Could be reset... */
4220             REGCP_UNWIND(ST.cp);
4221             /* Couldn't or didn't -- move forward. */
4222             ST.oldloc = locinput;
4223             if (do_utf8)
4224                 locinput += UTF8SKIP(locinput);
4225             else
4226                 locinput++;
4227             ST.count++;
4228           curly_try_B_min_known:
4229              /* find the next place where 'B' could work, then call B */
4230             {
4231                 int n;
4232                 if (do_utf8) {
4233                     n = (ST.oldloc == locinput) ? 0 : 1;
4234                     if (ST.c1 == ST.c2) {
4235                         STRLEN len;
4236                         /* set n to utf8_distance(oldloc, locinput) */
4237                         while (locinput <= ST.maxpos &&
4238                                utf8n_to_uvchr((U8*)locinput,
4239                                               UTF8_MAXBYTES, &len,
4240                                               uniflags) != (UV)ST.c1) {
4241                             locinput += len;
4242                             n++;
4243                         }
4244                     }
4245                     else {
4246                         /* set n to utf8_distance(oldloc, locinput) */
4247                         while (locinput <= ST.maxpos) {
4248                             STRLEN len;
4249                             const UV c = utf8n_to_uvchr((U8*)locinput,
4250                                                   UTF8_MAXBYTES, &len,
4251                                                   uniflags);
4252                             if (c == (UV)ST.c1 || c == (UV)ST.c2)
4253                                 break;
4254                             locinput += len;
4255                             n++;
4256                         }
4257                     }
4258                 }
4259                 else {
4260                     if (ST.c1 == ST.c2) {
4261                         while (locinput <= ST.maxpos &&
4262                                UCHARAT(locinput) != ST.c1)
4263                             locinput++;
4264                     }
4265                     else {
4266                         while (locinput <= ST.maxpos
4267                                && UCHARAT(locinput) != ST.c1
4268                                && UCHARAT(locinput) != ST.c2)
4269                             locinput++;
4270                     }
4271                     n = locinput - ST.oldloc;
4272                 }
4273                 if (locinput > ST.maxpos)
4274                     sayNO;
4275                 /* PL_reginput == oldloc now */
4276                 if (n) {
4277                     ST.count += n;
4278                     if (regrepeat(rex, ST.A, n) < n)
4279                         sayNO;
4280                 }
4281                 PL_reginput = locinput;
4282                 CURLY_SETPAREN(ST.paren, ST.count);
4283                 PUSH_STATE_GOTO(CURLY_B_min_known, ST.B);
4284             }
4285             /* NOTREACHED */
4286
4287
4288         case CURLY_B_min_fail:
4289             /* failed to find B in a non-greedy match where c1,c2 invalid */
4290             if (ST.paren && ST.count)
4291                 PL_regendp[ST.paren] = -1;
4292
4293             REGCP_UNWIND(ST.cp);
4294             /* failed -- move forward one */
4295             PL_reginput = locinput;
4296             if (regrepeat(rex, ST.A, 1)) {
4297                 ST.count++;
4298                 locinput = PL_reginput;
4299                 if (ST.count <= ST.max || (ST.max == REG_INFTY &&
4300                         ST.count > 0)) /* count overflow ? */
4301                 {
4302                   curly_try_B_min:
4303                     CURLY_SETPAREN(ST.paren, ST.count);
4304                     PUSH_STATE_GOTO(CURLY_B_min, ST.B);
4305                 }
4306             }
4307             sayNO;
4308             /* NOTREACHED */
4309
4310
4311         curly_try_B_max:
4312             /* a successful greedy match: now try to match B */
4313             {
4314                 UV c = 0;
4315                 if (ST.c1 != CHRTEST_VOID)
4316                     c = do_utf8 ? utf8n_to_uvchr((U8*)PL_reginput,
4317                                            UTF8_MAXBYTES, 0, uniflags)
4318                                 : (UV) UCHARAT(PL_reginput);
4319                 /* If it could work, try it. */
4320                 if (ST.c1 == CHRTEST_VOID || c == (UV)ST.c1 || c == (UV)ST.c2) {
4321                     CURLY_SETPAREN(ST.paren, ST.count);
4322                     PUSH_STATE_GOTO(CURLY_B_max, ST.B);
4323                     /* NOTREACHED */
4324                 }
4325             }
4326             /* FALL THROUGH */
4327         case CURLY_B_max_fail:
4328             /* failed to find B in a greedy match */
4329             if (ST.paren && ST.count)
4330                 PL_regendp[ST.paren] = -1;
4331
4332             REGCP_UNWIND(ST.cp);
4333             /*  back up. */
4334             if (--ST.count < ST.min)
4335                 sayNO;
4336             PL_reginput = locinput = HOPc(locinput, -1);
4337             goto curly_try_B_max;
4338
4339 #undef ST
4340
4341
4342         case END:
4343             if (locinput < reginfo->till) {
4344                 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
4345                                       "%sMatch possible, but length=%ld is smaller than requested=%ld, failing!%s\n",
4346                                       PL_colors[4],
4347                                       (long)(locinput - PL_reg_starttry),
4348                                       (long)(reginfo->till - PL_reg_starttry),
4349                                       PL_colors[5]));
4350                 sayNO_FINAL;            /* Cannot match: too short. */
4351             }
4352             PL_reginput = locinput;     /* put where regtry can find it */
4353             sayYES_FINAL;               /* Success! */
4354
4355         case SUCCEED: /* successful SUSPEND/UNLESSM/IFMATCH/CURLYM */
4356             DEBUG_EXECUTE_r(
4357             PerlIO_printf(Perl_debug_log,
4358                 "%*s  %ssubpattern success...%s\n",
4359                 REPORT_CODE_OFF+PL_regindent*2, "", PL_colors[4], PL_colors[5]));
4360             PL_reginput = locinput;     /* put where regtry can find it */
4361             sayYES_FINAL;               /* Success! */
4362
4363 #undef  ST
4364 #define ST st->u.ifmatch
4365
4366         case SUSPEND:   /* (?>A) */
4367             ST.wanted = 1;
4368             PL_reginput = locinput;
4369             goto do_ifmatch;    
4370
4371         case UNLESSM:   /* -ve lookaround: (?!A), or with flags, (?<!A) */
4372             ST.wanted = 0;
4373             goto ifmatch_trivial_fail_test;
4374
4375         case IFMATCH:   /* +ve lookaround: (?=A), or with flags, (?<=A) */
4376             ST.wanted = 1;
4377           ifmatch_trivial_fail_test:
4378             if (scan->flags) {
4379                 char * const s = HOPBACKc(locinput, scan->flags);
4380                 if (!s) {
4381                     /* trivial fail */
4382                     if (st->logical) {
4383                         st->logical = 0;
4384                         st->sw = 1 - (bool)ST.wanted;
4385                     }
4386                     else if (ST.wanted)
4387                         sayNO;
4388                     next = scan + ARG(scan);
4389                     if (next == scan)
4390                         next = NULL;
4391                     break;
4392                 }
4393                 PL_reginput = s;
4394             }
4395             else
4396                 PL_reginput = locinput;
4397
4398           do_ifmatch:
4399             ST.me = scan;
4400             /* execute body of (?...A) */
4401             PUSH_YES_STATE_GOTO(IFMATCH_A, NEXTOPER(NEXTOPER(scan)));
4402             /* NOTREACHED */
4403
4404         case IFMATCH_A_fail: /* body of (?...A) failed */
4405             ST.wanted = !ST.wanted;
4406             /* FALL THROUGH */
4407
4408         case IFMATCH_A: /* body of (?...A) succeeded */
4409             if (st->logical) {
4410                 st->logical = 0;
4411                 st->sw = (bool)ST.wanted;
4412             }
4413             else if (!ST.wanted)
4414                 sayNO;
4415
4416             if (OP(ST.me) == SUSPEND)
4417                 locinput = PL_reginput;
4418             else {
4419                 locinput = PL_reginput = st->locinput;
4420                 nextchr = UCHARAT(locinput);
4421             }
4422             scan = ST.me + ARG(ST.me);
4423             if (scan == ST.me)
4424                 scan = NULL;
4425             continue; /* execute B */
4426
4427 #undef ST
4428
4429         case LONGJMP:
4430             next = scan + ARG(scan);
4431             if (next == scan)
4432                 next = NULL;
4433             break;
4434         default:
4435             PerlIO_printf(Perl_error_log, "%"UVxf" %d\n",
4436                           PTR2UV(scan), OP(scan));
4437             Perl_croak(aTHX_ "regexp memory corruption");
4438         }
4439
4440         scan = next;
4441         continue;
4442         /* NOTREACHED */
4443
4444       push_yes_state:
4445         /* push a state that backtracks on success */
4446         st->u.yes.prev_yes_state = yes_state;
4447         yes_state = st;
4448         /* FALL THROUGH */
4449       push_state:
4450         /* push a new regex state, then continue at scan  */
4451         {
4452             regmatch_state *newst;
4453
4454             depth++;
4455             DEBUG_STATE_r(PerlIO_printf(Perl_debug_log,
4456                         "PUSH STATE(%d)\n", depth));
4457             st->locinput = locinput;
4458             newst = st+1; 
4459             if (newst >  SLAB_LAST(PL_regmatch_slab))
4460                 newst = S_push_slab(aTHX);
4461             PL_regmatch_state = newst;
4462             newst->cc = st->cc;
4463             /* XXX probably don't need to initialise these */
4464             newst->minmod = 0;
4465             newst->sw = 0;
4466             newst->logical = 0;
4467
4468
4469             locinput = PL_reginput;
4470             nextchr = UCHARAT(locinput);
4471             st = newst;
4472             continue;
4473             /* NOTREACHED */
4474         }
4475
4476         /* simulate recursively calling regmatch(), but without actually
4477          * recursing - ie save the current state on the heap rather than on
4478          * the stack, then re-enter the loop. This avoids complex regexes
4479          * blowing the processor stack */
4480
4481       start_recurse:
4482         {
4483             /* push new state */
4484             regmatch_state *oldst = st;
4485
4486             depth++;
4487             DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "PUSH RECURSE STATE(%d)\n", depth));
4488
4489             /* grab the next free state slot */
4490             st++;
4491             if (st >  SLAB_LAST(PL_regmatch_slab))
4492                 st = S_push_slab(aTHX);
4493             PL_regmatch_state = st;
4494
4495             oldst->next = next;
4496             oldst->n = n;
4497             oldst->locinput = locinput;
4498
4499             st->cc = oldst->cc;
4500             locinput = PL_reginput;
4501             nextchr = UCHARAT(locinput);
4502             st->minmod = 0;
4503             st->sw = 0;
4504             st->logical = 0;
4505             
4506 #ifdef DEBUGGING
4507             PL_regindent++;
4508 #endif
4509         }
4510     }
4511
4512
4513
4514     /*
4515     * We get here only if there's trouble -- normally "case END" is
4516     * the terminating point.
4517     */
4518     Perl_croak(aTHX_ "corrupted regexp pointers");
4519     /*NOTREACHED*/
4520     sayNO;
4521
4522 yes_final:
4523
4524     if (yes_state) {
4525         /* we have successfully completed a subexpression, but we must now
4526          * pop to the state marked by yes_state and continue from there */
4527         assert(st != yes_state);
4528         while (yes_state < SLAB_FIRST(PL_regmatch_slab)
4529             || yes_state > SLAB_LAST(PL_regmatch_slab))
4530         {
4531             /* not in this slab, pop slab */
4532             depth -= (st - SLAB_FIRST(PL_regmatch_slab) + 1);
4533             PL_regmatch_slab = PL_regmatch_slab->prev;
4534             st = SLAB_LAST(PL_regmatch_slab);
4535         }
4536         depth -= (st - yes_state);
4537         DEBUG_STATE_r(PerlIO_printf(Perl_debug_log, "POP STATES (%"UVuf"..%"UVuf")\n",
4538             (UV)(depth+1), (UV)(depth+(st - yes_state))));
4539         st = yes_state;
4540         yes_state = st->u.yes.prev_yes_state;
4541         PL_regmatch_state = st;
4542
4543         switch (st->resume_state) {
4544         case EVAL_A: 
4545         case IFMATCH_A:
4546         case CURLYM_A:
4547             state_num = st->resume_state;
4548             goto reenter_switch;
4549
4550         case CURLYM_B:
4551         case BRANCH_next:
4552         case TRIE_next:
4553         case CURLY_B_max:
4554         default:
4555             Perl_croak(aTHX_ "unexpected yes resume state");
4556         }
4557     }
4558
4559     DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch successful!%s\n",
4560                           PL_colors[4], PL_colors[5]));
4561 yes:
4562 #ifdef DEBUGGING
4563     PL_regindent--;
4564 #endif
4565
4566     result = 1;
4567     /* XXX this is duplicate(ish) code to that in the do_no section.
4568      * will disappear when REGFMATCH goes */
4569     if (depth) {
4570         /* restore previous state and re-enter */
4571         DEBUG_STATE_r(PerlIO_printf(Perl_debug_log, "POP STATE(%d)\n", depth));
4572         depth--;
4573         st--;
4574         if (st < SLAB_FIRST(PL_regmatch_slab)) {
4575             PL_regmatch_slab = PL_regmatch_slab->prev;
4576             st = SLAB_LAST(PL_regmatch_slab);
4577         }
4578         PL_regmatch_state = st;
4579         scan    = st->scan;
4580         next    = st->next;
4581         n       = st->n;
4582         locinput= st->locinput;
4583         nextchr = UCHARAT(locinput);
4584
4585         switch (st->resume_state) {
4586         case resume_CURLYX:
4587             goto resume_point_CURLYX;
4588         case resume_WHILEM1:
4589             goto resume_point_WHILEM1;
4590         case resume_WHILEM2:
4591             goto resume_point_WHILEM2;
4592         case resume_WHILEM3:
4593             goto resume_point_WHILEM3;
4594         case resume_WHILEM4:
4595             goto resume_point_WHILEM4;
4596         case resume_WHILEM5:
4597             goto resume_point_WHILEM5;
4598         case resume_WHILEM6:
4599             goto resume_point_WHILEM6;
4600
4601         case TRIE_next:
4602         case CURLYM_A:
4603         case CURLYM_B:
4604         case EVAL_A:
4605         case IFMATCH_A:
4606         case BRANCH_next:
4607         case CURLY_B_max:
4608         case CURLY_B_min:
4609         case CURLY_B_min_known:
4610             break;
4611
4612         default:
4613             Perl_croak(aTHX_ "regexp resume memory corruption");
4614         }
4615     }
4616     goto final_exit;
4617
4618 no:
4619     DEBUG_EXECUTE_r(
4620         PerlIO_printf(Perl_debug_log,
4621             "%*s  %sfailed...%s\n",
4622             REPORT_CODE_OFF+PL_regindent*2, "", 
4623             PL_colors[4], PL_colors[5])
4624         );
4625 no_final:
4626 do_no:
4627
4628 #ifdef DEBUGGING
4629     PL_regindent--;
4630 #endif
4631     result = 0;
4632
4633     if (depth) {
4634         /* there's a previous state to backtrack to */
4635         DEBUG_STATE_r(PerlIO_printf(Perl_debug_log, "POP STATE(%d)\n", depth));
4636         depth--;
4637         st--;
4638         if (st < SLAB_FIRST(PL_regmatch_slab)) {
4639             PL_regmatch_slab = PL_regmatch_slab->prev;
4640             st = SLAB_LAST(PL_regmatch_slab);
4641         }
4642         PL_regmatch_state = st;
4643         scan    = st->scan;
4644         next    = st->next;
4645         n       = st->n;
4646         locinput= st->locinput;
4647         nextchr = UCHARAT(locinput);
4648
4649         switch (st->resume_state) {
4650         case resume_CURLYX:
4651             goto resume_point_CURLYX;
4652         case resume_WHILEM1:
4653             goto resume_point_WHILEM1;
4654         case resume_WHILEM2:
4655             goto resume_point_WHILEM2;
4656         case resume_WHILEM3:
4657             goto resume_point_WHILEM3;
4658         case resume_WHILEM4:
4659             goto resume_point_WHILEM4;
4660         case resume_WHILEM5:
4661             goto resume_point_WHILEM5;
4662         case resume_WHILEM6:
4663             goto resume_point_WHILEM6;
4664
4665         case TRIE_next:
4666         case EVAL_A:
4667         case BRANCH_next:
4668         case CURLYM_A:
4669         case CURLYM_B:
4670         case IFMATCH_A:
4671         case CURLY_B_max:
4672         case CURLY_B_min:
4673         case CURLY_B_min_known:
4674             if (yes_state == st)
4675                 yes_state = st->u.yes.prev_yes_state;
4676             state_num = st->resume_state + 1; /* failure = success + 1 */
4677             goto reenter_switch;
4678
4679         default:
4680             Perl_croak(aTHX_ "regexp resume memory corruption");
4681         }
4682     }
4683
4684 final_exit:
4685
4686     /* restore original high-water mark */
4687     PL_regmatch_slab  = orig_slab;
4688     PL_regmatch_state = orig_state;
4689
4690     /* free all slabs above current one */
4691     if (orig_slab->next) {
4692         regmatch_slab *sl = orig_slab->next;
4693         orig_slab->next = NULL;
4694         while (sl) {
4695             regmatch_slab * const osl = sl;
4696             sl = sl->next;
4697             Safefree(osl);
4698         }
4699     }
4700
4701     return result;
4702
4703 }
4704
4705 /*
4706  - regrepeat - repeatedly match something simple, report how many
4707  */
4708 /*
4709  * [This routine now assumes that it will only match on things of length 1.
4710  * That was true before, but now we assume scan - reginput is the count,
4711  * rather than incrementing count on every character.  [Er, except utf8.]]
4712  */
4713 STATIC I32
4714 S_regrepeat(pTHX_ const regexp *prog, const regnode *p, I32 max)
4715 {
4716     dVAR;
4717     register char *scan;
4718     register I32 c;
4719     register char *loceol = PL_regeol;
4720     register I32 hardcount = 0;
4721     register bool do_utf8 = PL_reg_match_utf8;
4722
4723     scan = PL_reginput;
4724     if (max == REG_INFTY)
4725         max = I32_MAX;
4726     else if (max < loceol - scan)
4727         loceol = scan + max;
4728     switch (OP(p)) {
4729     case REG_ANY:
4730         if (do_utf8) {
4731             loceol = PL_regeol;
4732             while (scan < loceol && hardcount < max && *scan != '\n') {
4733                 scan += UTF8SKIP(scan);
4734                 hardcount++;
4735             }
4736         } else {
4737             while (scan < loceol && *scan != '\n')
4738                 scan++;
4739         }
4740         break;
4741     case SANY:
4742         if (do_utf8) {
4743             loceol = PL_regeol;
4744             while (scan < loceol && hardcount < max) {
4745                 scan += UTF8SKIP(scan);
4746                 hardcount++;
4747             }
4748         }
4749         else
4750             scan = loceol;
4751         break;
4752     case CANY:
4753         scan = loceol;
4754         break;
4755     case EXACT:         /* length of string is 1 */
4756         c = (U8)*STRING(p);
4757         while (scan < loceol && UCHARAT(scan) == c)
4758             scan++;
4759         break;
4760     case EXACTF:        /* length of string is 1 */
4761         c = (U8)*STRING(p);
4762         while (scan < loceol &&
4763                (UCHARAT(scan) == c || UCHARAT(scan) == PL_fold[c]))
4764             scan++;
4765         break;
4766     case EXACTFL:       /* length of string is 1 */
4767         PL_reg_flags |= RF_tainted;
4768         c = (U8)*STRING(p);
4769         while (scan < loceol &&
4770                (UCHARAT(scan) == c || UCHARAT(scan) == PL_fold_locale[c]))
4771             scan++;
4772         break;
4773     case ANYOF:
4774         if (do_utf8) {
4775             loceol = PL_regeol;
4776             while (hardcount < max && scan < loceol &&
4777                    reginclass(prog, p, (U8*)scan, 0, do_utf8)) {
4778                 scan += UTF8SKIP(scan);
4779                 hardcount++;
4780             }
4781         } else {
4782             while (scan < loceol && REGINCLASS(prog, p, (U8*)scan))
4783                 scan++;
4784         }
4785         break;
4786     case ALNUM:
4787         if (do_utf8) {
4788             loceol = PL_regeol;
4789             LOAD_UTF8_CHARCLASS_ALNUM();
4790             while (hardcount < max && scan < loceol &&
4791                    swash_fetch(PL_utf8_alnum, (U8*)scan, do_utf8)) {
4792                 scan += UTF8SKIP(scan);
4793                 hardcount++;
4794             }
4795         } else {
4796             while (scan < loceol && isALNUM(*scan))
4797                 scan++;
4798         }
4799         break;
4800     case ALNUML:
4801         PL_reg_flags |= RF_tainted;
4802         if (do_utf8) {
4803             loceol = PL_regeol;
4804             while (hardcount < max && scan < loceol &&
4805                    isALNUM_LC_utf8((U8*)scan)) {
4806                 scan += UTF8SKIP(scan);
4807                 hardcount++;
4808             }
4809         } else {
4810             while (scan < loceol && isALNUM_LC(*scan))
4811                 scan++;
4812         }
4813         break;
4814     case NALNUM:
4815         if (do_utf8) {
4816             loceol = PL_regeol;
4817             LOAD_UTF8_CHARCLASS_ALNUM();
4818             while (hardcount < max && scan < loceol &&
4819                    !swash_fetch(PL_utf8_alnum, (U8*)scan, do_utf8)) {
4820                 scan += UTF8SKIP(scan);
4821                 hardcount++;
4822             }
4823         } else {
4824             while (scan < loceol && !isALNUM(*scan))
4825                 scan++;
4826         }
4827         break;
4828     case NALNUML:
4829         PL_reg_flags |= RF_tainted;
4830         if (do_utf8) {
4831             loceol = PL_regeol;
4832             while (hardcount < max && scan < loceol &&
4833                    !isALNUM_LC_utf8((U8*)scan)) {
4834                 scan += UTF8SKIP(scan);
4835                 hardcount++;
4836             }
4837         } else {
4838             while (scan < loceol && !isALNUM_LC(*scan))
4839                 scan++;
4840         }
4841         break;
4842     case SPACE:
4843         if (do_utf8) {
4844             loceol = PL_regeol;
4845             LOAD_UTF8_CHARCLASS_SPACE();
4846             while (hardcount < max && scan < loceol &&
4847                    (*scan == ' ' ||
4848                     swash_fetch(PL_utf8_space,(U8*)scan, do_utf8))) {
4849                 scan += UTF8SKIP(scan);
4850                 hardcount++;
4851             }
4852         } else {
4853             while (scan < loceol && isSPACE(*scan))
4854                 scan++;
4855         }
4856         break;
4857     case SPACEL:
4858         PL_reg_flags |= RF_tainted;
4859         if (do_utf8) {
4860             loceol = PL_regeol;
4861             while (hardcount < max && scan < loceol &&
4862                    (*scan == ' ' || isSPACE_LC_utf8((U8*)scan))) {
4863                 scan += UTF8SKIP(scan);
4864                 hardcount++;
4865             }
4866         } else {
4867             while (scan < loceol && isSPACE_LC(*scan))
4868                 scan++;
4869         }
4870         break;
4871     case NSPACE:
4872         if (do_utf8) {
4873             loceol = PL_regeol;
4874             LOAD_UTF8_CHARCLASS_SPACE();
4875             while (hardcount < max && scan < loceol &&
4876                    !(*scan == ' ' ||
4877                      swash_fetch(PL_utf8_space,(U8*)scan, do_utf8))) {
4878                 scan += UTF8SKIP(scan);
4879                 hardcount++;
4880             }
4881         } else {
4882             while (scan < loceol && !isSPACE(*scan))
4883                 scan++;
4884             break;
4885         }
4886     case NSPACEL:
4887         PL_reg_flags |= RF_tainted;
4888         if (do_utf8) {
4889             loceol = PL_regeol;
4890             while (hardcount < max && scan < loceol &&
4891                    !(*scan == ' ' || isSPACE_LC_utf8((U8*)scan))) {
4892                 scan += UTF8SKIP(scan);
4893                 hardcount++;
4894             }
4895         } else {
4896             while (scan < loceol && !isSPACE_LC(*scan))
4897                 scan++;
4898         }
4899         break;
4900     case DIGIT:
4901         if (do_utf8) {
4902             loceol = PL_regeol;
4903             LOAD_UTF8_CHARCLASS_DIGIT();
4904             while (hardcount < max && scan < loceol &&
4905                    swash_fetch(PL_utf8_digit, (U8*)scan, do_utf8)) {
4906                 scan += UTF8SKIP(scan);
4907                 hardcount++;
4908             }
4909         } else {
4910             while (scan < loceol && isDIGIT(*scan))
4911                 scan++;
4912         }
4913         break;
4914     case NDIGIT:
4915         if (do_utf8) {
4916             loceol = PL_regeol;
4917             LOAD_UTF8_CHARCLASS_DIGIT();
4918             while (hardcount < max && scan < loceol &&
4919                    !swash_fetch(PL_utf8_digit, (U8*)scan, do_utf8)) {
4920                 scan += UTF8SKIP(scan);
4921                 hardcount++;
4922             }
4923         } else {
4924             while (scan < loceol && !isDIGIT(*scan))
4925                 scan++;
4926         }
4927         break;
4928     default:            /* Called on something of 0 width. */
4929         break;          /* So match right here or not at all. */
4930     }
4931
4932     if (hardcount)
4933         c = hardcount;
4934     else
4935         c = scan - PL_reginput;
4936     PL_reginput = scan;
4937
4938     DEBUG_r({
4939         GET_RE_DEBUG_FLAGS_DECL;
4940         DEBUG_EXECUTE_r({
4941             SV * const prop = sv_newmortal();
4942             regprop(prog, prop, p);
4943             PerlIO_printf(Perl_debug_log,
4944                         "%*s  %s can match %"IVdf" times out of %"IVdf"...\n",
4945                         REPORT_CODE_OFF+1, "", SvPVX_const(prop),(IV)c,(IV)max);
4946         });
4947     });
4948
4949     return(c);
4950 }
4951
4952
4953 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
4954 /*
4955 - regclass_swash - prepare the utf8 swash
4956 */
4957
4958 SV *
4959 Perl_regclass_swash(pTHX_ const regexp *prog, register const regnode* node, bool doinit, SV** listsvp, SV **altsvp)
4960 {
4961     dVAR;
4962     SV *sw  = NULL;
4963     SV *si  = NULL;
4964     SV *alt = NULL;
4965     const struct reg_data * const data = prog ? prog->data : NULL;
4966
4967     if (data && data->count) {
4968         const U32 n = ARG(node);
4969
4970         if (data->what[n] == 's') {
4971             SV * const rv = (SV*)data->data[n];
4972             AV * const av = (AV*)SvRV((SV*)rv);
4973             SV **const ary = AvARRAY(av);
4974             SV **a, **b;
4975         
4976             /* See the end of regcomp.c:S_regclass() for
4977              * documentation of these array elements. */
4978
4979             si = *ary;
4980             a  = SvROK(ary[1]) ? &ary[1] : 0;
4981             b  = SvTYPE(ary[2]) == SVt_PVAV ? &ary[2] : 0;
4982
4983             if (a)
4984                 sw = *a;
4985             else if (si && doinit) {
4986                 sw = swash_init("utf8", "", si, 1, 0);
4987                 (void)av_store(av, 1, sw);
4988             }
4989             if (b)
4990                 alt = *b;
4991         }
4992     }
4993         
4994     if (listsvp)
4995         *listsvp = si;
4996     if (altsvp)
4997         *altsvp  = alt;
4998
4999     return sw;
5000 }
5001 #endif
5002
5003 /*
5004  - reginclass - determine if a character falls into a character class
5005  
5006   The n is the ANYOF regnode, the p is the target string, lenp
5007   is pointer to the maximum length of how far to go in the p
5008   (if the lenp is zero, UTF8SKIP(p) is used),
5009   do_utf8 tells whether the target string is in UTF-8.
5010
5011  */
5012
5013 STATIC bool
5014 S_reginclass(pTHX_ const regexp *prog, register const regnode *n, register const U8* p, STRLEN* lenp, register bool do_utf8)
5015 {
5016     dVAR;
5017     const char flags = ANYOF_FLAGS(n);
5018     bool match = FALSE;
5019     UV c = *p;
5020     STRLEN len = 0;
5021     STRLEN plen;
5022
5023     if (do_utf8 && !UTF8_IS_INVARIANT(c)) {
5024         c = utf8n_to_uvchr(p, UTF8_MAXBYTES, &len,
5025                 (UTF8_ALLOW_DEFAULT & UTF8_ALLOW_ANYUV) | UTF8_CHECK_ONLY);
5026                 /* see [perl #37836] for UTF8_ALLOW_ANYUV */
5027         if (len == (STRLEN)-1) 
5028             Perl_croak(aTHX_ "Malformed UTF-8 character (fatal)");
5029     }
5030
5031     plen = lenp ? *lenp : UNISKIP(NATIVE_TO_UNI(c));
5032     if (do_utf8 || (flags & ANYOF_UNICODE)) {
5033         if (lenp)
5034             *lenp = 0;
5035         if (do_utf8 && !ANYOF_RUNTIME(n)) {
5036             if (len != (STRLEN)-1 && c < 256 && ANYOF_BITMAP_TEST(n, c))
5037                 match = TRUE;
5038         }
5039         if (!match && do_utf8 && (flags & ANYOF_UNICODE_ALL) && c >= 256)
5040             match = TRUE;
5041         if (!match) {
5042             AV *av;
5043             SV * const sw = regclass_swash(prog, n, TRUE, 0, (SV**)&av);
5044         
5045             if (sw) {
5046                 if (swash_fetch(sw, p, do_utf8))
5047                     match = TRUE;
5048                 else if (flags & ANYOF_FOLD) {
5049                     if (!match && lenp && av) {
5050                         I32 i;
5051                         for (i = 0; i <= av_len(av); i++) {
5052                             SV* const sv = *av_fetch(av, i, FALSE);
5053                             STRLEN len;
5054                             const char * const s = SvPV_const(sv, len);
5055                         
5056                             if (len <= plen && memEQ(s, (char*)p, len)) {
5057                                 *lenp = len;
5058                                 match = TRUE;
5059                                 break;
5060                             }
5061                         }
5062                     }
5063                     if (!match) {
5064                         U8 tmpbuf[UTF8_MAXBYTES_CASE+1];
5065                         STRLEN tmplen;
5066
5067                         to_utf8_fold(p, tmpbuf, &tmplen);
5068                         if (swash_fetch(sw, tmpbuf, do_utf8))
5069                             match = TRUE;
5070                     }
5071                 }
5072             }
5073         }
5074         if (match && lenp && *lenp == 0)
5075             *lenp = UNISKIP(NATIVE_TO_UNI(c));
5076     }
5077     if (!match && c < 256) {
5078         if (ANYOF_BITMAP_TEST(n, c))
5079             match = TRUE;
5080         else if (flags & ANYOF_FOLD) {
5081             U8 f;
5082
5083             if (flags & ANYOF_LOCALE) {
5084                 PL_reg_flags |= RF_tainted;
5085                 f = PL_fold_locale[c];
5086             }
5087             else
5088                 f = PL_fold[c];
5089             if (f != c && ANYOF_BITMAP_TEST(n, f))
5090                 match = TRUE;
5091         }
5092         
5093         if (!match && (flags & ANYOF_CLASS)) {
5094             PL_reg_flags |= RF_tainted;
5095             if (
5096                 (ANYOF_CLASS_TEST(n, ANYOF_ALNUM)   &&  isALNUM_LC(c))  ||
5097                 (ANYOF_CLASS_TEST(n, ANYOF_NALNUM)  && !isALNUM_LC(c))  ||
5098                 (ANYOF_CLASS_TEST(n, ANYOF_SPACE)   &&  isSPACE_LC(c))  ||
5099                 (ANYOF_CLASS_TEST(n, ANYOF_NSPACE)  && !isSPACE_LC(c))  ||
5100                 (ANYOF_CLASS_TEST(n, ANYOF_DIGIT)   &&  isDIGIT_LC(c))  ||
5101                 (ANYOF_CLASS_TEST(n, ANYOF_NDIGIT)  && !isDIGIT_LC(c))  ||
5102                 (ANYOF_CLASS_TEST(n, ANYOF_ALNUMC)  &&  isALNUMC_LC(c)) ||
5103                 (ANYOF_CLASS_TEST(n, ANYOF_NALNUMC) && !isALNUMC_LC(c)) ||
5104                 (ANYOF_CLASS_TEST(n, ANYOF_ALPHA)   &&  isALPHA_LC(c))  ||
5105                 (ANYOF_CLASS_TEST(n, ANYOF_NALPHA)  && !isALPHA_LC(c))  ||
5106                 (ANYOF_CLASS_TEST(n, ANYOF_ASCII)   &&  isASCII(c))     ||
5107                 (ANYOF_CLASS_TEST(n, ANYOF_NASCII)  && !isASCII(c))     ||
5108                 (ANYOF_CLASS_TEST(n, ANYOF_CNTRL)   &&  isCNTRL_LC(c))  ||
5109                 (ANYOF_CLASS_TEST(n, ANYOF_NCNTRL)  && !isCNTRL_LC(c))  ||
5110                 (ANYOF_CLASS_TEST(n, ANYOF_GRAPH)   &&  isGRAPH_LC(c))  ||
5111                 (ANYOF_CLASS_TEST(n, ANYOF_NGRAPH)  && !isGRAPH_LC(c))  ||
5112                 (ANYOF_CLASS_TEST(n, ANYOF_LOWER)   &&  isLOWER_LC(c))  ||
5113                 (ANYOF_CLASS_TEST(n, ANYOF_NLOWER)  && !isLOWER_LC(c))  ||
5114                 (ANYOF_CLASS_TEST(n, ANYOF_PRINT)   &&  isPRINT_LC(c))  ||
5115                 (ANYOF_CLASS_TEST(n, ANYOF_NPRINT)  && !isPRINT_LC(c))  ||
5116                 (ANYOF_CLASS_TEST(n, ANYOF_PUNCT)   &&  isPUNCT_LC(c))  ||
5117                 (ANYOF_CLASS_TEST(n, ANYOF_NPUNCT)  && !isPUNCT_LC(c))  ||
5118                 (ANYOF_CLASS_TEST(n, ANYOF_UPPER)   &&  isUPPER_LC(c))  ||
5119                 (ANYOF_CLASS_TEST(n, ANYOF_NUPPER)  && !isUPPER_LC(c))  ||
5120                 (ANYOF_CLASS_TEST(n, ANYOF_XDIGIT)  &&  isXDIGIT(c))    ||
5121                 (ANYOF_CLASS_TEST(n, ANYOF_NXDIGIT) && !isXDIGIT(c))    ||
5122                 (ANYOF_CLASS_TEST(n, ANYOF_PSXSPC)  &&  isPSXSPC(c))    ||
5123                 (ANYOF_CLASS_TEST(n, ANYOF_NPSXSPC) && !isPSXSPC(c))    ||
5124                 (ANYOF_CLASS_TEST(n, ANYOF_BLANK)   &&  isBLANK(c))     ||
5125                 (ANYOF_CLASS_TEST(n, ANYOF_NBLANK)  && !isBLANK(c))
5126                 ) /* How's that for a conditional? */
5127             {
5128                 match = TRUE;
5129             }
5130         }
5131     }
5132
5133     return (flags & ANYOF_INVERT) ? !match : match;
5134 }
5135
5136 STATIC U8 *
5137 S_reghop3(U8 *s, I32 off, const U8* lim)
5138 {
5139     dVAR;
5140     if (off >= 0) {
5141         while (off-- && s < lim) {
5142             /* XXX could check well-formedness here */
5143             s += UTF8SKIP(s);
5144         }
5145     }
5146     else {
5147         while (off++ && s > lim) {
5148             s--;
5149             if (UTF8_IS_CONTINUED(*s)) {
5150                 while (s > lim && UTF8_IS_CONTINUATION(*s))
5151                     s--;
5152             }
5153             /* XXX could check well-formedness here */
5154         }
5155     }
5156     return s;
5157 }
5158
5159 STATIC U8 *
5160 S_reghop4(U8 *s, I32 off, const U8* llim, const U8* rlim)
5161 {
5162     dVAR;
5163     if (off >= 0) {
5164         while (off-- && s < rlim) {
5165             /* XXX could check well-formedness here */
5166             s += UTF8SKIP(s);
5167         }
5168     }
5169     else {
5170         while (off++ && s > llim) {
5171             s--;
5172             if (UTF8_IS_CONTINUED(*s)) {
5173                 while (s > llim && UTF8_IS_CONTINUATION(*s))
5174                     s--;
5175             }
5176             /* XXX could check well-formedness here */
5177         }
5178     }
5179     return s;
5180 }
5181
5182
5183 STATIC U8 *
5184 S_reghopmaybe3(U8* s, I32 off, const U8* lim)
5185 {
5186     dVAR;
5187     if (off >= 0) {
5188         while (off-- && s < lim) {
5189             /* XXX could check well-formedness here */
5190             s += UTF8SKIP(s);
5191         }
5192         if (off >= 0)
5193             return NULL;
5194     }
5195     else {
5196         while (off++ && s > lim) {
5197             s--;
5198             if (UTF8_IS_CONTINUED(*s)) {
5199                 while (s > lim && UTF8_IS_CONTINUATION(*s))
5200                     s--;
5201             }
5202             /* XXX could check well-formedness here */
5203         }
5204         if (off <= 0)
5205             return NULL;
5206     }
5207     return s;
5208 }
5209
5210 static void
5211 restore_pos(pTHX_ void *arg)
5212 {
5213     dVAR;
5214     regexp * const rex = (regexp *)arg;
5215     if (PL_reg_eval_set) {
5216         if (PL_reg_oldsaved) {
5217             rex->subbeg = PL_reg_oldsaved;
5218             rex->sublen = PL_reg_oldsavedlen;
5219 #ifdef PERL_OLD_COPY_ON_WRITE
5220             rex->saved_copy = PL_nrs;
5221 #endif
5222             RX_MATCH_COPIED_on(rex);
5223         }
5224         PL_reg_magic->mg_len = PL_reg_oldpos;
5225         PL_reg_eval_set = 0;
5226         PL_curpm = PL_reg_oldcurpm;
5227     }   
5228 }
5229
5230 STATIC void
5231 S_to_utf8_substr(pTHX_ register regexp *prog)
5232 {
5233     if (prog->float_substr && !prog->float_utf8) {
5234         SV* const sv = newSVsv(prog->float_substr);
5235         prog->float_utf8 = sv;
5236         sv_utf8_upgrade(sv);
5237         if (SvTAIL(prog->float_substr))
5238             SvTAIL_on(sv);
5239         if (prog->float_substr == prog->check_substr)
5240             prog->check_utf8 = sv;
5241     }
5242     if (prog->anchored_substr && !prog->anchored_utf8) {
5243         SV* const sv = newSVsv(prog->anchored_substr);
5244         prog->anchored_utf8 = sv;
5245         sv_utf8_upgrade(sv);
5246         if (SvTAIL(prog->anchored_substr))
5247             SvTAIL_on(sv);
5248         if (prog->anchored_substr == prog->check_substr)
5249             prog->check_utf8 = sv;
5250     }
5251 }
5252
5253 STATIC void
5254 S_to_byte_substr(pTHX_ register regexp *prog)
5255 {
5256     dVAR;
5257     if (prog->float_utf8 && !prog->float_substr) {
5258         SV* sv = newSVsv(prog->float_utf8);
5259         prog->float_substr = sv;
5260         if (sv_utf8_downgrade(sv, TRUE)) {
5261             if (SvTAIL(prog->float_utf8))
5262                 SvTAIL_on(sv);
5263         } else {
5264             SvREFCNT_dec(sv);
5265             prog->float_substr = sv = &PL_sv_undef;
5266         }
5267         if (prog->float_utf8 == prog->check_utf8)
5268             prog->check_substr = sv;
5269     }
5270     if (prog->anchored_utf8 && !prog->anchored_substr) {
5271         SV* sv = newSVsv(prog->anchored_utf8);
5272         prog->anchored_substr = sv;
5273         if (sv_utf8_downgrade(sv, TRUE)) {
5274             if (SvTAIL(prog->anchored_utf8))
5275                 SvTAIL_on(sv);
5276         } else {
5277             SvREFCNT_dec(sv);
5278             prog->anchored_substr = sv = &PL_sv_undef;
5279         }
5280         if (prog->anchored_utf8 == prog->check_utf8)
5281             prog->check_substr = sv;
5282     }
5283 }
5284
5285 /*
5286  * Local variables:
5287  * c-indentation-style: bsd
5288  * c-basic-offset: 4
5289  * indent-tabs-mode: t
5290  * End:
5291  *
5292  * ex: set ts=8 sts=4 sw=4 noet:
5293  */