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