5 * One Ring to rule them all, One Ring to find them
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"]
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.
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.
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!
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.
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.
36 #ifdef PERL_EXT_RE_BUILD
41 * pregcomp and pregexec -- regsub and regerror are not used in perl
43 * Copyright (c) 1986 by University of Toronto.
44 * Written by Henry Spencer. Not derived from licensed software.
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:
50 * 1. The author is not responsible for the consequences of use of
51 * this software, no matter how awful, even if they arise
54 * 2. The origin of this software must not be misrepresented, either
55 * by explicit claim or by omission.
57 * 3. Altered versions must be plainly marked as such, and must not
58 * be misrepresented as being the original software.
60 **** Alterations to Henry's code are...
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
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.
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.
74 #define PERL_IN_REGEXEC_C
78 #ifdef PERL_IN_XSUB_RE
84 #define RF_tainted 1 /* tainted information used? */
85 #define RF_warned 2 /* warned about big count? */
87 #define RF_utf8 8 /* Pattern contains multibyte chars? */
89 #define UTF ((PL_reg_flags & RF_utf8) != 0)
91 #define RS_init 1 /* eval environment created */
92 #define RS_set 2 /* replsv value is set */
98 #define REGINCLASS(prog,p,c) (ANYOF_FLAGS(p) ? reginclass(prog,p,c,0,0) : ANYOF_BITMAP_TEST(p,*(c)))
104 #define CHR_SVLEN(sv) (do_utf8 ? sv_len_utf8(sv) : SvCUR(sv))
105 #define CHR_DIST(a,b) (PL_reg_match_utf8 ? utf8_distance(a,b) : a - b)
107 #define HOPc(pos,off) \
108 (char *)(PL_reg_match_utf8 \
109 ? reghop3((U8*)pos, off, (U8*)(off >= 0 ? PL_regeol : PL_bostr)) \
111 #define HOPBACKc(pos, off) \
112 (char*)(PL_reg_match_utf8\
113 ? reghopmaybe3((U8*)pos, -off, (U8*)PL_bostr) \
114 : (pos - off >= PL_bostr) \
118 #define HOP3(pos,off,lim) (PL_reg_match_utf8 ? reghop3((U8*)(pos), off, (U8*)(lim)) : (U8*)(pos + off))
119 #define HOP3c(pos,off,lim) ((char*)HOP3(pos,off,lim))
121 /* these are unrolled below in the CCC_TRY_XXX defined */
122 #define LOAD_UTF8_CHARCLASS(class,str) STMT_START { \
123 if (!CAT2(PL_utf8_,class)) { bool ok; ENTER; save_re_context(); ok=CAT2(is_utf8_,class)((const U8*)str); assert(ok); LEAVE; } } STMT_END
124 #define LOAD_UTF8_CHARCLASS_ALNUM() LOAD_UTF8_CHARCLASS(alnum,"a")
125 #define LOAD_UTF8_CHARCLASS_DIGIT() LOAD_UTF8_CHARCLASS(digit,"0")
126 #define LOAD_UTF8_CHARCLASS_SPACE() LOAD_UTF8_CHARCLASS(space," ")
127 #define LOAD_UTF8_CHARCLASS_MARK() LOAD_UTF8_CHARCLASS(mark, "\xcd\x86")
131 We dont use PERL_LEGACY_UNICODE_CHARCLASS_MAPPINGS as the direct test
132 so that it is possible to override the option here without having to
133 rebuild the entire core. as we are required to do if we change regcomp.h
134 which is where PERL_LEGACY_UNICODE_CHARCLASS_MAPPINGS is defined.
136 #if PERL_LEGACY_UNICODE_CHARCLASS_MAPPINGS
137 #define BROKEN_UNICODE_CHARCLASS_MAPPINGS
140 #ifdef BROKEN_UNICODE_CHARCLASS_MAPPINGS
141 #define LOAD_UTF8_CHARCLASS_PERL_WORD() LOAD_UTF8_CHARCLASS_ALNUM()
142 #define LOAD_UTF8_CHARCLASS_PERL_SPACE() LOAD_UTF8_CHARCLASS_SPACE()
143 #define LOAD_UTF8_CHARCLASS_POSIX_DIGIT() LOAD_UTF8_CHARCLASS_DIGIT()
144 #define RE_utf8_perl_word PL_utf8_alnum
145 #define RE_utf8_perl_space PL_utf8_space
146 #define RE_utf8_posix_digit PL_utf8_digit
147 #define perl_word alnum
148 #define perl_space space
149 #define posix_digit digit
151 #define LOAD_UTF8_CHARCLASS_PERL_WORD() LOAD_UTF8_CHARCLASS(perl_word,"a")
152 #define LOAD_UTF8_CHARCLASS_PERL_SPACE() LOAD_UTF8_CHARCLASS(perl_space," ")
153 #define LOAD_UTF8_CHARCLASS_POSIX_DIGIT() LOAD_UTF8_CHARCLASS(posix_digit,"0")
154 #define RE_utf8_perl_word PL_utf8_perl_word
155 #define RE_utf8_perl_space PL_utf8_perl_space
156 #define RE_utf8_posix_digit PL_utf8_posix_digit
160 #define CCC_TRY_AFF(NAME,NAMEL,CLASS,STR,LCFUNC_utf8,FUNC,LCFUNC) \
162 PL_reg_flags |= RF_tainted; \
167 if (do_utf8 && UTF8_IS_CONTINUED(nextchr)) { \
168 if (!CAT2(PL_utf8_,CLASS)) { \
172 ok=CAT2(is_utf8_,CLASS)((const U8*)STR); \
176 if (!(OP(scan) == NAME \
177 ? (bool)swash_fetch(CAT2(PL_utf8_,CLASS), (U8*)locinput, do_utf8) \
178 : LCFUNC_utf8((U8*)locinput))) \
182 locinput += PL_utf8skip[nextchr]; \
183 nextchr = UCHARAT(locinput); \
186 if (!(OP(scan) == NAME ? FUNC(nextchr) : LCFUNC(nextchr))) \
188 nextchr = UCHARAT(++locinput); \
191 #define CCC_TRY_NEG(NAME,NAMEL,CLASS,STR,LCFUNC_utf8,FUNC,LCFUNC) \
193 PL_reg_flags |= RF_tainted; \
196 if (!nextchr && locinput >= PL_regeol) \
198 if (do_utf8 && UTF8_IS_CONTINUED(nextchr)) { \
199 if (!CAT2(PL_utf8_,CLASS)) { \
203 ok=CAT2(is_utf8_,CLASS)((const U8*)STR); \
207 if ((OP(scan) == NAME \
208 ? (bool)swash_fetch(CAT2(PL_utf8_,CLASS), (U8*)locinput, do_utf8) \
209 : LCFUNC_utf8((U8*)locinput))) \
213 locinput += PL_utf8skip[nextchr]; \
214 nextchr = UCHARAT(locinput); \
217 if ((OP(scan) == NAME ? FUNC(nextchr) : LCFUNC(nextchr))) \
219 nextchr = UCHARAT(++locinput); \
226 /* TODO: Combine JUMPABLE and HAS_TEXT to cache OP(rn) */
228 /* for use after a quantifier and before an EXACT-like node -- japhy */
229 /* it would be nice to rework regcomp.sym to generate this stuff. sigh */
230 #define JUMPABLE(rn) ( \
232 (OP(rn) == CLOSE && (!cur_eval || cur_eval->u.eval.close_paren != ARG(rn))) || \
234 OP(rn) == SUSPEND || OP(rn) == IFMATCH || \
235 OP(rn) == PLUS || OP(rn) == MINMOD || \
236 OP(rn) == KEEPS || (PL_regkind[OP(rn)] == VERB) || \
237 (PL_regkind[OP(rn)] == CURLY && ARG1(rn) > 0) \
239 #define IS_EXACT(rn) (PL_regkind[OP(rn)] == EXACT)
241 #define HAS_TEXT(rn) ( IS_EXACT(rn) || PL_regkind[OP(rn)] == REF )
244 /* Currently these are only used when PL_regkind[OP(rn)] == EXACT so
245 we don't need this definition. */
246 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==REF || OP(rn)==NREF )
247 #define IS_TEXTF(rn) ( OP(rn)==EXACTF || OP(rn)==REFF || OP(rn)==NREFF )
248 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL || OP(rn)==REFFL || OP(rn)==NREFFL )
251 /* ... so we use this as its faster. */
252 #define IS_TEXT(rn) ( OP(rn)==EXACT )
253 #define IS_TEXTF(rn) ( OP(rn)==EXACTF )
254 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL )
259 Search for mandatory following text node; for lookahead, the text must
260 follow but for lookbehind (rn->flags != 0) we skip to the next step.
262 #define FIND_NEXT_IMPT(rn) STMT_START { \
263 while (JUMPABLE(rn)) { \
264 const OPCODE type = OP(rn); \
265 if (type == SUSPEND || PL_regkind[type] == CURLY) \
266 rn = NEXTOPER(NEXTOPER(rn)); \
267 else if (type == PLUS) \
269 else if (type == IFMATCH) \
270 rn = (rn->flags == 0) ? NEXTOPER(NEXTOPER(rn)) : rn + ARG(rn); \
271 else rn += NEXT_OFF(rn); \
276 static void restore_pos(pTHX_ void *arg);
279 S_regcppush(pTHX_ I32 parenfloor)
282 const int retval = PL_savestack_ix;
283 #define REGCP_PAREN_ELEMS 4
284 const int paren_elems_to_push = (PL_regsize - parenfloor) * REGCP_PAREN_ELEMS;
286 GET_RE_DEBUG_FLAGS_DECL;
288 if (paren_elems_to_push < 0)
289 Perl_croak(aTHX_ "panic: paren_elems_to_push < 0");
291 #define REGCP_OTHER_ELEMS 7
292 SSGROW(paren_elems_to_push + REGCP_OTHER_ELEMS);
294 for (p = PL_regsize; p > parenfloor; p--) {
295 /* REGCP_PARENS_ELEMS are pushed per pairs of parentheses. */
296 SSPUSHINT(PL_regoffs[p].end);
297 SSPUSHINT(PL_regoffs[p].start);
298 SSPUSHPTR(PL_reg_start_tmp[p]);
300 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
301 " saving \\%"UVuf" %"IVdf"(%"IVdf")..%"IVdf"\n",
302 (UV)p, (IV)PL_regoffs[p].start,
303 (IV)(PL_reg_start_tmp[p] - PL_bostr),
304 (IV)PL_regoffs[p].end
307 /* REGCP_OTHER_ELEMS are pushed in any case, parentheses or no. */
308 SSPUSHPTR(PL_regoffs);
309 SSPUSHINT(PL_regsize);
310 SSPUSHINT(*PL_reglastparen);
311 SSPUSHINT(*PL_reglastcloseparen);
312 SSPUSHPTR(PL_reginput);
313 #define REGCP_FRAME_ELEMS 2
314 /* REGCP_FRAME_ELEMS are part of the REGCP_OTHER_ELEMS and
315 * are needed for the regexp context stack bookkeeping. */
316 SSPUSHINT(paren_elems_to_push + REGCP_OTHER_ELEMS - REGCP_FRAME_ELEMS);
317 SSPUSHINT(SAVEt_REGCONTEXT); /* Magic cookie. */
322 /* These are needed since we do not localize EVAL nodes: */
323 #define REGCP_SET(cp) \
325 PerlIO_printf(Perl_debug_log, \
326 " Setting an EVAL scope, savestack=%"IVdf"\n", \
327 (IV)PL_savestack_ix)); \
330 #define REGCP_UNWIND(cp) \
332 if (cp != PL_savestack_ix) \
333 PerlIO_printf(Perl_debug_log, \
334 " Clearing an EVAL scope, savestack=%"IVdf"..%"IVdf"\n", \
335 (IV)(cp), (IV)PL_savestack_ix)); \
339 S_regcppop(pTHX_ const regexp *rex)
344 GET_RE_DEBUG_FLAGS_DECL;
346 PERL_ARGS_ASSERT_REGCPPOP;
348 /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
350 assert(i == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
351 i = SSPOPINT; /* Parentheses elements to pop. */
352 input = (char *) SSPOPPTR;
353 *PL_reglastcloseparen = SSPOPINT;
354 *PL_reglastparen = SSPOPINT;
355 PL_regsize = SSPOPINT;
356 PL_regoffs=(regexp_paren_pair *) SSPOPPTR;
359 /* Now restore the parentheses context. */
360 for (i -= (REGCP_OTHER_ELEMS - REGCP_FRAME_ELEMS);
361 i > 0; i -= REGCP_PAREN_ELEMS) {
363 U32 paren = (U32)SSPOPINT;
364 PL_reg_start_tmp[paren] = (char *) SSPOPPTR;
365 PL_regoffs[paren].start = SSPOPINT;
367 if (paren <= *PL_reglastparen)
368 PL_regoffs[paren].end = tmps;
370 PerlIO_printf(Perl_debug_log,
371 " restoring \\%"UVuf" to %"IVdf"(%"IVdf")..%"IVdf"%s\n",
372 (UV)paren, (IV)PL_regoffs[paren].start,
373 (IV)(PL_reg_start_tmp[paren] - PL_bostr),
374 (IV)PL_regoffs[paren].end,
375 (paren > *PL_reglastparen ? "(no)" : ""));
379 if (*PL_reglastparen + 1 <= rex->nparens) {
380 PerlIO_printf(Perl_debug_log,
381 " restoring \\%"IVdf"..\\%"IVdf" to undef\n",
382 (IV)(*PL_reglastparen + 1), (IV)rex->nparens);
386 /* It would seem that the similar code in regtry()
387 * already takes care of this, and in fact it is in
388 * a better location to since this code can #if 0-ed out
389 * but the code in regtry() is needed or otherwise tests
390 * requiring null fields (pat.t#187 and split.t#{13,14}
391 * (as of patchlevel 7877) will fail. Then again,
392 * this code seems to be necessary or otherwise
393 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
394 * --jhi updated by dapm */
395 for (i = *PL_reglastparen + 1; i <= rex->nparens; i++) {
397 PL_regoffs[i].start = -1;
398 PL_regoffs[i].end = -1;
404 #define regcpblow(cp) LEAVE_SCOPE(cp) /* Ignores regcppush()ed data. */
407 * pregexec and friends
410 #ifndef PERL_IN_XSUB_RE
412 - pregexec - match a regexp against a string
415 Perl_pregexec(pTHX_ REGEXP * const prog, char* stringarg, register char *strend,
416 char *strbeg, I32 minend, SV *screamer, U32 nosave)
417 /* strend: pointer to null at end of string */
418 /* strbeg: real beginning of string */
419 /* minend: end of match must be >=minend after stringarg. */
420 /* nosave: For optimizations. */
422 PERL_ARGS_ASSERT_PREGEXEC;
425 regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
426 nosave ? 0 : REXEC_COPY_STR);
431 * Need to implement the following flags for reg_anch:
433 * USE_INTUIT_NOML - Useful to call re_intuit_start() first
435 * INTUIT_AUTORITATIVE_NOML - Can trust a positive answer
436 * INTUIT_AUTORITATIVE_ML
437 * INTUIT_ONCE_NOML - Intuit can match in one location only.
440 * Another flag for this function: SECOND_TIME (so that float substrs
441 * with giant delta may be not rechecked).
444 /* Assumptions: if ANCH_GPOS, then strpos is anchored. XXXX Check GPOS logic */
446 /* If SCREAM, then SvPVX_const(sv) should be compatible with strpos and strend.
447 Otherwise, only SvCUR(sv) is used to get strbeg. */
449 /* XXXX We assume that strpos is strbeg unless sv. */
451 /* XXXX Some places assume that there is a fixed substring.
452 An update may be needed if optimizer marks as "INTUITable"
453 RExen without fixed substrings. Similarly, it is assumed that
454 lengths of all the strings are no more than minlen, thus they
455 cannot come from lookahead.
456 (Or minlen should take into account lookahead.)
457 NOTE: Some of this comment is not correct. minlen does now take account
458 of lookahead/behind. Further research is required. -- demerphq
462 /* A failure to find a constant substring means that there is no need to make
463 an expensive call to REx engine, thus we celebrate a failure. Similarly,
464 finding a substring too deep into the string means that less calls to
465 regtry() should be needed.
467 REx compiler's optimizer found 4 possible hints:
468 a) Anchored substring;
470 c) Whether we are anchored (beginning-of-line or \G);
471 d) First node (of those at offset 0) which may distingush positions;
472 We use a)b)d) and multiline-part of c), and try to find a position in the
473 string which does not contradict any of them.
476 /* Most of decisions we do here should have been done at compile time.
477 The nodes of the REx which we used for the search should have been
478 deleted from the finite automaton. */
481 Perl_re_intuit_start(pTHX_ REGEXP * const rx, SV *sv, char *strpos,
482 char *strend, const U32 flags, re_scream_pos_data *data)
485 struct regexp *const prog = (struct regexp *)SvANY(rx);
486 register I32 start_shift = 0;
487 /* Should be nonnegative! */
488 register I32 end_shift = 0;
493 const bool do_utf8 = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
495 register char *other_last = NULL; /* other substr checked before this */
496 char *check_at = NULL; /* check substr found at this pos */
497 const I32 multiline = prog->extflags & RXf_PMf_MULTILINE;
498 RXi_GET_DECL(prog,progi);
500 const char * const i_strpos = strpos;
502 GET_RE_DEBUG_FLAGS_DECL;
504 PERL_ARGS_ASSERT_RE_INTUIT_START;
506 RX_MATCH_UTF8_set(rx,do_utf8);
509 PL_reg_flags |= RF_utf8;
512 debug_start_match(rx, do_utf8, strpos, strend,
513 sv ? "Guessing start of match in sv for"
514 : "Guessing start of match in string for");
517 /* CHR_DIST() would be more correct here but it makes things slow. */
518 if (prog->minlen > strend - strpos) {
519 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
520 "String too short... [re_intuit_start]\n"));
524 strbeg = (sv && SvPOK(sv)) ? strend - SvCUR(sv) : strpos;
527 if (!prog->check_utf8 && prog->check_substr)
528 to_utf8_substr(prog);
529 check = prog->check_utf8;
531 if (!prog->check_substr && prog->check_utf8)
532 to_byte_substr(prog);
533 check = prog->check_substr;
535 if (check == &PL_sv_undef) {
536 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
537 "Non-utf8 string cannot match utf8 check string\n"));
540 if (prog->extflags & RXf_ANCH) { /* Match at beg-of-str or after \n */
541 ml_anch = !( (prog->extflags & RXf_ANCH_SINGLE)
542 || ( (prog->extflags & RXf_ANCH_BOL)
543 && !multiline ) ); /* Check after \n? */
546 if ( !(prog->extflags & RXf_ANCH_GPOS) /* Checked by the caller */
547 && !(prog->intflags & PREGf_IMPLICIT) /* not a real BOL */
548 /* SvCUR is not set on references: SvRV and SvPVX_const overlap */
550 && (strpos != strbeg)) {
551 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Not at start...\n"));
554 if (prog->check_offset_min == prog->check_offset_max &&
555 !(prog->extflags & RXf_CANY_SEEN)) {
556 /* Substring at constant offset from beg-of-str... */
559 s = HOP3c(strpos, prog->check_offset_min, strend);
562 slen = SvCUR(check); /* >= 1 */
564 if ( strend - s > slen || strend - s < slen - 1
565 || (strend - s == slen && strend[-1] != '\n')) {
566 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "String too long...\n"));
569 /* Now should match s[0..slen-2] */
571 if (slen && (*SvPVX_const(check) != *s
573 && memNE(SvPVX_const(check), s, slen)))) {
575 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "String not equal...\n"));
579 else if (*SvPVX_const(check) != *s
580 || ((slen = SvCUR(check)) > 1
581 && memNE(SvPVX_const(check), s, slen)))
584 goto success_at_start;
587 /* Match is anchored, but substr is not anchored wrt beg-of-str. */
589 start_shift = prog->check_offset_min; /* okay to underestimate on CC */
590 end_shift = prog->check_end_shift;
593 const I32 end = prog->check_offset_max + CHR_SVLEN(check)
594 - (SvTAIL(check) != 0);
595 const I32 eshift = CHR_DIST((U8*)strend, (U8*)s) - end;
597 if (end_shift < eshift)
601 else { /* Can match at random position */
604 start_shift = prog->check_offset_min; /* okay to underestimate on CC */
605 end_shift = prog->check_end_shift;
607 /* end shift should be non negative here */
610 #ifdef QDEBUGGING /* 7/99: reports of failure (with the older version) */
612 Perl_croak(aTHX_ "panic: end_shift: %"IVdf" pattern:\n%s\n ",
613 (IV)end_shift, RX_PRECOMP(prog));
617 /* Find a possible match in the region s..strend by looking for
618 the "check" substring in the region corrected by start/end_shift. */
621 I32 srch_start_shift = start_shift;
622 I32 srch_end_shift = end_shift;
623 if (srch_start_shift < 0 && strbeg - s > srch_start_shift) {
624 srch_end_shift -= ((strbeg - s) - srch_start_shift);
625 srch_start_shift = strbeg - s;
627 DEBUG_OPTIMISE_MORE_r({
628 PerlIO_printf(Perl_debug_log, "Check offset min: %"IVdf" Start shift: %"IVdf" End shift %"IVdf" Real End Shift: %"IVdf"\n",
629 (IV)prog->check_offset_min,
630 (IV)srch_start_shift,
632 (IV)prog->check_end_shift);
635 if (flags & REXEC_SCREAM) {
636 I32 p = -1; /* Internal iterator of scream. */
637 I32 * const pp = data ? data->scream_pos : &p;
639 if (PL_screamfirst[BmRARE(check)] >= 0
640 || ( BmRARE(check) == '\n'
641 && (BmPREVIOUS(check) == SvCUR(check) - 1)
643 s = screaminstr(sv, check,
644 srch_start_shift + (s - strbeg), srch_end_shift, pp, 0);
647 /* we may be pointing at the wrong string */
648 if (s && RXp_MATCH_COPIED(prog))
649 s = strbeg + (s - SvPVX_const(sv));
651 *data->scream_olds = s;
656 if (prog->extflags & RXf_CANY_SEEN) {
657 start_point= (U8*)(s + srch_start_shift);
658 end_point= (U8*)(strend - srch_end_shift);
660 start_point= HOP3(s, srch_start_shift, srch_start_shift < 0 ? strbeg : strend);
661 end_point= HOP3(strend, -srch_end_shift, strbeg);
663 DEBUG_OPTIMISE_MORE_r({
664 PerlIO_printf(Perl_debug_log, "fbm_instr len=%d str=<%.*s>\n",
665 (int)(end_point - start_point),
666 (int)(end_point - start_point) > 20 ? 20 : (int)(end_point - start_point),
670 s = fbm_instr( start_point, end_point,
671 check, multiline ? FBMrf_MULTILINE : 0);
674 /* Update the count-of-usability, remove useless subpatterns,
678 RE_PV_QUOTED_DECL(quoted, do_utf8, PERL_DEBUG_PAD_ZERO(0),
679 SvPVX_const(check), RE_SV_DUMPLEN(check), 30);
680 PerlIO_printf(Perl_debug_log, "%s %s substr %s%s%s",
681 (s ? "Found" : "Did not find"),
682 (check == (do_utf8 ? prog->anchored_utf8 : prog->anchored_substr)
683 ? "anchored" : "floating"),
686 (s ? " at offset " : "...\n") );
691 /* Finish the diagnostic message */
692 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%ld...\n", (long)(s - i_strpos)) );
694 /* XXX dmq: first branch is for positive lookbehind...
695 Our check string is offset from the beginning of the pattern.
696 So we need to do any stclass tests offset forward from that
705 /* Got a candidate. Check MBOL anchoring, and the *other* substr.
706 Start with the other substr.
707 XXXX no SCREAM optimization yet - and a very coarse implementation
708 XXXX /ttx+/ results in anchored="ttx", floating="x". floating will
709 *always* match. Probably should be marked during compile...
710 Probably it is right to do no SCREAM here...
713 if (do_utf8 ? (prog->float_utf8 && prog->anchored_utf8)
714 : (prog->float_substr && prog->anchored_substr))
716 /* Take into account the "other" substring. */
717 /* XXXX May be hopelessly wrong for UTF... */
720 if (check == (do_utf8 ? prog->float_utf8 : prog->float_substr)) {
723 char * const last = HOP3c(s, -start_shift, strbeg);
725 char * const saved_s = s;
728 t = s - prog->check_offset_max;
729 if (s - strpos > prog->check_offset_max /* signed-corrected t > strpos */
731 || ((t = (char*)reghopmaybe3((U8*)s, -(prog->check_offset_max), (U8*)strpos))
736 t = HOP3c(t, prog->anchored_offset, strend);
737 if (t < other_last) /* These positions already checked */
739 last2 = last1 = HOP3c(strend, -prog->minlen, strbeg);
742 /* XXXX It is not documented what units *_offsets are in.
743 We assume bytes, but this is clearly wrong.
744 Meaning this code needs to be carefully reviewed for errors.
748 /* On end-of-str: see comment below. */
749 must = do_utf8 ? prog->anchored_utf8 : prog->anchored_substr;
750 if (must == &PL_sv_undef) {
752 DEBUG_r(must = prog->anchored_utf8); /* for debug */
757 HOP3(HOP3(last1, prog->anchored_offset, strend)
758 + SvCUR(must), -(SvTAIL(must)!=0), strbeg),
760 multiline ? FBMrf_MULTILINE : 0
763 RE_PV_QUOTED_DECL(quoted, do_utf8, PERL_DEBUG_PAD_ZERO(0),
764 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
765 PerlIO_printf(Perl_debug_log, "%s anchored substr %s%s",
766 (s ? "Found" : "Contradicts"),
767 quoted, RE_SV_TAIL(must));
772 if (last1 >= last2) {
773 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
774 ", giving up...\n"));
777 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
778 ", trying floating at offset %ld...\n",
779 (long)(HOP3c(saved_s, 1, strend) - i_strpos)));
780 other_last = HOP3c(last1, prog->anchored_offset+1, strend);
781 s = HOP3c(last, 1, strend);
785 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " at offset %ld...\n",
786 (long)(s - i_strpos)));
787 t = HOP3c(s, -prog->anchored_offset, strbeg);
788 other_last = HOP3c(s, 1, strend);
796 else { /* Take into account the floating substring. */
798 char * const saved_s = s;
801 t = HOP3c(s, -start_shift, strbeg);
803 HOP3c(strend, -prog->minlen + prog->float_min_offset, strbeg);
804 if (CHR_DIST((U8*)last, (U8*)t) > prog->float_max_offset)
805 last = HOP3c(t, prog->float_max_offset, strend);
806 s = HOP3c(t, prog->float_min_offset, strend);
809 /* XXXX It is not documented what units *_offsets are in. Assume bytes. */
810 must = do_utf8 ? prog->float_utf8 : prog->float_substr;
811 /* fbm_instr() takes into account exact value of end-of-str
812 if the check is SvTAIL(ed). Since false positives are OK,
813 and end-of-str is not later than strend we are OK. */
814 if (must == &PL_sv_undef) {
816 DEBUG_r(must = prog->float_utf8); /* for debug message */
819 s = fbm_instr((unsigned char*)s,
820 (unsigned char*)last + SvCUR(must)
822 must, multiline ? FBMrf_MULTILINE : 0);
824 RE_PV_QUOTED_DECL(quoted, do_utf8, PERL_DEBUG_PAD_ZERO(0),
825 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
826 PerlIO_printf(Perl_debug_log, "%s floating substr %s%s",
827 (s ? "Found" : "Contradicts"),
828 quoted, RE_SV_TAIL(must));
832 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
833 ", giving up...\n"));
836 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
837 ", trying anchored starting at offset %ld...\n",
838 (long)(saved_s + 1 - i_strpos)));
840 s = HOP3c(t, 1, strend);
844 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " at offset %ld...\n",
845 (long)(s - i_strpos)));
846 other_last = s; /* Fix this later. --Hugo */
856 t= (char*)HOP3( s, -prog->check_offset_max, (prog->check_offset_max<0) ? strend : strpos);
858 DEBUG_OPTIMISE_MORE_r(
859 PerlIO_printf(Perl_debug_log,
860 "Check offset min:%"IVdf" max:%"IVdf" S:%"IVdf" t:%"IVdf" D:%"IVdf" end:%"IVdf"\n",
861 (IV)prog->check_offset_min,
862 (IV)prog->check_offset_max,
870 if (s - strpos > prog->check_offset_max /* signed-corrected t > strpos */
872 || ((t = (char*)reghopmaybe3((U8*)s, -prog->check_offset_max, (U8*) ((prog->check_offset_max<0) ? strend : strpos)))
875 /* Fixed substring is found far enough so that the match
876 cannot start at strpos. */
878 if (ml_anch && t[-1] != '\n') {
879 /* Eventually fbm_*() should handle this, but often
880 anchored_offset is not 0, so this check will not be wasted. */
881 /* XXXX In the code below we prefer to look for "^" even in
882 presence of anchored substrings. And we search even
883 beyond the found float position. These pessimizations
884 are historical artefacts only. */
886 while (t < strend - prog->minlen) {
888 if (t < check_at - prog->check_offset_min) {
889 if (do_utf8 ? prog->anchored_utf8 : prog->anchored_substr) {
890 /* Since we moved from the found position,
891 we definitely contradict the found anchored
892 substr. Due to the above check we do not
893 contradict "check" substr.
894 Thus we can arrive here only if check substr
895 is float. Redo checking for "other"=="fixed".
898 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Found /%s^%s/m at offset %ld, rescanning for anchored from offset %ld...\n",
899 PL_colors[0], PL_colors[1], (long)(strpos - i_strpos), (long)(strpos - i_strpos + prog->anchored_offset)));
900 goto do_other_anchored;
902 /* We don't contradict the found floating substring. */
903 /* XXXX Why not check for STCLASS? */
905 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Found /%s^%s/m at offset %ld...\n",
906 PL_colors[0], PL_colors[1], (long)(s - i_strpos)));
909 /* Position contradicts check-string */
910 /* XXXX probably better to look for check-string
911 than for "\n", so one should lower the limit for t? */
912 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Found /%s^%s/m, restarting lookup for check-string at offset %ld...\n",
913 PL_colors[0], PL_colors[1], (long)(t + 1 - i_strpos)));
914 other_last = strpos = s = t + 1;
919 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Did not find /%s^%s/m...\n",
920 PL_colors[0], PL_colors[1]));
924 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Starting position does not contradict /%s^%s/m...\n",
925 PL_colors[0], PL_colors[1]));
929 ++BmUSEFUL(do_utf8 ? prog->check_utf8 : prog->check_substr); /* hooray/5 */
932 /* The found string does not prohibit matching at strpos,
933 - no optimization of calling REx engine can be performed,
934 unless it was an MBOL and we are not after MBOL,
935 or a future STCLASS check will fail this. */
937 /* Even in this situation we may use MBOL flag if strpos is offset
938 wrt the start of the string. */
939 if (ml_anch && sv && !SvROK(sv) /* See prev comment on SvROK */
940 && (strpos != strbeg) && strpos[-1] != '\n'
941 /* May be due to an implicit anchor of m{.*foo} */
942 && !(prog->intflags & PREGf_IMPLICIT))
947 DEBUG_EXECUTE_r( if (ml_anch)
948 PerlIO_printf(Perl_debug_log, "Position at offset %ld does not contradict /%s^%s/m...\n",
949 (long)(strpos - i_strpos), PL_colors[0], PL_colors[1]);
952 if (!(prog->intflags & PREGf_NAUGHTY) /* XXXX If strpos moved? */
954 prog->check_utf8 /* Could be deleted already */
955 && --BmUSEFUL(prog->check_utf8) < 0
956 && (prog->check_utf8 == prog->float_utf8)
958 prog->check_substr /* Could be deleted already */
959 && --BmUSEFUL(prog->check_substr) < 0
960 && (prog->check_substr == prog->float_substr)
963 /* If flags & SOMETHING - do not do it many times on the same match */
964 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "... Disabling check substring...\n"));
965 SvREFCNT_dec(do_utf8 ? prog->check_utf8 : prog->check_substr);
966 if (do_utf8 ? prog->check_substr : prog->check_utf8)
967 SvREFCNT_dec(do_utf8 ? prog->check_substr : prog->check_utf8);
968 prog->check_substr = prog->check_utf8 = NULL; /* disable */
969 prog->float_substr = prog->float_utf8 = NULL; /* clear */
970 check = NULL; /* abort */
972 /* XXXX This is a remnant of the old implementation. It
973 looks wasteful, since now INTUIT can use many
975 prog->extflags &= ~RXf_USE_INTUIT;
982 /* XXXX BmUSEFUL already changed, maybe multiple change is meaningful... */
983 /* trie stclasses are too expensive to use here, we are better off to
984 leave it to regmatch itself */
985 if (progi->regstclass && PL_regkind[OP(progi->regstclass)]!=TRIE) {
986 /* minlen == 0 is possible if regstclass is \b or \B,
987 and the fixed substr is ''$.
988 Since minlen is already taken into account, s+1 is before strend;
989 accidentally, minlen >= 1 guaranties no false positives at s + 1
990 even for \b or \B. But (minlen? 1 : 0) below assumes that
991 regstclass does not come from lookahead... */
992 /* If regstclass takes bytelength more than 1: If charlength==1, OK.
993 This leaves EXACTF only, which is dealt with in find_byclass(). */
994 const U8* const str = (U8*)STRING(progi->regstclass);
995 const int cl_l = (PL_regkind[OP(progi->regstclass)] == EXACT
996 ? CHR_DIST(str+STR_LEN(progi->regstclass), str)
999 if (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
1000 endpos= HOP3c(s, (prog->minlen ? cl_l : 0), strend);
1001 else if (prog->float_substr || prog->float_utf8)
1002 endpos= HOP3c(HOP3c(check_at, -start_shift, strbeg), cl_l, strend);
1006 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "start_shift: %"IVdf" check_at: %"IVdf" s: %"IVdf" endpos: %"IVdf"\n",
1007 (IV)start_shift, (IV)(check_at - strbeg), (IV)(s - strbeg), (IV)(endpos - strbeg)));
1010 s = find_byclass(prog, progi->regstclass, s, endpos, NULL);
1013 const char *what = NULL;
1015 if (endpos == strend) {
1016 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1017 "Could not match STCLASS...\n") );
1020 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1021 "This position contradicts STCLASS...\n") );
1022 if ((prog->extflags & RXf_ANCH) && !ml_anch)
1024 /* Contradict one of substrings */
1025 if (prog->anchored_substr || prog->anchored_utf8) {
1026 if ((do_utf8 ? prog->anchored_utf8 : prog->anchored_substr) == check) {
1027 DEBUG_EXECUTE_r( what = "anchored" );
1029 s = HOP3c(t, 1, strend);
1030 if (s + start_shift + end_shift > strend) {
1031 /* XXXX Should be taken into account earlier? */
1032 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1033 "Could not match STCLASS...\n") );
1038 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1039 "Looking for %s substr starting at offset %ld...\n",
1040 what, (long)(s + start_shift - i_strpos)) );
1043 /* Have both, check_string is floating */
1044 if (t + start_shift >= check_at) /* Contradicts floating=check */
1045 goto retry_floating_check;
1046 /* Recheck anchored substring, but not floating... */
1050 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1051 "Looking for anchored substr starting at offset %ld...\n",
1052 (long)(other_last - i_strpos)) );
1053 goto do_other_anchored;
1055 /* Another way we could have checked stclass at the
1056 current position only: */
1061 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1062 "Looking for /%s^%s/m starting at offset %ld...\n",
1063 PL_colors[0], PL_colors[1], (long)(t - i_strpos)) );
1066 if (!(do_utf8 ? prog->float_utf8 : prog->float_substr)) /* Could have been deleted */
1068 /* Check is floating subtring. */
1069 retry_floating_check:
1070 t = check_at - start_shift;
1071 DEBUG_EXECUTE_r( what = "floating" );
1072 goto hop_and_restart;
1075 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1076 "By STCLASS: moving %ld --> %ld\n",
1077 (long)(t - i_strpos), (long)(s - i_strpos))
1081 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1082 "Does not contradict STCLASS...\n");
1087 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%s%s:%s match at offset %ld\n",
1088 PL_colors[4], (check ? "Guessed" : "Giving up"),
1089 PL_colors[5], (long)(s - i_strpos)) );
1092 fail_finish: /* Substring not found */
1093 if (prog->check_substr || prog->check_utf8) /* could be removed already */
1094 BmUSEFUL(do_utf8 ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
1096 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch rejected by optimizer%s\n",
1097 PL_colors[4], PL_colors[5]));
1101 #define DECL_TRIE_TYPE(scan) \
1102 const enum { trie_plain, trie_utf8, trie_utf8_fold, trie_latin_utf8_fold } \
1103 trie_type = (scan->flags != EXACT) \
1104 ? (do_utf8 ? trie_utf8_fold : (UTF ? trie_latin_utf8_fold : trie_plain)) \
1105 : (do_utf8 ? trie_utf8 : trie_plain)
1107 #define REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc, uscan, len, \
1108 uvc, charid, foldlen, foldbuf, uniflags) STMT_START { \
1109 UV uvc_unfolded = 0; \
1110 switch (trie_type) { \
1111 case trie_utf8_fold: \
1112 if ( foldlen>0 ) { \
1113 uvc_unfolded = uvc = utf8n_to_uvuni( uscan, UTF8_MAXLEN, &len, uniflags ); \
1118 uvc_unfolded = uvc = utf8n_to_uvuni( (U8*)uc, UTF8_MAXLEN, &len, uniflags ); \
1119 uvc = to_uni_fold( uvc, foldbuf, &foldlen ); \
1120 foldlen -= UNISKIP( uvc ); \
1121 uscan = foldbuf + UNISKIP( uvc ); \
1124 case trie_latin_utf8_fold: \
1125 if ( foldlen>0 ) { \
1126 uvc = utf8n_to_uvuni( uscan, UTF8_MAXLEN, &len, uniflags ); \
1132 uvc = to_uni_fold( *(U8*)uc, foldbuf, &foldlen ); \
1133 foldlen -= UNISKIP( uvc ); \
1134 uscan = foldbuf + UNISKIP( uvc ); \
1138 uvc = utf8n_to_uvuni( (U8*)uc, UTF8_MAXLEN, &len, uniflags ); \
1146 charid = trie->charmap[ uvc ]; \
1150 if (widecharmap) { \
1151 SV** const svpp = hv_fetch(widecharmap, \
1152 (char*)&uvc, sizeof(UV), 0); \
1154 charid = (U16)SvIV(*svpp); \
1157 if (!charid && trie_type == trie_utf8_fold && !UTF) { \
1158 charid = trie->charmap[uvc_unfolded]; \
1162 #define REXEC_FBC_EXACTISH_CHECK(CoNd) \
1164 char *my_strend= (char *)strend; \
1167 !ibcmp_utf8(s, &my_strend, 0, do_utf8, \
1168 m, NULL, ln, (bool)UTF)) \
1169 && (!reginfo || regtry(reginfo, &s)) ) \
1172 U8 foldbuf[UTF8_MAXBYTES_CASE+1]; \
1173 uvchr_to_utf8(tmpbuf, c); \
1174 f = to_utf8_fold(tmpbuf, foldbuf, &foldlen); \
1176 && (f == c1 || f == c2) \
1178 !ibcmp_utf8(s, &my_strend, 0, do_utf8,\
1179 m, NULL, ln, (bool)UTF)) \
1180 && (!reginfo || regtry(reginfo, &s)) ) \
1186 #define REXEC_FBC_EXACTISH_SCAN(CoNd) \
1190 && (ln == 1 || !(OP(c) == EXACTF \
1192 : ibcmp_locale(s, m, ln))) \
1193 && (!reginfo || regtry(reginfo, &s)) ) \
1199 #define REXEC_FBC_UTF8_SCAN(CoDe) \
1201 while (s + (uskip = UTF8SKIP(s)) <= strend) { \
1207 #define REXEC_FBC_SCAN(CoDe) \
1209 while (s < strend) { \
1215 #define REXEC_FBC_UTF8_CLASS_SCAN(CoNd) \
1216 REXEC_FBC_UTF8_SCAN( \
1218 if (tmp && (!reginfo || regtry(reginfo, &s))) \
1227 #define REXEC_FBC_CLASS_SCAN(CoNd) \
1230 if (tmp && (!reginfo || regtry(reginfo, &s))) \
1239 #define REXEC_FBC_TRYIT \
1240 if ((!reginfo || regtry(reginfo, &s))) \
1243 #define REXEC_FBC_CSCAN(CoNdUtF8,CoNd) \
1245 REXEC_FBC_UTF8_CLASS_SCAN(CoNdUtF8); \
1248 REXEC_FBC_CLASS_SCAN(CoNd); \
1252 #define REXEC_FBC_CSCAN_PRELOAD(UtFpReLoAd,CoNdUtF8,CoNd) \
1255 REXEC_FBC_UTF8_CLASS_SCAN(CoNdUtF8); \
1258 REXEC_FBC_CLASS_SCAN(CoNd); \
1262 #define REXEC_FBC_CSCAN_TAINT(CoNdUtF8,CoNd) \
1263 PL_reg_flags |= RF_tainted; \
1265 REXEC_FBC_UTF8_CLASS_SCAN(CoNdUtF8); \
1268 REXEC_FBC_CLASS_SCAN(CoNd); \
1272 #define DUMP_EXEC_POS(li,s,doutf8) \
1273 dump_exec_pos(li,s,(PL_regeol),(PL_bostr),(PL_reg_starttry),doutf8)
1275 /* We know what class REx starts with. Try to find this position... */
1276 /* if reginfo is NULL, its a dryrun */
1277 /* annoyingly all the vars in this routine have different names from their counterparts
1278 in regmatch. /grrr */
1281 S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
1282 const char *strend, regmatch_info *reginfo)
1285 const I32 doevery = (prog->intflags & PREGf_SKIP) == 0;
1289 register STRLEN uskip;
1293 register I32 tmp = 1; /* Scratch variable? */
1294 register const bool do_utf8 = PL_reg_match_utf8;
1295 RXi_GET_DECL(prog,progi);
1297 PERL_ARGS_ASSERT_FIND_BYCLASS;
1299 /* We know what class it must start with. */
1303 REXEC_FBC_UTF8_CLASS_SCAN((ANYOF_FLAGS(c) & ANYOF_UNICODE) ||
1304 !UTF8_IS_INVARIANT((U8)s[0]) ?
1305 reginclass(prog, c, (U8*)s, 0, do_utf8) :
1306 REGINCLASS(prog, c, (U8*)s));
1309 while (s < strend) {
1312 if (REGINCLASS(prog, c, (U8*)s) ||
1313 (ANYOF_FOLD_SHARP_S(c, s, strend) &&
1314 /* The assignment of 2 is intentional:
1315 * for the folded sharp s, the skip is 2. */
1316 (skip = SHARP_S_SKIP))) {
1317 if (tmp && (!reginfo || regtry(reginfo, &s)))
1330 if (tmp && (!reginfo || regtry(reginfo, &s)))
1338 ln = STR_LEN(c); /* length to match in octets/bytes */
1339 lnc = (I32) ln; /* length to match in characters */
1341 STRLEN ulen1, ulen2;
1343 U8 tmpbuf1[UTF8_MAXBYTES_CASE+1];
1344 U8 tmpbuf2[UTF8_MAXBYTES_CASE+1];
1345 /* used by commented-out code below */
1346 /*const U32 uniflags = UTF8_ALLOW_DEFAULT;*/
1348 /* XXX: Since the node will be case folded at compile
1349 time this logic is a little odd, although im not
1350 sure that its actually wrong. --dmq */
1352 c1 = to_utf8_lower((U8*)m, tmpbuf1, &ulen1);
1353 c2 = to_utf8_upper((U8*)m, tmpbuf2, &ulen2);
1355 /* XXX: This is kinda strange. to_utf8_XYZ returns the
1356 codepoint of the first character in the converted
1357 form, yet originally we did the extra step.
1358 No tests fail by commenting this code out however
1359 so Ive left it out. -- dmq.
1361 c1 = utf8n_to_uvchr(tmpbuf1, UTF8_MAXBYTES_CASE,
1363 c2 = utf8n_to_uvchr(tmpbuf2, UTF8_MAXBYTES_CASE,
1368 while (sm < ((U8 *) m + ln)) {
1383 c2 = PL_fold_locale[c1];
1385 e = HOP3c(strend, -((I32)lnc), s);
1387 if (!reginfo && e < s)
1388 e = s; /* Due to minlen logic of intuit() */
1390 /* The idea in the EXACTF* cases is to first find the
1391 * first character of the EXACTF* node and then, if
1392 * necessary, case-insensitively compare the full
1393 * text of the node. The c1 and c2 are the first
1394 * characters (though in Unicode it gets a bit
1395 * more complicated because there are more cases
1396 * than just upper and lower: one needs to use
1397 * the so-called folding case for case-insensitive
1398 * matching (called "loose matching" in Unicode).
1399 * ibcmp_utf8() will do just that. */
1401 if (do_utf8 || UTF) {
1403 U8 tmpbuf [UTF8_MAXBYTES+1];
1406 const U32 uniflags = UTF8_ALLOW_DEFAULT;
1408 /* Upper and lower of 1st char are equal -
1409 * probably not a "letter". */
1412 c = utf8n_to_uvchr((U8*)s, UTF8_MAXBYTES, &len,
1417 REXEC_FBC_EXACTISH_CHECK(c == c1);
1423 c = utf8n_to_uvchr((U8*)s, UTF8_MAXBYTES, &len,
1429 /* Handle some of the three Greek sigmas cases.
1430 * Note that not all the possible combinations
1431 * are handled here: some of them are handled
1432 * by the standard folding rules, and some of
1433 * them (the character class or ANYOF cases)
1434 * are handled during compiletime in
1435 * regexec.c:S_regclass(). */
1436 if (c == (UV)UNICODE_GREEK_CAPITAL_LETTER_SIGMA ||
1437 c == (UV)UNICODE_GREEK_SMALL_LETTER_FINAL_SIGMA)
1438 c = (UV)UNICODE_GREEK_SMALL_LETTER_SIGMA;
1440 REXEC_FBC_EXACTISH_CHECK(c == c1 || c == c2);
1445 /* Neither pattern nor string are UTF8 */
1447 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1);
1449 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1 || *(U8*)s == c2);
1453 PL_reg_flags |= RF_tainted;
1460 U8 * const r = reghop3((U8*)s, -1, (U8*)PL_bostr);
1461 tmp = utf8n_to_uvchr(r, UTF8SKIP(r), 0, UTF8_ALLOW_DEFAULT);
1463 tmp = ((OP(c) == BOUND ?
1464 isALNUM_uni(tmp) : isALNUM_LC_uvchr(UNI_TO_NATIVE(tmp))) != 0);
1465 LOAD_UTF8_CHARCLASS_ALNUM();
1466 REXEC_FBC_UTF8_SCAN(
1467 if (tmp == !(OP(c) == BOUND ?
1468 (bool)swash_fetch(PL_utf8_alnum, (U8*)s, do_utf8) :
1469 isALNUM_LC_utf8((U8*)s)))
1477 tmp = (s != PL_bostr) ? UCHARAT(s - 1) : '\n';
1478 tmp = ((OP(c) == BOUND ? isALNUM(tmp) : isALNUM_LC(tmp)) != 0);
1481 !(OP(c) == BOUND ? isALNUM(*s) : isALNUM_LC(*s))) {
1487 if ((!prog->minlen && tmp) && (!reginfo || regtry(reginfo, &s)))
1491 PL_reg_flags |= RF_tainted;
1498 U8 * const r = reghop3((U8*)s, -1, (U8*)PL_bostr);
1499 tmp = utf8n_to_uvchr(r, UTF8SKIP(r), 0, UTF8_ALLOW_DEFAULT);
1501 tmp = ((OP(c) == NBOUND ?
1502 isALNUM_uni(tmp) : isALNUM_LC_uvchr(UNI_TO_NATIVE(tmp))) != 0);
1503 LOAD_UTF8_CHARCLASS_ALNUM();
1504 REXEC_FBC_UTF8_SCAN(
1505 if (tmp == !(OP(c) == NBOUND ?
1506 (bool)swash_fetch(PL_utf8_alnum, (U8*)s, do_utf8) :
1507 isALNUM_LC_utf8((U8*)s)))
1509 else REXEC_FBC_TRYIT;
1513 tmp = (s != PL_bostr) ? UCHARAT(s - 1) : '\n';
1514 tmp = ((OP(c) == NBOUND ?
1515 isALNUM(tmp) : isALNUM_LC(tmp)) != 0);
1518 !(OP(c) == NBOUND ? isALNUM(*s) : isALNUM_LC(*s)))
1520 else REXEC_FBC_TRYIT;
1523 if ((!prog->minlen && !tmp) && (!reginfo || regtry(reginfo, &s)))
1527 REXEC_FBC_CSCAN_PRELOAD(
1528 LOAD_UTF8_CHARCLASS_PERL_WORD(),
1529 swash_fetch(RE_utf8_perl_word, (U8*)s, do_utf8),
1533 REXEC_FBC_CSCAN_TAINT(
1534 isALNUM_LC_utf8((U8*)s),
1538 REXEC_FBC_CSCAN_PRELOAD(
1539 LOAD_UTF8_CHARCLASS_PERL_WORD(),
1540 !swash_fetch(RE_utf8_perl_word, (U8*)s, do_utf8),
1544 REXEC_FBC_CSCAN_TAINT(
1545 !isALNUM_LC_utf8((U8*)s),
1549 REXEC_FBC_CSCAN_PRELOAD(
1550 LOAD_UTF8_CHARCLASS_PERL_SPACE(),
1551 *s == ' ' || swash_fetch(RE_utf8_perl_space,(U8*)s, do_utf8),
1555 REXEC_FBC_CSCAN_TAINT(
1556 *s == ' ' || isSPACE_LC_utf8((U8*)s),
1560 REXEC_FBC_CSCAN_PRELOAD(
1561 LOAD_UTF8_CHARCLASS_PERL_SPACE(),
1562 !(*s == ' ' || swash_fetch(RE_utf8_perl_space,(U8*)s, do_utf8)),
1566 REXEC_FBC_CSCAN_TAINT(
1567 !(*s == ' ' || isSPACE_LC_utf8((U8*)s)),
1571 REXEC_FBC_CSCAN_PRELOAD(
1572 LOAD_UTF8_CHARCLASS_POSIX_DIGIT(),
1573 swash_fetch(RE_utf8_posix_digit,(U8*)s, do_utf8),
1577 REXEC_FBC_CSCAN_TAINT(
1578 isDIGIT_LC_utf8((U8*)s),
1582 REXEC_FBC_CSCAN_PRELOAD(
1583 LOAD_UTF8_CHARCLASS_POSIX_DIGIT(),
1584 !swash_fetch(RE_utf8_posix_digit,(U8*)s, do_utf8),
1588 REXEC_FBC_CSCAN_TAINT(
1589 !isDIGIT_LC_utf8((U8*)s),
1595 is_LNBREAK_latin1(s)
1605 !is_VERTWS_latin1(s)
1610 is_HORIZWS_latin1(s)
1614 !is_HORIZWS_utf8(s),
1615 !is_HORIZWS_latin1(s)
1621 /* what trie are we using right now */
1623 = (reg_ac_data*)progi->data->data[ ARG( c ) ];
1625 = (reg_trie_data*)progi->data->data[ aho->trie ];
1626 HV *widecharmap = MUTABLE_HV(progi->data->data[ aho->trie + 1 ]);
1628 const char *last_start = strend - trie->minlen;
1630 const char *real_start = s;
1632 STRLEN maxlen = trie->maxlen;
1634 U8 **points; /* map of where we were in the input string
1635 when reading a given char. For ASCII this
1636 is unnecessary overhead as the relationship
1637 is always 1:1, but for Unicode, especially
1638 case folded Unicode this is not true. */
1639 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1643 GET_RE_DEBUG_FLAGS_DECL;
1645 /* We can't just allocate points here. We need to wrap it in
1646 * an SV so it gets freed properly if there is a croak while
1647 * running the match */
1650 sv_points=newSV(maxlen * sizeof(U8 *));
1651 SvCUR_set(sv_points,
1652 maxlen * sizeof(U8 *));
1653 SvPOK_on(sv_points);
1654 sv_2mortal(sv_points);
1655 points=(U8**)SvPV_nolen(sv_points );
1656 if ( trie_type != trie_utf8_fold
1657 && (trie->bitmap || OP(c)==AHOCORASICKC) )
1660 bitmap=(U8*)trie->bitmap;
1662 bitmap=(U8*)ANYOF_BITMAP(c);
1664 /* this is the Aho-Corasick algorithm modified a touch
1665 to include special handling for long "unknown char"
1666 sequences. The basic idea being that we use AC as long
1667 as we are dealing with a possible matching char, when
1668 we encounter an unknown char (and we have not encountered
1669 an accepting state) we scan forward until we find a legal
1671 AC matching is basically that of trie matching, except
1672 that when we encounter a failing transition, we fall back
1673 to the current states "fail state", and try the current char
1674 again, a process we repeat until we reach the root state,
1675 state 1, or a legal transition. If we fail on the root state
1676 then we can either terminate if we have reached an accepting
1677 state previously, or restart the entire process from the beginning
1681 while (s <= last_start) {
1682 const U32 uniflags = UTF8_ALLOW_DEFAULT;
1690 U8 *uscan = (U8*)NULL;
1691 U8 *leftmost = NULL;
1693 U32 accepted_word= 0;
1697 while ( state && uc <= (U8*)strend ) {
1699 U32 word = aho->states[ state ].wordnum;
1703 DEBUG_TRIE_EXECUTE_r(
1704 if ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
1705 dump_exec_pos( (char *)uc, c, strend, real_start,
1706 (char *)uc, do_utf8 );
1707 PerlIO_printf( Perl_debug_log,
1708 " Scanning for legal start char...\n");
1711 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
1716 if (uc >(U8*)last_start) break;
1720 U8 *lpos= points[ (pointpos - trie->wordlen[word-1] ) % maxlen ];
1721 if (!leftmost || lpos < leftmost) {
1722 DEBUG_r(accepted_word=word);
1728 points[pointpos++ % maxlen]= uc;
1729 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
1730 uscan, len, uvc, charid, foldlen,
1732 DEBUG_TRIE_EXECUTE_r({
1733 dump_exec_pos( (char *)uc, c, strend, real_start,
1735 PerlIO_printf(Perl_debug_log,
1736 " Charid:%3u CP:%4"UVxf" ",
1742 word = aho->states[ state ].wordnum;
1744 base = aho->states[ state ].trans.base;
1746 DEBUG_TRIE_EXECUTE_r({
1748 dump_exec_pos( (char *)uc, c, strend, real_start,
1750 PerlIO_printf( Perl_debug_log,
1751 "%sState: %4"UVxf", word=%"UVxf,
1752 failed ? " Fail transition to " : "",
1753 (UV)state, (UV)word);
1758 (base + charid > trie->uniquecharcount )
1759 && (base + charid - 1 - trie->uniquecharcount
1761 && trie->trans[base + charid - 1 -
1762 trie->uniquecharcount].check == state
1763 && (tmp=trie->trans[base + charid - 1 -
1764 trie->uniquecharcount ].next))
1766 DEBUG_TRIE_EXECUTE_r(
1767 PerlIO_printf( Perl_debug_log," - legal\n"));
1772 DEBUG_TRIE_EXECUTE_r(
1773 PerlIO_printf( Perl_debug_log," - fail\n"));
1775 state = aho->fail[state];
1779 /* we must be accepting here */
1780 DEBUG_TRIE_EXECUTE_r(
1781 PerlIO_printf( Perl_debug_log," - accepting\n"));
1790 if (!state) state = 1;
1793 if ( aho->states[ state ].wordnum ) {
1794 U8 *lpos = points[ (pointpos - trie->wordlen[aho->states[ state ].wordnum-1]) % maxlen ];
1795 if (!leftmost || lpos < leftmost) {
1796 DEBUG_r(accepted_word=aho->states[ state ].wordnum);
1801 s = (char*)leftmost;
1802 DEBUG_TRIE_EXECUTE_r({
1804 Perl_debug_log,"Matches word #%"UVxf" at position %"IVdf". Trying full pattern...\n",
1805 (UV)accepted_word, (IV)(s - real_start)
1808 if (!reginfo || regtry(reginfo, &s)) {
1814 DEBUG_TRIE_EXECUTE_r({
1815 PerlIO_printf( Perl_debug_log,"Pattern failed. Looking for new start point...\n");
1818 DEBUG_TRIE_EXECUTE_r(
1819 PerlIO_printf( Perl_debug_log,"No match.\n"));
1828 Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
1838 - regexec_flags - match a regexp against a string
1841 Perl_regexec_flags(pTHX_ REGEXP * const rx, char *stringarg, register char *strend,
1842 char *strbeg, I32 minend, SV *sv, void *data, U32 flags)
1843 /* strend: pointer to null at end of string */
1844 /* strbeg: real beginning of string */
1845 /* minend: end of match must be >=minend after stringarg. */
1846 /* data: May be used for some additional optimizations.
1847 Currently its only used, with a U32 cast, for transmitting
1848 the ganch offset when doing a /g match. This will change */
1849 /* nosave: For optimizations. */
1852 struct regexp *const prog = (struct regexp *)SvANY(rx);
1853 /*register*/ char *s;
1854 register regnode *c;
1855 /*register*/ char *startpos = stringarg;
1856 I32 minlen; /* must match at least this many chars */
1857 I32 dontbother = 0; /* how many characters not to try at end */
1858 I32 end_shift = 0; /* Same for the end. */ /* CC */
1859 I32 scream_pos = -1; /* Internal iterator of scream. */
1860 char *scream_olds = NULL;
1861 const bool do_utf8 = (bool)DO_UTF8(sv);
1863 RXi_GET_DECL(prog,progi);
1864 regmatch_info reginfo; /* create some info to pass to regtry etc */
1865 regexp_paren_pair *swap = NULL;
1866 GET_RE_DEBUG_FLAGS_DECL;
1868 PERL_ARGS_ASSERT_REGEXEC_FLAGS;
1869 PERL_UNUSED_ARG(data);
1871 /* Be paranoid... */
1872 if (prog == NULL || startpos == NULL) {
1873 Perl_croak(aTHX_ "NULL regexp parameter");
1877 multiline = prog->extflags & RXf_PMf_MULTILINE;
1878 reginfo.prog = rx; /* Yes, sorry that this is confusing. */
1880 RX_MATCH_UTF8_set(rx, do_utf8);
1882 debug_start_match(rx, do_utf8, startpos, strend,
1886 minlen = prog->minlen;
1888 if (strend - startpos < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
1889 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1890 "String too short [regexec_flags]...\n"));
1895 /* Check validity of program. */
1896 if (UCHARAT(progi->program) != REG_MAGIC) {
1897 Perl_croak(aTHX_ "corrupted regexp program");
1901 PL_reg_eval_set = 0;
1905 PL_reg_flags |= RF_utf8;
1907 /* Mark beginning of line for ^ and lookbehind. */
1908 reginfo.bol = startpos; /* XXX not used ??? */
1912 /* Mark end of line for $ (and such) */
1915 /* see how far we have to get to not match where we matched before */
1916 reginfo.till = startpos+minend;
1918 /* If there is a "must appear" string, look for it. */
1921 if (prog->extflags & RXf_GPOS_SEEN) { /* Need to set reginfo->ganch */
1923 if (flags & REXEC_IGNOREPOS){ /* Means: check only at start */
1924 reginfo.ganch = startpos + prog->gofs;
1925 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
1926 "GPOS IGNOREPOS: reginfo.ganch = startpos + %"UVxf"\n",(UV)prog->gofs));
1927 } else if (sv && SvTYPE(sv) >= SVt_PVMG
1929 && (mg = mg_find(sv, PERL_MAGIC_regex_global))
1930 && mg->mg_len >= 0) {
1931 reginfo.ganch = strbeg + mg->mg_len; /* Defined pos() */
1932 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
1933 "GPOS MAGIC: reginfo.ganch = strbeg + %"IVdf"\n",(IV)mg->mg_len));
1935 if (prog->extflags & RXf_ANCH_GPOS) {
1936 if (s > reginfo.ganch)
1938 s = reginfo.ganch - prog->gofs;
1939 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
1940 "GPOS ANCH_GPOS: s = ganch - %"UVxf"\n",(UV)prog->gofs));
1946 reginfo.ganch = strbeg + PTR2UV(data);
1947 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
1948 "GPOS DATA: reginfo.ganch= strbeg + %"UVxf"\n",PTR2UV(data)));
1950 } else { /* pos() not defined */
1951 reginfo.ganch = strbeg;
1952 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
1953 "GPOS: reginfo.ganch = strbeg\n"));
1956 if (PL_curpm && (PM_GETRE(PL_curpm) == rx)) {
1957 /* We have to be careful. If the previous successful match
1958 was from this regex we don't want a subsequent partially
1959 successful match to clobber the old results.
1960 So when we detect this possibility we add a swap buffer
1961 to the re, and switch the buffer each match. If we fail
1962 we switch it back, otherwise we leave it swapped.
1965 /* do we need a save destructor here for eval dies? */
1966 Newxz(prog->offs, (prog->nparens + 1), regexp_paren_pair);
1968 if (!(flags & REXEC_CHECKED) && (prog->check_substr != NULL || prog->check_utf8 != NULL)) {
1969 re_scream_pos_data d;
1971 d.scream_olds = &scream_olds;
1972 d.scream_pos = &scream_pos;
1973 s = re_intuit_start(rx, sv, s, strend, flags, &d);
1975 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Not present...\n"));
1976 goto phooey; /* not present */
1982 /* Simplest case: anchored match need be tried only once. */
1983 /* [unless only anchor is BOL and multiline is set] */
1984 if (prog->extflags & (RXf_ANCH & ~RXf_ANCH_GPOS)) {
1985 if (s == startpos && regtry(®info, &startpos))
1987 else if (multiline || (prog->intflags & PREGf_IMPLICIT)
1988 || (prog->extflags & RXf_ANCH_MBOL)) /* XXXX SBOL? */
1993 dontbother = minlen - 1;
1994 end = HOP3c(strend, -dontbother, strbeg) - 1;
1995 /* for multiline we only have to try after newlines */
1996 if (prog->check_substr || prog->check_utf8) {
2000 if (regtry(®info, &s))
2005 if (prog->extflags & RXf_USE_INTUIT) {
2006 s = re_intuit_start(rx, sv, s + 1, strend, flags, NULL);
2017 if (*s++ == '\n') { /* don't need PL_utf8skip here */
2018 if (regtry(®info, &s))
2025 } else if (RXf_GPOS_CHECK == (prog->extflags & RXf_GPOS_CHECK))
2027 /* the warning about reginfo.ganch being used without intialization
2028 is bogus -- we set it above, when prog->extflags & RXf_GPOS_SEEN
2029 and we only enter this block when the same bit is set. */
2030 char *tmp_s = reginfo.ganch - prog->gofs;
2032 if (tmp_s >= strbeg && regtry(®info, &tmp_s))
2037 /* Messy cases: unanchored match. */
2038 if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
2039 /* we have /x+whatever/ */
2040 /* it must be a one character string (XXXX Except UTF?) */
2045 if (!(do_utf8 ? prog->anchored_utf8 : prog->anchored_substr))
2046 do_utf8 ? to_utf8_substr(prog) : to_byte_substr(prog);
2047 ch = SvPVX_const(do_utf8 ? prog->anchored_utf8 : prog->anchored_substr)[0];
2052 DEBUG_EXECUTE_r( did_match = 1 );
2053 if (regtry(®info, &s)) goto got_it;
2055 while (s < strend && *s == ch)
2063 DEBUG_EXECUTE_r( did_match = 1 );
2064 if (regtry(®info, &s)) goto got_it;
2066 while (s < strend && *s == ch)
2071 DEBUG_EXECUTE_r(if (!did_match)
2072 PerlIO_printf(Perl_debug_log,
2073 "Did not find anchored character...\n")
2076 else if (prog->anchored_substr != NULL
2077 || prog->anchored_utf8 != NULL
2078 || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
2079 && prog->float_max_offset < strend - s)) {
2084 char *last1; /* Last position checked before */
2088 if (prog->anchored_substr || prog->anchored_utf8) {
2089 if (!(do_utf8 ? prog->anchored_utf8 : prog->anchored_substr))
2090 do_utf8 ? to_utf8_substr(prog) : to_byte_substr(prog);
2091 must = do_utf8 ? prog->anchored_utf8 : prog->anchored_substr;
2092 back_max = back_min = prog->anchored_offset;
2094 if (!(do_utf8 ? prog->float_utf8 : prog->float_substr))
2095 do_utf8 ? to_utf8_substr(prog) : to_byte_substr(prog);
2096 must = do_utf8 ? prog->float_utf8 : prog->float_substr;
2097 back_max = prog->float_max_offset;
2098 back_min = prog->float_min_offset;
2102 if (must == &PL_sv_undef)
2103 /* could not downgrade utf8 check substring, so must fail */
2109 last = HOP3c(strend, /* Cannot start after this */
2110 -(I32)(CHR_SVLEN(must)
2111 - (SvTAIL(must) != 0) + back_min), strbeg);
2114 last1 = HOPc(s, -1);
2116 last1 = s - 1; /* bogus */
2118 /* XXXX check_substr already used to find "s", can optimize if
2119 check_substr==must. */
2121 dontbother = end_shift;
2122 strend = HOPc(strend, -dontbother);
2123 while ( (s <= last) &&
2124 ((flags & REXEC_SCREAM)
2125 ? (s = screaminstr(sv, must, HOP3c(s, back_min, (back_min<0 ? strbeg : strend)) - strbeg,
2126 end_shift, &scream_pos, 0))
2127 : (s = fbm_instr((unsigned char*)HOP3(s, back_min, (back_min<0 ? strbeg : strend)),
2128 (unsigned char*)strend, must,
2129 multiline ? FBMrf_MULTILINE : 0))) ) {
2130 /* we may be pointing at the wrong string */
2131 if ((flags & REXEC_SCREAM) && RXp_MATCH_COPIED(prog))
2132 s = strbeg + (s - SvPVX_const(sv));
2133 DEBUG_EXECUTE_r( did_match = 1 );
2134 if (HOPc(s, -back_max) > last1) {
2135 last1 = HOPc(s, -back_min);
2136 s = HOPc(s, -back_max);
2139 char * const t = (last1 >= PL_bostr) ? HOPc(last1, 1) : last1 + 1;
2141 last1 = HOPc(s, -back_min);
2145 while (s <= last1) {
2146 if (regtry(®info, &s))
2152 while (s <= last1) {
2153 if (regtry(®info, &s))
2159 DEBUG_EXECUTE_r(if (!did_match) {
2160 RE_PV_QUOTED_DECL(quoted, do_utf8, PERL_DEBUG_PAD_ZERO(0),
2161 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
2162 PerlIO_printf(Perl_debug_log, "Did not find %s substr %s%s...\n",
2163 ((must == prog->anchored_substr || must == prog->anchored_utf8)
2164 ? "anchored" : "floating"),
2165 quoted, RE_SV_TAIL(must));
2169 else if ( (c = progi->regstclass) ) {
2171 const OPCODE op = OP(progi->regstclass);
2172 /* don't bother with what can't match */
2173 if (PL_regkind[op] != EXACT && op != CANY && PL_regkind[op] != TRIE)
2174 strend = HOPc(strend, -(minlen - 1));
2177 SV * const prop = sv_newmortal();
2178 regprop(prog, prop, c);
2180 RE_PV_QUOTED_DECL(quoted,do_utf8,PERL_DEBUG_PAD_ZERO(1),
2182 PerlIO_printf(Perl_debug_log,
2183 "Matching stclass %.*s against %s (%d chars)\n",
2184 (int)SvCUR(prop), SvPVX_const(prop),
2185 quoted, (int)(strend - s));
2188 if (find_byclass(prog, c, s, strend, ®info))
2190 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Contradicts stclass... [regexec_flags]\n"));
2194 if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
2199 if (!(do_utf8 ? prog->float_utf8 : prog->float_substr))
2200 do_utf8 ? to_utf8_substr(prog) : to_byte_substr(prog);
2201 float_real = do_utf8 ? prog->float_utf8 : prog->float_substr;
2203 if (flags & REXEC_SCREAM) {
2204 last = screaminstr(sv, float_real, s - strbeg,
2205 end_shift, &scream_pos, 1); /* last one */
2207 last = scream_olds; /* Only one occurrence. */
2208 /* we may be pointing at the wrong string */
2209 else if (RXp_MATCH_COPIED(prog))
2210 s = strbeg + (s - SvPVX_const(sv));
2214 const char * const little = SvPV_const(float_real, len);
2216 if (SvTAIL(float_real)) {
2217 if (memEQ(strend - len + 1, little, len - 1))
2218 last = strend - len + 1;
2219 else if (!multiline)
2220 last = memEQ(strend - len, little, len)
2221 ? strend - len : NULL;
2227 last = rninstr(s, strend, little, little + len);
2229 last = strend; /* matching "$" */
2234 PerlIO_printf(Perl_debug_log,
2235 "%sCan't trim the tail, match fails (should not happen)%s\n",
2236 PL_colors[4], PL_colors[5]));
2237 goto phooey; /* Should not happen! */
2239 dontbother = strend - last + prog->float_min_offset;
2241 if (minlen && (dontbother < minlen))
2242 dontbother = minlen - 1;
2243 strend -= dontbother; /* this one's always in bytes! */
2244 /* We don't know much -- general case. */
2247 if (regtry(®info, &s))
2256 if (regtry(®info, &s))
2258 } while (s++ < strend);
2267 RX_MATCH_TAINTED_set(rx, PL_reg_flags & RF_tainted);
2269 if (PL_reg_eval_set)
2270 restore_pos(aTHX_ prog);
2271 if (RXp_PAREN_NAMES(prog))
2272 (void)hv_iterinit(RXp_PAREN_NAMES(prog));
2274 /* make sure $`, $&, $', and $digit will work later */
2275 if ( !(flags & REXEC_NOT_FIRST) ) {
2276 RX_MATCH_COPY_FREE(rx);
2277 if (flags & REXEC_COPY_STR) {
2278 const I32 i = PL_regeol - startpos + (stringarg - strbeg);
2279 #ifdef PERL_OLD_COPY_ON_WRITE
2281 || (SvFLAGS(sv) & CAN_COW_MASK) == CAN_COW_FLAGS)) {
2283 PerlIO_printf(Perl_debug_log,
2284 "Copy on write: regexp capture, type %d\n",
2287 prog->saved_copy = sv_setsv_cow(prog->saved_copy, sv);
2288 prog->subbeg = (char *)SvPVX_const(prog->saved_copy);
2289 assert (SvPOKp(prog->saved_copy));
2293 RX_MATCH_COPIED_on(rx);
2294 s = savepvn(strbeg, i);
2300 prog->subbeg = strbeg;
2301 prog->sublen = PL_regeol - strbeg; /* strend may have been modified */
2308 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch failed%s\n",
2309 PL_colors[4], PL_colors[5]));
2310 if (PL_reg_eval_set)
2311 restore_pos(aTHX_ prog);
2313 /* we failed :-( roll it back */
2314 Safefree(prog->offs);
2323 - regtry - try match at specific point
2325 STATIC I32 /* 0 failure, 1 success */
2326 S_regtry(pTHX_ regmatch_info *reginfo, char **startpos)
2330 REGEXP *const rx = reginfo->prog;
2331 regexp *const prog = (struct regexp *)SvANY(rx);
2332 RXi_GET_DECL(prog,progi);
2333 GET_RE_DEBUG_FLAGS_DECL;
2335 PERL_ARGS_ASSERT_REGTRY;
2337 reginfo->cutpoint=NULL;
2339 if ((prog->extflags & RXf_EVAL_SEEN) && !PL_reg_eval_set) {
2342 PL_reg_eval_set = RS_init;
2343 DEBUG_EXECUTE_r(DEBUG_s(
2344 PerlIO_printf(Perl_debug_log, " setting stack tmpbase at %"IVdf"\n",
2345 (IV)(PL_stack_sp - PL_stack_base));
2348 cxstack[cxstack_ix].blk_oldsp = PL_stack_sp - PL_stack_base;
2349 /* Otherwise OP_NEXTSTATE will free whatever on stack now. */
2351 /* Apparently this is not needed, judging by wantarray. */
2352 /* SAVEI8(cxstack[cxstack_ix].blk_gimme);
2353 cxstack[cxstack_ix].blk_gimme = G_SCALAR; */
2356 /* Make $_ available to executed code. */
2357 if (reginfo->sv != DEFSV) {
2359 DEFSV_set(reginfo->sv);
2362 if (!(SvTYPE(reginfo->sv) >= SVt_PVMG && SvMAGIC(reginfo->sv)
2363 && (mg = mg_find(reginfo->sv, PERL_MAGIC_regex_global)))) {
2364 /* prepare for quick setting of pos */
2365 #ifdef PERL_OLD_COPY_ON_WRITE
2366 if (SvIsCOW(reginfo->sv))
2367 sv_force_normal_flags(reginfo->sv, 0);
2369 mg = sv_magicext(reginfo->sv, NULL, PERL_MAGIC_regex_global,
2370 &PL_vtbl_mglob, NULL, 0);
2374 PL_reg_oldpos = mg->mg_len;
2375 SAVEDESTRUCTOR_X(restore_pos, prog);
2377 if (!PL_reg_curpm) {
2378 Newxz(PL_reg_curpm, 1, PMOP);
2381 SV* const repointer = &PL_sv_undef;
2382 /* this regexp is also owned by the new PL_reg_curpm, which
2383 will try to free it. */
2384 av_push(PL_regex_padav, repointer);
2385 PL_reg_curpm->op_pmoffset = av_len(PL_regex_padav);
2386 PL_regex_pad = AvARRAY(PL_regex_padav);
2391 /* It seems that non-ithreads works both with and without this code.
2392 So for efficiency reasons it seems best not to have the code
2393 compiled when it is not needed. */
2394 /* This is safe against NULLs: */
2395 ReREFCNT_dec(PM_GETRE(PL_reg_curpm));
2396 /* PM_reg_curpm owns a reference to this regexp. */
2399 PM_SETRE(PL_reg_curpm, rx);
2400 PL_reg_oldcurpm = PL_curpm;
2401 PL_curpm = PL_reg_curpm;
2402 if (RXp_MATCH_COPIED(prog)) {
2403 /* Here is a serious problem: we cannot rewrite subbeg,
2404 since it may be needed if this match fails. Thus
2405 $` inside (?{}) could fail... */
2406 PL_reg_oldsaved = prog->subbeg;
2407 PL_reg_oldsavedlen = prog->sublen;
2408 #ifdef PERL_OLD_COPY_ON_WRITE
2409 PL_nrs = prog->saved_copy;
2411 RXp_MATCH_COPIED_off(prog);
2414 PL_reg_oldsaved = NULL;
2415 prog->subbeg = PL_bostr;
2416 prog->sublen = PL_regeol - PL_bostr; /* strend may have been modified */
2418 DEBUG_EXECUTE_r(PL_reg_starttry = *startpos);
2419 prog->offs[0].start = *startpos - PL_bostr;
2420 PL_reginput = *startpos;
2421 PL_reglastparen = &prog->lastparen;
2422 PL_reglastcloseparen = &prog->lastcloseparen;
2423 prog->lastparen = 0;
2424 prog->lastcloseparen = 0;
2426 PL_regoffs = prog->offs;
2427 if (PL_reg_start_tmpl <= prog->nparens) {
2428 PL_reg_start_tmpl = prog->nparens*3/2 + 3;
2429 if(PL_reg_start_tmp)
2430 Renew(PL_reg_start_tmp, PL_reg_start_tmpl, char*);
2432 Newx(PL_reg_start_tmp, PL_reg_start_tmpl, char*);
2435 /* XXXX What this code is doing here?!!! There should be no need
2436 to do this again and again, PL_reglastparen should take care of
2439 /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
2440 * Actually, the code in regcppop() (which Ilya may be meaning by
2441 * PL_reglastparen), is not needed at all by the test suite
2442 * (op/regexp, op/pat, op/split), but that code is needed otherwise
2443 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
2444 * Meanwhile, this code *is* needed for the
2445 * above-mentioned test suite tests to succeed. The common theme
2446 * on those tests seems to be returning null fields from matches.
2447 * --jhi updated by dapm */
2449 if (prog->nparens) {
2450 regexp_paren_pair *pp = PL_regoffs;
2452 for (i = prog->nparens; i > (I32)*PL_reglastparen; i--) {
2460 if (regmatch(reginfo, progi->program + 1)) {
2461 PL_regoffs[0].end = PL_reginput - PL_bostr;
2464 if (reginfo->cutpoint)
2465 *startpos= reginfo->cutpoint;
2466 REGCP_UNWIND(lastcp);
2471 #define sayYES goto yes
2472 #define sayNO goto no
2473 #define sayNO_SILENT goto no_silent
2475 /* we dont use STMT_START/END here because it leads to
2476 "unreachable code" warnings, which are bogus, but distracting. */
2477 #define CACHEsayNO \
2478 if (ST.cache_mask) \
2479 PL_reg_poscache[ST.cache_offset] |= ST.cache_mask; \
2482 /* this is used to determine how far from the left messages like
2483 'failed...' are printed. It should be set such that messages
2484 are inline with the regop output that created them.
2486 #define REPORT_CODE_OFF 32
2489 /* Make sure there is a test for this +1 options in re_tests */
2490 #define TRIE_INITAL_ACCEPT_BUFFLEN 4;
2492 #define CHRTEST_UNINIT -1001 /* c1/c2 haven't been calculated yet */
2493 #define CHRTEST_VOID -1000 /* the c1/c2 "next char" test should be skipped */
2495 #define SLAB_FIRST(s) (&(s)->states[0])
2496 #define SLAB_LAST(s) (&(s)->states[PERL_REGMATCH_SLAB_SLOTS-1])
2498 /* grab a new slab and return the first slot in it */
2500 STATIC regmatch_state *
2503 #if PERL_VERSION < 9 && !defined(PERL_CORE)
2506 regmatch_slab *s = PL_regmatch_slab->next;
2508 Newx(s, 1, regmatch_slab);
2509 s->prev = PL_regmatch_slab;
2511 PL_regmatch_slab->next = s;
2513 PL_regmatch_slab = s;
2514 return SLAB_FIRST(s);
2518 /* push a new state then goto it */
2520 #define PUSH_STATE_GOTO(state, node) \
2522 st->resume_state = state; \
2525 /* push a new state with success backtracking, then goto it */
2527 #define PUSH_YES_STATE_GOTO(state, node) \
2529 st->resume_state = state; \
2530 goto push_yes_state;
2536 regmatch() - main matching routine
2538 This is basically one big switch statement in a loop. We execute an op,
2539 set 'next' to point the next op, and continue. If we come to a point which
2540 we may need to backtrack to on failure such as (A|B|C), we push a
2541 backtrack state onto the backtrack stack. On failure, we pop the top
2542 state, and re-enter the loop at the state indicated. If there are no more
2543 states to pop, we return failure.
2545 Sometimes we also need to backtrack on success; for example /A+/, where
2546 after successfully matching one A, we need to go back and try to
2547 match another one; similarly for lookahead assertions: if the assertion
2548 completes successfully, we backtrack to the state just before the assertion
2549 and then carry on. In these cases, the pushed state is marked as
2550 'backtrack on success too'. This marking is in fact done by a chain of
2551 pointers, each pointing to the previous 'yes' state. On success, we pop to
2552 the nearest yes state, discarding any intermediate failure-only states.
2553 Sometimes a yes state is pushed just to force some cleanup code to be
2554 called at the end of a successful match or submatch; e.g. (??{$re}) uses
2555 it to free the inner regex.
2557 Note that failure backtracking rewinds the cursor position, while
2558 success backtracking leaves it alone.
2560 A pattern is complete when the END op is executed, while a subpattern
2561 such as (?=foo) is complete when the SUCCESS op is executed. Both of these
2562 ops trigger the "pop to last yes state if any, otherwise return true"
2565 A common convention in this function is to use A and B to refer to the two
2566 subpatterns (or to the first nodes thereof) in patterns like /A*B/: so A is
2567 the subpattern to be matched possibly multiple times, while B is the entire
2568 rest of the pattern. Variable and state names reflect this convention.
2570 The states in the main switch are the union of ops and failure/success of
2571 substates associated with with that op. For example, IFMATCH is the op
2572 that does lookahead assertions /(?=A)B/ and so the IFMATCH state means
2573 'execute IFMATCH'; while IFMATCH_A is a state saying that we have just
2574 successfully matched A and IFMATCH_A_fail is a state saying that we have
2575 just failed to match A. Resume states always come in pairs. The backtrack
2576 state we push is marked as 'IFMATCH_A', but when that is popped, we resume
2577 at IFMATCH_A or IFMATCH_A_fail, depending on whether we are backtracking
2578 on success or failure.
2580 The struct that holds a backtracking state is actually a big union, with
2581 one variant for each major type of op. The variable st points to the
2582 top-most backtrack struct. To make the code clearer, within each
2583 block of code we #define ST to alias the relevant union.
2585 Here's a concrete example of a (vastly oversimplified) IFMATCH
2591 #define ST st->u.ifmatch
2593 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
2594 ST.foo = ...; // some state we wish to save
2596 // push a yes backtrack state with a resume value of
2597 // IFMATCH_A/IFMATCH_A_fail, then continue execution at the
2599 PUSH_YES_STATE_GOTO(IFMATCH_A, A);
2602 case IFMATCH_A: // we have successfully executed A; now continue with B
2604 bar = ST.foo; // do something with the preserved value
2607 case IFMATCH_A_fail: // A failed, so the assertion failed
2608 ...; // do some housekeeping, then ...
2609 sayNO; // propagate the failure
2616 For any old-timers reading this who are familiar with the old recursive
2617 approach, the code above is equivalent to:
2619 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
2628 ...; // do some housekeeping, then ...
2629 sayNO; // propagate the failure
2632 The topmost backtrack state, pointed to by st, is usually free. If you
2633 want to claim it, populate any ST.foo fields in it with values you wish to
2634 save, then do one of
2636 PUSH_STATE_GOTO(resume_state, node);
2637 PUSH_YES_STATE_GOTO(resume_state, node);
2639 which sets that backtrack state's resume value to 'resume_state', pushes a
2640 new free entry to the top of the backtrack stack, then goes to 'node'.
2641 On backtracking, the free slot is popped, and the saved state becomes the
2642 new free state. An ST.foo field in this new top state can be temporarily
2643 accessed to retrieve values, but once the main loop is re-entered, it
2644 becomes available for reuse.
2646 Note that the depth of the backtrack stack constantly increases during the
2647 left-to-right execution of the pattern, rather than going up and down with
2648 the pattern nesting. For example the stack is at its maximum at Z at the
2649 end of the pattern, rather than at X in the following:
2651 /(((X)+)+)+....(Y)+....Z/
2653 The only exceptions to this are lookahead/behind assertions and the cut,
2654 (?>A), which pop all the backtrack states associated with A before
2657 Bascktrack state structs are allocated in slabs of about 4K in size.
2658 PL_regmatch_state and st always point to the currently active state,
2659 and PL_regmatch_slab points to the slab currently containing
2660 PL_regmatch_state. The first time regmatch() is called, the first slab is
2661 allocated, and is never freed until interpreter destruction. When the slab
2662 is full, a new one is allocated and chained to the end. At exit from
2663 regmatch(), slabs allocated since entry are freed.
2668 #define DEBUG_STATE_pp(pp) \
2670 DUMP_EXEC_POS(locinput, scan, do_utf8); \
2671 PerlIO_printf(Perl_debug_log, \
2672 " %*s"pp" %s%s%s%s%s\n", \
2674 PL_reg_name[st->resume_state], \
2675 ((st==yes_state||st==mark_state) ? "[" : ""), \
2676 ((st==yes_state) ? "Y" : ""), \
2677 ((st==mark_state) ? "M" : ""), \
2678 ((st==yes_state||st==mark_state) ? "]" : "") \
2683 #define REG_NODE_NUM(x) ((x) ? (int)((x)-prog) : -1)
2688 S_debug_start_match(pTHX_ const REGEXP *prog, const bool do_utf8,
2689 const char *start, const char *end, const char *blurb)
2691 const bool utf8_pat = RX_UTF8(prog) ? 1 : 0;
2693 PERL_ARGS_ASSERT_DEBUG_START_MATCH;
2698 RE_PV_QUOTED_DECL(s0, utf8_pat, PERL_DEBUG_PAD_ZERO(0),
2699 RX_PRECOMP_const(prog), RX_PRELEN(prog), 60);
2701 RE_PV_QUOTED_DECL(s1, do_utf8, PERL_DEBUG_PAD_ZERO(1),
2702 start, end - start, 60);
2704 PerlIO_printf(Perl_debug_log,
2705 "%s%s REx%s %s against %s\n",
2706 PL_colors[4], blurb, PL_colors[5], s0, s1);
2708 if (do_utf8||utf8_pat)
2709 PerlIO_printf(Perl_debug_log, "UTF-8 %s%s%s...\n",
2710 utf8_pat ? "pattern" : "",
2711 utf8_pat && do_utf8 ? " and " : "",
2712 do_utf8 ? "string" : ""
2718 S_dump_exec_pos(pTHX_ const char *locinput,
2719 const regnode *scan,
2720 const char *loc_regeol,
2721 const char *loc_bostr,
2722 const char *loc_reg_starttry,
2725 const int docolor = *PL_colors[0] || *PL_colors[2] || *PL_colors[4];
2726 const int taill = (docolor ? 10 : 7); /* 3 chars for "> <" */
2727 int l = (loc_regeol - locinput) > taill ? taill : (loc_regeol - locinput);
2728 /* The part of the string before starttry has one color
2729 (pref0_len chars), between starttry and current
2730 position another one (pref_len - pref0_len chars),
2731 after the current position the third one.
2732 We assume that pref0_len <= pref_len, otherwise we
2733 decrease pref0_len. */
2734 int pref_len = (locinput - loc_bostr) > (5 + taill) - l
2735 ? (5 + taill) - l : locinput - loc_bostr;
2738 PERL_ARGS_ASSERT_DUMP_EXEC_POS;
2740 while (do_utf8 && UTF8_IS_CONTINUATION(*(U8*)(locinput - pref_len)))
2742 pref0_len = pref_len - (locinput - loc_reg_starttry);
2743 if (l + pref_len < (5 + taill) && l < loc_regeol - locinput)
2744 l = ( loc_regeol - locinput > (5 + taill) - pref_len
2745 ? (5 + taill) - pref_len : loc_regeol - locinput);
2746 while (do_utf8 && UTF8_IS_CONTINUATION(*(U8*)(locinput + l)))
2750 if (pref0_len > pref_len)
2751 pref0_len = pref_len;
2753 const int is_uni = (do_utf8 && OP(scan) != CANY) ? 1 : 0;
2755 RE_PV_COLOR_DECL(s0,len0,is_uni,PERL_DEBUG_PAD(0),
2756 (locinput - pref_len),pref0_len, 60, 4, 5);
2758 RE_PV_COLOR_DECL(s1,len1,is_uni,PERL_DEBUG_PAD(1),
2759 (locinput - pref_len + pref0_len),
2760 pref_len - pref0_len, 60, 2, 3);
2762 RE_PV_COLOR_DECL(s2,len2,is_uni,PERL_DEBUG_PAD(2),
2763 locinput, loc_regeol - locinput, 10, 0, 1);
2765 const STRLEN tlen=len0+len1+len2;
2766 PerlIO_printf(Perl_debug_log,
2767 "%4"IVdf" <%.*s%.*s%s%.*s>%*s|",
2768 (IV)(locinput - loc_bostr),
2771 (docolor ? "" : "> <"),
2773 (int)(tlen > 19 ? 0 : 19 - tlen),
2780 /* reg_check_named_buff_matched()
2781 * Checks to see if a named buffer has matched. The data array of
2782 * buffer numbers corresponding to the buffer is expected to reside
2783 * in the regexp->data->data array in the slot stored in the ARG() of
2784 * node involved. Note that this routine doesn't actually care about the
2785 * name, that information is not preserved from compilation to execution.
2786 * Returns the index of the leftmost defined buffer with the given name
2787 * or 0 if non of the buffers matched.
2790 S_reg_check_named_buff_matched(pTHX_ const regexp *rex, const regnode *scan)
2793 RXi_GET_DECL(rex,rexi);
2794 SV *sv_dat= MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
2795 I32 *nums=(I32*)SvPVX(sv_dat);
2797 PERL_ARGS_ASSERT_REG_CHECK_NAMED_BUFF_MATCHED;
2799 for ( n=0; n<SvIVX(sv_dat); n++ ) {
2800 if ((I32)*PL_reglastparen >= nums[n] &&
2801 PL_regoffs[nums[n]].end != -1)
2810 /* free all slabs above current one - called during LEAVE_SCOPE */
2813 S_clear_backtrack_stack(pTHX_ void *p)
2815 regmatch_slab *s = PL_regmatch_slab->next;
2820 PL_regmatch_slab->next = NULL;
2822 regmatch_slab * const osl = s;
2829 #define SETREX(Re1,Re2) \
2830 if (PL_reg_eval_set) PM_SETRE((PL_reg_curpm), (Re2)); \
2833 STATIC I32 /* 0 failure, 1 success */
2834 S_regmatch(pTHX_ regmatch_info *reginfo, regnode *prog)
2836 #if PERL_VERSION < 9 && !defined(PERL_CORE)
2840 register const bool do_utf8 = PL_reg_match_utf8;
2841 const U32 uniflags = UTF8_ALLOW_DEFAULT;
2842 REGEXP *rex_sv = reginfo->prog;
2843 regexp *rex = (struct regexp *)SvANY(rex_sv);
2844 RXi_GET_DECL(rex,rexi);
2846 /* the current state. This is a cached copy of PL_regmatch_state */
2847 register regmatch_state *st;
2848 /* cache heavy used fields of st in registers */
2849 register regnode *scan;
2850 register regnode *next;
2851 register U32 n = 0; /* general value; init to avoid compiler warning */
2852 register I32 ln = 0; /* len or last; init to avoid compiler warning */
2853 register char *locinput = PL_reginput;
2854 register I32 nextchr; /* is always set to UCHARAT(locinput) */
2856 bool result = 0; /* return value of S_regmatch */
2857 int depth = 0; /* depth of backtrack stack */
2858 U32 nochange_depth = 0; /* depth of GOSUB recursion with nochange */
2859 const U32 max_nochange_depth =
2860 (3 * rex->nparens > MAX_RECURSE_EVAL_NOCHANGE_DEPTH) ?
2861 3 * rex->nparens : MAX_RECURSE_EVAL_NOCHANGE_DEPTH;
2862 regmatch_state *yes_state = NULL; /* state to pop to on success of
2864 /* mark_state piggy backs on the yes_state logic so that when we unwind
2865 the stack on success we can update the mark_state as we go */
2866 regmatch_state *mark_state = NULL; /* last mark state we have seen */
2867 regmatch_state *cur_eval = NULL; /* most recent EVAL_AB state */
2868 struct regmatch_state *cur_curlyx = NULL; /* most recent curlyx */
2870 bool no_final = 0; /* prevent failure from backtracking? */
2871 bool do_cutgroup = 0; /* no_final only until next branch/trie entry */
2872 char *startpoint = PL_reginput;
2873 SV *popmark = NULL; /* are we looking for a mark? */
2874 SV *sv_commit = NULL; /* last mark name seen in failure */
2875 SV *sv_yes_mark = NULL; /* last mark name we have seen
2876 during a successfull match */
2877 U32 lastopen = 0; /* last open we saw */
2878 bool has_cutgroup = RX_HAS_CUTGROUP(rex) ? 1 : 0;
2879 SV* const oreplsv = GvSV(PL_replgv);
2880 /* these three flags are set by various ops to signal information to
2881 * the very next op. They have a useful lifetime of exactly one loop
2882 * iteration, and are not preserved or restored by state pushes/pops
2884 bool sw = 0; /* the condition value in (?(cond)a|b) */
2885 bool minmod = 0; /* the next "{n,m}" is a "{n,m}?" */
2886 int logical = 0; /* the following EVAL is:
2890 or the following IFMATCH/UNLESSM is:
2891 false: plain (?=foo)
2892 true: used as a condition: (?(?=foo))
2895 GET_RE_DEBUG_FLAGS_DECL;
2898 PERL_ARGS_ASSERT_REGMATCH;
2900 DEBUG_OPTIMISE_r( DEBUG_EXECUTE_r({
2901 PerlIO_printf(Perl_debug_log,"regmatch start\n");
2903 /* on first ever call to regmatch, allocate first slab */
2904 if (!PL_regmatch_slab) {
2905 Newx(PL_regmatch_slab, 1, regmatch_slab);
2906 PL_regmatch_slab->prev = NULL;
2907 PL_regmatch_slab->next = NULL;
2908 PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
2911 oldsave = PL_savestack_ix;
2912 SAVEDESTRUCTOR_X(S_clear_backtrack_stack, NULL);
2913 SAVEVPTR(PL_regmatch_slab);
2914 SAVEVPTR(PL_regmatch_state);
2916 /* grab next free state slot */
2917 st = ++PL_regmatch_state;
2918 if (st > SLAB_LAST(PL_regmatch_slab))
2919 st = PL_regmatch_state = S_push_slab(aTHX);
2921 /* Note that nextchr is a byte even in UTF */
2922 nextchr = UCHARAT(locinput);
2924 while (scan != NULL) {
2927 SV * const prop = sv_newmortal();
2928 regnode *rnext=regnext(scan);
2929 DUMP_EXEC_POS( locinput, scan, do_utf8 );
2930 regprop(rex, prop, scan);
2932 PerlIO_printf(Perl_debug_log,
2933 "%3"IVdf":%*s%s(%"IVdf")\n",
2934 (IV)(scan - rexi->program), depth*2, "",
2936 (PL_regkind[OP(scan)] == END || !rnext) ?
2937 0 : (IV)(rnext - rexi->program));
2940 next = scan + NEXT_OFF(scan);
2943 state_num = OP(scan);
2945 REH_CALL_REGEXEC_HOOK(rex, scan, reginfo, st);
2948 assert(PL_reglastparen == &rex->lastparen);
2949 assert(PL_reglastcloseparen == &rex->lastcloseparen);
2950 assert(PL_regoffs == rex->offs);
2952 switch (state_num) {
2954 if (locinput == PL_bostr)
2956 /* reginfo->till = reginfo->bol; */
2961 if (locinput == PL_bostr ||
2962 ((nextchr || locinput < PL_regeol) && locinput[-1] == '\n'))
2968 if (locinput == PL_bostr)
2972 if (locinput == reginfo->ganch)
2977 /* update the startpoint */
2978 st->u.keeper.val = PL_regoffs[0].start;
2979 PL_reginput = locinput;
2980 PL_regoffs[0].start = locinput - PL_bostr;
2981 PUSH_STATE_GOTO(KEEPS_next, next);
2983 case KEEPS_next_fail:
2984 /* rollback the start point change */
2985 PL_regoffs[0].start = st->u.keeper.val;
2991 if ((nextchr || locinput < PL_regeol) && nextchr != '\n')
2996 if ((nextchr || locinput < PL_regeol) && nextchr != '\n')
2998 if (PL_regeol - locinput > 1)
3002 if (PL_regeol != locinput)
3006 if (!nextchr && locinput >= PL_regeol)
3009 locinput += PL_utf8skip[nextchr];
3010 if (locinput > PL_regeol)
3012 nextchr = UCHARAT(locinput);
3015 nextchr = UCHARAT(++locinput);
3018 if (!nextchr && locinput >= PL_regeol)
3020 nextchr = UCHARAT(++locinput);
3023 if ((!nextchr && locinput >= PL_regeol) || nextchr == '\n')
3026 locinput += PL_utf8skip[nextchr];
3027 if (locinput > PL_regeol)
3029 nextchr = UCHARAT(locinput);
3032 nextchr = UCHARAT(++locinput);
3036 #define ST st->u.trie
3038 /* In this case the charclass data is available inline so
3039 we can fail fast without a lot of extra overhead.
3041 if (scan->flags == EXACT || !do_utf8) {
3042 if(!ANYOF_BITMAP_TEST(scan, *locinput)) {
3044 PerlIO_printf(Perl_debug_log,
3045 "%*s %sfailed to match trie start class...%s\n",
3046 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
3055 /* what type of TRIE am I? (utf8 makes this contextual) */
3056 DECL_TRIE_TYPE(scan);
3058 /* what trie are we using right now */
3059 reg_trie_data * const trie
3060 = (reg_trie_data*)rexi->data->data[ ARG( scan ) ];
3061 HV * widecharmap = MUTABLE_HV(rexi->data->data[ ARG( scan ) + 1 ]);
3062 U32 state = trie->startstate;
3064 if (trie->bitmap && trie_type != trie_utf8_fold &&
3065 !TRIE_BITMAP_TEST(trie,*locinput)
3067 if (trie->states[ state ].wordnum) {
3069 PerlIO_printf(Perl_debug_log,
3070 "%*s %smatched empty string...%s\n",
3071 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
3076 PerlIO_printf(Perl_debug_log,
3077 "%*s %sfailed to match trie start class...%s\n",
3078 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
3085 U8 *uc = ( U8* )locinput;
3089 U8 *uscan = (U8*)NULL;
3091 SV *sv_accept_buff = NULL;
3092 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
3094 ST.accepted = 0; /* how many accepting states we have seen */
3096 ST.jump = trie->jump;
3099 traverse the TRIE keeping track of all accepting states
3100 we transition through until we get to a failing node.
3103 while ( state && uc <= (U8*)PL_regeol ) {
3104 U32 base = trie->states[ state ].trans.base;
3107 /* We use charid to hold the wordnum as we don't use it
3108 for charid until after we have done the wordnum logic.
3109 We define an alias just so that the wordnum logic reads
3112 #define got_wordnum charid
3113 got_wordnum = trie->states[ state ].wordnum;
3115 if ( got_wordnum ) {
3116 if ( ! ST.accepted ) {
3118 SAVETMPS; /* XXX is this necessary? dmq */
3119 bufflen = TRIE_INITAL_ACCEPT_BUFFLEN;
3120 sv_accept_buff=newSV(bufflen *
3121 sizeof(reg_trie_accepted) - 1);
3122 SvCUR_set(sv_accept_buff, 0);
3123 SvPOK_on(sv_accept_buff);
3124 sv_2mortal(sv_accept_buff);
3127 (reg_trie_accepted*)SvPV_nolen(sv_accept_buff );
3130 if (ST.accepted >= bufflen) {
3132 ST.accept_buff =(reg_trie_accepted*)
3133 SvGROW(sv_accept_buff,
3134 bufflen * sizeof(reg_trie_accepted));
3136 SvCUR_set(sv_accept_buff,SvCUR(sv_accept_buff)
3137 + sizeof(reg_trie_accepted));
3140 ST.accept_buff[ST.accepted].wordnum = got_wordnum;
3141 ST.accept_buff[ST.accepted].endpos = uc;
3143 } while (trie->nextword && (got_wordnum= trie->nextword[got_wordnum]));
3147 DEBUG_TRIE_EXECUTE_r({
3148 DUMP_EXEC_POS( (char *)uc, scan, do_utf8 );
3149 PerlIO_printf( Perl_debug_log,
3150 "%*s %sState: %4"UVxf" Accepted: %4"UVxf" ",
3151 2+depth * 2, "", PL_colors[4],
3152 (UV)state, (UV)ST.accepted );
3156 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
3157 uscan, len, uvc, charid, foldlen,
3161 (base + charid > trie->uniquecharcount )
3162 && (base + charid - 1 - trie->uniquecharcount
3164 && trie->trans[base + charid - 1 -
3165 trie->uniquecharcount].check == state)
3167 state = trie->trans[base + charid - 1 -
3168 trie->uniquecharcount ].next;
3179 DEBUG_TRIE_EXECUTE_r(
3180 PerlIO_printf( Perl_debug_log,
3181 "Charid:%3x CP:%4"UVxf" After State: %4"UVxf"%s\n",
3182 charid, uvc, (UV)state, PL_colors[5] );
3189 PerlIO_printf( Perl_debug_log,
3190 "%*s %sgot %"IVdf" possible matches%s\n",
3191 REPORT_CODE_OFF + depth * 2, "",
3192 PL_colors[4], (IV)ST.accepted, PL_colors[5] );
3195 goto trie_first_try; /* jump into the fail handler */
3197 case TRIE_next_fail: /* we failed - try next alterative */
3199 REGCP_UNWIND(ST.cp);
3200 for (n = *PL_reglastparen; n > ST.lastparen; n--)
3201 PL_regoffs[n].end = -1;
3202 *PL_reglastparen = n;
3211 ST.lastparen = *PL_reglastparen;
3214 if ( ST.accepted == 1 ) {
3215 /* only one choice left - just continue */
3217 AV *const trie_words
3218 = MUTABLE_AV(rexi->data->data[ARG(ST.me)+TRIE_WORDS_OFFSET]);
3219 SV ** const tmp = av_fetch( trie_words,
3220 ST.accept_buff[ 0 ].wordnum-1, 0 );
3221 SV *sv= tmp ? sv_newmortal() : NULL;
3223 PerlIO_printf( Perl_debug_log,
3224 "%*s %sonly one match left: #%d <%s>%s\n",
3225 REPORT_CODE_OFF+depth*2, "", PL_colors[4],
3226 ST.accept_buff[ 0 ].wordnum,
3227 tmp ? pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 0,
3228 PL_colors[0], PL_colors[1],
3229 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)
3231 : "not compiled under -Dr",
3234 PL_reginput = (char *)ST.accept_buff[ 0 ].endpos;
3235 /* in this case we free tmps/leave before we call regmatch
3236 as we wont be using accept_buff again. */
3238 locinput = PL_reginput;
3239 nextchr = UCHARAT(locinput);
3240 if ( !ST.jump || !ST.jump[ST.accept_buff[0].wordnum])
3243 scan = ST.me + ST.jump[ST.accept_buff[0].wordnum];
3244 if (!has_cutgroup) {
3249 PUSH_YES_STATE_GOTO(TRIE_next, scan);
3252 continue; /* execute rest of RE */
3255 if ( !ST.accepted-- ) {
3257 PerlIO_printf( Perl_debug_log,
3258 "%*s %sTRIE failed...%s\n",
3259 REPORT_CODE_OFF+depth*2, "",
3270 There are at least two accepting states left. Presumably
3271 the number of accepting states is going to be low,
3272 typically two. So we simply scan through to find the one
3273 with lowest wordnum. Once we find it, we swap the last
3274 state into its place and decrement the size. We then try to
3275 match the rest of the pattern at the point where the word
3276 ends. If we succeed, control just continues along the
3277 regex; if we fail we return here to try the next accepting
3284 for( cur = 1 ; cur <= ST.accepted ; cur++ ) {
3285 DEBUG_TRIE_EXECUTE_r(
3286 PerlIO_printf( Perl_debug_log,
3287 "%*s %sgot %"IVdf" (%d) as best, looking at %"IVdf" (%d)%s\n",
3288 REPORT_CODE_OFF + depth * 2, "", PL_colors[4],
3289 (IV)best, ST.accept_buff[ best ].wordnum, (IV)cur,
3290 ST.accept_buff[ cur ].wordnum, PL_colors[5] );
3293 if (ST.accept_buff[cur].wordnum <
3294 ST.accept_buff[best].wordnum)
3299 AV *const trie_words
3300 = MUTABLE_AV(rexi->data->data[ARG(ST.me)+TRIE_WORDS_OFFSET]);
3301 SV ** const tmp = av_fetch( trie_words,
3302 ST.accept_buff[ best ].wordnum - 1, 0 );
3303 regnode *nextop=(!ST.jump || !ST.jump[ST.accept_buff[best].wordnum]) ?
3305 ST.me + ST.jump[ST.accept_buff[best].wordnum];
3306 SV *sv= tmp ? sv_newmortal() : NULL;
3308 PerlIO_printf( Perl_debug_log,
3309 "%*s %strying alternation #%d <%s> at node #%d %s\n",
3310 REPORT_CODE_OFF+depth*2, "", PL_colors[4],
3311 ST.accept_buff[best].wordnum,
3312 tmp ? pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 0,
3313 PL_colors[0], PL_colors[1],
3314 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)
3315 ) : "not compiled under -Dr",
3316 REG_NODE_NUM(nextop),
3320 if ( best<ST.accepted ) {
3321 reg_trie_accepted tmp = ST.accept_buff[ best ];
3322 ST.accept_buff[ best ] = ST.accept_buff[ ST.accepted ];
3323 ST.accept_buff[ ST.accepted ] = tmp;
3326 PL_reginput = (char *)ST.accept_buff[ best ].endpos;
3327 if ( !ST.jump || !ST.jump[ST.accept_buff[best].wordnum]) {
3330 scan = ST.me + ST.jump[ST.accept_buff[best].wordnum];
3332 PUSH_YES_STATE_GOTO(TRIE_next, scan);
3337 /* we dont want to throw this away, see bug 57042*/
3338 if (oreplsv != GvSV(PL_replgv))
3339 sv_setsv(oreplsv, GvSV(PL_replgv));
3346 char *s = STRING(scan);
3348 if (do_utf8 != UTF) {
3349 /* The target and the pattern have differing utf8ness. */
3351 const char * const e = s + ln;
3354 /* The target is utf8, the pattern is not utf8. */
3359 if (NATIVE_TO_UNI(*(U8*)s) !=
3360 utf8n_to_uvuni((U8*)l, UTF8_MAXBYTES, &ulen,
3368 /* The target is not utf8, the pattern is utf8. */
3373 if (NATIVE_TO_UNI(*((U8*)l)) !=
3374 utf8n_to_uvuni((U8*)s, UTF8_MAXBYTES, &ulen,
3382 nextchr = UCHARAT(locinput);
3385 /* The target and the pattern have the same utf8ness. */
3386 /* Inline the first character, for speed. */
3387 if (UCHARAT(s) != nextchr)
3389 if (PL_regeol - locinput < ln)
3391 if (ln > 1 && memNE(s, locinput, ln))
3394 nextchr = UCHARAT(locinput);
3398 PL_reg_flags |= RF_tainted;
3401 char * const s = STRING(scan);
3404 if (do_utf8 || UTF) {
3405 /* Either target or the pattern are utf8. */
3406 const char * const l = locinput;
3407 char *e = PL_regeol;
3409 if (ibcmp_utf8(s, 0, ln, (bool)UTF,
3410 l, &e, 0, do_utf8)) {
3411 /* One more case for the sharp s:
3412 * pack("U0U*", 0xDF) =~ /ss/i,
3413 * the 0xC3 0x9F are the UTF-8
3414 * byte sequence for the U+00DF. */
3417 toLOWER(s[0]) == 's' &&
3419 toLOWER(s[1]) == 's' &&
3426 nextchr = UCHARAT(locinput);
3430 /* Neither the target and the pattern are utf8. */
3432 /* Inline the first character, for speed. */
3433 if (UCHARAT(s) != nextchr &&
3434 UCHARAT(s) != ((OP(scan) == EXACTF)
3435 ? PL_fold : PL_fold_locale)[nextchr])
3437 if (PL_regeol - locinput < ln)
3439 if (ln > 1 && (OP(scan) == EXACTF
3440 ? ibcmp(s, locinput, ln)
3441 : ibcmp_locale(s, locinput, ln)))
3444 nextchr = UCHARAT(locinput);
3449 PL_reg_flags |= RF_tainted;
3453 /* was last char in word? */
3455 if (locinput == PL_bostr)
3458 const U8 * const r = reghop3((U8*)locinput, -1, (U8*)PL_bostr);
3460 ln = utf8n_to_uvchr(r, UTF8SKIP(r), 0, uniflags);
3462 if (OP(scan) == BOUND || OP(scan) == NBOUND) {
3463 ln = isALNUM_uni(ln);
3464 LOAD_UTF8_CHARCLASS_ALNUM();
3465 n = swash_fetch(PL_utf8_alnum, (U8*)locinput, do_utf8);
3468 ln = isALNUM_LC_uvchr(UNI_TO_NATIVE(ln));
3469 n = isALNUM_LC_utf8((U8*)locinput);
3473 ln = (locinput != PL_bostr) ?
3474 UCHARAT(locinput - 1) : '\n';
3475 if (OP(scan) == BOUND || OP(scan) == NBOUND) {
3477 n = isALNUM(nextchr);
3480 ln = isALNUM_LC(ln);
3481 n = isALNUM_LC(nextchr);
3484 if (((!ln) == (!n)) == (OP(scan) == BOUND ||
3485 OP(scan) == BOUNDL))
3490 STRLEN inclasslen = PL_regeol - locinput;
3492 if (!reginclass(rex, scan, (U8*)locinput, &inclasslen, do_utf8))
3494 if (locinput >= PL_regeol)
3496 locinput += inclasslen ? inclasslen : UTF8SKIP(locinput);
3497 nextchr = UCHARAT(locinput);
3502 nextchr = UCHARAT(locinput);
3503 if (!REGINCLASS(rex, scan, (U8*)locinput))
3505 if (!nextchr && locinput >= PL_regeol)
3507 nextchr = UCHARAT(++locinput);
3511 /* If we might have the case of the German sharp s
3512 * in a casefolding Unicode character class. */
3514 if (ANYOF_FOLD_SHARP_S(scan, locinput, PL_regeol)) {
3515 locinput += SHARP_S_SKIP;
3516 nextchr = UCHARAT(locinput);
3521 /* Special char classes - The defines start on line 129 or so */
3522 CCC_TRY_AFF( ALNUM, ALNUML, perl_word, "a", isALNUM_LC_utf8, isALNUM, isALNUM_LC);
3523 CCC_TRY_NEG(NALNUM, NALNUML, perl_word, "a", isALNUM_LC_utf8, isALNUM, isALNUM_LC);
3525 CCC_TRY_AFF( SPACE, SPACEL, perl_space, " ", isSPACE_LC_utf8, isSPACE, isSPACE_LC);
3526 CCC_TRY_NEG(NSPACE, NSPACEL, perl_space, " ", isSPACE_LC_utf8, isSPACE, isSPACE_LC);
3528 CCC_TRY_AFF( DIGIT, DIGITL, posix_digit, "0", isDIGIT_LC_utf8, isDIGIT, isDIGIT_LC);
3529 CCC_TRY_NEG(NDIGIT, NDIGITL, posix_digit, "0", isDIGIT_LC_utf8, isDIGIT, isDIGIT_LC);
3532 if (locinput >= PL_regeol)
3535 LOAD_UTF8_CHARCLASS_MARK();
3536 if (swash_fetch(PL_utf8_mark,(U8*)locinput, do_utf8))
3538 locinput += PL_utf8skip[nextchr];
3539 while (locinput < PL_regeol &&
3540 swash_fetch(PL_utf8_mark,(U8*)locinput, do_utf8))
3541 locinput += UTF8SKIP(locinput);
3542 if (locinput > PL_regeol)
3547 nextchr = UCHARAT(locinput);
3554 PL_reg_flags |= RF_tainted;
3559 n = reg_check_named_buff_matched(rex,scan);
3562 type = REF + ( type - NREF );
3569 PL_reg_flags |= RF_tainted;
3573 n = ARG(scan); /* which paren pair */
3576 ln = PL_regoffs[n].start;
3577 PL_reg_leftiter = PL_reg_maxiter; /* Void cache */
3578 if (*PL_reglastparen < n || ln == -1)
3579 sayNO; /* Do not match unless seen CLOSEn. */
3580 if (ln == PL_regoffs[n].end)
3584 if (do_utf8 && type != REF) { /* REF can do byte comparison */
3586 const char *e = PL_bostr + PL_regoffs[n].end;
3588 * Note that we can't do the "other character" lookup trick as
3589 * in the 8-bit case (no pun intended) because in Unicode we
3590 * have to map both upper and title case to lower case.
3594 STRLEN ulen1, ulen2;
3595 U8 tmpbuf1[UTF8_MAXBYTES_CASE+1];
3596 U8 tmpbuf2[UTF8_MAXBYTES_CASE+1];
3600 toLOWER_utf8((U8*)s, tmpbuf1, &ulen1);
3601 toLOWER_utf8((U8*)l, tmpbuf2, &ulen2);
3602 if (ulen1 != ulen2 || memNE((char *)tmpbuf1, (char *)tmpbuf2, ulen1))
3609 nextchr = UCHARAT(locinput);
3613 /* Inline the first character, for speed. */
3614 if (UCHARAT(s) != nextchr &&
3616 (UCHARAT(s) != (type == REFF
3617 ? PL_fold : PL_fold_locale)[nextchr])))
3619 ln = PL_regoffs[n].end - ln;
3620 if (locinput + ln > PL_regeol)
3622 if (ln > 1 && (type == REF
3623 ? memNE(s, locinput, ln)
3625 ? ibcmp(s, locinput, ln)
3626 : ibcmp_locale(s, locinput, ln))))
3629 nextchr = UCHARAT(locinput);
3639 #define ST st->u.eval
3644 regexp_internal *rei;
3645 regnode *startpoint;
3648 case GOSUB: /* /(...(?1))/ /(...(?&foo))/ */
3649 if (cur_eval && cur_eval->locinput==locinput) {
3650 if (cur_eval->u.eval.close_paren == (U32)ARG(scan))
3651 Perl_croak(aTHX_ "Infinite recursion in regex");
3652 if ( ++nochange_depth > max_nochange_depth )
3654 "Pattern subroutine nesting without pos change"
3655 " exceeded limit in regex");
3662 (void)ReREFCNT_inc(rex_sv);
3663 if (OP(scan)==GOSUB) {
3664 startpoint = scan + ARG2L(scan);
3665 ST.close_paren = ARG(scan);
3667 startpoint = rei->program+1;
3670 goto eval_recurse_doit;
3672 case EVAL: /* /(?{A})B/ /(??{A})B/ and /(?(?{A})X|Y)B/ */
3673 if (cur_eval && cur_eval->locinput==locinput) {
3674 if ( ++nochange_depth > max_nochange_depth )
3675 Perl_croak(aTHX_ "EVAL without pos change exceeded limit in regex");
3680 /* execute the code in the {...} */
3682 SV ** const before = SP;
3683 OP_4tree * const oop = PL_op;
3684 COP * const ocurcop = PL_curcop;
3686 char *saved_regeol = PL_regeol;
3689 PL_op = (OP_4tree*)rexi->data->data[n];
3690 DEBUG_STATE_r( PerlIO_printf(Perl_debug_log,
3691 " re_eval 0x%"UVxf"\n", PTR2UV(PL_op)) );
3692 PAD_SAVE_LOCAL(old_comppad, (PAD*)rexi->data->data[n + 2]);
3693 PL_regoffs[0].end = PL_reg_magic->mg_len = locinput - PL_bostr;
3696 SV *sv_mrk = get_sv("REGMARK", 1);
3697 sv_setsv(sv_mrk, sv_yes_mark);
3700 CALLRUNOPS(aTHX); /* Scalar context. */
3703 ret = &PL_sv_undef; /* protect against empty (?{}) blocks. */
3710 PAD_RESTORE_LOCAL(old_comppad);
3711 PL_curcop = ocurcop;
3712 PL_regeol = saved_regeol;
3715 sv_setsv(save_scalar(PL_replgv), ret);
3719 if (logical == 2) { /* Postponed subexpression: /(??{...})/ */
3722 /* extract RE object from returned value; compiling if
3728 SV *const sv = SvRV(ret);
3730 if (SvTYPE(sv) == SVt_REGEXP) {
3732 } else if (SvSMAGICAL(sv)) {
3733 mg = mg_find(sv, PERL_MAGIC_qr);
3736 } else if (SvTYPE(ret) == SVt_REGEXP) {
3738 } else if (SvSMAGICAL(ret)) {
3739 if (SvGMAGICAL(ret)) {
3740 /* I don't believe that there is ever qr magic
3742 assert(!mg_find(ret, PERL_MAGIC_qr));
3743 sv_unmagic(ret, PERL_MAGIC_qr);
3746 mg = mg_find(ret, PERL_MAGIC_qr);
3747 /* testing suggests mg only ends up non-NULL for
3748 scalars who were upgraded and compiled in the
3749 else block below. In turn, this is only
3750 triggered in the "postponed utf8 string" tests
3756 rx = (REGEXP *) mg->mg_obj; /*XXX:dmq*/
3760 rx = reg_temp_copy(rx);
3764 const I32 osize = PL_regsize;
3767 assert (SvUTF8(ret));
3768 } else if (SvUTF8(ret)) {
3769 /* Not doing UTF-8, despite what the SV says. Is
3770 this only if we're trapped in use 'bytes'? */
3771 /* Make a copy of the octet sequence, but without
3772 the flag on, as the compiler now honours the
3773 SvUTF8 flag on ret. */
3775 const char *const p = SvPV(ret, len);
3776 ret = newSVpvn_flags(p, len, SVs_TEMP);
3778 rx = CALLREGCOMP(ret, pm_flags);
3780 & (SVs_TEMP | SVs_PADTMP | SVf_READONLY
3782 /* This isn't a first class regexp. Instead, it's
3783 caching a regexp onto an existing, Perl visible
3785 sv_magic(ret, MUTABLE_SV(rx), PERL_MAGIC_qr, 0, 0);
3790 re = (struct regexp *)SvANY(rx);
3792 RXp_MATCH_COPIED_off(re);
3793 re->subbeg = rex->subbeg;
3794 re->sublen = rex->sublen;
3797 debug_start_match(re_sv, do_utf8, locinput, PL_regeol,
3798 "Matching embedded");
3800 startpoint = rei->program + 1;
3801 ST.close_paren = 0; /* only used for GOSUB */
3802 /* borrowed from regtry */
3803 if (PL_reg_start_tmpl <= re->nparens) {
3804 PL_reg_start_tmpl = re->nparens*3/2 + 3;
3805 if(PL_reg_start_tmp)
3806 Renew(PL_reg_start_tmp, PL_reg_start_tmpl, char*);
3808 Newx(PL_reg_start_tmp, PL_reg_start_tmpl, char*);
3811 eval_recurse_doit: /* Share code with GOSUB below this line */
3812 /* run the pattern returned from (??{...}) */
3813 ST.cp = regcppush(0); /* Save *all* the positions. */
3814 REGCP_SET(ST.lastcp);
3816 PL_regoffs = re->offs; /* essentially NOOP on GOSUB */
3818 /* see regtry, specifically PL_reglast(?:close)?paren is a pointer! (i dont know why) :dmq */
3819 PL_reglastparen = &re->lastparen;
3820 PL_reglastcloseparen = &re->lastcloseparen;
3822 re->lastcloseparen = 0;
3824 PL_reginput = locinput;
3827 /* XXXX This is too dramatic a measure... */
3830 ST.toggle_reg_flags = PL_reg_flags;
3832 PL_reg_flags |= RF_utf8;
3834 PL_reg_flags &= ~RF_utf8;
3835 ST.toggle_reg_flags ^= PL_reg_flags; /* diff of old and new */
3837 ST.prev_rex = rex_sv;
3838 ST.prev_curlyx = cur_curlyx;
3839 SETREX(rex_sv,re_sv);
3844 ST.prev_eval = cur_eval;
3846 /* now continue from first node in postoned RE */
3847 PUSH_YES_STATE_GOTO(EVAL_AB, startpoint);
3850 /* logical is 1, /(?(?{...})X|Y)/ */
3851 sw = (bool)SvTRUE(ret);
3856 case EVAL_AB: /* cleanup after a successful (??{A})B */
3857 /* note: this is called twice; first after popping B, then A */
3858 PL_reg_flags ^= ST.toggle_reg_flags;
3859 ReREFCNT_dec(rex_sv);
3860 SETREX(rex_sv,ST.prev_rex);
3861 rex = (struct regexp *)SvANY(rex_sv);
3862 rexi = RXi_GET(rex);
3864 cur_eval = ST.prev_eval;
3865 cur_curlyx = ST.prev_curlyx;
3867 /* rex was changed so update the pointer in PL_reglastparen and PL_reglastcloseparen */
3868 PL_reglastparen = &rex->lastparen;
3869 PL_reglastcloseparen = &rex->lastcloseparen;
3870 /* also update PL_regoffs */
3871 PL_regoffs = rex->offs;
3873 /* XXXX This is too dramatic a measure... */
3875 if ( nochange_depth )
3880 case EVAL_AB_fail: /* unsuccessfully ran A or B in (??{A})B */
3881 /* note: this is called twice; first after popping B, then A */
3882 PL_reg_flags ^= ST.toggle_reg_flags;
3883 ReREFCNT_dec(rex_sv);
3884 SETREX(rex_sv,ST.prev_rex);
3885 rex = (struct regexp *)SvANY(rex_sv);
3886 rexi = RXi_GET(rex);
3887 /* rex was changed so update the pointer in PL_reglastparen and PL_reglastcloseparen */
3888 PL_reglastparen = &rex->lastparen;
3889 PL_reglastcloseparen = &rex->lastcloseparen;
3891 PL_reginput = locinput;
3892 REGCP_UNWIND(ST.lastcp);
3894 cur_eval = ST.prev_eval;
3895 cur_curlyx = ST.prev_curlyx;
3896 /* XXXX This is too dramatic a measure... */
3898 if ( nochange_depth )
3904 n = ARG(scan); /* which paren pair */
3905 PL_reg_start_tmp[n] = locinput;
3911 n = ARG(scan); /* which paren pair */
3912 PL_regoffs[n].start = PL_reg_start_tmp[n] - PL_bostr;
3913 PL_regoffs[n].end = locinput - PL_bostr;
3914 /*if (n > PL_regsize)
3916 if (n > *PL_reglastparen)
3917 *PL_reglastparen = n;
3918 *PL_reglastcloseparen = n;
3919 if (cur_eval && cur_eval->u.eval.close_paren == n) {
3927 cursor && OP(cursor)!=END;
3928 cursor=regnext(cursor))
3930 if ( OP(cursor)==CLOSE ){
3932 if ( n <= lastopen ) {
3934 = PL_reg_start_tmp[n] - PL_bostr;
3935 PL_regoffs[n].end = locinput - PL_bostr;
3936 /*if (n > PL_regsize)
3938 if (n > *PL_reglastparen)
3939 *PL_reglastparen = n;
3940 *PL_reglastcloseparen = n;
3941 if ( n == ARG(scan) || (cur_eval &&
3942 cur_eval->u.eval.close_paren == n))
3951 n = ARG(scan); /* which paren pair */
3952 sw = (bool)(*PL_reglastparen >= n && PL_regoffs[n].end != -1);
3955 /* reg_check_named_buff_matched returns 0 for no match */
3956 sw = (bool)(0 < reg_check_named_buff_matched(rex,scan));
3960 sw = (cur_eval && (!n || cur_eval->u.eval.close_paren == n));
3966 PL_reg_leftiter = PL_reg_maxiter; /* Void cache */
3968 next = NEXTOPER(NEXTOPER(scan));
3970 next = scan + ARG(scan);
3971 if (OP(next) == IFTHEN) /* Fake one. */
3972 next = NEXTOPER(NEXTOPER(next));
3976 logical = scan->flags;
3979 /*******************************************************************
3981 The CURLYX/WHILEM pair of ops handle the most generic case of the /A*B/
3982 pattern, where A and B are subpatterns. (For simple A, CURLYM or
3983 STAR/PLUS/CURLY/CURLYN are used instead.)
3985 A*B is compiled as <CURLYX><A><WHILEM><B>
3987 On entry to the subpattern, CURLYX is called. This pushes a CURLYX
3988 state, which contains the current count, initialised to -1. It also sets
3989 cur_curlyx to point to this state, with any previous value saved in the
3992 CURLYX then jumps straight to the WHILEM op, rather than executing A,
3993 since the pattern may possibly match zero times (i.e. it's a while {} loop
3994 rather than a do {} while loop).
3996 Each entry to WHILEM represents a successful match of A. The count in the
3997 CURLYX block is incremented, another WHILEM state is pushed, and execution
3998 passes to A or B depending on greediness and the current count.
4000 For example, if matching against the string a1a2a3b (where the aN are
4001 substrings that match /A/), then the match progresses as follows: (the
4002 pushed states are interspersed with the bits of strings matched so far):
4005 <CURLYX cnt=0><WHILEM>
4006 <CURLYX cnt=1><WHILEM> a1 <WHILEM>
4007 <CURLYX cnt=2><WHILEM> a1 <WHILEM> a2 <WHILEM>
4008 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM>
4009 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM> b
4011 (Contrast this with something like CURLYM, which maintains only a single
4015 a1 <CURLYM cnt=1> a2
4016 a1 a2 <CURLYM cnt=2> a3
4017 a1 a2 a3 <CURLYM cnt=3> b
4020 Each WHILEM state block marks a point to backtrack to upon partial failure
4021 of A or B, and also contains some minor state data related to that
4022 iteration. The CURLYX block, pointed to by cur_curlyx, contains the
4023 overall state, such as the count, and pointers to the A and B ops.
4025 This is complicated slightly by nested CURLYX/WHILEM's. Since cur_curlyx
4026 must always point to the *current* CURLYX block, the rules are:
4028 When executing CURLYX, save the old cur_curlyx in the CURLYX state block,
4029 and set cur_curlyx to point the new block.
4031 When popping the CURLYX block after a successful or unsuccessful match,
4032 restore the previous cur_curlyx.
4034 When WHILEM is about to execute B, save the current cur_curlyx, and set it
4035 to the outer one saved in the CURLYX block.
4037 When popping the WHILEM block after a successful or unsuccessful B match,
4038 restore the previous cur_curlyx.
4040 Here's an example for the pattern (AI* BI)*BO
4041 I and O refer to inner and outer, C and W refer to CURLYX and WHILEM:
4044 curlyx backtrack stack
4045 ------ ---------------
4047 CO <CO prev=NULL> <WO>
4048 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
4049 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
4050 NULL <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi <WO prev=CO> bo
4052 At this point the pattern succeeds, and we work back down the stack to
4053 clean up, restoring as we go:
4055 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
4056 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
4057 CO <CO prev=NULL> <WO>
4060 *******************************************************************/
4062 #define ST st->u.curlyx
4064 case CURLYX: /* start of /A*B/ (for complex A) */
4066 /* No need to save/restore up to this paren */
4067 I32 parenfloor = scan->flags;
4069 assert(next); /* keep Coverity happy */
4070 if (OP(PREVOPER(next)) == NOTHING) /* LONGJMP */
4073 /* XXXX Probably it is better to teach regpush to support
4074 parenfloor > PL_regsize... */
4075 if (parenfloor > (I32)*PL_reglastparen)
4076 parenfloor = *PL_reglastparen; /* Pessimization... */
4078 ST.prev_curlyx= cur_curlyx;
4080 ST.cp = PL_savestack_ix;
4082 /* these fields contain the state of the current curly.
4083 * they are accessed by subsequent WHILEMs */
4084 ST.parenfloor = parenfloor;
4085 ST.min = ARG1(scan);
4086 ST.max = ARG2(scan);
4087 ST.A = NEXTOPER(scan) + EXTRA_STEP_2ARGS;
4091 ST.count = -1; /* this will be updated by WHILEM */
4092 ST.lastloc = NULL; /* this will be updated by WHILEM */
4094 PL_reginput = locinput;
4095 PUSH_YES_STATE_GOTO(CURLYX_end, PREVOPER(next));
4099 case CURLYX_end: /* just finished matching all of A*B */
4100 cur_curlyx = ST.prev_curlyx;
4104 case CURLYX_end_fail: /* just failed to match all of A*B */
4106 cur_curlyx = ST.prev_curlyx;
4112 #define ST st->u.whilem
4114 case WHILEM: /* just matched an A in /A*B/ (for complex A) */
4116 /* see the discussion above about CURLYX/WHILEM */
4118 assert(cur_curlyx); /* keep Coverity happy */
4119 n = ++cur_curlyx->u.curlyx.count; /* how many A's matched */
4120 ST.save_lastloc = cur_curlyx->u.curlyx.lastloc;
4121 ST.cache_offset = 0;
4124 PL_reginput = locinput;
4126 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
4127 "%*s whilem: matched %ld out of %ld..%ld\n",
4128 REPORT_CODE_OFF+depth*2, "", (long)n,
4129 (long)cur_curlyx->u.curlyx.min,
4130 (long)cur_curlyx->u.curlyx.max)
4133 /* First just match a string of min A's. */
4135 if (n < cur_curlyx->u.curlyx.min) {
4136 cur_curlyx->u.curlyx.lastloc = locinput;
4137 PUSH_STATE_GOTO(WHILEM_A_pre, cur_curlyx->u.curlyx.A);
4141 /* If degenerate A matches "", assume A done. */
4143 if (locinput == cur_curlyx->u.curlyx.lastloc) {
4144 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
4145 "%*s whilem: empty match detected, trying continuation...\n",
4146 REPORT_CODE_OFF+depth*2, "")
4148 goto do_whilem_B_max;
4151 /* super-linear cache processing */
4155 if (!PL_reg_maxiter) {
4156 /* start the countdown: Postpone detection until we
4157 * know the match is not *that* much linear. */
4158 PL_reg_maxiter = (PL_regeol - PL_bostr + 1) * (scan->flags>>4);
4159 /* possible overflow for long strings and many CURLYX's */
4160 if (PL_reg_maxiter < 0)
4161 PL_reg_maxiter = I32_MAX;
4162 PL_reg_leftiter = PL_reg_maxiter;
4165 if (PL_reg_leftiter-- == 0) {
4166 /* initialise cache */
4167 const I32 size = (PL_reg_maxiter + 7)/8;
4168 if (PL_reg_poscache) {
4169 if ((I32)PL_reg_poscache_size < size) {
4170 Renew(PL_reg_poscache, size, char);
4171 PL_reg_poscache_size = size;
4173 Zero(PL_reg_poscache, size, char);
4176 PL_reg_poscache_size = size;
4177 Newxz(PL_reg_poscache, size, char);
4179 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
4180 "%swhilem: Detected a super-linear match, switching on caching%s...\n",
4181 PL_colors[4], PL_colors[5])
4185 if (PL_reg_leftiter < 0) {
4186 /* have we already failed at this position? */
4188 offset = (scan->flags & 0xf) - 1
4189 + (locinput - PL_bostr) * (scan->flags>>4);
4190 mask = 1 << (offset % 8);
4192 if (PL_reg_poscache[offset] & mask) {
4193 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
4194 "%*s whilem: (cache) already tried at this position...\n",
4195 REPORT_CODE_OFF+depth*2, "")
4197 sayNO; /* cache records failure */
4199 ST.cache_offset = offset;
4200 ST.cache_mask = mask;
4204 /* Prefer B over A for minimal matching. */
4206 if (cur_curlyx->u.curlyx.minmod) {
4207 ST.save_curlyx = cur_curlyx;
4208 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
4209 ST.cp = regcppush(ST.save_curlyx->u.curlyx.parenfloor);
4210 REGCP_SET(ST.lastcp);
4211 PUSH_YES_STATE_GOTO(WHILEM_B_min, ST.save_curlyx->u.curlyx.B);
4215 /* Prefer A over B for maximal matching. */
4217 if (n < cur_curlyx->u.curlyx.max) { /* More greed allowed? */
4218 ST.cp = regcppush(cur_curlyx->u.curlyx.parenfloor);
4219 cur_curlyx->u.curlyx.lastloc = locinput;
4220 REGCP_SET(ST.lastcp);
4221 PUSH_STATE_GOTO(WHILEM_A_max, cur_curlyx->u.curlyx.A);
4224 goto do_whilem_B_max;
4228 case WHILEM_B_min: /* just matched B in a minimal match */
4229 case WHILEM_B_max: /* just matched B in a maximal match */
4230 cur_curlyx = ST.save_curlyx;
4234 case WHILEM_B_max_fail: /* just failed to match B in a maximal match */
4235 cur_curlyx = ST.save_curlyx;
4236 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
4237 cur_curlyx->u.curlyx.count--;
4241 case WHILEM_A_min_fail: /* just failed to match A in a minimal match */
4242 REGCP_UNWIND(ST.lastcp);
4245 case WHILEM_A_pre_fail: /* just failed to match even minimal A */
4246 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
4247 cur_curlyx->u.curlyx.count--;
4251 case WHILEM_A_max_fail: /* just failed to match A in a maximal match */
4252 REGCP_UNWIND(ST.lastcp);
4253 regcppop(rex); /* Restore some previous $<digit>s? */
4254 PL_reginput = locinput;
4255 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
4256 "%*s whilem: failed, trying continuation...\n",
4257 REPORT_CODE_OFF+depth*2, "")
4260 if (cur_curlyx->u.curlyx.count >= REG_INFTY
4261 && ckWARN(WARN_REGEXP)
4262 && !(PL_reg_flags & RF_warned))
4264 PL_reg_flags |= RF_warned;
4265 Perl_warner(aTHX_ packWARN(WARN_REGEXP), "%s limit (%d) exceeded",
4266 "Complex regular subexpression recursion",
4271 ST.save_curlyx = cur_curlyx;
4272 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
4273 PUSH_YES_STATE_GOTO(WHILEM_B_max, ST.save_curlyx->u.curlyx.B);
4276 case WHILEM_B_min_fail: /* just failed to match B in a minimal match */
4277 cur_curlyx = ST.save_curlyx;
4278 REGCP_UNWIND(ST.lastcp);
4281 if (cur_curlyx->u.curlyx.count >= cur_curlyx->u.curlyx.max) {
4282 /* Maximum greed exceeded */
4283 if (cur_curlyx->u.curlyx.count >= REG_INFTY
4284 && ckWARN(WARN_REGEXP)
4285 && !(PL_reg_flags & RF_warned))
4287 PL_reg_flags |= RF_warned;
4288 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
4289 "%s limit (%d) exceeded",
4290 "Complex regular subexpression recursion",
4293 cur_curlyx->u.curlyx.count--;
4297 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
4298 "%*s trying longer...\n", REPORT_CODE_OFF+depth*2, "")
4300 /* Try grabbing another A and see if it helps. */
4301 PL_reginput = locinput;
4302 cur_curlyx->u.curlyx.lastloc = locinput;
4303 ST.cp = regcppush(cur_curlyx->u.curlyx.parenfloor);
4304 REGCP_SET(ST.lastcp);
4305 PUSH_STATE_GOTO(WHILEM_A_min, ST.save_curlyx->u.curlyx.A);
4309 #define ST st->u.branch
4311 case BRANCHJ: /* /(...|A|...)/ with long next pointer */
4312 next = scan + ARG(scan);
4315 scan = NEXTOPER(scan);
4318 case BRANCH: /* /(...|A|...)/ */
4319 scan = NEXTOPER(scan); /* scan now points to inner node */
4320 ST.lastparen = *PL_reglastparen;
4321 ST.next_branch = next;
4323 PL_reginput = locinput;
4325 /* Now go into the branch */
4327 PUSH_YES_STATE_GOTO(BRANCH_next, scan);
4329 PUSH_STATE_GOTO(BRANCH_next, scan);
4333 PL_reginput = locinput;
4334 sv_yes_mark = st->u.mark.mark_name = scan->flags ? NULL :
4335 MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
4336 PUSH_STATE_GOTO(CUTGROUP_next,next);
4338 case CUTGROUP_next_fail:
4341 if (st->u.mark.mark_name)
4342 sv_commit = st->u.mark.mark_name;
4348 case BRANCH_next_fail: /* that branch failed; try the next, if any */
4353 REGCP_UNWIND(ST.cp);
4354 for (n = *PL_reglastparen; n > ST.lastparen; n--)
4355 PL_regoffs[n].end = -1;
4356 *PL_reglastparen = n;
4357 /*dmq: *PL_reglastcloseparen = n; */
4358 scan = ST.next_branch;
4359 /* no more branches? */
4360 if (!scan || (OP(scan) != BRANCH && OP(scan) != BRANCHJ)) {
4362 PerlIO_printf( Perl_debug_log,
4363 "%*s %sBRANCH failed...%s\n",
4364 REPORT_CODE_OFF+depth*2, "",
4370 continue; /* execute next BRANCH[J] op */
4378 #define ST st->u.curlym
4380 case CURLYM: /* /A{m,n}B/ where A is fixed-length */
4382 /* This is an optimisation of CURLYX that enables us to push
4383 * only a single backtracking state, no matter how many matches
4384 * there are in {m,n}. It relies on the pattern being constant
4385 * length, with no parens to influence future backrefs
4389 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
4391 /* if paren positive, emulate an OPEN/CLOSE around A */
4393 U32 paren = ST.me->flags;
4394 if (paren > PL_regsize)
4396 if (paren > *PL_reglastparen)
4397 *PL_reglastparen = paren;
4398 scan += NEXT_OFF(scan); /* Skip former OPEN. */
4406 ST.c1 = CHRTEST_UNINIT;
4409 if (!(ST.minmod ? ARG1(ST.me) : ARG2(ST.me))) /* min/max */
4412 curlym_do_A: /* execute the A in /A{m,n}B/ */
4413 PL_reginput = locinput;
4414 PUSH_YES_STATE_GOTO(CURLYM_A, ST.A); /* match A */
4417 case CURLYM_A: /* we've just matched an A */
4418 locinput = st->locinput;
4419 nextchr = UCHARAT(locinput);
4422 /* after first match, determine A's length: u.curlym.alen */
4423 if (ST.count == 1) {
4424 if (PL_reg_match_utf8) {
4426 while (s < PL_reginput) {
4432 ST.alen = PL_reginput - locinput;
4435 ST.count = ST.minmod ? ARG1(ST.me) : ARG2(ST.me);
4438 PerlIO_printf(Perl_debug_log,
4439 "%*s CURLYM now matched %"IVdf" times, len=%"IVdf"...\n",
4440 (int)(REPORT_CODE_OFF+(depth*2)), "",
4441 (IV) ST.count, (IV)ST.alen)
4444 locinput = PL_reginput;
4446 if (cur_eval && cur_eval->u.eval.close_paren &&
4447 cur_eval->u.eval.close_paren == (U32)ST.me->flags)
4451 I32 max = (ST.minmod ? ARG1(ST.me) : ARG2(ST.me));
4452 if ( max == REG_INFTY || ST.count < max )
4453 goto curlym_do_A; /* try to match another A */
4455 goto curlym_do_B; /* try to match B */
4457 case CURLYM_A_fail: /* just failed to match an A */
4458 REGCP_UNWIND(ST.cp);
4460 if (ST.minmod || ST.count < ARG1(ST.me) /* min*/
4461 || (cur_eval && cur_eval->u.eval.close_paren &&
4462 cur_eval->u.eval.close_paren == (U32)ST.me->flags))
4465 curlym_do_B: /* execute the B in /A{m,n}B/ */
4466 PL_reginput = locinput;
4467 if (ST.c1 == CHRTEST_UNINIT) {
4468 /* calculate c1 and c2 for possible match of 1st char
4469 * following curly */
4470 ST.c1 = ST.c2 = CHRTEST_VOID;
4471 if (HAS_TEXT(ST.B) || JUMPABLE(ST.B)) {
4472 regnode *text_node = ST.B;
4473 if (! HAS_TEXT(text_node))
4474 FIND_NEXT_IMPT(text_node);
4477 (HAS_TEXT(text_node) && PL_regkind[OP(text_node)] == EXACT)
4479 But the former is redundant in light of the latter.
4481 if this changes back then the macro for
4482 IS_TEXT and friends need to change.
4484 if (PL_regkind[OP(text_node)] == EXACT)
4487 ST.c1 = (U8)*STRING(text_node);
4489 (IS_TEXTF(text_node))
4491 : (IS_TEXTFL(text_node))
4492 ? PL_fold_locale[ST.c1]
4499 PerlIO_printf(Perl_debug_log,
4500 "%*s CURLYM trying tail with matches=%"IVdf"...\n",
4501 (int)(REPORT_CODE_OFF+(depth*2)),
4504 if (ST.c1 != CHRTEST_VOID
4505 && UCHARAT(PL_reginput) != ST.c1
4506 && UCHARAT(PL_reginput) != ST.c2)
4508 /* simulate B failing */
4510 PerlIO_printf(Perl_debug_log,
4511 "%*s CURLYM Fast bail c1=%"IVdf" c2=%"IVdf"\n",
4512 (int)(REPORT_CODE_OFF+(depth*2)),"",
4515 state_num = CURLYM_B_fail;
4516 goto reenter_switch;
4520 /* mark current A as captured */
4521 I32 paren = ST.me->flags;
4523 PL_regoffs[paren].start
4524 = HOPc(PL_reginput, -ST.alen) - PL_bostr;
4525 PL_regoffs[paren].end = PL_reginput - PL_bostr;
4526 /*dmq: *PL_reglastcloseparen = paren; */
4529 PL_regoffs[paren].end = -1;
4530 if (cur_eval && cur_eval->u.eval.close_paren &&
4531 cur_eval->u.eval.close_paren == (U32)ST.me->flags)
4540 PUSH_STATE_GOTO(CURLYM_B, ST.B); /* match B */
4543 case CURLYM_B_fail: /* just failed to match a B */
4544 REGCP_UNWIND(ST.cp);
4546 I32 max = ARG2(ST.me);
4547 if (max != REG_INFTY && ST.count == max)
4549 goto curlym_do_A; /* try to match a further A */
4551 /* backtrack one A */
4552 if (ST.count == ARG1(ST.me) /* min */)
4555 locinput = HOPc(locinput, -ST.alen);
4556 goto curlym_do_B; /* try to match B */
4559 #define ST st->u.curly
4561 #define CURLY_SETPAREN(paren, success) \
4564 PL_regoffs[paren].start = HOPc(locinput, -1) - PL_bostr; \
4565 PL_regoffs[paren].end = locinput - PL_bostr; \
4566 *PL_reglastcloseparen = paren; \
4569 PL_regoffs[paren].end = -1; \
4572 case STAR: /* /A*B/ where A is width 1 */
4576 scan = NEXTOPER(scan);
4578 case PLUS: /* /A+B/ where A is width 1 */
4582 scan = NEXTOPER(scan);
4584 case CURLYN: /* /(A){m,n}B/ where A is width 1 */
4585 ST.paren = scan->flags; /* Which paren to set */
4586 if (ST.paren > PL_regsize)
4587 PL_regsize = ST.paren;
4588 if (ST.paren > *PL_reglastparen)
4589 *PL_reglastparen = ST.paren;
4590 ST.min = ARG1(scan); /* min to match */
4591 ST.max = ARG2(scan); /* max to match */
4592 if (cur_eval && cur_eval->u.eval.close_paren &&
4593 cur_eval->u.eval.close_paren == (U32)ST.paren) {
4597 scan = regnext(NEXTOPER(scan) + NODE_STEP_REGNODE);
4599 case CURLY: /* /A{m,n}B/ where A is width 1 */
4601 ST.min = ARG1(scan); /* min to match */
4602 ST.max = ARG2(scan); /* max to match */
4603 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
4606 * Lookahead to avoid useless match attempts
4607 * when we know what character comes next.
4609 * Used to only do .*x and .*?x, but now it allows
4610 * for )'s, ('s and (?{ ... })'s to be in the way
4611 * of the quantifier and the EXACT-like node. -- japhy
4614 if (ST.min > ST.max) /* XXX make this a compile-time check? */
4616 if (HAS_TEXT(next) || JUMPABLE(next)) {
4618 regnode *text_node = next;
4620 if (! HAS_TEXT(text_node))
4621 FIND_NEXT_IMPT(text_node);
4623 if (! HAS_TEXT(text_node))
4624 ST.c1 = ST.c2 = CHRTEST_VOID;
4626 if ( PL_regkind[OP(text_node)] != EXACT ) {
4627 ST.c1 = ST.c2 = CHRTEST_VOID;
4628 goto assume_ok_easy;
4631 s = (U8*)STRING(text_node);
4633 /* Currently we only get here when
4635 PL_rekind[OP(text_node)] == EXACT
4637 if this changes back then the macro for IS_TEXT and
4638 friends need to change. */
4641 if (IS_TEXTF(text_node))
4642 ST.c2 = PL_fold[ST.c1];
4643 else if (IS_TEXTFL(text_node))
4644 ST.c2 = PL_fold_locale[ST.c1];
4647 if (IS_TEXTF(text_node)) {
4648 STRLEN ulen1, ulen2;
4649 U8 tmpbuf1[UTF8_MAXBYTES_CASE+1];
4650 U8 tmpbuf2[UTF8_MAXBYTES_CASE+1];
4652 to_utf8_lower((U8*)s, tmpbuf1, &ulen1);
4653 to_utf8_upper((U8*)s, tmpbuf2, &ulen2);
4655 ST.c1 = utf8n_to_uvchr(tmpbuf1, UTF8_MAXLEN, 0,
4657 0 : UTF8_ALLOW_ANY);
4658 ST.c2 = utf8n_to_uvchr(tmpbuf2, UTF8_MAXLEN, 0,
4660 0 : UTF8_ALLOW_ANY);
4662 ST.c1 = utf8n_to_uvuni(tmpbuf1, UTF8_MAXBYTES, 0,
4664 ST.c2 = utf8n_to_uvuni(tmpbuf2, UTF8_MAXBYTES, 0,
4669 ST.c2 = ST.c1 = utf8n_to_uvchr(s, UTF8_MAXBYTES, 0,
4676 ST.c1 = ST.c2 = CHRTEST_VOID;
4681 PL_reginput = locinput;
4684 if (ST.min && regrepeat(rex, ST.A, ST.min, depth) < ST.min)
4687 locinput = PL_reginput;
4689 if (ST.c1 == CHRTEST_VOID)
4690 goto curly_try_B_min;
4692 ST.oldloc = locinput;
4694 /* set ST.maxpos to the furthest point along the
4695 * string that could possibly match */
4696 if (ST.max == REG_INFTY) {
4697 ST.maxpos = PL_regeol - 1;
4699 while (UTF8_IS_CONTINUATION(*(U8*)ST.maxpos))
4703 int m = ST.max - ST.min;
4704 for (ST.maxpos = locinput;
4705 m >0 && ST.maxpos + UTF8SKIP(ST.maxpos) <= PL_regeol; m--)
4706 ST.maxpos += UTF8SKIP(ST.maxpos);
4709 ST.maxpos = locinput + ST.max - ST.min;
4710 if (ST.maxpos >= PL_regeol)
4711 ST.maxpos = PL_regeol - 1;
4713 goto curly_try_B_min_known;
4717 ST.count = regrepeat(rex, ST.A, ST.max, depth);
4718 locinput = PL_reginput;
4719 if (ST.count < ST.min)
4721 if ((ST.count > ST.min)
4722 && (PL_regkind[OP(ST.B)] == EOL) && (OP(ST.B) != MEOL))
4724 /* A{m,n} must come at the end of the string, there's
4725 * no point in backing off ... */
4727 /* ...except that $ and \Z can match before *and* after
4728 newline at the end. Consider "\n\n" =~ /\n+\Z\n/.
4729 We may back off by one in this case. */
4730 if (UCHARAT(PL_reginput - 1) == '\n' && OP(ST.B) != EOS)
4734 goto curly_try_B_max;
4739 case CURLY_B_min_known_fail:
4740 /* failed to find B in a non-greedy match where c1,c2 valid */
4741 if (ST.paren && ST.count)
4742 PL_regoffs[ST.paren].end = -1;
4744 PL_reginput = locinput; /* Could be reset... */
4745 REGCP_UNWIND(ST.cp);
4746 /* Couldn't or didn't -- move forward. */
4747 ST.oldloc = locinput;
4749 locinput += UTF8SKIP(locinput);
4753 curly_try_B_min_known:
4754 /* find the next place where 'B' could work, then call B */
4758 n = (ST.oldloc == locinput) ? 0 : 1;
4759 if (ST.c1 == ST.c2) {
4761 /* set n to utf8_distance(oldloc, locinput) */
4762 while (locinput <= ST.maxpos &&
4763 utf8n_to_uvchr((U8*)locinput,
4764 UTF8_MAXBYTES, &len,
4765 uniflags) != (UV)ST.c1) {
4771 /* set n to utf8_distance(oldloc, locinput) */
4772 while (locinput <= ST.maxpos) {
4774 const UV c = utf8n_to_uvchr((U8*)locinput,
4775 UTF8_MAXBYTES, &len,
4777 if (c == (UV)ST.c1 || c == (UV)ST.c2)
4785 if (ST.c1 == ST.c2) {
4786 while (locinput <= ST.maxpos &&
4787 UCHARAT(locinput) != ST.c1)
4791 while (locinput <= ST.maxpos
4792 && UCHARAT(locinput) != ST.c1
4793 && UCHARAT(locinput) != ST.c2)
4796 n = locinput - ST.oldloc;
4798 if (locinput > ST.maxpos)
4800 /* PL_reginput == oldloc now */
4803 if (regrepeat(rex, ST.A, n, depth) < n)
4806 PL_reginput = locinput;
4807 CURLY_SETPAREN(ST.paren, ST.count);
4808 if (cur_eval && cur_eval->u.eval.close_paren &&
4809 cur_eval->u.eval.close_paren == (U32)ST.paren) {
4812 PUSH_STATE_GOTO(CURLY_B_min_known, ST.B);
4817 case CURLY_B_min_fail:
4818 /* failed to find B in a non-greedy match where c1,c2 invalid */
4819 if (ST.paren && ST.count)
4820 PL_regoffs[ST.paren].end = -1;
4822 REGCP_UNWIND(ST.cp);
4823 /* failed -- move forward one */
4824 PL_reginput = locinput;
4825 if (regrepeat(rex, ST.A, 1, depth)) {
4827 locinput = PL_reginput;
4828 if (ST.count <= ST.max || (ST.max == REG_INFTY &&
4829 ST.count > 0)) /* count overflow ? */
4832 CURLY_SETPAREN(ST.paren, ST.count);
4833 if (cur_eval && cur_eval->u.eval.close_paren &&
4834 cur_eval->u.eval.close_paren == (U32)ST.paren) {
4837 PUSH_STATE_GOTO(CURLY_B_min, ST.B);
4845 /* a successful greedy match: now try to match B */
4846 if (cur_eval && cur_eval->u.eval.close_paren &&
4847 cur_eval->u.eval.close_paren == (U32)ST.paren) {
4852 if (ST.c1 != CHRTEST_VOID)
4853 c = do_utf8 ? utf8n_to_uvchr((U8*)PL_reginput,
4854 UTF8_MAXBYTES, 0, uniflags)
4855 : (UV) UCHARAT(PL_reginput);
4856 /* If it could work, try it. */
4857 if (ST.c1 == CHRTEST_VOID || c == (UV)ST.c1 || c == (UV)ST.c2) {
4858 CURLY_SETPAREN(ST.paren, ST.count);
4859 PUSH_STATE_GOTO(CURLY_B_max, ST.B);
4864 case CURLY_B_max_fail:
4865 /* failed to find B in a greedy match */
4866 if (ST.paren && ST.count)
4867 PL_regoffs[ST.paren].end = -1;
4869 REGCP_UNWIND(ST.cp);
4871 if (--ST.count < ST.min)
4873 PL_reginput = locinput = HOPc(locinput, -1);
4874 goto curly_try_B_max;
4881 /* we've just finished A in /(??{A})B/; now continue with B */
4883 st->u.eval.toggle_reg_flags
4884 = cur_eval->u.eval.toggle_reg_flags;
4885 PL_reg_flags ^= st->u.eval.toggle_reg_flags;
4887 st->u.eval.prev_rex = rex_sv; /* inner */
4888 SETREX(rex_sv,cur_eval->u.eval.prev_rex);
4889 rex = (struct regexp *)SvANY(rex_sv);
4890 rexi = RXi_GET(rex);
4891 cur_curlyx = cur_eval->u.eval.prev_curlyx;
4892 ReREFCNT_inc(rex_sv);
4893 st->u.eval.cp = regcppush(0); /* Save *all* the positions. */
4895 /* rex was changed so update the pointer in PL_reglastparen and PL_reglastcloseparen */
4896 PL_reglastparen = &rex->lastparen;
4897 PL_reglastcloseparen = &rex->lastcloseparen;
4899 REGCP_SET(st->u.eval.lastcp);
4900 PL_reginput = locinput;
4902 /* Restore parens of the outer rex without popping the
4904 tmpix = PL_savestack_ix;
4905 PL_savestack_ix = cur_eval->u.eval.lastcp;
4907 PL_savestack_ix = tmpix;
4909 st->u.eval.prev_eval = cur_eval;
4910 cur_eval = cur_eval->u.eval.prev_eval;
4912 PerlIO_printf(Perl_debug_log, "%*s EVAL trying tail ... %"UVxf"\n",
4913 REPORT_CODE_OFF+depth*2, "",PTR2UV(cur_eval)););
4914 if ( nochange_depth )
4917 PUSH_YES_STATE_GOTO(EVAL_AB,
4918 st->u.eval.prev_eval->u.eval.B); /* match B */
4921 if (locinput < reginfo->till) {
4922 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
4923 "%sMatch possible, but length=%ld is smaller than requested=%ld, failing!%s\n",
4925 (long)(locinput - PL_reg_starttry),
4926 (long)(reginfo->till - PL_reg_starttry),
4929 sayNO_SILENT; /* Cannot match: too short. */
4931 PL_reginput = locinput; /* put where regtry can find it */
4932 sayYES; /* Success! */
4934 case SUCCEED: /* successful SUSPEND/UNLESSM/IFMATCH/CURLYM */
4936 PerlIO_printf(Perl_debug_log,
4937 "%*s %ssubpattern success...%s\n",
4938 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5]));
4939 PL_reginput = locinput; /* put where regtry can find it */
4940 sayYES; /* Success! */
4943 #define ST st->u.ifmatch
4945 case SUSPEND: /* (?>A) */
4947 PL_reginput = locinput;
4950 case UNLESSM: /* -ve lookaround: (?!A), or with flags, (?<!A) */
4952 goto ifmatch_trivial_fail_test;
4954 case IFMATCH: /* +ve lookaround: (?=A), or with flags, (?<=A) */
4956 ifmatch_trivial_fail_test:
4958 char * const s = HOPBACKc(locinput, scan->flags);
4963 sw = 1 - (bool)ST.wanted;
4967 next = scan + ARG(scan);
4975 PL_reginput = locinput;
4979 ST.logical = logical;
4980 logical = 0; /* XXX: reset state of logical once it has been saved into ST */
4982 /* execute body of (?...A) */
4983 PUSH_YES_STATE_GOTO(IFMATCH_A, NEXTOPER(NEXTOPER(scan)));
4986 case IFMATCH_A_fail: /* body of (?...A) failed */
4987 ST.wanted = !ST.wanted;
4990 case IFMATCH_A: /* body of (?...A) succeeded */
4992 sw = (bool)ST.wanted;
4994 else if (!ST.wanted)
4997 if (OP(ST.me) == SUSPEND)
4998 locinput = PL_reginput;
5000 locinput = PL_reginput = st->locinput;
5001 nextchr = UCHARAT(locinput);
5003 scan = ST.me + ARG(ST.me);
5006 continue; /* execute B */
5011 next = scan + ARG(scan);
5016 reginfo->cutpoint = PL_regeol;
5019 PL_reginput = locinput;
5021 sv_yes_mark = sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
5022 PUSH_STATE_GOTO(COMMIT_next,next);
5024 case COMMIT_next_fail:
5031 #define ST st->u.mark
5033 ST.prev_mark = mark_state;
5034 ST.mark_name = sv_commit = sv_yes_mark
5035 = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
5037 ST.mark_loc = PL_reginput = locinput;
5038 PUSH_YES_STATE_GOTO(MARKPOINT_next,next);
5040 case MARKPOINT_next:
5041 mark_state = ST.prev_mark;
5044 case MARKPOINT_next_fail:
5045 if (popmark && sv_eq(ST.mark_name,popmark))
5047 if (ST.mark_loc > startpoint)
5048 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
5049 popmark = NULL; /* we found our mark */
5050 sv_commit = ST.mark_name;
5053 PerlIO_printf(Perl_debug_log,
5054 "%*s %ssetting cutpoint to mark:%"SVf"...%s\n",
5055 REPORT_CODE_OFF+depth*2, "",
5056 PL_colors[4], SVfARG(sv_commit), PL_colors[5]);
5059 mark_state = ST.prev_mark;
5060 sv_yes_mark = mark_state ?
5061 mark_state->u.mark.mark_name : NULL;
5065 PL_reginput = locinput;
5067 /* (*SKIP) : if we fail we cut here*/
5068 ST.mark_name = NULL;
5069 ST.mark_loc = locinput;
5070 PUSH_STATE_GOTO(SKIP_next,next);
5072 /* (*SKIP:NAME) : if there is a (*MARK:NAME) fail where it was,
5073 otherwise do nothing. Meaning we need to scan
5075 regmatch_state *cur = mark_state;
5076 SV *find = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
5079 if ( sv_eq( cur->u.mark.mark_name,
5082 ST.mark_name = find;
5083 PUSH_STATE_GOTO( SKIP_next, next );
5085 cur = cur->u.mark.prev_mark;
5088 /* Didn't find our (*MARK:NAME) so ignore this (*SKIP:NAME) */
5090 case SKIP_next_fail:
5092 /* (*CUT:NAME) - Set up to search for the name as we
5093 collapse the stack*/
5094 popmark = ST.mark_name;
5096 /* (*CUT) - No name, we cut here.*/
5097 if (ST.mark_loc > startpoint)
5098 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
5099 /* but we set sv_commit to latest mark_name if there
5100 is one so they can test to see how things lead to this
5103 sv_commit=mark_state->u.mark.mark_name;
5111 if ( n == (U32)what_len_TRICKYFOLD(locinput,do_utf8,ln) ) {
5113 } else if ( 0xDF == n && !do_utf8 && !UTF ) {
5116 U8 folded[UTF8_MAXBYTES_CASE+1];
5118 const char * const l = locinput;
5119 char *e = PL_regeol;
5120 to_uni_fold(n, folded, &foldlen);
5122 if (ibcmp_utf8((const char*) folded, 0, foldlen, 1,
5123 l, &e, 0, do_utf8)) {
5128 nextchr = UCHARAT(locinput);
5131 if ((n=is_LNBREAK(locinput,do_utf8))) {
5133 nextchr = UCHARAT(locinput);
5138 #define CASE_CLASS(nAmE) \
5140 if ((n=is_##nAmE(locinput,do_utf8))) { \
5142 nextchr = UCHARAT(locinput); \
5147 if ((n=is_##nAmE(locinput,do_utf8))) { \
5150 locinput += UTF8SKIP(locinput); \
5151 nextchr = UCHARAT(locinput); \
5156 CASE_CLASS(HORIZWS);
5160 PerlIO_printf(Perl_error_log, "%"UVxf" %d\n",
5161 PTR2UV(scan), OP(scan));
5162 Perl_croak(aTHX_ "regexp memory corruption");
5166 /* switch break jumps here */
5167 scan = next; /* prepare to execute the next op and ... */
5168 continue; /* ... jump back to the top, reusing st */
5172 /* push a state that backtracks on success */
5173 st->u.yes.prev_yes_state = yes_state;
5177 /* push a new regex state, then continue at scan */
5179 regmatch_state *newst;
5182 regmatch_state *cur = st;
5183 regmatch_state *curyes = yes_state;
5185 regmatch_slab *slab = PL_regmatch_slab;
5186 for (;curd > -1;cur--,curd--) {
5187 if (cur < SLAB_FIRST(slab)) {
5189 cur = SLAB_LAST(slab);
5191 PerlIO_printf(Perl_error_log, "%*s#%-3d %-10s %s\n",
5192 REPORT_CODE_OFF + 2 + depth * 2,"",
5193 curd, PL_reg_name[cur->resume_state],
5194 (curyes == cur) ? "yes" : ""
5197 curyes = cur->u.yes.prev_yes_state;
5200 DEBUG_STATE_pp("push")
5203 st->locinput = locinput;
5205 if (newst > SLAB_LAST(PL_regmatch_slab))
5206 newst = S_push_slab(aTHX);
5207 PL_regmatch_state = newst;
5209 locinput = PL_reginput;
5210 nextchr = UCHARAT(locinput);
5218 * We get here only if there's trouble -- normally "case END" is
5219 * the terminating point.
5221 Perl_croak(aTHX_ "corrupted regexp pointers");
5227 /* we have successfully completed a subexpression, but we must now
5228 * pop to the state marked by yes_state and continue from there */
5229 assert(st != yes_state);
5231 while (st != yes_state) {
5233 if (st < SLAB_FIRST(PL_regmatch_slab)) {
5234 PL_regmatch_slab = PL_regmatch_slab->prev;
5235 st = SLAB_LAST(PL_regmatch_slab);
5239 DEBUG_STATE_pp("pop (no final)");
5241 DEBUG_STATE_pp("pop (yes)");
5247 while (yes_state < SLAB_FIRST(PL_regmatch_slab)
5248 || yes_state > SLAB_LAST(PL_regmatch_slab))
5250 /* not in this slab, pop slab */
5251 depth -= (st - SLAB_FIRST(PL_regmatch_slab) + 1);
5252 PL_regmatch_slab = PL_regmatch_slab->prev;
5253 st = SLAB_LAST(PL_regmatch_slab);
5255 depth -= (st - yes_state);
5258 yes_state = st->u.yes.prev_yes_state;
5259 PL_regmatch_state = st;
5262 locinput= st->locinput;
5263 nextchr = UCHARAT(locinput);
5265 state_num = st->resume_state + no_final;
5266 goto reenter_switch;
5269 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch successful!%s\n",
5270 PL_colors[4], PL_colors[5]));
5272 if (PL_reg_eval_set) {
5273 /* each successfully executed (?{...}) block does the equivalent of
5274 * local $^R = do {...}
5275 * When popping the save stack, all these locals would be undone;
5276 * bypass this by setting the outermost saved $^R to the latest
5278 if (oreplsv != GvSV(PL_replgv))
5279 sv_setsv(oreplsv, GvSV(PL_replgv));
5286 PerlIO_printf(Perl_debug_log,
5287 "%*s %sfailed...%s\n",
5288 REPORT_CODE_OFF+depth*2, "",
5289 PL_colors[4], PL_colors[5])
5301 /* there's a previous state to backtrack to */
5303 if (st < SLAB_FIRST(PL_regmatch_slab)) {
5304 PL_regmatch_slab = PL_regmatch_slab->prev;
5305 st = SLAB_LAST(PL_regmatch_slab);
5307 PL_regmatch_state = st;
5308 locinput= st->locinput;
5309 nextchr = UCHARAT(locinput);
5311 DEBUG_STATE_pp("pop");
5313 if (yes_state == st)
5314 yes_state = st->u.yes.prev_yes_state;
5316 state_num = st->resume_state + 1; /* failure = success + 1 */
5317 goto reenter_switch;
5322 if (rex->intflags & PREGf_VERBARG_SEEN) {
5323 SV *sv_err = get_sv("REGERROR", 1);
5324 SV *sv_mrk = get_sv("REGMARK", 1);
5326 sv_commit = &PL_sv_no;
5328 sv_yes_mark = &PL_sv_yes;
5331 sv_commit = &PL_sv_yes;
5332 sv_yes_mark = &PL_sv_no;
5334 sv_setsv(sv_err, sv_commit);
5335 sv_setsv(sv_mrk, sv_yes_mark);
5338 /* clean up; in particular, free all slabs above current one */
5339 LEAVE_SCOPE(oldsave);
5345 - regrepeat - repeatedly match something simple, report how many
5348 * [This routine now assumes that it will only match on things of length 1.
5349 * That was true before, but now we assume scan - reginput is the count,
5350 * rather than incrementing count on every character. [Er, except utf8.]]
5353 S_regrepeat(pTHX_ const regexp *prog, const regnode *p, I32 max, int depth)
5356 register char *scan;
5358 register char *loceol = PL_regeol;
5359 register I32 hardcount = 0;
5360 register bool do_utf8 = PL_reg_match_utf8;
5362 PERL_UNUSED_ARG(depth);
5365 PERL_ARGS_ASSERT_REGREPEAT;
5368 if (max == REG_INFTY)
5370 else if (max < loceol - scan)
5371 loceol = scan + max;
5376 while (scan < loceol && hardcount < max && *scan != '\n') {
5377 scan += UTF8SKIP(scan);
5381 while (scan < loceol && *scan != '\n')
5388 while (scan < loceol && hardcount < max) {
5389 scan += UTF8SKIP(scan);
5399 case EXACT: /* length of string is 1 */
5401 while (scan < loceol && UCHARAT(scan) == c)
5404 case EXACTF: /* length of string is 1 */
5406 while (scan < loceol &&
5407 (UCHARAT(scan) == c || UCHARAT(scan) == PL_fold[c]))
5410 case EXACTFL: /* length of string is 1 */
5411 PL_reg_flags |= RF_tainted;
5413 while (scan < loceol &&
5414 (UCHARAT(scan) == c || UCHARAT(scan) == PL_fold_locale[c]))
5420 while (hardcount < max && scan < loceol &&
5421 reginclass(prog, p, (U8*)scan, 0, do_utf8)) {
5422 scan += UTF8SKIP(scan);
5426 while (scan < loceol && REGINCLASS(prog, p, (U8*)scan))
5433 LOAD_UTF8_CHARCLASS_ALNUM();
5434 while (hardcount < max && scan < loceol &&
5435 swash_fetch(PL_utf8_alnum, (U8*)scan, do_utf8)) {
5436 scan += UTF8SKIP(scan);
5440 while (scan < loceol && isALNUM(*scan))
5445 PL_reg_flags |= RF_tainted;
5448 while (hardcount < max && scan < loceol &&
5449 isALNUM_LC_utf8((U8*)scan)) {
5450 scan += UTF8SKIP(scan);
5454 while (scan < loceol && isALNUM_LC(*scan))
5461 LOAD_UTF8_CHARCLASS_ALNUM();
5462 while (hardcount < max && scan < loceol &&
5463 !swash_fetch(PL_utf8_alnum, (U8*)scan, do_utf8)) {
5464 scan += UTF8SKIP(scan);
5468 while (scan < loceol && !isALNUM(*scan))
5473 PL_reg_flags |= RF_tainted;
5476 while (hardcount < max && scan < loceol &&
5477 !isALNUM_LC_utf8((U8*)scan)) {
5478 scan += UTF8SKIP(scan);
5482 while (scan < loceol && !isALNUM_LC(*scan))
5489 LOAD_UTF8_CHARCLASS_SPACE();
5490 while (hardcount < max && scan < loceol &&
5492 swash_fetch(PL_utf8_space,(U8*)scan, do_utf8))) {
5493 scan += UTF8SKIP(scan);
5497 while (scan < loceol && isSPACE(*scan))
5502 PL_reg_flags |= RF_tainted;
5505 while (hardcount < max && scan < loceol &&
5506 (*scan == ' ' || isSPACE_LC_utf8((U8*)scan))) {
5507 scan += UTF8SKIP(scan);
5511 while (scan < loceol && isSPACE_LC(*scan))
5518 LOAD_UTF8_CHARCLASS_SPACE();
5519 while (hardcount < max && scan < loceol &&
5521 swash_fetch(PL_utf8_space,(U8*)scan, do_utf8))) {
5522 scan += UTF8SKIP(scan);
5526 while (scan < loceol && !isSPACE(*scan))
5531 PL_reg_flags |= RF_tainted;
5534 while (hardcount < max && scan < loceol &&
5535 !(*scan == ' ' || isSPACE_LC_utf8((U8*)scan))) {
5536 scan += UTF8SKIP(scan);
5540 while (scan < loceol && !isSPACE_LC(*scan))
5547 LOAD_UTF8_CHARCLASS_DIGIT();
5548 while (hardcount < max && scan < loceol &&
5549 swash_fetch(PL_utf8_digit, (U8*)scan, do_utf8)) {
5550 scan += UTF8SKIP(scan);
5554 while (scan < loceol && isDIGIT(*scan))
5561 LOAD_UTF8_CHARCLASS_DIGIT();
5562 while (hardcount < max && scan < loceol &&
5563 !swash_fetch(PL_utf8_digit, (U8*)scan, do_utf8)) {
5564 scan += UTF8SKIP(scan);
5568 while (scan < loceol && !isDIGIT(*scan))
5574 while (hardcount < max && scan < loceol && (c=is_LNBREAK_utf8(scan))) {
5580 LNBREAK can match two latin chars, which is ok,
5581 because we have a null terminated string, but we
5582 have to use hardcount in this situation
5584 while (scan < loceol && (c=is_LNBREAK_latin1(scan))) {
5593 while (hardcount < max && scan < loceol && (c=is_HORIZWS_utf8(scan))) {
5598 while (scan < loceol && is_HORIZWS_latin1(scan))
5605 while (hardcount < max && scan < loceol && !is_HORIZWS_utf8(scan)) {
5606 scan += UTF8SKIP(scan);
5610 while (scan < loceol && !is_HORIZWS_latin1(scan))
5618 while (hardcount < max && scan < loceol && (c=is_VERTWS_utf8(scan))) {
5623 while (scan < loceol && is_VERTWS_latin1(scan))
5631 while (hardcount < max && scan < loceol && !is_VERTWS_utf8(scan)) {
5632 scan += UTF8SKIP(scan);
5636 while (scan < loceol && !is_VERTWS_latin1(scan))
5642 default: /* Called on something of 0 width. */
5643 break; /* So match right here or not at all. */
5649 c = scan - PL_reginput;
5653 GET_RE_DEBUG_FLAGS_DECL;
5655 SV * const prop = sv_newmortal();
5656 regprop(prog, prop, p);
5657 PerlIO_printf(Perl_debug_log,
5658 "%*s %s can match %"IVdf" times out of %"IVdf"...\n",
5659 REPORT_CODE_OFF + depth*2, "", SvPVX_const(prop),(IV)c,(IV)max);
5667 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
5669 - regclass_swash - prepare the utf8 swash
5673 Perl_regclass_swash(pTHX_ const regexp *prog, register const regnode* node, bool doinit, SV** listsvp, SV **altsvp)
5679 RXi_GET_DECL(prog,progi);
5680 const struct reg_data * const data = prog ? progi->data : NULL;
5682 PERL_ARGS_ASSERT_REGCLASS_SWASH;
5684 if (data && data->count) {
5685 const U32 n = ARG(node);
5687 if (data->what[n] == 's') {
5688 SV * const rv = MUTABLE_SV(data->data[n]);
5689 AV * const av = MUTABLE_AV(SvRV(rv));
5690 SV **const ary = AvARRAY(av);
5693 /* See the end of regcomp.c:S_regclass() for
5694 * documentation of these array elements. */
5697 a = SvROK(ary[1]) ? &ary[1] : NULL;
5698 b = SvTYPE(ary[2]) == SVt_PVAV ? &ary[2] : NULL;
5702 else if (si && doinit) {
5703 sw = swash_init("utf8", "", si, 1, 0);
5704 (void)av_store(av, 1, sw);
5721 - reginclass - determine if a character falls into a character class
5723 The n is the ANYOF regnode, the p is the target string, lenp
5724 is pointer to the maximum length of how far to go in the p
5725 (if the lenp is zero, UTF8SKIP(p) is used),
5726 do_utf8 tells whether the target string is in UTF-8.
5731 S_reginclass(pTHX_ const regexp *prog, register const regnode *n, register const U8* p, STRLEN* lenp, register bool do_utf8)
5734 const char flags = ANYOF_FLAGS(n);
5740 PERL_ARGS_ASSERT_REGINCLASS;
5742 if (do_utf8 && !UTF8_IS_INVARIANT(c)) {
5743 c = utf8n_to_uvchr(p, UTF8_MAXBYTES, &len,
5744 (UTF8_ALLOW_DEFAULT & UTF8_ALLOW_ANYUV) | UTF8_CHECK_ONLY);
5745 /* see [perl #37836] for UTF8_ALLOW_ANYUV */
5746 if (len == (STRLEN)-1)
5747 Perl_croak(aTHX_ "Malformed UTF-8 character (fatal)");
5750 plen = lenp ? *lenp : UNISKIP(NATIVE_TO_UNI(c));
5751 if (do_utf8 || (flags & ANYOF_UNICODE)) {
5754 if (do_utf8 && !ANYOF_RUNTIME(n)) {
5755 if (len != (STRLEN)-1 && c < 256 && ANYOF_BITMAP_TEST(n, c))
5758 if (!match && do_utf8 && (flags & ANYOF_UNICODE_ALL) && c >= 256)
5762 SV * const sw = regclass_swash(prog, n, TRUE, 0, (SV**)&av);
5770 utf8_p = bytes_to_utf8(p, &len);
5772 if (swash_fetch(sw, utf8_p, 1))
5774 else if (flags & ANYOF_FOLD) {
5775 if (!match && lenp && av) {
5777 for (i = 0; i <= av_len(av); i++) {
5778 SV* const sv = *av_fetch(av, i, FALSE);
5780 const char * const s = SvPV_const(sv, len);
5781 if (len <= plen && memEQ(s, (char*)utf8_p, len)) {
5789 U8 tmpbuf[UTF8_MAXBYTES_CASE+1];
5792 to_utf8_fold(utf8_p, tmpbuf, &tmplen);
5793 if (swash_fetch(sw, tmpbuf, 1))
5798 /* If we allocated a string above, free it */
5799 if (! do_utf8) Safefree(utf8_p);
5802 if (match && lenp && *lenp == 0)
5803 *lenp = UNISKIP(NATIVE_TO_UNI(c));
5805 if (!match && c < 256) {
5806 if (ANYOF_BITMAP_TEST(n, c))
5808 else if (flags & ANYOF_FOLD) {
5811 if (flags & ANYOF_LOCALE) {
5812 PL_reg_flags |= RF_tainted;
5813 f = PL_fold_locale[c];
5817 if (f != c && ANYOF_BITMAP_TEST(n, f))
5821 if (!match && (flags & ANYOF_CLASS)) {
5822 PL_reg_flags |= RF_tainted;
5824 (ANYOF_CLASS_TEST(n, ANYOF_ALNUM) && isALNUM_LC(c)) ||
5825 (ANYOF_CLASS_TEST(n, ANYOF_NALNUM) && !isALNUM_LC(c)) ||
5826 (ANYOF_CLASS_TEST(n, ANYOF_SPACE) && isSPACE_LC(c)) ||
5827 (ANYOF_CLASS_TEST(n, ANYOF_NSPACE) && !isSPACE_LC(c)) ||
5828 (ANYOF_CLASS_TEST(n, ANYOF_DIGIT) && isDIGIT_LC(c)) ||
5829 (ANYOF_CLASS_TEST(n, ANYOF_NDIGIT) && !isDIGIT_LC(c)) ||
5830 (ANYOF_CLASS_TEST(n, ANYOF_ALNUMC) && isALNUMC_LC(c)) ||
5831 (ANYOF_CLASS_TEST(n, ANYOF_NALNUMC) && !isALNUMC_LC(c)) ||
5832 (ANYOF_CLASS_TEST(n, ANYOF_ALPHA) && isALPHA_LC(c)) ||
5833 (ANYOF_CLASS_TEST(n, ANYOF_NALPHA) && !isALPHA_LC(c)) ||
5834 (ANYOF_CLASS_TEST(n, ANYOF_ASCII) && isASCII(c)) ||
5835 (ANYOF_CLASS_TEST(n, ANYOF_NASCII) && !isASCII(c)) ||
5836 (ANYOF_CLASS_TEST(n, ANYOF_CNTRL) && isCNTRL_LC(c)) ||
5837 (ANYOF_CLASS_TEST(n, ANYOF_NCNTRL) && !isCNTRL_LC(c)) ||
5838 (ANYOF_CLASS_TEST(n, ANYOF_GRAPH) && isGRAPH_LC(c)) ||
5839 (ANYOF_CLASS_TEST(n, ANYOF_NGRAPH) && !isGRAPH_LC(c)) ||
5840 (ANYOF_CLASS_TEST(n, ANYOF_LOWER) && isLOWER_LC(c)) ||
5841 (ANYOF_CLASS_TEST(n, ANYOF_NLOWER) && !isLOWER_LC(c)) ||
5842 (ANYOF_CLASS_TEST(n, ANYOF_PRINT) && isPRINT_LC(c)) ||
5843 (ANYOF_CLASS_TEST(n, ANYOF_NPRINT) && !isPRINT_LC(c)) ||
5844 (ANYOF_CLASS_TEST(n, ANYOF_PUNCT) && isPUNCT_LC(c)) ||
5845 (ANYOF_CLASS_TEST(n, ANYOF_NPUNCT) && !isPUNCT_LC(c)) ||
5846 (ANYOF_CLASS_TEST(n, ANYOF_UPPER) && isUPPER_LC(c)) ||
5847 (ANYOF_CLASS_TEST(n, ANYOF_NUPPER) && !isUPPER_LC(c)) ||
5848 (ANYOF_CLASS_TEST(n, ANYOF_XDIGIT) && isXDIGIT(c)) ||
5849 (ANYOF_CLASS_TEST(n, ANYOF_NXDIGIT) && !isXDIGIT(c)) ||
5850 (ANYOF_CLASS_TEST(n, ANYOF_PSXSPC) && isPSXSPC(c)) ||
5851 (ANYOF_CLASS_TEST(n, ANYOF_NPSXSPC) && !isPSXSPC(c)) ||
5852 (ANYOF_CLASS_TEST(n, ANYOF_BLANK) && isBLANK(c)) ||
5853 (ANYOF_CLASS_TEST(n, ANYOF_NBLANK) && !isBLANK(c))
5854 ) /* How's that for a conditional? */
5861 return (flags & ANYOF_INVERT) ? !match : match;
5865 S_reghop3(U8 *s, I32 off, const U8* lim)
5869 PERL_ARGS_ASSERT_REGHOP3;
5872 while (off-- && s < lim) {
5873 /* XXX could check well-formedness here */
5878 while (off++ && s > lim) {
5880 if (UTF8_IS_CONTINUED(*s)) {
5881 while (s > lim && UTF8_IS_CONTINUATION(*s))
5884 /* XXX could check well-formedness here */
5891 /* there are a bunch of places where we use two reghop3's that should
5892 be replaced with this routine. but since thats not done yet
5893 we ifdef it out - dmq
5896 S_reghop4(U8 *s, I32 off, const U8* llim, const U8* rlim)
5900 PERL_ARGS_ASSERT_REGHOP4;
5903 while (off-- && s < rlim) {
5904 /* XXX could check well-formedness here */
5909 while (off++ && s > llim) {
5911 if (UTF8_IS_CONTINUED(*s)) {
5912 while (s > llim && UTF8_IS_CONTINUATION(*s))
5915 /* XXX could check well-formedness here */
5923 S_reghopmaybe3(U8* s, I32 off, const U8* lim)
5927 PERL_ARGS_ASSERT_REGHOPMAYBE3;
5930 while (off-- && s < lim) {
5931 /* XXX could check well-formedness here */
5938 while (off++ && s > lim) {
5940 if (UTF8_IS_CONTINUED(*s)) {
5941 while (s > lim && UTF8_IS_CONTINUATION(*s))
5944 /* XXX could check well-formedness here */
5953 restore_pos(pTHX_ void *arg)
5956 regexp * const rex = (regexp *)arg;
5957 if (PL_reg_eval_set) {
5958 if (PL_reg_oldsaved) {
5959 rex->subbeg = PL_reg_oldsaved;
5960 rex->sublen = PL_reg_oldsavedlen;
5961 #ifdef PERL_OLD_COPY_ON_WRITE
5962 rex->saved_copy = PL_nrs;
5964 RXp_MATCH_COPIED_on(rex);
5966 PL_reg_magic->mg_len = PL_reg_oldpos;
5967 PL_reg_eval_set = 0;
5968 PL_curpm = PL_reg_oldcurpm;
5973 S_to_utf8_substr(pTHX_ register regexp *prog)
5977 PERL_ARGS_ASSERT_TO_UTF8_SUBSTR;
5980 if (prog->substrs->data[i].substr
5981 && !prog->substrs->data[i].utf8_substr) {
5982 SV* const sv = newSVsv(prog->substrs->data[i].substr);
5983 prog->substrs->data[i].utf8_substr = sv;
5984 sv_utf8_upgrade(sv);
5985 if (SvVALID(prog->substrs->data[i].substr)) {
5986 const U8 flags = BmFLAGS(prog->substrs->data[i].substr);
5987 if (flags & FBMcf_TAIL) {
5988 /* Trim the trailing \n that fbm_compile added last
5990 SvCUR_set(sv, SvCUR(sv) - 1);
5991 /* Whilst this makes the SV technically "invalid" (as its
5992 buffer is no longer followed by "\0") when fbm_compile()
5993 adds the "\n" back, a "\0" is restored. */
5995 fbm_compile(sv, flags);
5997 if (prog->substrs->data[i].substr == prog->check_substr)
5998 prog->check_utf8 = sv;
6004 S_to_byte_substr(pTHX_ register regexp *prog)
6009 PERL_ARGS_ASSERT_TO_BYTE_SUBSTR;
6012 if (prog->substrs->data[i].utf8_substr
6013 && !prog->substrs->data[i].substr) {
6014 SV* sv = newSVsv(prog->substrs->data[i].utf8_substr);
6015 if (sv_utf8_downgrade(sv, TRUE)) {
6016 if (SvVALID(prog->substrs->data[i].utf8_substr)) {
6018 = BmFLAGS(prog->substrs->data[i].utf8_substr);
6019 if (flags & FBMcf_TAIL) {
6020 /* Trim the trailing \n that fbm_compile added last
6022 SvCUR_set(sv, SvCUR(sv) - 1);
6024 fbm_compile(sv, flags);
6030 prog->substrs->data[i].substr = sv;
6031 if (prog->substrs->data[i].utf8_substr == prog->check_utf8)
6032 prog->check_substr = sv;
6039 * c-indentation-style: bsd
6041 * indent-tabs-mode: t
6044 * ex: set ts=8 sts=4 sw=4 noet: