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? e.g. locale */
85 #define RF_warned 2 /* warned about big count? */
87 #define RF_utf8 8 /* Pattern contains multibyte chars? */
89 #define UTF_PATTERN ((PL_reg_flags & RF_utf8) != 0)
95 /* Valid for non-utf8 strings, non-ANYOFV nodes only: avoids the reginclass
96 * call if there are no complications: i.e., if everything matchable is
97 * straight forward in the bitmap */
98 #define REGINCLASS(prog,p,c) (ANYOF_FLAGS(p) ? reginclass(prog,p,c,0,0) \
99 : ANYOF_BITMAP_TEST(p,*(c)))
105 #define CHR_SVLEN(sv) (utf8_target ? sv_len_utf8(sv) : SvCUR(sv))
106 #define CHR_DIST(a,b) (PL_reg_match_utf8 ? utf8_distance(a,b) : a - b)
108 #define HOPc(pos,off) \
109 (char *)(PL_reg_match_utf8 \
110 ? reghop3((U8*)pos, off, (U8*)(off >= 0 ? PL_regeol : PL_bostr)) \
112 #define HOPBACKc(pos, off) \
113 (char*)(PL_reg_match_utf8\
114 ? reghopmaybe3((U8*)pos, -off, (U8*)PL_bostr) \
115 : (pos - off >= PL_bostr) \
119 #define HOP3(pos,off,lim) (PL_reg_match_utf8 ? reghop3((U8*)(pos), off, (U8*)(lim)) : (U8*)(pos + off))
120 #define HOP3c(pos,off,lim) ((char*)HOP3(pos,off,lim))
122 /* these are unrolled below in the CCC_TRY_XXX defined */
124 /* Often 'str' is a hard-coded utf8 string instead of utfebcdic. so just
125 * skip the check on EBCDIC platforms */
126 # define LOAD_UTF8_CHARCLASS(class,str) LOAD_UTF8_CHARCLASS_NO_CHECK(class)
128 # define LOAD_UTF8_CHARCLASS(class,str) STMT_START { \
129 if (!CAT2(PL_utf8_,class)) { \
131 ENTER; save_re_context(); \
132 ok=CAT2(is_utf8_,class)((const U8*)str); \
133 PERL_UNUSED_VAR(ok); \
134 assert(ok); assert(CAT2(PL_utf8_,class)); LEAVE; } } STMT_END
137 /* Doesn't do an assert to verify that is correct */
138 #define LOAD_UTF8_CHARCLASS_NO_CHECK(class) STMT_START { \
139 if (!CAT2(PL_utf8_,class)) { \
140 bool throw_away PERL_UNUSED_DECL; \
141 ENTER; save_re_context(); \
142 throw_away = CAT2(is_utf8_,class)((const U8*)" "); \
145 #define LOAD_UTF8_CHARCLASS_ALNUM() LOAD_UTF8_CHARCLASS(alnum,"a")
146 #define LOAD_UTF8_CHARCLASS_DIGIT() LOAD_UTF8_CHARCLASS(digit,"0")
147 #define LOAD_UTF8_CHARCLASS_SPACE() LOAD_UTF8_CHARCLASS(space," ")
149 #define LOAD_UTF8_CHARCLASS_GCB() /* Grapheme cluster boundaries */ \
150 LOAD_UTF8_CHARCLASS(X_begin, " "); \
151 LOAD_UTF8_CHARCLASS(X_non_hangul, "A"); \
152 /* These are utf8 constants, and not utf-ebcdic constants, so the \
153 * assert should likely and hopefully fail on an EBCDIC machine */ \
154 LOAD_UTF8_CHARCLASS(X_extend, "\xcc\x80"); /* U+0300 */ \
156 /* No asserts are done for these, in case called on an early \
157 * Unicode version in which they map to nothing */ \
158 LOAD_UTF8_CHARCLASS_NO_CHECK(X_prepend);/* U+0E40 "\xe0\xb9\x80" */ \
159 LOAD_UTF8_CHARCLASS_NO_CHECK(X_L); /* U+1100 "\xe1\x84\x80" */ \
160 LOAD_UTF8_CHARCLASS_NO_CHECK(X_LV); /* U+AC00 "\xea\xb0\x80" */ \
161 LOAD_UTF8_CHARCLASS_NO_CHECK(X_LVT); /* U+AC01 "\xea\xb0\x81" */ \
162 LOAD_UTF8_CHARCLASS_NO_CHECK(X_LV_LVT_V);/* U+AC01 "\xea\xb0\x81" */\
163 LOAD_UTF8_CHARCLASS_NO_CHECK(X_T); /* U+11A8 "\xe1\x86\xa8" */ \
164 LOAD_UTF8_CHARCLASS_NO_CHECK(X_V) /* U+1160 "\xe1\x85\xa0" */
166 #define PLACEHOLDER /* Something for the preprocessor to grab onto */
168 /* The actual code for CCC_TRY, which uses several variables from the routine
169 * it's callable from. It is designed to be the bulk of a case statement.
170 * FUNC is the macro or function to call on non-utf8 targets that indicate if
171 * nextchr matches the class.
172 * UTF8_TEST is the whole test string to use for utf8 targets
173 * LOAD is what to use to test, and if not present to load in the swash for the
175 * POS_OR_NEG is either empty or ! to complement the results of FUNC or
177 * The logic is: Fail if we're at the end-of-string; otherwise if the target is
178 * utf8 and a variant, load the swash if necessary and test using the utf8
179 * test. Advance to the next character if test is ok, otherwise fail; If not
180 * utf8 or an invariant under utf8, use the non-utf8 test, and fail if it
181 * fails, or advance to the next character */
183 #define _CCC_TRY_CODE(POS_OR_NEG, FUNC, UTF8_TEST, CLASS, STR) \
184 if (locinput >= PL_regeol) { \
187 if (utf8_target && UTF8_IS_CONTINUED(nextchr)) { \
188 LOAD_UTF8_CHARCLASS(CLASS, STR); \
189 if (POS_OR_NEG (UTF8_TEST)) { \
192 locinput += PL_utf8skip[nextchr]; \
193 nextchr = UCHARAT(locinput); \
196 if (POS_OR_NEG (FUNC(nextchr))) { \
199 nextchr = UCHARAT(++locinput); \
202 /* Handle the non-locale cases for a character class and its complement. It
203 * calls _CCC_TRY_CODE with a ! to complement the test for the character class.
204 * This is because that code fails when the test succeeds, so we want to have
205 * the test fail so that the code succeeds. The swash is stored in a
206 * predictable PL_ place */
207 #define _CCC_TRY_NONLOCALE(NAME, NNAME, FUNC, \
210 _CCC_TRY_CODE( !, FUNC, \
211 cBOOL(swash_fetch(CAT2(PL_utf8_,CLASS), \
212 (U8*)locinput, TRUE)), \
215 _CCC_TRY_CODE( PLACEHOLDER , FUNC, \
216 cBOOL(swash_fetch(CAT2(PL_utf8_,CLASS), \
217 (U8*)locinput, TRUE)), \
220 /* Generate the case statements for both locale and non-locale character
221 * classes in regmatch for classes that don't have special unicode semantics.
222 * Locales don't use an immediate swash, but an intermediary special locale
223 * function that is called on the pointer to the current place in the input
224 * string. That function will resolve to needing the same swash. One might
225 * think that because we don't know what the locale will match, we shouldn't
226 * check with the swash loading function that it loaded properly; ie, that we
227 * should use LOAD_UTF8_CHARCLASS_NO_CHECK for those, but what is passed to the
228 * regular LOAD_UTF8_CHARCLASS is in non-locale terms, and so locale is
230 #define CCC_TRY(NAME, NNAME, FUNC, \
231 NAMEL, NNAMEL, LCFUNC, LCFUNC_utf8, \
232 NAMEA, NNAMEA, FUNCA, \
235 PL_reg_flags |= RF_tainted; \
236 _CCC_TRY_CODE( !, LCFUNC, LCFUNC_utf8((U8*)locinput), CLASS, STR) \
238 PL_reg_flags |= RF_tainted; \
239 _CCC_TRY_CODE( PLACEHOLDER, LCFUNC, LCFUNC_utf8((U8*)locinput), \
242 if (locinput >= PL_regeol || ! FUNCA(nextchr)) { \
245 /* Matched a utf8-invariant, so don't have to worry about utf8 */ \
246 nextchr = UCHARAT(++locinput); \
249 if (locinput >= PL_regeol || FUNCA(nextchr)) { \
253 locinput += PL_utf8skip[nextchr]; \
254 nextchr = UCHARAT(locinput); \
257 nextchr = UCHARAT(++locinput); \
260 /* Generate the non-locale cases */ \
261 _CCC_TRY_NONLOCALE(NAME, NNAME, FUNC, CLASS, STR)
263 /* This is like CCC_TRY, but has an extra set of parameters for generating case
264 * statements to handle separate Unicode semantics nodes */
265 #define CCC_TRY_U(NAME, NNAME, FUNC, \
266 NAMEL, NNAMEL, LCFUNC, LCFUNC_utf8, \
267 NAMEU, NNAMEU, FUNCU, \
268 NAMEA, NNAMEA, FUNCA, \
270 CCC_TRY(NAME, NNAME, FUNC, \
271 NAMEL, NNAMEL, LCFUNC, LCFUNC_utf8, \
272 NAMEA, NNAMEA, FUNCA, \
274 _CCC_TRY_NONLOCALE(NAMEU, NNAMEU, FUNCU, CLASS, STR)
276 /* TODO: Combine JUMPABLE and HAS_TEXT to cache OP(rn) */
278 /* for use after a quantifier and before an EXACT-like node -- japhy */
279 /* it would be nice to rework regcomp.sym to generate this stuff. sigh
281 * NOTE that *nothing* that affects backtracking should be in here, specifically
282 * VERBS must NOT be included. JUMPABLE is used to determine if we can ignore a
283 * node that is in between two EXACT like nodes when ascertaining what the required
284 * "follow" character is. This should probably be moved to regex compile time
285 * although it may be done at run time beause of the REF possibility - more
286 * investigation required. -- demerphq
288 #define JUMPABLE(rn) ( \
290 (OP(rn) == CLOSE && (!cur_eval || cur_eval->u.eval.close_paren != ARG(rn))) || \
292 OP(rn) == SUSPEND || OP(rn) == IFMATCH || \
293 OP(rn) == PLUS || OP(rn) == MINMOD || \
295 (PL_regkind[OP(rn)] == CURLY && ARG1(rn) > 0) \
297 #define IS_EXACT(rn) (PL_regkind[OP(rn)] == EXACT)
299 #define HAS_TEXT(rn) ( IS_EXACT(rn) || PL_regkind[OP(rn)] == REF )
302 /* Currently these are only used when PL_regkind[OP(rn)] == EXACT so
303 we don't need this definition. */
304 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==REF || OP(rn)==NREF )
305 #define IS_TEXTF(rn) ( OP(rn)==EXACTFU || OP(rn)==EXACTFU_SS || OP(rn)==EXACTFU_TRICKYFOLD || OP(rn)==EXACTFA || OP(rn)==EXACTF || OP(rn)==REFF || OP(rn)==NREFF )
306 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL || OP(rn)==REFFL || OP(rn)==NREFFL )
309 /* ... so we use this as its faster. */
310 #define IS_TEXT(rn) ( OP(rn)==EXACT )
311 #define IS_TEXTFU(rn) ( OP(rn)==EXACTFU || OP(rn)==EXACTFU_SS || OP(rn)==EXACTFU_TRICKYFOLD || OP(rn) == EXACTFA)
312 #define IS_TEXTF(rn) ( OP(rn)==EXACTF )
313 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL )
318 Search for mandatory following text node; for lookahead, the text must
319 follow but for lookbehind (rn->flags != 0) we skip to the next step.
321 #define FIND_NEXT_IMPT(rn) STMT_START { \
322 while (JUMPABLE(rn)) { \
323 const OPCODE type = OP(rn); \
324 if (type == SUSPEND || PL_regkind[type] == CURLY) \
325 rn = NEXTOPER(NEXTOPER(rn)); \
326 else if (type == PLUS) \
328 else if (type == IFMATCH) \
329 rn = (rn->flags == 0) ? NEXTOPER(NEXTOPER(rn)) : rn + ARG(rn); \
330 else rn += NEXT_OFF(rn); \
335 static void restore_pos(pTHX_ void *arg);
337 #define REGCP_PAREN_ELEMS 3
338 #define REGCP_OTHER_ELEMS 3
339 #define REGCP_FRAME_ELEMS 1
340 /* REGCP_FRAME_ELEMS are not part of the REGCP_OTHER_ELEMS and
341 * are needed for the regexp context stack bookkeeping. */
344 S_regcppush(pTHX_ const regexp *rex, I32 parenfloor)
347 const int retval = PL_savestack_ix;
348 const int paren_elems_to_push = (PL_regsize - parenfloor) * REGCP_PAREN_ELEMS;
349 const UV total_elems = paren_elems_to_push + REGCP_OTHER_ELEMS;
350 const UV elems_shifted = total_elems << SAVE_TIGHT_SHIFT;
352 GET_RE_DEBUG_FLAGS_DECL;
354 PERL_ARGS_ASSERT_REGCPPUSH;
356 if (paren_elems_to_push < 0)
357 Perl_croak(aTHX_ "panic: paren_elems_to_push, %i < 0",
358 paren_elems_to_push);
360 if ((elems_shifted >> SAVE_TIGHT_SHIFT) != total_elems)
361 Perl_croak(aTHX_ "panic: paren_elems_to_push offset %"UVuf
362 " out of range (%lu-%ld)",
363 total_elems, (unsigned long)PL_regsize, (long)parenfloor);
365 SSGROW(total_elems + REGCP_FRAME_ELEMS);
368 if ((int)PL_regsize > (int)parenfloor)
369 PerlIO_printf(Perl_debug_log,
370 "rex=0x%"UVxf" offs=0x%"UVxf": saving capture indices:\n",
375 for (p = parenfloor+1; p <= (I32)PL_regsize; p++) {
376 /* REGCP_PARENS_ELEMS are pushed per pairs of parentheses. */
377 SSPUSHINT(rex->offs[p].end);
378 SSPUSHINT(rex->offs[p].start);
379 SSPUSHINT(rex->offs[p].start_tmp);
380 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
381 " \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"\n",
383 (IV)rex->offs[p].start,
384 (IV)rex->offs[p].start_tmp,
388 /* REGCP_OTHER_ELEMS are pushed in any case, parentheses or no. */
389 SSPUSHINT(PL_regsize);
390 SSPUSHINT(rex->lastparen);
391 SSPUSHINT(rex->lastcloseparen);
392 SSPUSHUV(SAVEt_REGCONTEXT | elems_shifted); /* Magic cookie. */
397 /* These are needed since we do not localize EVAL nodes: */
398 #define REGCP_SET(cp) \
400 PerlIO_printf(Perl_debug_log, \
401 " Setting an EVAL scope, savestack=%"IVdf"\n", \
402 (IV)PL_savestack_ix)); \
405 #define REGCP_UNWIND(cp) \
407 if (cp != PL_savestack_ix) \
408 PerlIO_printf(Perl_debug_log, \
409 " Clearing an EVAL scope, savestack=%"IVdf"..%"IVdf"\n", \
410 (IV)(cp), (IV)PL_savestack_ix)); \
413 #define UNWIND_PAREN(lp, lcp) \
414 for (n = rex->lastparen; n > lp; n--) \
415 rex->offs[n].end = -1; \
416 rex->lastparen = n; \
417 rex->lastcloseparen = lcp;
421 S_regcppop(pTHX_ regexp *rex)
426 GET_RE_DEBUG_FLAGS_DECL;
428 PERL_ARGS_ASSERT_REGCPPOP;
430 /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
432 assert((i & SAVE_MASK) == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
433 i >>= SAVE_TIGHT_SHIFT; /* Parentheses elements to pop. */
434 rex->lastcloseparen = SSPOPINT;
435 rex->lastparen = SSPOPINT;
436 PL_regsize = SSPOPINT;
438 i -= REGCP_OTHER_ELEMS;
439 /* Now restore the parentheses context. */
441 if (i || rex->lastparen + 1 <= rex->nparens)
442 PerlIO_printf(Perl_debug_log,
443 "rex=0x%"UVxf" offs=0x%"UVxf": restoring capture indices to:\n",
449 for ( ; i > 0; i -= REGCP_PAREN_ELEMS) {
451 rex->offs[paren].start_tmp = SSPOPINT;
452 rex->offs[paren].start = SSPOPINT;
454 if (paren <= rex->lastparen)
455 rex->offs[paren].end = tmps;
456 DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
457 " \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"%s\n",
459 (IV)rex->offs[paren].start,
460 (IV)rex->offs[paren].start_tmp,
461 (IV)rex->offs[paren].end,
462 (paren > rex->lastparen ? "(skipped)" : ""));
467 /* It would seem that the similar code in regtry()
468 * already takes care of this, and in fact it is in
469 * a better location to since this code can #if 0-ed out
470 * but the code in regtry() is needed or otherwise tests
471 * requiring null fields (pat.t#187 and split.t#{13,14}
472 * (as of patchlevel 7877) will fail. Then again,
473 * this code seems to be necessary or otherwise
474 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
475 * --jhi updated by dapm */
476 for (i = rex->lastparen + 1; i <= rex->nparens; i++) {
478 rex->offs[i].start = -1;
479 rex->offs[i].end = -1;
480 DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
481 " \\%"UVuf": %s ..-1 undeffing\n",
483 (i > PL_regsize) ? "-1" : " "
489 /* restore the parens and associated vars at savestack position ix,
490 * but without popping the stack */
493 S_regcp_restore(pTHX_ regexp *rex, I32 ix)
495 I32 tmpix = PL_savestack_ix;
496 PL_savestack_ix = ix;
498 PL_savestack_ix = tmpix;
501 #define regcpblow(cp) LEAVE_SCOPE(cp) /* Ignores regcppush()ed data. */
504 * pregexec and friends
507 #ifndef PERL_IN_XSUB_RE
509 - pregexec - match a regexp against a string
512 Perl_pregexec(pTHX_ REGEXP * const prog, char* stringarg, register char *strend,
513 char *strbeg, I32 minend, SV *screamer, U32 nosave)
514 /* strend: pointer to null at end of string */
515 /* strbeg: real beginning of string */
516 /* minend: end of match must be >=minend after stringarg. */
517 /* nosave: For optimizations. */
519 PERL_ARGS_ASSERT_PREGEXEC;
522 regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
523 nosave ? 0 : REXEC_COPY_STR);
528 * Need to implement the following flags for reg_anch:
530 * USE_INTUIT_NOML - Useful to call re_intuit_start() first
532 * INTUIT_AUTORITATIVE_NOML - Can trust a positive answer
533 * INTUIT_AUTORITATIVE_ML
534 * INTUIT_ONCE_NOML - Intuit can match in one location only.
537 * Another flag for this function: SECOND_TIME (so that float substrs
538 * with giant delta may be not rechecked).
541 /* Assumptions: if ANCH_GPOS, then strpos is anchored. XXXX Check GPOS logic */
543 /* If SCREAM, then SvPVX_const(sv) should be compatible with strpos and strend.
544 Otherwise, only SvCUR(sv) is used to get strbeg. */
546 /* XXXX We assume that strpos is strbeg unless sv. */
548 /* XXXX Some places assume that there is a fixed substring.
549 An update may be needed if optimizer marks as "INTUITable"
550 RExen without fixed substrings. Similarly, it is assumed that
551 lengths of all the strings are no more than minlen, thus they
552 cannot come from lookahead.
553 (Or minlen should take into account lookahead.)
554 NOTE: Some of this comment is not correct. minlen does now take account
555 of lookahead/behind. Further research is required. -- demerphq
559 /* A failure to find a constant substring means that there is no need to make
560 an expensive call to REx engine, thus we celebrate a failure. Similarly,
561 finding a substring too deep into the string means that less calls to
562 regtry() should be needed.
564 REx compiler's optimizer found 4 possible hints:
565 a) Anchored substring;
567 c) Whether we are anchored (beginning-of-line or \G);
568 d) First node (of those at offset 0) which may distinguish positions;
569 We use a)b)d) and multiline-part of c), and try to find a position in the
570 string which does not contradict any of them.
573 /* Most of decisions we do here should have been done at compile time.
574 The nodes of the REx which we used for the search should have been
575 deleted from the finite automaton. */
578 Perl_re_intuit_start(pTHX_ REGEXP * const rx, SV *sv, char *strpos,
579 char *strend, const U32 flags, re_scream_pos_data *data)
582 struct regexp *const prog = (struct regexp *)SvANY(rx);
584 /* Should be nonnegative! */
590 const bool utf8_target = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
592 char *other_last = NULL; /* other substr checked before this */
593 char *check_at = NULL; /* check substr found at this pos */
594 char *checked_upto = NULL; /* how far into the string we have already checked using find_byclass*/
595 const I32 multiline = prog->extflags & RXf_PMf_MULTILINE;
596 RXi_GET_DECL(prog,progi);
598 const char * const i_strpos = strpos;
600 GET_RE_DEBUG_FLAGS_DECL;
602 PERL_ARGS_ASSERT_RE_INTUIT_START;
603 PERL_UNUSED_ARG(flags);
604 PERL_UNUSED_ARG(data);
606 RX_MATCH_UTF8_set(rx,utf8_target);
609 PL_reg_flags |= RF_utf8;
612 debug_start_match(rx, utf8_target, strpos, strend,
613 sv ? "Guessing start of match in sv for"
614 : "Guessing start of match in string for");
617 /* CHR_DIST() would be more correct here but it makes things slow. */
618 if (prog->minlen > strend - strpos) {
619 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
620 "String too short... [re_intuit_start]\n"));
624 strbeg = (sv && SvPOK(sv)) ? strend - SvCUR(sv) : strpos;
627 if (!prog->check_utf8 && prog->check_substr)
628 to_utf8_substr(prog);
629 check = prog->check_utf8;
631 if (!prog->check_substr && prog->check_utf8)
632 to_byte_substr(prog);
633 check = prog->check_substr;
635 if (check == &PL_sv_undef) {
636 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
637 "Non-utf8 string cannot match utf8 check string\n"));
640 if (prog->extflags & RXf_ANCH) { /* Match at beg-of-str or after \n */
641 ml_anch = !( (prog->extflags & RXf_ANCH_SINGLE)
642 || ( (prog->extflags & RXf_ANCH_BOL)
643 && !multiline ) ); /* Check after \n? */
646 if ( !(prog->extflags & RXf_ANCH_GPOS) /* Checked by the caller */
647 && !(prog->intflags & PREGf_IMPLICIT) /* not a real BOL */
648 /* SvCUR is not set on references: SvRV and SvPVX_const overlap */
650 && (strpos != strbeg)) {
651 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Not at start...\n"));
654 if (prog->check_offset_min == prog->check_offset_max &&
655 !(prog->extflags & RXf_CANY_SEEN)) {
656 /* Substring at constant offset from beg-of-str... */
659 s = HOP3c(strpos, prog->check_offset_min, strend);
662 slen = SvCUR(check); /* >= 1 */
664 if ( strend - s > slen || strend - s < slen - 1
665 || (strend - s == slen && strend[-1] != '\n')) {
666 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "String too long...\n"));
669 /* Now should match s[0..slen-2] */
671 if (slen && (*SvPVX_const(check) != *s
673 && memNE(SvPVX_const(check), s, slen)))) {
675 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "String not equal...\n"));
679 else if (*SvPVX_const(check) != *s
680 || ((slen = SvCUR(check)) > 1
681 && memNE(SvPVX_const(check), s, slen)))
684 goto success_at_start;
687 /* Match is anchored, but substr is not anchored wrt beg-of-str. */
689 start_shift = prog->check_offset_min; /* okay to underestimate on CC */
690 end_shift = prog->check_end_shift;
693 const I32 end = prog->check_offset_max + CHR_SVLEN(check)
694 - (SvTAIL(check) != 0);
695 const I32 eshift = CHR_DIST((U8*)strend, (U8*)s) - end;
697 if (end_shift < eshift)
701 else { /* Can match at random position */
704 start_shift = prog->check_offset_min; /* okay to underestimate on CC */
705 end_shift = prog->check_end_shift;
707 /* end shift should be non negative here */
710 #ifdef QDEBUGGING /* 7/99: reports of failure (with the older version) */
712 Perl_croak(aTHX_ "panic: end_shift: %"IVdf" pattern:\n%s\n ",
713 (IV)end_shift, RX_PRECOMP(prog));
717 /* Find a possible match in the region s..strend by looking for
718 the "check" substring in the region corrected by start/end_shift. */
721 I32 srch_start_shift = start_shift;
722 I32 srch_end_shift = end_shift;
725 if (srch_start_shift < 0 && strbeg - s > srch_start_shift) {
726 srch_end_shift -= ((strbeg - s) - srch_start_shift);
727 srch_start_shift = strbeg - s;
729 DEBUG_OPTIMISE_MORE_r({
730 PerlIO_printf(Perl_debug_log, "Check offset min: %"IVdf" Start shift: %"IVdf" End shift %"IVdf" Real End Shift: %"IVdf"\n",
731 (IV)prog->check_offset_min,
732 (IV)srch_start_shift,
734 (IV)prog->check_end_shift);
737 if (prog->extflags & RXf_CANY_SEEN) {
738 start_point= (U8*)(s + srch_start_shift);
739 end_point= (U8*)(strend - srch_end_shift);
741 start_point= HOP3(s, srch_start_shift, srch_start_shift < 0 ? strbeg : strend);
742 end_point= HOP3(strend, -srch_end_shift, strbeg);
744 DEBUG_OPTIMISE_MORE_r({
745 PerlIO_printf(Perl_debug_log, "fbm_instr len=%d str=<%.*s>\n",
746 (int)(end_point - start_point),
747 (int)(end_point - start_point) > 20 ? 20 : (int)(end_point - start_point),
751 s = fbm_instr( start_point, end_point,
752 check, multiline ? FBMrf_MULTILINE : 0);
754 /* Update the count-of-usability, remove useless subpatterns,
758 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
759 SvPVX_const(check), RE_SV_DUMPLEN(check), 30);
760 PerlIO_printf(Perl_debug_log, "%s %s substr %s%s%s",
761 (s ? "Found" : "Did not find"),
762 (check == (utf8_target ? prog->anchored_utf8 : prog->anchored_substr)
763 ? "anchored" : "floating"),
766 (s ? " at offset " : "...\n") );
771 /* Finish the diagnostic message */
772 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%ld...\n", (long)(s - i_strpos)) );
774 /* XXX dmq: first branch is for positive lookbehind...
775 Our check string is offset from the beginning of the pattern.
776 So we need to do any stclass tests offset forward from that
785 /* Got a candidate. Check MBOL anchoring, and the *other* substr.
786 Start with the other substr.
787 XXXX no SCREAM optimization yet - and a very coarse implementation
788 XXXX /ttx+/ results in anchored="ttx", floating="x". floating will
789 *always* match. Probably should be marked during compile...
790 Probably it is right to do no SCREAM here...
793 if (utf8_target ? (prog->float_utf8 && prog->anchored_utf8)
794 : (prog->float_substr && prog->anchored_substr))
796 /* Take into account the "other" substring. */
797 /* XXXX May be hopelessly wrong for UTF... */
800 if (check == (utf8_target ? prog->float_utf8 : prog->float_substr)) {
803 char * const last = HOP3c(s, -start_shift, strbeg);
805 char * const saved_s = s;
808 t = s - prog->check_offset_max;
809 if (s - strpos > prog->check_offset_max /* signed-corrected t > strpos */
811 || ((t = (char*)reghopmaybe3((U8*)s, -(prog->check_offset_max), (U8*)strpos))
816 t = HOP3c(t, prog->anchored_offset, strend);
817 if (t < other_last) /* These positions already checked */
819 last2 = last1 = HOP3c(strend, -prog->minlen, strbeg);
822 /* XXXX It is not documented what units *_offsets are in.
823 We assume bytes, but this is clearly wrong.
824 Meaning this code needs to be carefully reviewed for errors.
828 /* On end-of-str: see comment below. */
829 must = utf8_target ? prog->anchored_utf8 : prog->anchored_substr;
830 if (must == &PL_sv_undef) {
832 DEBUG_r(must = prog->anchored_utf8); /* for debug */
837 HOP3(HOP3(last1, prog->anchored_offset, strend)
838 + SvCUR(must), -(SvTAIL(must)!=0), strbeg),
840 multiline ? FBMrf_MULTILINE : 0
843 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
844 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
845 PerlIO_printf(Perl_debug_log, "%s anchored substr %s%s",
846 (s ? "Found" : "Contradicts"),
847 quoted, RE_SV_TAIL(must));
852 if (last1 >= last2) {
853 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
854 ", giving up...\n"));
857 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
858 ", trying floating at offset %ld...\n",
859 (long)(HOP3c(saved_s, 1, strend) - i_strpos)));
860 other_last = HOP3c(last1, prog->anchored_offset+1, strend);
861 s = HOP3c(last, 1, strend);
865 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " at offset %ld...\n",
866 (long)(s - i_strpos)));
867 t = HOP3c(s, -prog->anchored_offset, strbeg);
868 other_last = HOP3c(s, 1, strend);
876 else { /* Take into account the floating substring. */
878 char * const saved_s = s;
881 t = HOP3c(s, -start_shift, strbeg);
883 HOP3c(strend, -prog->minlen + prog->float_min_offset, strbeg);
884 if (CHR_DIST((U8*)last, (U8*)t) > prog->float_max_offset)
885 last = HOP3c(t, prog->float_max_offset, strend);
886 s = HOP3c(t, prog->float_min_offset, strend);
889 /* XXXX It is not documented what units *_offsets are in. Assume bytes. */
890 must = utf8_target ? prog->float_utf8 : prog->float_substr;
891 /* fbm_instr() takes into account exact value of end-of-str
892 if the check is SvTAIL(ed). Since false positives are OK,
893 and end-of-str is not later than strend we are OK. */
894 if (must == &PL_sv_undef) {
896 DEBUG_r(must = prog->float_utf8); /* for debug message */
899 s = fbm_instr((unsigned char*)s,
900 (unsigned char*)last + SvCUR(must)
902 must, multiline ? FBMrf_MULTILINE : 0);
904 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
905 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
906 PerlIO_printf(Perl_debug_log, "%s floating substr %s%s",
907 (s ? "Found" : "Contradicts"),
908 quoted, RE_SV_TAIL(must));
912 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
913 ", giving up...\n"));
916 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
917 ", trying anchored starting at offset %ld...\n",
918 (long)(saved_s + 1 - i_strpos)));
920 s = HOP3c(t, 1, strend);
924 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " at offset %ld...\n",
925 (long)(s - i_strpos)));
926 other_last = s; /* Fix this later. --Hugo */
936 t= (char*)HOP3( s, -prog->check_offset_max, (prog->check_offset_max<0) ? strend : strpos);
938 DEBUG_OPTIMISE_MORE_r(
939 PerlIO_printf(Perl_debug_log,
940 "Check offset min:%"IVdf" max:%"IVdf" S:%"IVdf" t:%"IVdf" D:%"IVdf" end:%"IVdf"\n",
941 (IV)prog->check_offset_min,
942 (IV)prog->check_offset_max,
950 if (s - strpos > prog->check_offset_max /* signed-corrected t > strpos */
952 || ((t = (char*)reghopmaybe3((U8*)s, -prog->check_offset_max, (U8*) ((prog->check_offset_max<0) ? strend : strpos)))
955 /* Fixed substring is found far enough so that the match
956 cannot start at strpos. */
958 if (ml_anch && t[-1] != '\n') {
959 /* Eventually fbm_*() should handle this, but often
960 anchored_offset is not 0, so this check will not be wasted. */
961 /* XXXX In the code below we prefer to look for "^" even in
962 presence of anchored substrings. And we search even
963 beyond the found float position. These pessimizations
964 are historical artefacts only. */
966 while (t < strend - prog->minlen) {
968 if (t < check_at - prog->check_offset_min) {
969 if (utf8_target ? prog->anchored_utf8 : prog->anchored_substr) {
970 /* Since we moved from the found position,
971 we definitely contradict the found anchored
972 substr. Due to the above check we do not
973 contradict "check" substr.
974 Thus we can arrive here only if check substr
975 is float. Redo checking for "other"=="fixed".
978 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Found /%s^%s/m at offset %ld, rescanning for anchored from offset %ld...\n",
979 PL_colors[0], PL_colors[1], (long)(strpos - i_strpos), (long)(strpos - i_strpos + prog->anchored_offset)));
980 goto do_other_anchored;
982 /* We don't contradict the found floating substring. */
983 /* XXXX Why not check for STCLASS? */
985 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Found /%s^%s/m at offset %ld...\n",
986 PL_colors[0], PL_colors[1], (long)(s - i_strpos)));
989 /* Position contradicts check-string */
990 /* XXXX probably better to look for check-string
991 than for "\n", so one should lower the limit for t? */
992 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Found /%s^%s/m, restarting lookup for check-string at offset %ld...\n",
993 PL_colors[0], PL_colors[1], (long)(t + 1 - i_strpos)));
994 other_last = strpos = s = t + 1;
999 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Did not find /%s^%s/m...\n",
1000 PL_colors[0], PL_colors[1]));
1004 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Starting position does not contradict /%s^%s/m...\n",
1005 PL_colors[0], PL_colors[1]));
1009 ++BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr); /* hooray/5 */
1012 /* The found string does not prohibit matching at strpos,
1013 - no optimization of calling REx engine can be performed,
1014 unless it was an MBOL and we are not after MBOL,
1015 or a future STCLASS check will fail this. */
1017 /* Even in this situation we may use MBOL flag if strpos is offset
1018 wrt the start of the string. */
1019 if (ml_anch && sv && !SvROK(sv) /* See prev comment on SvROK */
1020 && (strpos != strbeg) && strpos[-1] != '\n'
1021 /* May be due to an implicit anchor of m{.*foo} */
1022 && !(prog->intflags & PREGf_IMPLICIT))
1027 DEBUG_EXECUTE_r( if (ml_anch)
1028 PerlIO_printf(Perl_debug_log, "Position at offset %ld does not contradict /%s^%s/m...\n",
1029 (long)(strpos - i_strpos), PL_colors[0], PL_colors[1]);
1032 if (!(prog->intflags & PREGf_NAUGHTY) /* XXXX If strpos moved? */
1034 prog->check_utf8 /* Could be deleted already */
1035 && --BmUSEFUL(prog->check_utf8) < 0
1036 && (prog->check_utf8 == prog->float_utf8)
1038 prog->check_substr /* Could be deleted already */
1039 && --BmUSEFUL(prog->check_substr) < 0
1040 && (prog->check_substr == prog->float_substr)
1043 /* If flags & SOMETHING - do not do it many times on the same match */
1044 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "... Disabling check substring...\n"));
1045 /* XXX Does the destruction order has to change with utf8_target? */
1046 SvREFCNT_dec(utf8_target ? prog->check_utf8 : prog->check_substr);
1047 SvREFCNT_dec(utf8_target ? prog->check_substr : prog->check_utf8);
1048 prog->check_substr = prog->check_utf8 = NULL; /* disable */
1049 prog->float_substr = prog->float_utf8 = NULL; /* clear */
1050 check = NULL; /* abort */
1052 /* XXXX If the check string was an implicit check MBOL, then we need to unset the relevant flag
1053 see http://bugs.activestate.com/show_bug.cgi?id=87173 */
1054 if (prog->intflags & PREGf_IMPLICIT)
1055 prog->extflags &= ~RXf_ANCH_MBOL;
1056 /* XXXX This is a remnant of the old implementation. It
1057 looks wasteful, since now INTUIT can use many
1058 other heuristics. */
1059 prog->extflags &= ~RXf_USE_INTUIT;
1060 /* XXXX What other flags might need to be cleared in this branch? */
1066 /* Last resort... */
1067 /* XXXX BmUSEFUL already changed, maybe multiple change is meaningful... */
1068 /* trie stclasses are too expensive to use here, we are better off to
1069 leave it to regmatch itself */
1070 if (progi->regstclass && PL_regkind[OP(progi->regstclass)]!=TRIE) {
1071 /* minlen == 0 is possible if regstclass is \b or \B,
1072 and the fixed substr is ''$.
1073 Since minlen is already taken into account, s+1 is before strend;
1074 accidentally, minlen >= 1 guaranties no false positives at s + 1
1075 even for \b or \B. But (minlen? 1 : 0) below assumes that
1076 regstclass does not come from lookahead... */
1077 /* If regstclass takes bytelength more than 1: If charlength==1, OK.
1078 This leaves EXACTF-ish only, which are dealt with in find_byclass(). */
1079 const U8* const str = (U8*)STRING(progi->regstclass);
1080 const int cl_l = (PL_regkind[OP(progi->regstclass)] == EXACT
1081 ? CHR_DIST(str+STR_LEN(progi->regstclass), str)
1084 if (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
1085 endpos= HOP3c(s, (prog->minlen ? cl_l : 0), strend);
1086 else if (prog->float_substr || prog->float_utf8)
1087 endpos= HOP3c(HOP3c(check_at, -start_shift, strbeg), cl_l, strend);
1091 if (checked_upto < s)
1093 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "start_shift: %"IVdf" check_at: %"IVdf" s: %"IVdf" endpos: %"IVdf" checked_upto: %"IVdf"\n",
1094 (IV)start_shift, (IV)(check_at - strbeg), (IV)(s - strbeg), (IV)(endpos - strbeg), (IV)(checked_upto- strbeg)));
1097 s = find_byclass(prog, progi->regstclass, checked_upto, endpos, NULL);
1102 const char *what = NULL;
1104 if (endpos == strend) {
1105 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1106 "Could not match STCLASS...\n") );
1109 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1110 "This position contradicts STCLASS...\n") );
1111 if ((prog->extflags & RXf_ANCH) && !ml_anch)
1113 checked_upto = HOPBACKc(endpos, start_shift);
1114 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "start_shift: %"IVdf" check_at: %"IVdf" endpos: %"IVdf" checked_upto: %"IVdf"\n",
1115 (IV)start_shift, (IV)(check_at - strbeg), (IV)(endpos - strbeg), (IV)(checked_upto- strbeg)));
1116 /* Contradict one of substrings */
1117 if (prog->anchored_substr || prog->anchored_utf8) {
1118 if ((utf8_target ? prog->anchored_utf8 : prog->anchored_substr) == check) {
1119 DEBUG_EXECUTE_r( what = "anchored" );
1121 s = HOP3c(t, 1, strend);
1122 if (s + start_shift + end_shift > strend) {
1123 /* XXXX Should be taken into account earlier? */
1124 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1125 "Could not match STCLASS...\n") );
1130 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1131 "Looking for %s substr starting at offset %ld...\n",
1132 what, (long)(s + start_shift - i_strpos)) );
1135 /* Have both, check_string is floating */
1136 if (t + start_shift >= check_at) /* Contradicts floating=check */
1137 goto retry_floating_check;
1138 /* Recheck anchored substring, but not floating... */
1142 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1143 "Looking for anchored substr starting at offset %ld...\n",
1144 (long)(other_last - i_strpos)) );
1145 goto do_other_anchored;
1147 /* Another way we could have checked stclass at the
1148 current position only: */
1153 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1154 "Looking for /%s^%s/m starting at offset %ld...\n",
1155 PL_colors[0], PL_colors[1], (long)(t - i_strpos)) );
1158 if (!(utf8_target ? prog->float_utf8 : prog->float_substr)) /* Could have been deleted */
1160 /* Check is floating substring. */
1161 retry_floating_check:
1162 t = check_at - start_shift;
1163 DEBUG_EXECUTE_r( what = "floating" );
1164 goto hop_and_restart;
1167 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1168 "By STCLASS: moving %ld --> %ld\n",
1169 (long)(t - i_strpos), (long)(s - i_strpos))
1173 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1174 "Does not contradict STCLASS...\n");
1179 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%s%s:%s match at offset %ld\n",
1180 PL_colors[4], (check ? "Guessed" : "Giving up"),
1181 PL_colors[5], (long)(s - i_strpos)) );
1184 fail_finish: /* Substring not found */
1185 if (prog->check_substr || prog->check_utf8) /* could be removed already */
1186 BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
1188 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch rejected by optimizer%s\n",
1189 PL_colors[4], PL_colors[5]));
1193 #define DECL_TRIE_TYPE(scan) \
1194 const enum { trie_plain, trie_utf8, trie_utf8_fold, trie_latin_utf8_fold } \
1195 trie_type = ((scan->flags == EXACT) \
1196 ? (utf8_target ? trie_utf8 : trie_plain) \
1197 : (utf8_target ? trie_utf8_fold : trie_latin_utf8_fold))
1199 #define REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc, uscan, len, \
1200 uvc, charid, foldlen, foldbuf, uniflags) STMT_START { \
1202 switch (trie_type) { \
1203 case trie_utf8_fold: \
1204 if ( foldlen>0 ) { \
1205 uvc = utf8n_to_uvuni( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1210 uvc = to_utf8_fold( (const U8*) uc, foldbuf, &foldlen ); \
1211 len = UTF8SKIP(uc); \
1212 skiplen = UNISKIP( uvc ); \
1213 foldlen -= skiplen; \
1214 uscan = foldbuf + skiplen; \
1217 case trie_latin_utf8_fold: \
1218 if ( foldlen>0 ) { \
1219 uvc = utf8n_to_uvuni( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1225 uvc = _to_fold_latin1( (U8) *uc, foldbuf, &foldlen, 1); \
1226 skiplen = UNISKIP( uvc ); \
1227 foldlen -= skiplen; \
1228 uscan = foldbuf + skiplen; \
1232 uvc = utf8n_to_uvuni( (const U8*) uc, UTF8_MAXLEN, &len, uniflags ); \
1239 charid = trie->charmap[ uvc ]; \
1243 if (widecharmap) { \
1244 SV** const svpp = hv_fetch(widecharmap, \
1245 (char*)&uvc, sizeof(UV), 0); \
1247 charid = (U16)SvIV(*svpp); \
1252 #define REXEC_FBC_EXACTISH_SCAN(CoNd) \
1256 && (ln == 1 || folder(s, pat_string, ln)) \
1257 && (!reginfo || regtry(reginfo, &s)) ) \
1263 #define REXEC_FBC_UTF8_SCAN(CoDe) \
1265 while (s + (uskip = UTF8SKIP(s)) <= strend) { \
1271 #define REXEC_FBC_SCAN(CoDe) \
1273 while (s < strend) { \
1279 #define REXEC_FBC_UTF8_CLASS_SCAN(CoNd) \
1280 REXEC_FBC_UTF8_SCAN( \
1282 if (tmp && (!reginfo || regtry(reginfo, &s))) \
1291 #define REXEC_FBC_CLASS_SCAN(CoNd) \
1294 if (tmp && (!reginfo || regtry(reginfo, &s))) \
1303 #define REXEC_FBC_TRYIT \
1304 if ((!reginfo || regtry(reginfo, &s))) \
1307 #define REXEC_FBC_CSCAN(CoNdUtF8,CoNd) \
1308 if (utf8_target) { \
1309 REXEC_FBC_UTF8_CLASS_SCAN(CoNdUtF8); \
1312 REXEC_FBC_CLASS_SCAN(CoNd); \
1315 #define REXEC_FBC_CSCAN_PRELOAD(UtFpReLoAd,CoNdUtF8,CoNd) \
1316 if (utf8_target) { \
1318 REXEC_FBC_UTF8_CLASS_SCAN(CoNdUtF8); \
1321 REXEC_FBC_CLASS_SCAN(CoNd); \
1324 #define REXEC_FBC_CSCAN_TAINT(CoNdUtF8,CoNd) \
1325 PL_reg_flags |= RF_tainted; \
1326 if (utf8_target) { \
1327 REXEC_FBC_UTF8_CLASS_SCAN(CoNdUtF8); \
1330 REXEC_FBC_CLASS_SCAN(CoNd); \
1333 #define DUMP_EXEC_POS(li,s,doutf8) \
1334 dump_exec_pos(li,s,(PL_regeol),(PL_bostr),(PL_reg_starttry),doutf8)
1337 #define UTF8_NOLOAD(TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1338 tmp = (s != PL_bostr) ? UCHARAT(s - 1) : '\n'; \
1339 tmp = TEST_NON_UTF8(tmp); \
1340 REXEC_FBC_UTF8_SCAN( \
1341 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1350 #define UTF8_LOAD(TeSt1_UtF8, TeSt2_UtF8, IF_SUCCESS, IF_FAIL) \
1351 if (s == PL_bostr) { \
1355 U8 * const r = reghop3((U8*)s, -1, (U8*)PL_bostr); \
1356 tmp = utf8n_to_uvchr(r, UTF8SKIP(r), 0, UTF8_ALLOW_DEFAULT); \
1359 LOAD_UTF8_CHARCLASS_ALNUM(); \
1360 REXEC_FBC_UTF8_SCAN( \
1361 if (tmp == ! (TeSt2_UtF8)) { \
1370 /* The only difference between the BOUND and NBOUND cases is that
1371 * REXEC_FBC_TRYIT is called when matched in BOUND, and when non-matched in
1372 * NBOUND. This is accomplished by passing it in either the if or else clause,
1373 * with the other one being empty */
1374 #define FBC_BOUND(TEST_NON_UTF8, TEST1_UTF8, TEST2_UTF8) \
1375 FBC_BOUND_COMMON(UTF8_LOAD(TEST1_UTF8, TEST2_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1377 #define FBC_BOUND_NOLOAD(TEST_NON_UTF8, TEST1_UTF8, TEST2_UTF8) \
1378 FBC_BOUND_COMMON(UTF8_NOLOAD(TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1380 #define FBC_NBOUND(TEST_NON_UTF8, TEST1_UTF8, TEST2_UTF8) \
1381 FBC_BOUND_COMMON(UTF8_LOAD(TEST1_UTF8, TEST2_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1383 #define FBC_NBOUND_NOLOAD(TEST_NON_UTF8, TEST1_UTF8, TEST2_UTF8) \
1384 FBC_BOUND_COMMON(UTF8_NOLOAD(TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1387 /* Common to the BOUND and NBOUND cases. Unfortunately the UTF8 tests need to
1388 * be passed in completely with the variable name being tested, which isn't
1389 * such a clean interface, but this is easier to read than it was before. We
1390 * are looking for the boundary (or non-boundary between a word and non-word
1391 * character. The utf8 and non-utf8 cases have the same logic, but the details
1392 * must be different. Find the "wordness" of the character just prior to this
1393 * one, and compare it with the wordness of this one. If they differ, we have
1394 * a boundary. At the beginning of the string, pretend that the previous
1395 * character was a new-line */
1396 #define FBC_BOUND_COMMON(UTF8_CODE, TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1397 if (utf8_target) { \
1400 else { /* Not utf8 */ \
1401 tmp = (s != PL_bostr) ? UCHARAT(s - 1) : '\n'; \
1402 tmp = TEST_NON_UTF8(tmp); \
1404 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1413 if ((!prog->minlen && tmp) && (!reginfo || regtry(reginfo, &s))) \
1416 /* We know what class REx starts with. Try to find this position... */
1417 /* if reginfo is NULL, its a dryrun */
1418 /* annoyingly all the vars in this routine have different names from their counterparts
1419 in regmatch. /grrr */
1422 S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
1423 const char *strend, regmatch_info *reginfo)
1426 const I32 doevery = (prog->intflags & PREGf_SKIP) == 0;
1427 char *pat_string; /* The pattern's exactish string */
1428 char *pat_end; /* ptr to end char of pat_string */
1429 re_fold_t folder; /* Function for computing non-utf8 folds */
1430 const U8 *fold_array; /* array for folding ords < 256 */
1437 I32 tmp = 1; /* Scratch variable? */
1438 const bool utf8_target = PL_reg_match_utf8;
1439 UV utf8_fold_flags = 0;
1440 RXi_GET_DECL(prog,progi);
1442 PERL_ARGS_ASSERT_FIND_BYCLASS;
1444 /* We know what class it must start with. */
1448 if (utf8_target || OP(c) == ANYOFV) {
1449 STRLEN inclasslen = strend - s;
1450 REXEC_FBC_UTF8_CLASS_SCAN(
1451 reginclass(prog, c, (U8*)s, &inclasslen, utf8_target));
1454 REXEC_FBC_CLASS_SCAN(REGINCLASS(prog, c, (U8*)s));
1459 if (tmp && (!reginfo || regtry(reginfo, &s)))
1467 if (UTF_PATTERN || utf8_target) {
1468 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
1469 goto do_exactf_utf8;
1471 fold_array = PL_fold_latin1; /* Latin1 folds are not affected by */
1472 folder = foldEQ_latin1; /* /a, except the sharp s one which */
1473 goto do_exactf_non_utf8; /* isn't dealt with by these */
1478 /* regcomp.c already folded this if pattern is in UTF-8 */
1479 utf8_fold_flags = 0;
1480 goto do_exactf_utf8;
1482 fold_array = PL_fold;
1484 goto do_exactf_non_utf8;
1487 if (UTF_PATTERN || utf8_target) {
1488 utf8_fold_flags = FOLDEQ_UTF8_LOCALE;
1489 goto do_exactf_utf8;
1491 fold_array = PL_fold_locale;
1492 folder = foldEQ_locale;
1493 goto do_exactf_non_utf8;
1497 utf8_fold_flags = FOLDEQ_S2_ALREADY_FOLDED;
1499 goto do_exactf_utf8;
1501 case EXACTFU_TRICKYFOLD:
1503 if (UTF_PATTERN || utf8_target) {
1504 utf8_fold_flags = (UTF_PATTERN) ? FOLDEQ_S2_ALREADY_FOLDED : 0;
1505 goto do_exactf_utf8;
1508 /* Any 'ss' in the pattern should have been replaced by regcomp,
1509 * so we don't have to worry here about this single special case
1510 * in the Latin1 range */
1511 fold_array = PL_fold_latin1;
1512 folder = foldEQ_latin1;
1516 do_exactf_non_utf8: /* Neither pattern nor string are UTF8, and there
1517 are no glitches with fold-length differences
1518 between the target string and pattern */
1520 /* The idea in the non-utf8 EXACTF* cases is to first find the
1521 * first character of the EXACTF* node and then, if necessary,
1522 * case-insensitively compare the full text of the node. c1 is the
1523 * first character. c2 is its fold. This logic will not work for
1524 * Unicode semantics and the german sharp ss, which hence should
1525 * not be compiled into a node that gets here. */
1526 pat_string = STRING(c);
1527 ln = STR_LEN(c); /* length to match in octets/bytes */
1529 /* We know that we have to match at least 'ln' bytes (which is the
1530 * same as characters, since not utf8). If we have to match 3
1531 * characters, and there are only 2 availabe, we know without
1532 * trying that it will fail; so don't start a match past the
1533 * required minimum number from the far end */
1534 e = HOP3c(strend, -((I32)ln), s);
1536 if (!reginfo && e < s) {
1537 e = s; /* Due to minlen logic of intuit() */
1541 c2 = fold_array[c1];
1542 if (c1 == c2) { /* If char and fold are the same */
1543 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1);
1546 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1 || *(U8*)s == c2);
1555 /* If one of the operands is in utf8, we can't use the simpler
1556 * folding above, due to the fact that many different characters
1557 * can have the same fold, or portion of a fold, or different-
1559 pat_string = STRING(c);
1560 ln = STR_LEN(c); /* length to match in octets/bytes */
1561 pat_end = pat_string + ln;
1562 lnc = (UTF_PATTERN) /* length to match in characters */
1563 ? utf8_length((U8 *) pat_string, (U8 *) pat_end)
1566 /* We have 'lnc' characters to match in the pattern, but because of
1567 * multi-character folding, each character in the target can match
1568 * up to 3 characters (Unicode guarantees it will never exceed
1569 * this) if it is utf8-encoded; and up to 2 if not (based on the
1570 * fact that the Latin 1 folds are already determined, and the
1571 * only multi-char fold in that range is the sharp-s folding to
1572 * 'ss'. Thus, a pattern character can match as little as 1/3 of a
1573 * string character. Adjust lnc accordingly, rounding up, so that
1574 * if we need to match at least 4+1/3 chars, that really is 5. */
1575 expansion = (utf8_target) ? UTF8_MAX_FOLD_CHAR_EXPAND : 2;
1576 lnc = (lnc + expansion - 1) / expansion;
1578 /* As in the non-UTF8 case, if we have to match 3 characters, and
1579 * only 2 are left, it's guaranteed to fail, so don't start a
1580 * match that would require us to go beyond the end of the string
1582 e = HOP3c(strend, -((I32)lnc), s);
1584 if (!reginfo && e < s) {
1585 e = s; /* Due to minlen logic of intuit() */
1588 /* XXX Note that we could recalculate e to stop the loop earlier,
1589 * as the worst case expansion above will rarely be met, and as we
1590 * go along we would usually find that e moves further to the left.
1591 * This would happen only after we reached the point in the loop
1592 * where if there were no expansion we should fail. Unclear if
1593 * worth the expense */
1596 char *my_strend= (char *)strend;
1597 if (foldEQ_utf8_flags(s, &my_strend, 0, utf8_target,
1598 pat_string, NULL, ln, cBOOL(UTF_PATTERN), utf8_fold_flags)
1599 && (!reginfo || regtry(reginfo, &s)) )
1603 s += (utf8_target) ? UTF8SKIP(s) : 1;
1608 PL_reg_flags |= RF_tainted;
1609 FBC_BOUND(isALNUM_LC,
1610 isALNUM_LC_uvchr(UNI_TO_NATIVE(tmp)),
1611 isALNUM_LC_utf8((U8*)s));
1614 PL_reg_flags |= RF_tainted;
1615 FBC_NBOUND(isALNUM_LC,
1616 isALNUM_LC_uvchr(UNI_TO_NATIVE(tmp)),
1617 isALNUM_LC_utf8((U8*)s));
1620 FBC_BOUND(isWORDCHAR,
1622 cBOOL(swash_fetch(PL_utf8_alnum, (U8*)s, utf8_target)));
1625 FBC_BOUND_NOLOAD(isWORDCHAR_A,
1627 isWORDCHAR_A((U8*)s));
1630 FBC_NBOUND(isWORDCHAR,
1632 cBOOL(swash_fetch(PL_utf8_alnum, (U8*)s, utf8_target)));
1635 FBC_NBOUND_NOLOAD(isWORDCHAR_A,
1637 isWORDCHAR_A((U8*)s));
1640 FBC_BOUND(isWORDCHAR_L1,
1642 cBOOL(swash_fetch(PL_utf8_alnum, (U8*)s, utf8_target)));
1645 FBC_NBOUND(isWORDCHAR_L1,
1647 cBOOL(swash_fetch(PL_utf8_alnum, (U8*)s, utf8_target)));
1650 REXEC_FBC_CSCAN_TAINT(
1651 isALNUM_LC_utf8((U8*)s),
1656 REXEC_FBC_CSCAN_PRELOAD(
1657 LOAD_UTF8_CHARCLASS_ALNUM(),
1658 swash_fetch(PL_utf8_alnum,(U8*)s, utf8_target),
1659 isWORDCHAR_L1((U8) *s)
1663 REXEC_FBC_CSCAN_PRELOAD(
1664 LOAD_UTF8_CHARCLASS_ALNUM(),
1665 swash_fetch(PL_utf8_alnum,(U8*)s, utf8_target),
1670 /* Don't need to worry about utf8, as it can match only a single
1671 * byte invariant character */
1672 REXEC_FBC_CLASS_SCAN( isWORDCHAR_A(*s));
1675 REXEC_FBC_CSCAN_PRELOAD(
1676 LOAD_UTF8_CHARCLASS_ALNUM(),
1677 !swash_fetch(PL_utf8_alnum,(U8*)s, utf8_target),
1678 ! isWORDCHAR_L1((U8) *s)
1682 REXEC_FBC_CSCAN_PRELOAD(
1683 LOAD_UTF8_CHARCLASS_ALNUM(),
1684 !swash_fetch(PL_utf8_alnum, (U8*)s, utf8_target),
1695 REXEC_FBC_CSCAN_TAINT(
1696 !isALNUM_LC_utf8((U8*)s),
1701 REXEC_FBC_CSCAN_PRELOAD(
1702 LOAD_UTF8_CHARCLASS_SPACE(),
1703 *s == ' ' || swash_fetch(PL_utf8_space,(U8*)s, utf8_target),
1708 REXEC_FBC_CSCAN_PRELOAD(
1709 LOAD_UTF8_CHARCLASS_SPACE(),
1710 *s == ' ' || swash_fetch(PL_utf8_space,(U8*)s, utf8_target),
1715 /* Don't need to worry about utf8, as it can match only a single
1716 * byte invariant character */
1717 REXEC_FBC_CLASS_SCAN( isSPACE_A(*s));
1720 REXEC_FBC_CSCAN_TAINT(
1721 isSPACE_LC_utf8((U8*)s),
1726 REXEC_FBC_CSCAN_PRELOAD(
1727 LOAD_UTF8_CHARCLASS_SPACE(),
1728 !( *s == ' ' || swash_fetch(PL_utf8_space,(U8*)s, utf8_target)),
1729 ! isSPACE_L1((U8) *s)
1733 REXEC_FBC_CSCAN_PRELOAD(
1734 LOAD_UTF8_CHARCLASS_SPACE(),
1735 !(*s == ' ' || swash_fetch(PL_utf8_space,(U8*)s, utf8_target)),
1746 REXEC_FBC_CSCAN_TAINT(
1747 !isSPACE_LC_utf8((U8*)s),
1752 REXEC_FBC_CSCAN_PRELOAD(
1753 LOAD_UTF8_CHARCLASS_DIGIT(),
1754 swash_fetch(PL_utf8_digit,(U8*)s, utf8_target),
1759 /* Don't need to worry about utf8, as it can match only a single
1760 * byte invariant character */
1761 REXEC_FBC_CLASS_SCAN( isDIGIT_A(*s));
1764 REXEC_FBC_CSCAN_TAINT(
1765 isDIGIT_LC_utf8((U8*)s),
1770 REXEC_FBC_CSCAN_PRELOAD(
1771 LOAD_UTF8_CHARCLASS_DIGIT(),
1772 !swash_fetch(PL_utf8_digit,(U8*)s, utf8_target),
1783 REXEC_FBC_CSCAN_TAINT(
1784 !isDIGIT_LC_utf8((U8*)s),
1791 is_LNBREAK_latin1(s)
1803 !is_VERTWS_latin1(s)
1809 is_HORIZWS_latin1(s)
1814 !is_HORIZWS_utf8(s),
1815 !is_HORIZWS_latin1(s)
1819 /* Don't need to worry about utf8, as it can match only a single
1820 * byte invariant character. The flag in this node type is the
1821 * class number to pass to _generic_isCC() to build a mask for
1822 * searching in PL_charclass[] */
1823 REXEC_FBC_CLASS_SCAN( _generic_isCC_A(*s, FLAGS(c)));
1827 !_generic_isCC_A(*s, FLAGS(c)),
1828 !_generic_isCC_A(*s, FLAGS(c))
1836 /* what trie are we using right now */
1838 = (reg_ac_data*)progi->data->data[ ARG( c ) ];
1840 = (reg_trie_data*)progi->data->data[ aho->trie ];
1841 HV *widecharmap = MUTABLE_HV(progi->data->data[ aho->trie + 1 ]);
1843 const char *last_start = strend - trie->minlen;
1845 const char *real_start = s;
1847 STRLEN maxlen = trie->maxlen;
1849 U8 **points; /* map of where we were in the input string
1850 when reading a given char. For ASCII this
1851 is unnecessary overhead as the relationship
1852 is always 1:1, but for Unicode, especially
1853 case folded Unicode this is not true. */
1854 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1858 GET_RE_DEBUG_FLAGS_DECL;
1860 /* We can't just allocate points here. We need to wrap it in
1861 * an SV so it gets freed properly if there is a croak while
1862 * running the match */
1865 sv_points=newSV(maxlen * sizeof(U8 *));
1866 SvCUR_set(sv_points,
1867 maxlen * sizeof(U8 *));
1868 SvPOK_on(sv_points);
1869 sv_2mortal(sv_points);
1870 points=(U8**)SvPV_nolen(sv_points );
1871 if ( trie_type != trie_utf8_fold
1872 && (trie->bitmap || OP(c)==AHOCORASICKC) )
1875 bitmap=(U8*)trie->bitmap;
1877 bitmap=(U8*)ANYOF_BITMAP(c);
1879 /* this is the Aho-Corasick algorithm modified a touch
1880 to include special handling for long "unknown char"
1881 sequences. The basic idea being that we use AC as long
1882 as we are dealing with a possible matching char, when
1883 we encounter an unknown char (and we have not encountered
1884 an accepting state) we scan forward until we find a legal
1886 AC matching is basically that of trie matching, except
1887 that when we encounter a failing transition, we fall back
1888 to the current states "fail state", and try the current char
1889 again, a process we repeat until we reach the root state,
1890 state 1, or a legal transition. If we fail on the root state
1891 then we can either terminate if we have reached an accepting
1892 state previously, or restart the entire process from the beginning
1896 while (s <= last_start) {
1897 const U32 uniflags = UTF8_ALLOW_DEFAULT;
1905 U8 *uscan = (U8*)NULL;
1906 U8 *leftmost = NULL;
1908 U32 accepted_word= 0;
1912 while ( state && uc <= (U8*)strend ) {
1914 U32 word = aho->states[ state ].wordnum;
1918 DEBUG_TRIE_EXECUTE_r(
1919 if ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
1920 dump_exec_pos( (char *)uc, c, strend, real_start,
1921 (char *)uc, utf8_target );
1922 PerlIO_printf( Perl_debug_log,
1923 " Scanning for legal start char...\n");
1927 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
1931 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
1937 if (uc >(U8*)last_start) break;
1941 U8 *lpos= points[ (pointpos - trie->wordinfo[word].len) % maxlen ];
1942 if (!leftmost || lpos < leftmost) {
1943 DEBUG_r(accepted_word=word);
1949 points[pointpos++ % maxlen]= uc;
1950 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
1951 uscan, len, uvc, charid, foldlen,
1953 DEBUG_TRIE_EXECUTE_r({
1954 dump_exec_pos( (char *)uc, c, strend, real_start,
1956 PerlIO_printf(Perl_debug_log,
1957 " Charid:%3u CP:%4"UVxf" ",
1963 word = aho->states[ state ].wordnum;
1965 base = aho->states[ state ].trans.base;
1967 DEBUG_TRIE_EXECUTE_r({
1969 dump_exec_pos( (char *)uc, c, strend, real_start,
1971 PerlIO_printf( Perl_debug_log,
1972 "%sState: %4"UVxf", word=%"UVxf,
1973 failed ? " Fail transition to " : "",
1974 (UV)state, (UV)word);
1980 ( ((offset = base + charid
1981 - 1 - trie->uniquecharcount)) >= 0)
1982 && ((U32)offset < trie->lasttrans)
1983 && trie->trans[offset].check == state
1984 && (tmp=trie->trans[offset].next))
1986 DEBUG_TRIE_EXECUTE_r(
1987 PerlIO_printf( Perl_debug_log," - legal\n"));
1992 DEBUG_TRIE_EXECUTE_r(
1993 PerlIO_printf( Perl_debug_log," - fail\n"));
1995 state = aho->fail[state];
1999 /* we must be accepting here */
2000 DEBUG_TRIE_EXECUTE_r(
2001 PerlIO_printf( Perl_debug_log," - accepting\n"));
2010 if (!state) state = 1;
2013 if ( aho->states[ state ].wordnum ) {
2014 U8 *lpos = points[ (pointpos - trie->wordinfo[aho->states[ state ].wordnum].len) % maxlen ];
2015 if (!leftmost || lpos < leftmost) {
2016 DEBUG_r(accepted_word=aho->states[ state ].wordnum);
2021 s = (char*)leftmost;
2022 DEBUG_TRIE_EXECUTE_r({
2024 Perl_debug_log,"Matches word #%"UVxf" at position %"IVdf". Trying full pattern...\n",
2025 (UV)accepted_word, (IV)(s - real_start)
2028 if (!reginfo || regtry(reginfo, &s)) {
2034 DEBUG_TRIE_EXECUTE_r({
2035 PerlIO_printf( Perl_debug_log,"Pattern failed. Looking for new start point...\n");
2038 DEBUG_TRIE_EXECUTE_r(
2039 PerlIO_printf( Perl_debug_log,"No match.\n"));
2048 Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
2058 - regexec_flags - match a regexp against a string
2061 Perl_regexec_flags(pTHX_ REGEXP * const rx, char *stringarg, register char *strend,
2062 char *strbeg, I32 minend, SV *sv, void *data, U32 flags)
2063 /* strend: pointer to null at end of string */
2064 /* strbeg: real beginning of string */
2065 /* minend: end of match must be >=minend after stringarg. */
2066 /* data: May be used for some additional optimizations.
2067 Currently its only used, with a U32 cast, for transmitting
2068 the ganch offset when doing a /g match. This will change */
2069 /* nosave: For optimizations. */
2072 struct regexp *const prog = (struct regexp *)SvANY(rx);
2073 /*register*/ char *s;
2075 /*register*/ char *startpos = stringarg;
2076 I32 minlen; /* must match at least this many chars */
2077 I32 dontbother = 0; /* how many characters not to try at end */
2078 I32 end_shift = 0; /* Same for the end. */ /* CC */
2079 I32 scream_pos = -1; /* Internal iterator of scream. */
2080 char *scream_olds = NULL;
2081 const bool utf8_target = cBOOL(DO_UTF8(sv));
2083 RXi_GET_DECL(prog,progi);
2084 regmatch_info reginfo; /* create some info to pass to regtry etc */
2085 regexp_paren_pair *swap = NULL;
2086 GET_RE_DEBUG_FLAGS_DECL;
2088 PERL_ARGS_ASSERT_REGEXEC_FLAGS;
2089 PERL_UNUSED_ARG(data);
2091 /* Be paranoid... */
2092 if (prog == NULL || startpos == NULL) {
2093 Perl_croak(aTHX_ "NULL regexp parameter");
2097 multiline = prog->extflags & RXf_PMf_MULTILINE;
2098 reginfo.prog = rx; /* Yes, sorry that this is confusing. */
2100 RX_MATCH_UTF8_set(rx, utf8_target);
2102 debug_start_match(rx, utf8_target, startpos, strend,
2106 minlen = prog->minlen;
2108 if (strend - startpos < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
2109 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
2110 "String too short [regexec_flags]...\n"));
2115 /* Check validity of program. */
2116 if (UCHARAT(progi->program) != REG_MAGIC) {
2117 Perl_croak(aTHX_ "corrupted regexp program");
2121 PL_reg_state.re_state_eval_setup_done = FALSE;
2125 PL_reg_flags |= RF_utf8;
2127 /* Mark beginning of line for ^ and lookbehind. */
2128 reginfo.bol = startpos; /* XXX not used ??? */
2132 /* Mark end of line for $ (and such) */
2135 /* see how far we have to get to not match where we matched before */
2136 reginfo.till = startpos+minend;
2138 /* If there is a "must appear" string, look for it. */
2141 if (prog->extflags & RXf_GPOS_SEEN) { /* Need to set reginfo->ganch */
2143 if (flags & REXEC_IGNOREPOS){ /* Means: check only at start */
2144 reginfo.ganch = startpos + prog->gofs;
2145 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
2146 "GPOS IGNOREPOS: reginfo.ganch = startpos + %"UVxf"\n",(UV)prog->gofs));
2147 } else if (sv && SvTYPE(sv) >= SVt_PVMG
2149 && (mg = mg_find(sv, PERL_MAGIC_regex_global))
2150 && mg->mg_len >= 0) {
2151 reginfo.ganch = strbeg + mg->mg_len; /* Defined pos() */
2152 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
2153 "GPOS MAGIC: reginfo.ganch = strbeg + %"IVdf"\n",(IV)mg->mg_len));
2155 if (prog->extflags & RXf_ANCH_GPOS) {
2156 if (s > reginfo.ganch)
2158 s = reginfo.ganch - prog->gofs;
2159 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
2160 "GPOS ANCH_GPOS: s = ganch - %"UVxf"\n",(UV)prog->gofs));
2166 reginfo.ganch = strbeg + PTR2UV(data);
2167 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
2168 "GPOS DATA: reginfo.ganch= strbeg + %"UVxf"\n",PTR2UV(data)));
2170 } else { /* pos() not defined */
2171 reginfo.ganch = strbeg;
2172 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
2173 "GPOS: reginfo.ganch = strbeg\n"));
2176 if (PL_curpm && (PM_GETRE(PL_curpm) == rx)) {
2177 /* We have to be careful. If the previous successful match
2178 was from this regex we don't want a subsequent partially
2179 successful match to clobber the old results.
2180 So when we detect this possibility we add a swap buffer
2181 to the re, and switch the buffer each match. If we fail
2182 we switch it back, otherwise we leave it swapped.
2185 /* do we need a save destructor here for eval dies? */
2186 Newxz(prog->offs, (prog->nparens + 1), regexp_paren_pair);
2187 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
2188 "rex=0x%"UVxf" saving offs: orig=0x%"UVxf" new=0x%"UVxf"\n",
2194 if (!(flags & REXEC_CHECKED) && (prog->check_substr != NULL || prog->check_utf8 != NULL)) {
2195 re_scream_pos_data d;
2197 d.scream_olds = &scream_olds;
2198 d.scream_pos = &scream_pos;
2199 s = re_intuit_start(rx, sv, s, strend, flags, &d);
2201 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Not present...\n"));
2202 goto phooey; /* not present */
2208 /* Simplest case: anchored match need be tried only once. */
2209 /* [unless only anchor is BOL and multiline is set] */
2210 if (prog->extflags & (RXf_ANCH & ~RXf_ANCH_GPOS)) {
2211 if (s == startpos && regtry(®info, &startpos))
2213 else if (multiline || (prog->intflags & PREGf_IMPLICIT)
2214 || (prog->extflags & RXf_ANCH_MBOL)) /* XXXX SBOL? */
2219 dontbother = minlen - 1;
2220 end = HOP3c(strend, -dontbother, strbeg) - 1;
2221 /* for multiline we only have to try after newlines */
2222 if (prog->check_substr || prog->check_utf8) {
2223 /* because of the goto we can not easily reuse the macros for bifurcating the
2224 unicode/non-unicode match modes here like we do elsewhere - demerphq */
2227 goto after_try_utf8;
2229 if (regtry(®info, &s)) {
2236 if (prog->extflags & RXf_USE_INTUIT) {
2237 s = re_intuit_start(rx, sv, s + UTF8SKIP(s), strend, flags, NULL);
2246 } /* end search for check string in unicode */
2248 if (s == startpos) {
2249 goto after_try_latin;
2252 if (regtry(®info, &s)) {
2259 if (prog->extflags & RXf_USE_INTUIT) {
2260 s = re_intuit_start(rx, sv, s + 1, strend, flags, NULL);
2269 } /* end search for check string in latin*/
2270 } /* end search for check string */
2271 else { /* search for newline */
2273 /*XXX: The s-- is almost definitely wrong here under unicode - demeprhq*/
2276 /* We can use a more efficient search as newlines are the same in unicode as they are in latin */
2277 while (s <= end) { /* note it could be possible to match at the end of the string */
2278 if (*s++ == '\n') { /* don't need PL_utf8skip here */
2279 if (regtry(®info, &s))
2283 } /* end search for newline */
2284 } /* end anchored/multiline check string search */
2286 } else if (RXf_GPOS_CHECK == (prog->extflags & RXf_GPOS_CHECK))
2288 /* the warning about reginfo.ganch being used without initialization
2289 is bogus -- we set it above, when prog->extflags & RXf_GPOS_SEEN
2290 and we only enter this block when the same bit is set. */
2291 char *tmp_s = reginfo.ganch - prog->gofs;
2293 if (tmp_s >= strbeg && regtry(®info, &tmp_s))
2298 /* Messy cases: unanchored match. */
2299 if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
2300 /* we have /x+whatever/ */
2301 /* it must be a one character string (XXXX Except UTF_PATTERN?) */
2306 if (!(utf8_target ? prog->anchored_utf8 : prog->anchored_substr))
2307 utf8_target ? to_utf8_substr(prog) : to_byte_substr(prog);
2308 ch = SvPVX_const(utf8_target ? prog->anchored_utf8 : prog->anchored_substr)[0];
2313 DEBUG_EXECUTE_r( did_match = 1 );
2314 if (regtry(®info, &s)) goto got_it;
2316 while (s < strend && *s == ch)
2324 DEBUG_EXECUTE_r( did_match = 1 );
2325 if (regtry(®info, &s)) goto got_it;
2327 while (s < strend && *s == ch)
2332 DEBUG_EXECUTE_r(if (!did_match)
2333 PerlIO_printf(Perl_debug_log,
2334 "Did not find anchored character...\n")
2337 else if (prog->anchored_substr != NULL
2338 || prog->anchored_utf8 != NULL
2339 || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
2340 && prog->float_max_offset < strend - s)) {
2345 char *last1; /* Last position checked before */
2349 if (prog->anchored_substr || prog->anchored_utf8) {
2350 if (!(utf8_target ? prog->anchored_utf8 : prog->anchored_substr))
2351 utf8_target ? to_utf8_substr(prog) : to_byte_substr(prog);
2352 must = utf8_target ? prog->anchored_utf8 : prog->anchored_substr;
2353 back_max = back_min = prog->anchored_offset;
2355 if (!(utf8_target ? prog->float_utf8 : prog->float_substr))
2356 utf8_target ? to_utf8_substr(prog) : to_byte_substr(prog);
2357 must = utf8_target ? prog->float_utf8 : prog->float_substr;
2358 back_max = prog->float_max_offset;
2359 back_min = prog->float_min_offset;
2363 if (must == &PL_sv_undef)
2364 /* could not downgrade utf8 check substring, so must fail */
2370 last = HOP3c(strend, /* Cannot start after this */
2371 -(I32)(CHR_SVLEN(must)
2372 - (SvTAIL(must) != 0) + back_min), strbeg);
2375 last1 = HOPc(s, -1);
2377 last1 = s - 1; /* bogus */
2379 /* XXXX check_substr already used to find "s", can optimize if
2380 check_substr==must. */
2382 dontbother = end_shift;
2383 strend = HOPc(strend, -dontbother);
2384 while ( (s <= last) &&
2385 (s = fbm_instr((unsigned char*)HOP3(s, back_min, (back_min<0 ? strbeg : strend)),
2386 (unsigned char*)strend, must,
2387 multiline ? FBMrf_MULTILINE : 0)) ) {
2388 DEBUG_EXECUTE_r( did_match = 1 );
2389 if (HOPc(s, -back_max) > last1) {
2390 last1 = HOPc(s, -back_min);
2391 s = HOPc(s, -back_max);
2394 char * const t = (last1 >= PL_bostr) ? HOPc(last1, 1) : last1 + 1;
2396 last1 = HOPc(s, -back_min);
2400 while (s <= last1) {
2401 if (regtry(®info, &s))
2407 while (s <= last1) {
2408 if (regtry(®info, &s))
2414 DEBUG_EXECUTE_r(if (!did_match) {
2415 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
2416 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
2417 PerlIO_printf(Perl_debug_log, "Did not find %s substr %s%s...\n",
2418 ((must == prog->anchored_substr || must == prog->anchored_utf8)
2419 ? "anchored" : "floating"),
2420 quoted, RE_SV_TAIL(must));
2424 else if ( (c = progi->regstclass) ) {
2426 const OPCODE op = OP(progi->regstclass);
2427 /* don't bother with what can't match */
2428 if (PL_regkind[op] != EXACT && op != CANY && PL_regkind[op] != TRIE)
2429 strend = HOPc(strend, -(minlen - 1));
2432 SV * const prop = sv_newmortal();
2433 regprop(prog, prop, c);
2435 RE_PV_QUOTED_DECL(quoted,utf8_target,PERL_DEBUG_PAD_ZERO(1),
2437 PerlIO_printf(Perl_debug_log,
2438 "Matching stclass %.*s against %s (%d bytes)\n",
2439 (int)SvCUR(prop), SvPVX_const(prop),
2440 quoted, (int)(strend - s));
2443 if (find_byclass(prog, c, s, strend, ®info))
2445 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Contradicts stclass... [regexec_flags]\n"));
2449 if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
2456 if (!(utf8_target ? prog->float_utf8 : prog->float_substr))
2457 utf8_target ? to_utf8_substr(prog) : to_byte_substr(prog);
2458 float_real = utf8_target ? prog->float_utf8 : prog->float_substr;
2460 little = SvPV_const(float_real, len);
2461 if (SvTAIL(float_real)) {
2462 /* This means that float_real contains an artificial \n on the end
2463 * due to the presence of something like this: /foo$/
2464 * where we can match both "foo" and "foo\n" at the end of the string.
2465 * So we have to compare the end of the string first against the float_real
2466 * without the \n and then against the full float_real with the string.
2467 * We have to watch out for cases where the string might be smaller
2468 * than the float_real or the float_real without the \n.
2470 char *checkpos= strend - len;
2472 PerlIO_printf(Perl_debug_log,
2473 "%sChecking for float_real.%s\n",
2474 PL_colors[4], PL_colors[5]));
2475 if (checkpos + 1 < strbeg) {
2476 /* can't match, even if we remove the trailing \n string is too short to match */
2478 PerlIO_printf(Perl_debug_log,
2479 "%sString shorter than required trailing substring, cannot match.%s\n",
2480 PL_colors[4], PL_colors[5]));
2482 } else if (memEQ(checkpos + 1, little, len - 1)) {
2483 /* can match, the end of the string matches without the "\n" */
2484 last = checkpos + 1;
2485 } else if (checkpos < strbeg) {
2486 /* cant match, string is too short when the "\n" is included */
2488 PerlIO_printf(Perl_debug_log,
2489 "%sString does not contain required trailing substring, cannot match.%s\n",
2490 PL_colors[4], PL_colors[5]));
2492 } else if (!multiline) {
2493 /* non multiline match, so compare with the "\n" at the end of the string */
2494 if (memEQ(checkpos, little, len)) {
2498 PerlIO_printf(Perl_debug_log,
2499 "%sString does not contain required trailing substring, cannot match.%s\n",
2500 PL_colors[4], PL_colors[5]));
2504 /* multiline match, so we have to search for a place where the full string is located */
2510 last = rninstr(s, strend, little, little + len);
2512 last = strend; /* matching "$" */
2515 /* at one point this block contained a comment which was probably
2516 * incorrect, which said that this was a "should not happen" case.
2517 * Even if it was true when it was written I am pretty sure it is
2518 * not anymore, so I have removed the comment and replaced it with
2521 PerlIO_printf(Perl_debug_log,
2522 "String does not contain required substring, cannot match.\n"
2526 dontbother = strend - last + prog->float_min_offset;
2528 if (minlen && (dontbother < minlen))
2529 dontbother = minlen - 1;
2530 strend -= dontbother; /* this one's always in bytes! */
2531 /* We don't know much -- general case. */
2534 if (regtry(®info, &s))
2543 if (regtry(®info, &s))
2545 } while (s++ < strend);
2555 PerlIO_printf(Perl_debug_log,
2556 "rex=0x%"UVxf" freeing offs: 0x%"UVxf"\n",
2562 RX_MATCH_TAINTED_set(rx, PL_reg_flags & RF_tainted);
2564 if (PL_reg_state.re_state_eval_setup_done)
2565 restore_pos(aTHX_ prog);
2566 if (RXp_PAREN_NAMES(prog))
2567 (void)hv_iterinit(RXp_PAREN_NAMES(prog));
2569 /* make sure $`, $&, $', and $digit will work later */
2570 if ( !(flags & REXEC_NOT_FIRST) ) {
2571 RX_MATCH_COPY_FREE(rx);
2572 if (flags & REXEC_COPY_STR) {
2573 const I32 i = PL_regeol - startpos + (stringarg - strbeg);
2574 #ifdef PERL_OLD_COPY_ON_WRITE
2576 || (SvFLAGS(sv) & CAN_COW_MASK) == CAN_COW_FLAGS)) {
2578 PerlIO_printf(Perl_debug_log,
2579 "Copy on write: regexp capture, type %d\n",
2582 prog->saved_copy = sv_setsv_cow(prog->saved_copy, sv);
2583 prog->subbeg = (char *)SvPVX_const(prog->saved_copy);
2584 assert (SvPOKp(prog->saved_copy));
2588 RX_MATCH_COPIED_on(rx);
2589 s = savepvn(strbeg, i);
2595 prog->subbeg = strbeg;
2596 prog->sublen = PL_regeol - strbeg; /* strend may have been modified */
2603 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch failed%s\n",
2604 PL_colors[4], PL_colors[5]));
2605 if (PL_reg_state.re_state_eval_setup_done)
2606 restore_pos(aTHX_ prog);
2608 /* we failed :-( roll it back */
2609 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
2610 "rex=0x%"UVxf" rolling back offs: freeing=0x%"UVxf" restoring=0x%"UVxf"\n",
2615 Safefree(prog->offs);
2623 /* Set which rex is pointed to by PL_reg_state, handling ref counting.
2624 * Do inc before dec, in case old and new rex are the same */
2625 #define SET_reg_curpm(Re2) \
2626 if (PL_reg_state.re_state_eval_setup_done) { \
2627 (void)ReREFCNT_inc(Re2); \
2628 ReREFCNT_dec(PM_GETRE(PL_reg_curpm)); \
2629 PM_SETRE((PL_reg_curpm), (Re2)); \
2634 - regtry - try match at specific point
2636 STATIC I32 /* 0 failure, 1 success */
2637 S_regtry(pTHX_ regmatch_info *reginfo, char **startpos)
2641 REGEXP *const rx = reginfo->prog;
2642 regexp *const prog = (struct regexp *)SvANY(rx);
2643 RXi_GET_DECL(prog,progi);
2644 GET_RE_DEBUG_FLAGS_DECL;
2646 PERL_ARGS_ASSERT_REGTRY;
2648 reginfo->cutpoint=NULL;
2650 if ((prog->extflags & RXf_EVAL_SEEN)
2651 && !PL_reg_state.re_state_eval_setup_done)
2655 PL_reg_state.re_state_eval_setup_done = TRUE;
2657 /* Make $_ available to executed code. */
2658 if (reginfo->sv != DEFSV) {
2660 DEFSV_set(reginfo->sv);
2663 if (!(SvTYPE(reginfo->sv) >= SVt_PVMG && SvMAGIC(reginfo->sv)
2664 && (mg = mg_find(reginfo->sv, PERL_MAGIC_regex_global)))) {
2665 /* prepare for quick setting of pos */
2666 #ifdef PERL_OLD_COPY_ON_WRITE
2667 if (SvIsCOW(reginfo->sv))
2668 sv_force_normal_flags(reginfo->sv, 0);
2670 mg = sv_magicext(reginfo->sv, NULL, PERL_MAGIC_regex_global,
2671 &PL_vtbl_mglob, NULL, 0);
2675 PL_reg_oldpos = mg->mg_len;
2676 SAVEDESTRUCTOR_X(restore_pos, prog);
2678 if (!PL_reg_curpm) {
2679 Newxz(PL_reg_curpm, 1, PMOP);
2682 SV* const repointer = &PL_sv_undef;
2683 /* this regexp is also owned by the new PL_reg_curpm, which
2684 will try to free it. */
2685 av_push(PL_regex_padav, repointer);
2686 PL_reg_curpm->op_pmoffset = av_len(PL_regex_padav);
2687 PL_regex_pad = AvARRAY(PL_regex_padav);
2692 PL_reg_oldcurpm = PL_curpm;
2693 PL_curpm = PL_reg_curpm;
2694 if (RXp_MATCH_COPIED(prog)) {
2695 /* Here is a serious problem: we cannot rewrite subbeg,
2696 since it may be needed if this match fails. Thus
2697 $` inside (?{}) could fail... */
2698 PL_reg_oldsaved = prog->subbeg;
2699 PL_reg_oldsavedlen = prog->sublen;
2700 #ifdef PERL_OLD_COPY_ON_WRITE
2701 PL_nrs = prog->saved_copy;
2703 RXp_MATCH_COPIED_off(prog);
2706 PL_reg_oldsaved = NULL;
2707 prog->subbeg = PL_bostr;
2708 prog->sublen = PL_regeol - PL_bostr; /* strend may have been modified */
2711 PL_reg_starttry = *startpos;
2713 prog->offs[0].start = *startpos - PL_bostr;
2714 PL_reginput = *startpos;
2715 prog->lastparen = 0;
2716 prog->lastcloseparen = 0;
2719 /* XXXX What this code is doing here?!!! There should be no need
2720 to do this again and again, prog->lastparen should take care of
2723 /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
2724 * Actually, the code in regcppop() (which Ilya may be meaning by
2725 * prog->lastparen), is not needed at all by the test suite
2726 * (op/regexp, op/pat, op/split), but that code is needed otherwise
2727 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
2728 * Meanwhile, this code *is* needed for the
2729 * above-mentioned test suite tests to succeed. The common theme
2730 * on those tests seems to be returning null fields from matches.
2731 * --jhi updated by dapm */
2733 if (prog->nparens) {
2734 regexp_paren_pair *pp = prog->offs;
2736 for (i = prog->nparens; i > (I32)prog->lastparen; i--) {
2744 if (regmatch(reginfo, progi->program + 1)) {
2745 prog->offs[0].end = PL_reginput - PL_bostr;
2748 if (reginfo->cutpoint)
2749 *startpos= reginfo->cutpoint;
2750 REGCP_UNWIND(lastcp);
2755 #define sayYES goto yes
2756 #define sayNO goto no
2757 #define sayNO_SILENT goto no_silent
2759 /* we dont use STMT_START/END here because it leads to
2760 "unreachable code" warnings, which are bogus, but distracting. */
2761 #define CACHEsayNO \
2762 if (ST.cache_mask) \
2763 PL_reg_poscache[ST.cache_offset] |= ST.cache_mask; \
2766 /* this is used to determine how far from the left messages like
2767 'failed...' are printed. It should be set such that messages
2768 are inline with the regop output that created them.
2770 #define REPORT_CODE_OFF 32
2773 #define CHRTEST_UNINIT -1001 /* c1/c2 haven't been calculated yet */
2774 #define CHRTEST_VOID -1000 /* the c1/c2 "next char" test should be skipped */
2776 #define SLAB_FIRST(s) (&(s)->states[0])
2777 #define SLAB_LAST(s) (&(s)->states[PERL_REGMATCH_SLAB_SLOTS-1])
2779 /* grab a new slab and return the first slot in it */
2781 STATIC regmatch_state *
2784 #if PERL_VERSION < 9 && !defined(PERL_CORE)
2787 regmatch_slab *s = PL_regmatch_slab->next;
2789 Newx(s, 1, regmatch_slab);
2790 s->prev = PL_regmatch_slab;
2792 PL_regmatch_slab->next = s;
2794 PL_regmatch_slab = s;
2795 return SLAB_FIRST(s);
2799 /* push a new state then goto it */
2801 #define PUSH_STATE_GOTO(state, node) \
2803 st->resume_state = state; \
2806 /* push a new state with success backtracking, then goto it */
2808 #define PUSH_YES_STATE_GOTO(state, node) \
2810 st->resume_state = state; \
2811 goto push_yes_state;
2817 regmatch() - main matching routine
2819 This is basically one big switch statement in a loop. We execute an op,
2820 set 'next' to point the next op, and continue. If we come to a point which
2821 we may need to backtrack to on failure such as (A|B|C), we push a
2822 backtrack state onto the backtrack stack. On failure, we pop the top
2823 state, and re-enter the loop at the state indicated. If there are no more
2824 states to pop, we return failure.
2826 Sometimes we also need to backtrack on success; for example /A+/, where
2827 after successfully matching one A, we need to go back and try to
2828 match another one; similarly for lookahead assertions: if the assertion
2829 completes successfully, we backtrack to the state just before the assertion
2830 and then carry on. In these cases, the pushed state is marked as
2831 'backtrack on success too'. This marking is in fact done by a chain of
2832 pointers, each pointing to the previous 'yes' state. On success, we pop to
2833 the nearest yes state, discarding any intermediate failure-only states.
2834 Sometimes a yes state is pushed just to force some cleanup code to be
2835 called at the end of a successful match or submatch; e.g. (??{$re}) uses
2836 it to free the inner regex.
2838 Note that failure backtracking rewinds the cursor position, while
2839 success backtracking leaves it alone.
2841 A pattern is complete when the END op is executed, while a subpattern
2842 such as (?=foo) is complete when the SUCCESS op is executed. Both of these
2843 ops trigger the "pop to last yes state if any, otherwise return true"
2846 A common convention in this function is to use A and B to refer to the two
2847 subpatterns (or to the first nodes thereof) in patterns like /A*B/: so A is
2848 the subpattern to be matched possibly multiple times, while B is the entire
2849 rest of the pattern. Variable and state names reflect this convention.
2851 The states in the main switch are the union of ops and failure/success of
2852 substates associated with with that op. For example, IFMATCH is the op
2853 that does lookahead assertions /(?=A)B/ and so the IFMATCH state means
2854 'execute IFMATCH'; while IFMATCH_A is a state saying that we have just
2855 successfully matched A and IFMATCH_A_fail is a state saying that we have
2856 just failed to match A. Resume states always come in pairs. The backtrack
2857 state we push is marked as 'IFMATCH_A', but when that is popped, we resume
2858 at IFMATCH_A or IFMATCH_A_fail, depending on whether we are backtracking
2859 on success or failure.
2861 The struct that holds a backtracking state is actually a big union, with
2862 one variant for each major type of op. The variable st points to the
2863 top-most backtrack struct. To make the code clearer, within each
2864 block of code we #define ST to alias the relevant union.
2866 Here's a concrete example of a (vastly oversimplified) IFMATCH
2872 #define ST st->u.ifmatch
2874 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
2875 ST.foo = ...; // some state we wish to save
2877 // push a yes backtrack state with a resume value of
2878 // IFMATCH_A/IFMATCH_A_fail, then continue execution at the
2880 PUSH_YES_STATE_GOTO(IFMATCH_A, A);
2883 case IFMATCH_A: // we have successfully executed A; now continue with B
2885 bar = ST.foo; // do something with the preserved value
2888 case IFMATCH_A_fail: // A failed, so the assertion failed
2889 ...; // do some housekeeping, then ...
2890 sayNO; // propagate the failure
2897 For any old-timers reading this who are familiar with the old recursive
2898 approach, the code above is equivalent to:
2900 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
2909 ...; // do some housekeeping, then ...
2910 sayNO; // propagate the failure
2913 The topmost backtrack state, pointed to by st, is usually free. If you
2914 want to claim it, populate any ST.foo fields in it with values you wish to
2915 save, then do one of
2917 PUSH_STATE_GOTO(resume_state, node);
2918 PUSH_YES_STATE_GOTO(resume_state, node);
2920 which sets that backtrack state's resume value to 'resume_state', pushes a
2921 new free entry to the top of the backtrack stack, then goes to 'node'.
2922 On backtracking, the free slot is popped, and the saved state becomes the
2923 new free state. An ST.foo field in this new top state can be temporarily
2924 accessed to retrieve values, but once the main loop is re-entered, it
2925 becomes available for reuse.
2927 Note that the depth of the backtrack stack constantly increases during the
2928 left-to-right execution of the pattern, rather than going up and down with
2929 the pattern nesting. For example the stack is at its maximum at Z at the
2930 end of the pattern, rather than at X in the following:
2932 /(((X)+)+)+....(Y)+....Z/
2934 The only exceptions to this are lookahead/behind assertions and the cut,
2935 (?>A), which pop all the backtrack states associated with A before
2938 Backtrack state structs are allocated in slabs of about 4K in size.
2939 PL_regmatch_state and st always point to the currently active state,
2940 and PL_regmatch_slab points to the slab currently containing
2941 PL_regmatch_state. The first time regmatch() is called, the first slab is
2942 allocated, and is never freed until interpreter destruction. When the slab
2943 is full, a new one is allocated and chained to the end. At exit from
2944 regmatch(), slabs allocated since entry are freed.
2949 #define DEBUG_STATE_pp(pp) \
2951 DUMP_EXEC_POS(locinput, scan, utf8_target); \
2952 PerlIO_printf(Perl_debug_log, \
2953 " %*s"pp" %s%s%s%s%s\n", \
2955 PL_reg_name[st->resume_state], \
2956 ((st==yes_state||st==mark_state) ? "[" : ""), \
2957 ((st==yes_state) ? "Y" : ""), \
2958 ((st==mark_state) ? "M" : ""), \
2959 ((st==yes_state||st==mark_state) ? "]" : "") \
2964 #define REG_NODE_NUM(x) ((x) ? (int)((x)-prog) : -1)
2969 S_debug_start_match(pTHX_ const REGEXP *prog, const bool utf8_target,
2970 const char *start, const char *end, const char *blurb)
2972 const bool utf8_pat = RX_UTF8(prog) ? 1 : 0;
2974 PERL_ARGS_ASSERT_DEBUG_START_MATCH;
2979 RE_PV_QUOTED_DECL(s0, utf8_pat, PERL_DEBUG_PAD_ZERO(0),
2980 RX_PRECOMP_const(prog), RX_PRELEN(prog), 60);
2982 RE_PV_QUOTED_DECL(s1, utf8_target, PERL_DEBUG_PAD_ZERO(1),
2983 start, end - start, 60);
2985 PerlIO_printf(Perl_debug_log,
2986 "%s%s REx%s %s against %s\n",
2987 PL_colors[4], blurb, PL_colors[5], s0, s1);
2989 if (utf8_target||utf8_pat)
2990 PerlIO_printf(Perl_debug_log, "UTF-8 %s%s%s...\n",
2991 utf8_pat ? "pattern" : "",
2992 utf8_pat && utf8_target ? " and " : "",
2993 utf8_target ? "string" : ""
2999 S_dump_exec_pos(pTHX_ const char *locinput,
3000 const regnode *scan,
3001 const char *loc_regeol,
3002 const char *loc_bostr,
3003 const char *loc_reg_starttry,
3004 const bool utf8_target)
3006 const int docolor = *PL_colors[0] || *PL_colors[2] || *PL_colors[4];
3007 const int taill = (docolor ? 10 : 7); /* 3 chars for "> <" */
3008 int l = (loc_regeol - locinput) > taill ? taill : (loc_regeol - locinput);
3009 /* The part of the string before starttry has one color
3010 (pref0_len chars), between starttry and current
3011 position another one (pref_len - pref0_len chars),
3012 after the current position the third one.
3013 We assume that pref0_len <= pref_len, otherwise we
3014 decrease pref0_len. */
3015 int pref_len = (locinput - loc_bostr) > (5 + taill) - l
3016 ? (5 + taill) - l : locinput - loc_bostr;
3019 PERL_ARGS_ASSERT_DUMP_EXEC_POS;
3021 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput - pref_len)))
3023 pref0_len = pref_len - (locinput - loc_reg_starttry);
3024 if (l + pref_len < (5 + taill) && l < loc_regeol - locinput)
3025 l = ( loc_regeol - locinput > (5 + taill) - pref_len
3026 ? (5 + taill) - pref_len : loc_regeol - locinput);
3027 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput + l)))
3031 if (pref0_len > pref_len)
3032 pref0_len = pref_len;
3034 const int is_uni = (utf8_target && OP(scan) != CANY) ? 1 : 0;
3036 RE_PV_COLOR_DECL(s0,len0,is_uni,PERL_DEBUG_PAD(0),
3037 (locinput - pref_len),pref0_len, 60, 4, 5);
3039 RE_PV_COLOR_DECL(s1,len1,is_uni,PERL_DEBUG_PAD(1),
3040 (locinput - pref_len + pref0_len),
3041 pref_len - pref0_len, 60, 2, 3);
3043 RE_PV_COLOR_DECL(s2,len2,is_uni,PERL_DEBUG_PAD(2),
3044 locinput, loc_regeol - locinput, 10, 0, 1);
3046 const STRLEN tlen=len0+len1+len2;
3047 PerlIO_printf(Perl_debug_log,
3048 "%4"IVdf" <%.*s%.*s%s%.*s>%*s|",
3049 (IV)(locinput - loc_bostr),
3052 (docolor ? "" : "> <"),
3054 (int)(tlen > 19 ? 0 : 19 - tlen),
3061 /* reg_check_named_buff_matched()
3062 * Checks to see if a named buffer has matched. The data array of
3063 * buffer numbers corresponding to the buffer is expected to reside
3064 * in the regexp->data->data array in the slot stored in the ARG() of
3065 * node involved. Note that this routine doesn't actually care about the
3066 * name, that information is not preserved from compilation to execution.
3067 * Returns the index of the leftmost defined buffer with the given name
3068 * or 0 if non of the buffers matched.
3071 S_reg_check_named_buff_matched(pTHX_ const regexp *rex, const regnode *scan)
3074 RXi_GET_DECL(rex,rexi);
3075 SV *sv_dat= MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
3076 I32 *nums=(I32*)SvPVX(sv_dat);
3078 PERL_ARGS_ASSERT_REG_CHECK_NAMED_BUFF_MATCHED;
3080 for ( n=0; n<SvIVX(sv_dat); n++ ) {
3081 if ((I32)rex->lastparen >= nums[n] &&
3082 rex->offs[nums[n]].end != -1)
3091 /* free all slabs above current one - called during LEAVE_SCOPE */
3094 S_clear_backtrack_stack(pTHX_ void *p)
3096 regmatch_slab *s = PL_regmatch_slab->next;
3101 PL_regmatch_slab->next = NULL;
3103 regmatch_slab * const osl = s;
3110 STATIC I32 /* 0 failure, 1 success */
3111 S_regmatch(pTHX_ regmatch_info *reginfo, regnode *prog)
3113 #if PERL_VERSION < 9 && !defined(PERL_CORE)
3117 const bool utf8_target = PL_reg_match_utf8;
3118 const U32 uniflags = UTF8_ALLOW_DEFAULT;
3119 REGEXP *rex_sv = reginfo->prog;
3120 regexp *rex = (struct regexp *)SvANY(rex_sv);
3121 RXi_GET_DECL(rex,rexi);
3123 /* the current state. This is a cached copy of PL_regmatch_state */
3125 /* cache heavy used fields of st in registers */
3128 U32 n = 0; /* general value; init to avoid compiler warning */
3129 I32 ln = 0; /* len or last; init to avoid compiler warning */
3130 char *locinput = PL_reginput;
3131 I32 nextchr; /* is always set to UCHARAT(locinput) */
3133 bool result = 0; /* return value of S_regmatch */
3134 int depth = 0; /* depth of backtrack stack */
3135 U32 nochange_depth = 0; /* depth of GOSUB recursion with nochange */
3136 const U32 max_nochange_depth =
3137 (3 * rex->nparens > MAX_RECURSE_EVAL_NOCHANGE_DEPTH) ?
3138 3 * rex->nparens : MAX_RECURSE_EVAL_NOCHANGE_DEPTH;
3139 regmatch_state *yes_state = NULL; /* state to pop to on success of
3141 /* mark_state piggy backs on the yes_state logic so that when we unwind
3142 the stack on success we can update the mark_state as we go */
3143 regmatch_state *mark_state = NULL; /* last mark state we have seen */
3144 regmatch_state *cur_eval = NULL; /* most recent EVAL_AB state */
3145 struct regmatch_state *cur_curlyx = NULL; /* most recent curlyx */
3147 bool no_final = 0; /* prevent failure from backtracking? */
3148 bool do_cutgroup = 0; /* no_final only until next branch/trie entry */
3149 char *startpoint = PL_reginput;
3150 SV *popmark = NULL; /* are we looking for a mark? */
3151 SV *sv_commit = NULL; /* last mark name seen in failure */
3152 SV *sv_yes_mark = NULL; /* last mark name we have seen
3153 during a successful match */
3154 U32 lastopen = 0; /* last open we saw */
3155 bool has_cutgroup = RX_HAS_CUTGROUP(rex) ? 1 : 0;
3156 SV* const oreplsv = GvSV(PL_replgv);
3157 /* these three flags are set by various ops to signal information to
3158 * the very next op. They have a useful lifetime of exactly one loop
3159 * iteration, and are not preserved or restored by state pushes/pops
3161 bool sw = 0; /* the condition value in (?(cond)a|b) */
3162 bool minmod = 0; /* the next "{n,m}" is a "{n,m}?" */
3163 int logical = 0; /* the following EVAL is:
3167 or the following IFMATCH/UNLESSM is:
3168 false: plain (?=foo)
3169 true: used as a condition: (?(?=foo))
3171 PAD* last_pad = NULL;
3173 I32 gimme = G_SCALAR;
3174 CV *caller_cv = NULL; /* who called us */
3175 CV *last_pushed_cv = NULL; /* most recently called (?{}) CV */
3176 CHECKPOINT runops_cp; /* savestack position before executing EVAL */
3179 GET_RE_DEBUG_FLAGS_DECL;
3182 /* shut up 'may be used uninitialized' compiler warnings for dMULTICALL */
3183 multicall_oldcatch = 0;
3184 multicall_cv = NULL;
3186 PERL_UNUSED_VAR(multicall_cop);
3187 PERL_UNUSED_VAR(newsp);
3190 PERL_ARGS_ASSERT_REGMATCH;
3192 DEBUG_OPTIMISE_r( DEBUG_EXECUTE_r({
3193 PerlIO_printf(Perl_debug_log,"regmatch start\n");
3195 /* on first ever call to regmatch, allocate first slab */
3196 if (!PL_regmatch_slab) {
3197 Newx(PL_regmatch_slab, 1, regmatch_slab);
3198 PL_regmatch_slab->prev = NULL;
3199 PL_regmatch_slab->next = NULL;
3200 PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
3203 oldsave = PL_savestack_ix;
3204 SAVEDESTRUCTOR_X(S_clear_backtrack_stack, NULL);
3205 SAVEVPTR(PL_regmatch_slab);
3206 SAVEVPTR(PL_regmatch_state);
3208 /* grab next free state slot */
3209 st = ++PL_regmatch_state;
3210 if (st > SLAB_LAST(PL_regmatch_slab))
3211 st = PL_regmatch_state = S_push_slab(aTHX);
3213 /* Note that nextchr is a byte even in UTF */
3214 nextchr = UCHARAT(locinput);
3216 while (scan != NULL) {
3219 SV * const prop = sv_newmortal();
3220 regnode *rnext=regnext(scan);
3221 DUMP_EXEC_POS( locinput, scan, utf8_target );
3222 regprop(rex, prop, scan);
3224 PerlIO_printf(Perl_debug_log,
3225 "%3"IVdf":%*s%s(%"IVdf")\n",
3226 (IV)(scan - rexi->program), depth*2, "",
3228 (PL_regkind[OP(scan)] == END || !rnext) ?
3229 0 : (IV)(rnext - rexi->program));
3232 next = scan + NEXT_OFF(scan);
3235 state_num = OP(scan);
3237 REH_CALL_EXEC_NODE_HOOK(rex, scan, reginfo, st);
3240 switch (state_num) {
3242 if (locinput == PL_bostr)
3244 /* reginfo->till = reginfo->bol; */
3249 if (locinput == PL_bostr ||
3250 ((nextchr || locinput < PL_regeol) && locinput[-1] == '\n'))
3256 if (locinput == PL_bostr)
3260 if (locinput == reginfo->ganch)
3265 /* update the startpoint */
3266 st->u.keeper.val = rex->offs[0].start;
3267 PL_reginput = locinput;
3268 rex->offs[0].start = locinput - PL_bostr;
3269 PUSH_STATE_GOTO(KEEPS_next, next);
3271 case KEEPS_next_fail:
3272 /* rollback the start point change */
3273 rex->offs[0].start = st->u.keeper.val;
3279 if ((nextchr || locinput < PL_regeol) && nextchr != '\n')
3284 if ((nextchr || locinput < PL_regeol) && nextchr != '\n')
3286 if (PL_regeol - locinput > 1)
3290 if (PL_regeol != locinput)
3294 if (!nextchr && locinput >= PL_regeol)
3297 locinput += PL_utf8skip[nextchr];
3298 if (locinput > PL_regeol)
3300 nextchr = UCHARAT(locinput);
3303 nextchr = UCHARAT(++locinput);
3306 if (!nextchr && locinput >= PL_regeol)
3308 nextchr = UCHARAT(++locinput);
3311 if ((!nextchr && locinput >= PL_regeol) || nextchr == '\n')
3314 locinput += PL_utf8skip[nextchr];
3315 if (locinput > PL_regeol)
3317 nextchr = UCHARAT(locinput);
3320 nextchr = UCHARAT(++locinput);
3324 #define ST st->u.trie
3326 /* In this case the charclass data is available inline so
3327 we can fail fast without a lot of extra overhead.
3329 if(!ANYOF_BITMAP_TEST(scan, *locinput)) {
3331 PerlIO_printf(Perl_debug_log,
3332 "%*s %sfailed to match trie start class...%s\n",
3333 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
3336 assert(0); /* NOTREACHED */
3340 /* the basic plan of execution of the trie is:
3341 * At the beginning, run though all the states, and
3342 * find the longest-matching word. Also remember the position
3343 * of the shortest matching word. For example, this pattern:
3346 * when matched against the string "abcde", will generate
3347 * accept states for all words except 3, with the longest
3348 * matching word being 4, and the shortest being 1 (with
3349 * the position being after char 1 of the string).
3351 * Then for each matching word, in word order (i.e. 1,2,4,5),
3352 * we run the remainder of the pattern; on each try setting
3353 * the current position to the character following the word,
3354 * returning to try the next word on failure.
3356 * We avoid having to build a list of words at runtime by
3357 * using a compile-time structure, wordinfo[].prev, which
3358 * gives, for each word, the previous accepting word (if any).
3359 * In the case above it would contain the mappings 1->2, 2->0,
3360 * 3->0, 4->5, 5->1. We can use this table to generate, from
3361 * the longest word (4 above), a list of all words, by
3362 * following the list of prev pointers; this gives us the
3363 * unordered list 4,5,1,2. Then given the current word we have
3364 * just tried, we can go through the list and find the
3365 * next-biggest word to try (so if we just failed on word 2,
3366 * the next in the list is 4).
3368 * Since at runtime we don't record the matching position in
3369 * the string for each word, we have to work that out for
3370 * each word we're about to process. The wordinfo table holds
3371 * the character length of each word; given that we recorded
3372 * at the start: the position of the shortest word and its
3373 * length in chars, we just need to move the pointer the
3374 * difference between the two char lengths. Depending on
3375 * Unicode status and folding, that's cheap or expensive.
3377 * This algorithm is optimised for the case where are only a
3378 * small number of accept states, i.e. 0,1, or maybe 2.
3379 * With lots of accepts states, and having to try all of them,
3380 * it becomes quadratic on number of accept states to find all
3385 /* what type of TRIE am I? (utf8 makes this contextual) */
3386 DECL_TRIE_TYPE(scan);
3388 /* what trie are we using right now */
3389 reg_trie_data * const trie
3390 = (reg_trie_data*)rexi->data->data[ ARG( scan ) ];
3391 HV * widecharmap = MUTABLE_HV(rexi->data->data[ ARG( scan ) + 1 ]);
3392 U32 state = trie->startstate;
3394 if (trie->bitmap && !TRIE_BITMAP_TEST(trie,*locinput) ) {
3395 if (trie->states[ state ].wordnum) {
3397 PerlIO_printf(Perl_debug_log,
3398 "%*s %smatched empty string...%s\n",
3399 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
3405 PerlIO_printf(Perl_debug_log,
3406 "%*s %sfailed to match trie start class...%s\n",
3407 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
3414 U8 *uc = ( U8* )locinput;
3418 U8 *uscan = (U8*)NULL;
3419 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
3420 U32 charcount = 0; /* how many input chars we have matched */
3421 U32 accepted = 0; /* have we seen any accepting states? */
3423 ST.jump = trie->jump;
3426 ST.longfold = FALSE; /* char longer if folded => it's harder */
3429 /* fully traverse the TRIE; note the position of the
3430 shortest accept state and the wordnum of the longest
3433 while ( state && uc <= (U8*)PL_regeol ) {
3434 U32 base = trie->states[ state ].trans.base;
3438 wordnum = trie->states[ state ].wordnum;
3440 if (wordnum) { /* it's an accept state */
3443 /* record first match position */
3445 ST.firstpos = (U8*)locinput;
3450 ST.firstchars = charcount;
3453 if (!ST.nextword || wordnum < ST.nextword)
3454 ST.nextword = wordnum;
3455 ST.topword = wordnum;
3458 DEBUG_TRIE_EXECUTE_r({
3459 DUMP_EXEC_POS( (char *)uc, scan, utf8_target );
3460 PerlIO_printf( Perl_debug_log,
3461 "%*s %sState: %4"UVxf" Accepted: %c ",
3462 2+depth * 2, "", PL_colors[4],
3463 (UV)state, (accepted ? 'Y' : 'N'));
3466 /* read a char and goto next state */
3469 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
3470 uscan, len, uvc, charid, foldlen,
3477 base + charid - 1 - trie->uniquecharcount)) >= 0)
3479 && ((U32)offset < trie->lasttrans)
3480 && trie->trans[offset].check == state)
3482 state = trie->trans[offset].next;
3493 DEBUG_TRIE_EXECUTE_r(
3494 PerlIO_printf( Perl_debug_log,
3495 "Charid:%3x CP:%4"UVxf" After State: %4"UVxf"%s\n",
3496 charid, uvc, (UV)state, PL_colors[5] );
3502 /* calculate total number of accept states */
3507 w = trie->wordinfo[w].prev;
3510 ST.accepted = accepted;
3514 PerlIO_printf( Perl_debug_log,
3515 "%*s %sgot %"IVdf" possible matches%s\n",
3516 REPORT_CODE_OFF + depth * 2, "",
3517 PL_colors[4], (IV)ST.accepted, PL_colors[5] );
3519 goto trie_first_try; /* jump into the fail handler */
3521 assert(0); /* NOTREACHED */
3523 case TRIE_next_fail: /* we failed - try next alternative */
3525 REGCP_UNWIND(ST.cp);
3526 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
3528 if (!--ST.accepted) {
3530 PerlIO_printf( Perl_debug_log,
3531 "%*s %sTRIE failed...%s\n",
3532 REPORT_CODE_OFF+depth*2, "",
3539 /* Find next-highest word to process. Note that this code
3540 * is O(N^2) per trie run (O(N) per branch), so keep tight */
3543 U16 const nextword = ST.nextword;
3544 reg_trie_wordinfo * const wordinfo
3545 = ((reg_trie_data*)rexi->data->data[ARG(ST.me)])->wordinfo;
3546 for (word=ST.topword; word; word=wordinfo[word].prev) {
3547 if (word > nextword && (!min || word < min))
3560 ST.lastparen = rex->lastparen;
3561 ST.lastcloseparen = rex->lastcloseparen;
3565 /* find start char of end of current word */
3567 U32 chars; /* how many chars to skip */
3568 U8 *uc = ST.firstpos;
3569 reg_trie_data * const trie
3570 = (reg_trie_data*)rexi->data->data[ARG(ST.me)];
3572 assert((trie->wordinfo[ST.nextword].len - trie->prefixlen)
3574 chars = (trie->wordinfo[ST.nextword].len - trie->prefixlen)
3578 /* the hard option - fold each char in turn and find
3579 * its folded length (which may be different */
3580 U8 foldbuf[UTF8_MAXBYTES_CASE + 1];
3588 uvc = utf8n_to_uvuni((U8*)uc, UTF8_MAXLEN, &len,
3596 uvc = to_uni_fold(uvc, foldbuf, &foldlen);
3601 uvc = utf8n_to_uvuni(uscan, UTF8_MAXLEN, &len,
3615 PL_reginput = (char *)uc;
3618 scan = ST.me + ((ST.jump && ST.jump[ST.nextword])
3619 ? ST.jump[ST.nextword]
3623 PerlIO_printf( Perl_debug_log,
3624 "%*s %sTRIE matched word #%d, continuing%s\n",
3625 REPORT_CODE_OFF+depth*2, "",
3632 if (ST.accepted > 1 || has_cutgroup) {
3633 PUSH_STATE_GOTO(TRIE_next, scan);
3634 assert(0); /* NOTREACHED */
3636 /* only one choice left - just continue */
3638 AV *const trie_words
3639 = MUTABLE_AV(rexi->data->data[ARG(ST.me)+TRIE_WORDS_OFFSET]);
3640 SV ** const tmp = av_fetch( trie_words,
3642 SV *sv= tmp ? sv_newmortal() : NULL;
3644 PerlIO_printf( Perl_debug_log,
3645 "%*s %sonly one match left, short-circuiting: #%d <%s>%s\n",
3646 REPORT_CODE_OFF+depth*2, "", PL_colors[4],
3648 tmp ? pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 0,
3649 PL_colors[0], PL_colors[1],
3650 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)|PERL_PV_ESCAPE_NONASCII
3652 : "not compiled under -Dr",
3656 locinput = PL_reginput;
3657 nextchr = UCHARAT(locinput);
3658 continue; /* execute rest of RE */
3659 assert(0); /* NOTREACHED */
3663 char *s = STRING(scan);
3665 if (utf8_target != UTF_PATTERN) {
3666 /* The target and the pattern have differing utf8ness. */
3668 const char * const e = s + ln;
3671 /* The target is utf8, the pattern is not utf8. */
3676 if (NATIVE_TO_UNI(*(U8*)s) !=
3677 utf8n_to_uvuni((U8*)l, UTF8_MAXBYTES, &ulen,
3685 /* The target is not utf8, the pattern is utf8. */
3690 if (NATIVE_TO_UNI(*((U8*)l)) !=
3691 utf8n_to_uvuni((U8*)s, UTF8_MAXBYTES, &ulen,
3699 nextchr = UCHARAT(locinput);
3702 /* The target and the pattern have the same utf8ness. */
3703 /* Inline the first character, for speed. */
3704 if (UCHARAT(s) != nextchr)
3706 if (PL_regeol - locinput < ln)
3708 if (ln > 1 && memNE(s, locinput, ln))
3711 nextchr = UCHARAT(locinput);
3716 const U8 * fold_array;
3718 U32 fold_utf8_flags;
3720 PL_reg_flags |= RF_tainted;
3721 folder = foldEQ_locale;
3722 fold_array = PL_fold_locale;
3723 fold_utf8_flags = FOLDEQ_UTF8_LOCALE;
3727 case EXACTFU_TRICKYFOLD:
3729 folder = foldEQ_latin1;
3730 fold_array = PL_fold_latin1;
3731 fold_utf8_flags = (UTF_PATTERN) ? FOLDEQ_S1_ALREADY_FOLDED : 0;
3735 folder = foldEQ_latin1;
3736 fold_array = PL_fold_latin1;
3737 fold_utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
3742 fold_array = PL_fold;
3743 fold_utf8_flags = 0;
3749 if (utf8_target || UTF_PATTERN || state_num == EXACTFU_SS) {
3750 /* Either target or the pattern are utf8, or has the issue where
3751 * the fold lengths may differ. */
3752 const char * const l = locinput;
3753 char *e = PL_regeol;
3755 if (! foldEQ_utf8_flags(s, 0, ln, cBOOL(UTF_PATTERN),
3756 l, &e, 0, utf8_target, fold_utf8_flags))
3761 nextchr = UCHARAT(locinput);
3765 /* Neither the target nor the pattern are utf8 */
3766 if (UCHARAT(s) != nextchr &&
3767 UCHARAT(s) != fold_array[nextchr])
3771 if (PL_regeol - locinput < ln)
3773 if (ln > 1 && ! folder(s, locinput, ln))
3776 nextchr = UCHARAT(locinput);
3780 /* XXX Could improve efficiency by separating these all out using a
3781 * macro or in-line function. At that point regcomp.c would no longer
3782 * have to set the FLAGS fields of these */
3785 PL_reg_flags |= RF_tainted;
3793 /* was last char in word? */
3795 && FLAGS(scan) != REGEX_ASCII_RESTRICTED_CHARSET
3796 && FLAGS(scan) != REGEX_ASCII_MORE_RESTRICTED_CHARSET)
3798 if (locinput == PL_bostr)
3801 const U8 * const r = reghop3((U8*)locinput, -1, (U8*)PL_bostr);
3803 ln = utf8n_to_uvchr(r, UTF8SKIP(r), 0, uniflags);
3805 if (FLAGS(scan) != REGEX_LOCALE_CHARSET) {
3806 ln = isALNUM_uni(ln);
3807 LOAD_UTF8_CHARCLASS_ALNUM();
3808 n = swash_fetch(PL_utf8_alnum, (U8*)locinput, utf8_target);
3811 ln = isALNUM_LC_uvchr(UNI_TO_NATIVE(ln));
3812 n = isALNUM_LC_utf8((U8*)locinput);
3817 /* Here the string isn't utf8, or is utf8 and only ascii
3818 * characters are to match \w. In the latter case looking at
3819 * the byte just prior to the current one may be just the final
3820 * byte of a multi-byte character. This is ok. There are two
3822 * 1) it is a single byte character, and then the test is doing
3823 * just what it's supposed to.
3824 * 2) it is a multi-byte character, in which case the final
3825 * byte is never mistakable for ASCII, and so the test
3826 * will say it is not a word character, which is the
3827 * correct answer. */
3828 ln = (locinput != PL_bostr) ?
3829 UCHARAT(locinput - 1) : '\n';
3830 switch (FLAGS(scan)) {
3831 case REGEX_UNICODE_CHARSET:
3832 ln = isWORDCHAR_L1(ln);
3833 n = isWORDCHAR_L1(nextchr);
3835 case REGEX_LOCALE_CHARSET:
3836 ln = isALNUM_LC(ln);
3837 n = isALNUM_LC(nextchr);
3839 case REGEX_DEPENDS_CHARSET:
3841 n = isALNUM(nextchr);
3843 case REGEX_ASCII_RESTRICTED_CHARSET:
3844 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
3845 ln = isWORDCHAR_A(ln);
3846 n = isWORDCHAR_A(nextchr);
3849 Perl_croak(aTHX_ "panic: Unexpected FLAGS %u in op %u", FLAGS(scan), OP(scan));
3853 /* Note requires that all BOUNDs be lower than all NBOUNDs in
3855 if (((!ln) == (!n)) == (OP(scan) < NBOUND))
3860 if (utf8_target || state_num == ANYOFV) {
3861 STRLEN inclasslen = PL_regeol - locinput;
3862 if (locinput >= PL_regeol)
3865 if (!reginclass(rex, scan, (U8*)locinput, &inclasslen, utf8_target))
3867 locinput += inclasslen;
3868 nextchr = UCHARAT(locinput);
3873 nextchr = UCHARAT(locinput);
3874 if (!nextchr && locinput >= PL_regeol)
3876 if (!REGINCLASS(rex, scan, (U8*)locinput))
3878 nextchr = UCHARAT(++locinput);
3882 /* Special char classes - The defines start on line 129 or so */
3883 CCC_TRY_U(ALNUM, NALNUM, isWORDCHAR,
3884 ALNUML, NALNUML, isALNUM_LC, isALNUM_LC_utf8,
3885 ALNUMU, NALNUMU, isWORDCHAR_L1,
3886 ALNUMA, NALNUMA, isWORDCHAR_A,
3889 CCC_TRY_U(SPACE, NSPACE, isSPACE,
3890 SPACEL, NSPACEL, isSPACE_LC, isSPACE_LC_utf8,
3891 SPACEU, NSPACEU, isSPACE_L1,
3892 SPACEA, NSPACEA, isSPACE_A,
3895 CCC_TRY(DIGIT, NDIGIT, isDIGIT,
3896 DIGITL, NDIGITL, isDIGIT_LC, isDIGIT_LC_utf8,
3897 DIGITA, NDIGITA, isDIGIT_A,
3901 if (locinput >= PL_regeol || ! _generic_isCC_A(nextchr, FLAGS(scan))) {
3904 /* Matched a utf8-invariant, so don't have to worry about utf8 */
3905 nextchr = UCHARAT(++locinput);
3908 if (locinput >= PL_regeol || _generic_isCC_A(nextchr, FLAGS(scan))) {
3912 locinput += PL_utf8skip[nextchr];
3913 nextchr = UCHARAT(locinput);
3916 nextchr = UCHARAT(++locinput);
3920 case CLUMP: /* Match \X: logical Unicode character. This is defined as
3921 a Unicode extended Grapheme Cluster */
3922 /* From http://www.unicode.org/reports/tr29 (5.2 version). An
3923 extended Grapheme Cluster is:
3926 | Prepend* Begin Extend*
3929 Begin is (Hangul-syllable | ! Control)
3930 Extend is (Grapheme_Extend | Spacing_Mark)
3931 Control is [ GCB_Control CR LF ]
3933 The discussion below shows how the code for CLUMP is derived
3934 from this regex. Note that most of these concepts are from
3935 property values of the Grapheme Cluster Boundary (GCB) property.
3936 No code point can have multiple property values for a given
3937 property. Thus a code point in Prepend can't be in Control, but
3938 it must be in !Control. This is why Control above includes
3939 GCB_Control plus CR plus LF. The latter two are used in the GCB
3940 property separately, and so can't be in GCB_Control, even though
3941 they logically are controls. Control is not the same as gc=cc,
3942 but includes format and other characters as well.
3944 The Unicode definition of Hangul-syllable is:
3946 | (L* ( ( V | LV ) V* | LVT ) T*)
3949 Each of these is a value for the GCB property, and hence must be
3950 disjoint, so the order they are tested is immaterial, so the
3951 above can safely be changed to
3954 | (L* ( LVT | ( V | LV ) V*) T*)
3956 The last two terms can be combined like this:
3958 | (( LVT | ( V | LV ) V*) T*))
3960 And refactored into this:
3961 L* (L | LVT T* | V V* T* | LV V* T*)
3963 That means that if we have seen any L's at all we can quit
3964 there, but if the next character is an LVT, a V, or an LV we
3967 There is a subtlety with Prepend* which showed up in testing.
3968 Note that the Begin, and only the Begin is required in:
3969 | Prepend* Begin Extend*
3970 Also, Begin contains '! Control'. A Prepend must be a
3971 '! Control', which means it must also be a Begin. What it
3972 comes down to is that if we match Prepend* and then find no
3973 suitable Begin afterwards, that if we backtrack the last
3974 Prepend, that one will be a suitable Begin.
3977 if (locinput >= PL_regeol)
3979 if (! utf8_target) {
3981 /* Match either CR LF or '.', as all the other possibilities
3983 locinput++; /* Match the . or CR */
3984 if (nextchr == '\r' /* And if it was CR, and the next is LF,
3986 && locinput < PL_regeol
3987 && UCHARAT(locinput) == '\n') locinput++;
3991 /* Utf8: See if is ( CR LF ); already know that locinput <
3992 * PL_regeol, so locinput+1 is in bounds */
3993 if (nextchr == '\r' && UCHARAT(locinput + 1) == '\n') {
3997 /* In case have to backtrack to beginning, then match '.' */
3998 char *starting = locinput;
4000 /* In case have to backtrack the last prepend */
4001 char *previous_prepend = 0;
4003 LOAD_UTF8_CHARCLASS_GCB();
4005 /* Match (prepend)* */
4006 while (locinput < PL_regeol
4007 && swash_fetch(PL_utf8_X_prepend,
4008 (U8*)locinput, utf8_target))
4010 previous_prepend = locinput;
4011 locinput += UTF8SKIP(locinput);
4014 /* As noted above, if we matched a prepend character, but
4015 * the next thing won't match, back off the last prepend we
4016 * matched, as it is guaranteed to match the begin */
4017 if (previous_prepend
4018 && (locinput >= PL_regeol
4019 || ! swash_fetch(PL_utf8_X_begin,
4020 (U8*)locinput, utf8_target)))
4022 locinput = previous_prepend;
4025 /* Note that here we know PL_regeol > locinput, as we
4026 * tested that upon input to this switch case, and if we
4027 * moved locinput forward, we tested the result just above
4028 * and it either passed, or we backed off so that it will
4030 if (! swash_fetch(PL_utf8_X_begin, (U8*)locinput, utf8_target)) {
4032 /* Here did not match the required 'Begin' in the
4033 * second term. So just match the very first
4034 * character, the '.' of the final term of the regex */
4035 locinput = starting + UTF8SKIP(starting);
4038 /* Here is the beginning of a character that can have
4039 * an extender. It is either a hangul syllable, or a
4041 if (swash_fetch(PL_utf8_X_non_hangul,
4042 (U8*)locinput, utf8_target))
4045 /* Here not a Hangul syllable, must be a
4046 * ('! * Control') */
4047 locinput += UTF8SKIP(locinput);
4050 /* Here is a Hangul syllable. It can be composed
4051 * of several individual characters. One
4052 * possibility is T+ */
4053 if (swash_fetch(PL_utf8_X_T,
4054 (U8*)locinput, utf8_target))
4056 while (locinput < PL_regeol
4057 && swash_fetch(PL_utf8_X_T,
4058 (U8*)locinput, utf8_target))
4060 locinput += UTF8SKIP(locinput);
4064 /* Here, not T+, but is a Hangul. That means
4065 * it is one of the others: L, LV, LVT or V,
4067 * L* (L | LVT T* | V V* T* | LV V* T*) */
4070 while (locinput < PL_regeol
4071 && swash_fetch(PL_utf8_X_L,
4072 (U8*)locinput, utf8_target))
4074 locinput += UTF8SKIP(locinput);
4077 /* Here, have exhausted L*. If the next
4078 * character is not an LV, LVT nor V, it means
4079 * we had to have at least one L, so matches L+
4080 * in the original equation, we have a complete
4081 * hangul syllable. Are done. */
4083 if (locinput < PL_regeol
4084 && swash_fetch(PL_utf8_X_LV_LVT_V,
4085 (U8*)locinput, utf8_target))
4088 /* Otherwise keep going. Must be LV, LVT
4089 * or V. See if LVT */
4090 if (swash_fetch(PL_utf8_X_LVT,
4091 (U8*)locinput, utf8_target))
4093 locinput += UTF8SKIP(locinput);
4096 /* Must be V or LV. Take it, then
4098 locinput += UTF8SKIP(locinput);
4099 while (locinput < PL_regeol
4100 && swash_fetch(PL_utf8_X_V,
4101 (U8*)locinput, utf8_target))
4103 locinput += UTF8SKIP(locinput);
4107 /* And any of LV, LVT, or V can be followed
4109 while (locinput < PL_regeol
4110 && swash_fetch(PL_utf8_X_T,
4114 locinput += UTF8SKIP(locinput);
4120 /* Match any extender */
4121 while (locinput < PL_regeol
4122 && swash_fetch(PL_utf8_X_extend,
4123 (U8*)locinput, utf8_target))
4125 locinput += UTF8SKIP(locinput);
4129 if (locinput > PL_regeol) sayNO;
4131 nextchr = UCHARAT(locinput);
4135 { /* The capture buffer cases. The ones beginning with N for the
4136 named buffers just convert to the equivalent numbered and
4137 pretend they were called as the corresponding numbered buffer
4139 /* don't initialize these in the declaration, it makes C++
4144 const U8 *fold_array;
4147 PL_reg_flags |= RF_tainted;
4148 folder = foldEQ_locale;
4149 fold_array = PL_fold_locale;
4151 utf8_fold_flags = FOLDEQ_UTF8_LOCALE;
4155 folder = foldEQ_latin1;
4156 fold_array = PL_fold_latin1;
4158 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
4162 folder = foldEQ_latin1;
4163 fold_array = PL_fold_latin1;
4165 utf8_fold_flags = 0;
4170 fold_array = PL_fold;
4172 utf8_fold_flags = 0;
4179 utf8_fold_flags = 0;
4182 /* For the named back references, find the corresponding buffer
4184 n = reg_check_named_buff_matched(rex,scan);
4189 goto do_nref_ref_common;
4192 PL_reg_flags |= RF_tainted;
4193 folder = foldEQ_locale;
4194 fold_array = PL_fold_locale;
4195 utf8_fold_flags = FOLDEQ_UTF8_LOCALE;
4199 folder = foldEQ_latin1;
4200 fold_array = PL_fold_latin1;
4201 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
4205 folder = foldEQ_latin1;
4206 fold_array = PL_fold_latin1;
4207 utf8_fold_flags = 0;
4212 fold_array = PL_fold;
4213 utf8_fold_flags = 0;
4219 utf8_fold_flags = 0;
4223 n = ARG(scan); /* which paren pair */
4226 ln = rex->offs[n].start;
4227 PL_reg_leftiter = PL_reg_maxiter; /* Void cache */
4228 if (rex->lastparen < n || ln == -1)
4229 sayNO; /* Do not match unless seen CLOSEn. */
4230 if (ln == rex->offs[n].end)
4234 if (type != REF /* REF can do byte comparison */
4235 && (utf8_target || type == REFFU))
4236 { /* XXX handle REFFL better */
4237 char * limit = PL_regeol;
4239 /* This call case insensitively compares the entire buffer
4240 * at s, with the current input starting at locinput, but
4241 * not going off the end given by PL_regeol, and returns in
4242 * limit upon success, how much of the current input was
4244 if (! foldEQ_utf8_flags(s, NULL, rex->offs[n].end - ln, utf8_target,
4245 locinput, &limit, 0, utf8_target, utf8_fold_flags))
4250 nextchr = UCHARAT(locinput);
4254 /* Not utf8: Inline the first character, for speed. */
4255 if (UCHARAT(s) != nextchr &&
4257 UCHARAT(s) != fold_array[nextchr]))
4259 ln = rex->offs[n].end - ln;
4260 if (locinput + ln > PL_regeol)
4262 if (ln > 1 && (type == REF
4263 ? memNE(s, locinput, ln)
4264 : ! folder(s, locinput, ln)))
4267 nextchr = UCHARAT(locinput);
4277 #define ST st->u.eval
4282 regexp_internal *rei;
4283 regnode *startpoint;
4286 case GOSUB: /* /(...(?1))/ /(...(?&foo))/ */
4287 if (cur_eval && cur_eval->locinput==locinput) {
4288 if (cur_eval->u.eval.close_paren == (U32)ARG(scan))
4289 Perl_croak(aTHX_ "Infinite recursion in regex");
4290 if ( ++nochange_depth > max_nochange_depth )
4292 "Pattern subroutine nesting without pos change"
4293 " exceeded limit in regex");
4300 if (OP(scan)==GOSUB) {
4301 startpoint = scan + ARG2L(scan);
4302 ST.close_paren = ARG(scan);
4304 startpoint = rei->program+1;
4307 goto eval_recurse_doit;
4308 assert(0); /* NOTREACHED */
4309 case EVAL: /* /(?{A})B/ /(??{A})B/ and /(?(?{A})X|Y)B/ */
4310 if (cur_eval && cur_eval->locinput==locinput) {
4311 if ( ++nochange_depth > max_nochange_depth )
4312 Perl_croak(aTHX_ "EVAL without pos change exceeded limit in regex");
4317 /* execute the code in the {...} */
4321 OP * const oop = PL_op;
4322 COP * const ocurcop = PL_curcop;
4324 char *saved_regeol = PL_regeol;
4325 struct re_save_state saved_state;
4328 /* save *all* paren positions */
4330 REGCP_SET(runops_cp);
4332 /* To not corrupt the existing regex state while executing the
4333 * eval we would normally put it on the save stack, like with
4334 * save_re_context. However, re-evals have a weird scoping so we
4335 * can't just add ENTER/LEAVE here. With that, things like
4337 * (?{$a=2})(a(?{local$a=$a+1}))*aak*c(?{$b=$a})
4339 * would break, as they expect the localisation to be unwound
4340 * only when the re-engine backtracks through the bit that
4343 * What we do instead is just saving the state in a local c
4346 Copy(&PL_reg_state, &saved_state, 1, struct re_save_state);
4348 PL_reg_state.re_reparsing = FALSE;
4351 caller_cv = find_runcv(NULL);
4355 if (rexi->data->what[n] == 'r') { /* code from an external qr */
4356 newcv = ((struct regexp *)SvANY(
4357 (REGEXP*)(rexi->data->data[n])
4360 nop = (OP*)rexi->data->data[n+1];
4362 else if (rexi->data->what[n] == 'l') { /* literal code */
4364 nop = (OP*)rexi->data->data[n];
4365 assert(CvDEPTH(newcv));
4368 /* literal with own CV */
4369 assert(rexi->data->what[n] == 'L');
4370 newcv = rex->qr_anoncv;
4371 nop = (OP*)rexi->data->data[n];
4374 /* normally if we're about to execute code from the same
4375 * CV that we used previously, we just use the existing
4376 * CX stack entry. However, its possible that in the
4377 * meantime we may have backtracked, popped from the save
4378 * stack, and undone the SAVECOMPPAD(s) associated with
4379 * PUSH_MULTICALL; in which case PL_comppad no longer
4380 * points to newcv's pad. */
4381 if (newcv != last_pushed_cv || PL_comppad != last_pad)
4383 I32 depth = (newcv == caller_cv) ? 0 : 1;
4384 if (last_pushed_cv) {
4385 CHANGE_MULTICALL_WITHDEPTH(newcv, depth);
4388 PUSH_MULTICALL_WITHDEPTH(newcv, depth);
4390 last_pushed_cv = newcv;
4392 last_pad = PL_comppad;
4394 /* the initial nextstate you would normally execute
4395 * at the start of an eval (which would cause error
4396 * messages to come from the eval), may be optimised
4397 * away from the execution path in the regex code blocks;
4398 * so manually set PL_curcop to it initially */
4400 OP *o = cUNOPx(nop)->op_first;
4401 assert(o->op_type == OP_NULL);
4402 if (o->op_targ == OP_SCOPE) {
4403 o = cUNOPo->op_first;
4406 assert(o->op_targ == OP_LEAVE);
4407 o = cUNOPo->op_first;
4408 assert(o->op_type == OP_ENTER);
4412 if (o->op_type != OP_STUB) {
4413 assert( o->op_type == OP_NEXTSTATE
4414 || o->op_type == OP_DBSTATE
4415 || (o->op_type == OP_NULL
4416 && ( o->op_targ == OP_NEXTSTATE
4417 || o->op_targ == OP_DBSTATE
4421 PL_curcop = (COP*)o;
4426 DEBUG_STATE_r( PerlIO_printf(Perl_debug_log,
4427 " re EVAL PL_op=0x%"UVxf"\n", PTR2UV(nop)) );
4429 rex->offs[0].end = PL_reg_magic->mg_len = locinput - PL_bostr;
4432 SV *sv_mrk = get_sv("REGMARK", 1);
4433 sv_setsv(sv_mrk, sv_yes_mark);
4436 /* we don't use MULTICALL here as we want to call the
4437 * first op of the block of interest, rather than the
4438 * first op of the sub */
4441 CALLRUNOPS(aTHX); /* Scalar context. */
4444 ret = &PL_sv_undef; /* protect against empty (?{}) blocks. */
4450 /* before restoring everything, evaluate the returned
4451 * value, so that 'uninit' warnings don't use the wrong
4452 * PL_op or pad. Also need to process any magic vars
4453 * (e.g. $1) *before* parentheses are restored */
4458 if (logical == 0) /* (?{})/ */
4459 sv_setsv(save_scalar(PL_replgv), ret); /* $^R */
4460 else if (logical == 1) { /* /(?(?{...})X|Y)/ */
4461 sw = cBOOL(SvTRUE(ret));
4464 else { /* /(??{}) */
4465 /* if its overloaded, let the regex compiler handle
4466 * it; otherwise extract regex, or stringify */
4467 if (!SvAMAGIC(ret)) {
4471 if (SvTYPE(sv) == SVt_REGEXP)
4472 re_sv = (REGEXP*) sv;
4473 else if (SvSMAGICAL(sv)) {
4474 MAGIC *mg = mg_find(sv, PERL_MAGIC_qr);
4476 re_sv = (REGEXP *) mg->mg_obj;
4479 /* force any magic, undef warnings here */
4481 ret = sv_mortalcopy(ret);
4482 (void) SvPV_force_nolen(ret);
4488 Copy(&saved_state, &PL_reg_state, 1, struct re_save_state);
4490 /* *** Note that at this point we don't restore
4491 * PL_comppad, (or pop the CxSUB) on the assumption it may
4492 * be used again soon. This is safe as long as nothing
4493 * in the regexp code uses the pad ! */
4495 PL_curcop = ocurcop;
4496 PL_regeol = saved_regeol;
4497 S_regcp_restore(aTHX_ rex, runops_cp);
4503 /* only /(??{})/ from now on */
4506 /* extract RE object from returned value; compiling if
4510 re_sv = reg_temp_copy(NULL, re_sv);
4514 const I32 osize = PL_regsize;
4516 if (SvUTF8(ret) && IN_BYTES) {
4517 /* In use 'bytes': make a copy of the octet
4518 * sequence, but without the flag on */
4520 const char *const p = SvPV(ret, len);
4521 ret = newSVpvn_flags(p, len, SVs_TEMP);
4523 if (rex->intflags & PREGf_USE_RE_EVAL)
4524 pm_flags |= PMf_USE_RE_EVAL;
4526 /* if we got here, it should be an engine which
4527 * supports compiling code blocks and stuff */
4528 assert(rex->engine && rex->engine->op_comp);
4529 assert(!(scan->flags & ~RXf_PMf_COMPILETIME));
4530 re_sv = rex->engine->op_comp(aTHX_ &ret, 1, NULL,
4531 rex->engine, NULL, NULL,
4532 /* copy /msix etc to inner pattern */
4537 & (SVs_TEMP | SVs_PADTMP | SVf_READONLY
4539 /* This isn't a first class regexp. Instead, it's
4540 caching a regexp onto an existing, Perl visible
4542 sv_magic(ret, MUTABLE_SV(re_sv), PERL_MAGIC_qr, 0, 0);
4545 /* safe to do now that any $1 etc has been
4546 * interpolated into the new pattern string and
4548 S_regcp_restore(aTHX_ rex, runops_cp);
4550 re = (struct regexp *)SvANY(re_sv);
4552 RXp_MATCH_COPIED_off(re);
4553 re->subbeg = rex->subbeg;
4554 re->sublen = rex->sublen;
4557 debug_start_match(re_sv, utf8_target, locinput, PL_regeol,
4558 "Matching embedded");
4560 startpoint = rei->program + 1;
4561 ST.close_paren = 0; /* only used for GOSUB */
4563 eval_recurse_doit: /* Share code with GOSUB below this line */
4564 /* run the pattern returned from (??{...}) */
4565 ST.cp = regcppush(rex, 0); /* Save *all* the positions. */
4566 REGCP_SET(ST.lastcp);
4569 re->lastcloseparen = 0;
4571 PL_reginput = locinput;
4574 /* XXXX This is too dramatic a measure... */
4577 ST.toggle_reg_flags = PL_reg_flags;
4579 PL_reg_flags |= RF_utf8;
4581 PL_reg_flags &= ~RF_utf8;
4582 ST.toggle_reg_flags ^= PL_reg_flags; /* diff of old and new */
4584 ST.prev_rex = rex_sv;
4585 ST.prev_curlyx = cur_curlyx;
4587 SET_reg_curpm(rex_sv);
4592 ST.prev_eval = cur_eval;
4594 /* now continue from first node in postoned RE */
4595 PUSH_YES_STATE_GOTO(EVAL_AB, startpoint);
4596 assert(0); /* NOTREACHED */
4599 case EVAL_AB: /* cleanup after a successful (??{A})B */
4600 /* note: this is called twice; first after popping B, then A */
4601 PL_reg_flags ^= ST.toggle_reg_flags;
4602 rex_sv = ST.prev_rex;
4603 SET_reg_curpm(rex_sv);
4604 rex = (struct regexp *)SvANY(rex_sv);
4605 rexi = RXi_GET(rex);
4607 cur_eval = ST.prev_eval;
4608 cur_curlyx = ST.prev_curlyx;
4610 /* XXXX This is too dramatic a measure... */
4612 if ( nochange_depth )
4617 case EVAL_AB_fail: /* unsuccessfully ran A or B in (??{A})B */
4618 /* note: this is called twice; first after popping B, then A */
4619 PL_reg_flags ^= ST.toggle_reg_flags;
4620 rex_sv = ST.prev_rex;
4621 SET_reg_curpm(rex_sv);
4622 rex = (struct regexp *)SvANY(rex_sv);
4623 rexi = RXi_GET(rex);
4625 PL_reginput = locinput;
4626 REGCP_UNWIND(ST.lastcp);
4628 cur_eval = ST.prev_eval;
4629 cur_curlyx = ST.prev_curlyx;
4630 /* XXXX This is too dramatic a measure... */
4632 if ( nochange_depth )
4638 n = ARG(scan); /* which paren pair */
4639 rex->offs[n].start_tmp = locinput - PL_bostr;
4642 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
4643 "rex=0x%"UVxf" offs=0x%"UVxf": \\%"UVuf": set %"IVdf" tmp; regsize=%"UVuf"\n",
4647 (IV)rex->offs[n].start_tmp,
4653 /* XXX really need to log other places start/end are set too */
4654 #define CLOSE_CAPTURE \
4655 rex->offs[n].start = rex->offs[n].start_tmp; \
4656 rex->offs[n].end = locinput - PL_bostr; \
4657 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log, \
4658 "rex=0x%"UVxf" offs=0x%"UVxf": \\%"UVuf": set %"IVdf"..%"IVdf"\n", \
4660 PTR2UV(rex->offs), \
4662 (IV)rex->offs[n].start, \
4663 (IV)rex->offs[n].end \
4667 n = ARG(scan); /* which paren pair */
4669 /*if (n > PL_regsize)
4671 if (n > rex->lastparen)
4673 rex->lastcloseparen = n;
4674 if (cur_eval && cur_eval->u.eval.close_paren == n) {
4682 cursor && OP(cursor)!=END;
4683 cursor=regnext(cursor))
4685 if ( OP(cursor)==CLOSE ){
4687 if ( n <= lastopen ) {
4689 /*if (n > PL_regsize)
4691 if (n > rex->lastparen)
4693 rex->lastcloseparen = n;
4694 if ( n == ARG(scan) || (cur_eval &&
4695 cur_eval->u.eval.close_paren == n))
4704 n = ARG(scan); /* which paren pair */
4705 sw = cBOOL(rex->lastparen >= n && rex->offs[n].end != -1);
4708 /* reg_check_named_buff_matched returns 0 for no match */
4709 sw = cBOOL(0 < reg_check_named_buff_matched(rex,scan));
4713 sw = (cur_eval && (!n || cur_eval->u.eval.close_paren == n));
4719 PL_reg_leftiter = PL_reg_maxiter; /* Void cache */
4721 next = NEXTOPER(NEXTOPER(scan));
4723 next = scan + ARG(scan);
4724 if (OP(next) == IFTHEN) /* Fake one. */
4725 next = NEXTOPER(NEXTOPER(next));
4729 logical = scan->flags;
4732 /*******************************************************************
4734 The CURLYX/WHILEM pair of ops handle the most generic case of the /A*B/
4735 pattern, where A and B are subpatterns. (For simple A, CURLYM or
4736 STAR/PLUS/CURLY/CURLYN are used instead.)
4738 A*B is compiled as <CURLYX><A><WHILEM><B>
4740 On entry to the subpattern, CURLYX is called. This pushes a CURLYX
4741 state, which contains the current count, initialised to -1. It also sets
4742 cur_curlyx to point to this state, with any previous value saved in the
4745 CURLYX then jumps straight to the WHILEM op, rather than executing A,
4746 since the pattern may possibly match zero times (i.e. it's a while {} loop
4747 rather than a do {} while loop).
4749 Each entry to WHILEM represents a successful match of A. The count in the
4750 CURLYX block is incremented, another WHILEM state is pushed, and execution
4751 passes to A or B depending on greediness and the current count.
4753 For example, if matching against the string a1a2a3b (where the aN are
4754 substrings that match /A/), then the match progresses as follows: (the
4755 pushed states are interspersed with the bits of strings matched so far):
4758 <CURLYX cnt=0><WHILEM>
4759 <CURLYX cnt=1><WHILEM> a1 <WHILEM>
4760 <CURLYX cnt=2><WHILEM> a1 <WHILEM> a2 <WHILEM>
4761 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM>
4762 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM> b
4764 (Contrast this with something like CURLYM, which maintains only a single
4768 a1 <CURLYM cnt=1> a2
4769 a1 a2 <CURLYM cnt=2> a3
4770 a1 a2 a3 <CURLYM cnt=3> b
4773 Each WHILEM state block marks a point to backtrack to upon partial failure
4774 of A or B, and also contains some minor state data related to that
4775 iteration. The CURLYX block, pointed to by cur_curlyx, contains the
4776 overall state, such as the count, and pointers to the A and B ops.
4778 This is complicated slightly by nested CURLYX/WHILEM's. Since cur_curlyx
4779 must always point to the *current* CURLYX block, the rules are:
4781 When executing CURLYX, save the old cur_curlyx in the CURLYX state block,
4782 and set cur_curlyx to point the new block.
4784 When popping the CURLYX block after a successful or unsuccessful match,
4785 restore the previous cur_curlyx.
4787 When WHILEM is about to execute B, save the current cur_curlyx, and set it
4788 to the outer one saved in the CURLYX block.
4790 When popping the WHILEM block after a successful or unsuccessful B match,
4791 restore the previous cur_curlyx.
4793 Here's an example for the pattern (AI* BI)*BO
4794 I and O refer to inner and outer, C and W refer to CURLYX and WHILEM:
4797 curlyx backtrack stack
4798 ------ ---------------
4800 CO <CO prev=NULL> <WO>
4801 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
4802 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
4803 NULL <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi <WO prev=CO> bo
4805 At this point the pattern succeeds, and we work back down the stack to
4806 clean up, restoring as we go:
4808 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
4809 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
4810 CO <CO prev=NULL> <WO>
4813 *******************************************************************/
4815 #define ST st->u.curlyx
4817 case CURLYX: /* start of /A*B/ (for complex A) */
4819 /* No need to save/restore up to this paren */
4820 I32 parenfloor = scan->flags;
4822 assert(next); /* keep Coverity happy */
4823 if (OP(PREVOPER(next)) == NOTHING) /* LONGJMP */
4826 /* XXXX Probably it is better to teach regpush to support
4827 parenfloor > PL_regsize... */
4828 if (parenfloor > (I32)rex->lastparen)
4829 parenfloor = rex->lastparen; /* Pessimization... */
4831 ST.prev_curlyx= cur_curlyx;
4833 ST.cp = PL_savestack_ix;
4835 /* these fields contain the state of the current curly.
4836 * they are accessed by subsequent WHILEMs */
4837 ST.parenfloor = parenfloor;
4842 ST.count = -1; /* this will be updated by WHILEM */
4843 ST.lastloc = NULL; /* this will be updated by WHILEM */
4845 PL_reginput = locinput;
4846 PUSH_YES_STATE_GOTO(CURLYX_end, PREVOPER(next));
4847 assert(0); /* NOTREACHED */
4850 case CURLYX_end: /* just finished matching all of A*B */
4851 cur_curlyx = ST.prev_curlyx;
4853 assert(0); /* NOTREACHED */
4855 case CURLYX_end_fail: /* just failed to match all of A*B */
4857 cur_curlyx = ST.prev_curlyx;
4859 assert(0); /* NOTREACHED */
4863 #define ST st->u.whilem
4865 case WHILEM: /* just matched an A in /A*B/ (for complex A) */
4867 /* see the discussion above about CURLYX/WHILEM */
4869 int min = ARG1(cur_curlyx->u.curlyx.me);
4870 int max = ARG2(cur_curlyx->u.curlyx.me);
4871 regnode *A = NEXTOPER(cur_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS;
4873 assert(cur_curlyx); /* keep Coverity happy */
4874 n = ++cur_curlyx->u.curlyx.count; /* how many A's matched */
4875 ST.save_lastloc = cur_curlyx->u.curlyx.lastloc;
4876 ST.cache_offset = 0;
4879 PL_reginput = locinput;
4881 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
4882 "%*s whilem: matched %ld out of %d..%d\n",
4883 REPORT_CODE_OFF+depth*2, "", (long)n, min, max)
4886 /* First just match a string of min A's. */
4889 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor);
4890 cur_curlyx->u.curlyx.lastloc = locinput;
4891 REGCP_SET(ST.lastcp);
4893 PUSH_STATE_GOTO(WHILEM_A_pre, A);
4894 assert(0); /* NOTREACHED */
4897 /* If degenerate A matches "", assume A done. */
4899 if (locinput == cur_curlyx->u.curlyx.lastloc) {
4900 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
4901 "%*s whilem: empty match detected, trying continuation...\n",
4902 REPORT_CODE_OFF+depth*2, "")
4904 goto do_whilem_B_max;
4907 /* super-linear cache processing */
4911 if (!PL_reg_maxiter) {
4912 /* start the countdown: Postpone detection until we
4913 * know the match is not *that* much linear. */
4914 PL_reg_maxiter = (PL_regeol - PL_bostr + 1) * (scan->flags>>4);
4915 /* possible overflow for long strings and many CURLYX's */
4916 if (PL_reg_maxiter < 0)
4917 PL_reg_maxiter = I32_MAX;
4918 PL_reg_leftiter = PL_reg_maxiter;
4921 if (PL_reg_leftiter-- == 0) {
4922 /* initialise cache */
4923 const I32 size = (PL_reg_maxiter + 7)/8;
4924 if (PL_reg_poscache) {
4925 if ((I32)PL_reg_poscache_size < size) {
4926 Renew(PL_reg_poscache, size, char);
4927 PL_reg_poscache_size = size;
4929 Zero(PL_reg_poscache, size, char);
4932 PL_reg_poscache_size = size;
4933 Newxz(PL_reg_poscache, size, char);
4935 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
4936 "%swhilem: Detected a super-linear match, switching on caching%s...\n",
4937 PL_colors[4], PL_colors[5])
4941 if (PL_reg_leftiter < 0) {
4942 /* have we already failed at this position? */
4944 offset = (scan->flags & 0xf) - 1
4945 + (locinput - PL_bostr) * (scan->flags>>4);
4946 mask = 1 << (offset % 8);
4948 if (PL_reg_poscache[offset] & mask) {
4949 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
4950 "%*s whilem: (cache) already tried at this position...\n",
4951 REPORT_CODE_OFF+depth*2, "")
4953 sayNO; /* cache records failure */
4955 ST.cache_offset = offset;
4956 ST.cache_mask = mask;
4960 /* Prefer B over A for minimal matching. */
4962 if (cur_curlyx->u.curlyx.minmod) {
4963 ST.save_curlyx = cur_curlyx;
4964 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
4965 ST.cp = regcppush(rex, ST.save_curlyx->u.curlyx.parenfloor);
4966 REGCP_SET(ST.lastcp);
4967 PUSH_YES_STATE_GOTO(WHILEM_B_min, ST.save_curlyx->u.curlyx.B);
4968 assert(0); /* NOTREACHED */
4971 /* Prefer A over B for maximal matching. */
4973 if (n < max) { /* More greed allowed? */
4974 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor);
4975 cur_curlyx->u.curlyx.lastloc = locinput;
4976 REGCP_SET(ST.lastcp);
4977 PUSH_STATE_GOTO(WHILEM_A_max, A);
4978 assert(0); /* NOTREACHED */
4980 goto do_whilem_B_max;
4982 assert(0); /* NOTREACHED */
4984 case WHILEM_B_min: /* just matched B in a minimal match */
4985 case WHILEM_B_max: /* just matched B in a maximal match */
4986 cur_curlyx = ST.save_curlyx;
4988 assert(0); /* NOTREACHED */
4990 case WHILEM_B_max_fail: /* just failed to match B in a maximal match */
4991 cur_curlyx = ST.save_curlyx;
4992 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
4993 cur_curlyx->u.curlyx.count--;
4995 assert(0); /* NOTREACHED */
4997 case WHILEM_A_min_fail: /* just failed to match A in a minimal match */
4999 case WHILEM_A_pre_fail: /* just failed to match even minimal A */
5000 REGCP_UNWIND(ST.lastcp);
5002 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
5003 cur_curlyx->u.curlyx.count--;
5005 assert(0); /* NOTREACHED */
5007 case WHILEM_A_max_fail: /* just failed to match A in a maximal match */
5008 REGCP_UNWIND(ST.lastcp);
5009 regcppop(rex); /* Restore some previous $<digit>s? */
5010 PL_reginput = locinput;
5011 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
5012 "%*s whilem: failed, trying continuation...\n",
5013 REPORT_CODE_OFF+depth*2, "")
5016 if (cur_curlyx->u.curlyx.count >= REG_INFTY
5017 && ckWARN(WARN_REGEXP)
5018 && !(PL_reg_flags & RF_warned))
5020 PL_reg_flags |= RF_warned;
5021 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
5022 "Complex regular subexpression recursion limit (%d) "
5028 ST.save_curlyx = cur_curlyx;
5029 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
5030 PUSH_YES_STATE_GOTO(WHILEM_B_max, ST.save_curlyx->u.curlyx.B);
5031 assert(0); /* NOTREACHED */
5033 case WHILEM_B_min_fail: /* just failed to match B in a minimal match */
5034 cur_curlyx = ST.save_curlyx;
5035 REGCP_UNWIND(ST.lastcp);
5038 if (cur_curlyx->u.curlyx.count >= /*max*/ARG2(cur_curlyx->u.curlyx.me)) {
5039 /* Maximum greed exceeded */
5040 if (cur_curlyx->u.curlyx.count >= REG_INFTY
5041 && ckWARN(WARN_REGEXP)
5042 && !(PL_reg_flags & RF_warned))
5044 PL_reg_flags |= RF_warned;
5045 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
5046 "Complex regular subexpression recursion "
5047 "limit (%d) exceeded",
5050 cur_curlyx->u.curlyx.count--;
5054 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
5055 "%*s trying longer...\n", REPORT_CODE_OFF+depth*2, "")
5057 /* Try grabbing another A and see if it helps. */
5058 PL_reginput = locinput;
5059 cur_curlyx->u.curlyx.lastloc = locinput;
5060 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor);
5061 REGCP_SET(ST.lastcp);
5062 PUSH_STATE_GOTO(WHILEM_A_min,
5063 /*A*/ NEXTOPER(ST.save_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS);
5064 assert(0); /* NOTREACHED */
5067 #define ST st->u.branch
5069 case BRANCHJ: /* /(...|A|...)/ with long next pointer */
5070 next = scan + ARG(scan);
5073 scan = NEXTOPER(scan);
5076 case BRANCH: /* /(...|A|...)/ */
5077 scan = NEXTOPER(scan); /* scan now points to inner node */
5078 ST.lastparen = rex->lastparen;
5079 ST.lastcloseparen = rex->lastcloseparen;
5080 ST.next_branch = next;
5082 PL_reginput = locinput;
5084 /* Now go into the branch */
5086 PUSH_YES_STATE_GOTO(BRANCH_next, scan);
5088 PUSH_STATE_GOTO(BRANCH_next, scan);
5090 assert(0); /* NOTREACHED */
5092 PL_reginput = locinput;
5093 sv_yes_mark = st->u.mark.mark_name = scan->flags ? NULL :
5094 MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
5095 PUSH_STATE_GOTO(CUTGROUP_next,next);
5096 assert(0); /* NOTREACHED */
5097 case CUTGROUP_next_fail:
5100 if (st->u.mark.mark_name)
5101 sv_commit = st->u.mark.mark_name;
5103 assert(0); /* NOTREACHED */
5106 assert(0); /* NOTREACHED */
5107 case BRANCH_next_fail: /* that branch failed; try the next, if any */
5112 REGCP_UNWIND(ST.cp);
5113 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
5114 scan = ST.next_branch;
5115 /* no more branches? */
5116 if (!scan || (OP(scan) != BRANCH && OP(scan) != BRANCHJ)) {
5118 PerlIO_printf( Perl_debug_log,
5119 "%*s %sBRANCH failed...%s\n",
5120 REPORT_CODE_OFF+depth*2, "",
5126 continue; /* execute next BRANCH[J] op */
5127 assert(0); /* NOTREACHED */
5134 #define ST st->u.curlym
5136 case CURLYM: /* /A{m,n}B/ where A is fixed-length */
5138 /* This is an optimisation of CURLYX that enables us to push
5139 * only a single backtracking state, no matter how many matches
5140 * there are in {m,n}. It relies on the pattern being constant
5141 * length, with no parens to influence future backrefs
5145 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
5147 ST.lastparen = rex->lastparen;
5148 ST.lastcloseparen = rex->lastcloseparen;
5150 /* if paren positive, emulate an OPEN/CLOSE around A */
5152 U32 paren = ST.me->flags;
5153 if (paren > PL_regsize)
5155 scan += NEXT_OFF(scan); /* Skip former OPEN. */
5163 ST.c1 = CHRTEST_UNINIT;
5166 if (!(ST.minmod ? ARG1(ST.me) : ARG2(ST.me))) /* min/max */
5169 curlym_do_A: /* execute the A in /A{m,n}B/ */
5170 PL_reginput = locinput;
5171 PUSH_YES_STATE_GOTO(CURLYM_A, ST.A); /* match A */
5172 assert(0); /* NOTREACHED */
5174 case CURLYM_A: /* we've just matched an A */
5175 locinput = st->locinput;
5176 nextchr = UCHARAT(locinput);
5179 /* after first match, determine A's length: u.curlym.alen */
5180 if (ST.count == 1) {
5181 if (PL_reg_match_utf8) {
5183 while (s < PL_reginput) {
5189 ST.alen = PL_reginput - locinput;
5192 ST.count = ST.minmod ? ARG1(ST.me) : ARG2(ST.me);
5195 PerlIO_printf(Perl_debug_log,
5196 "%*s CURLYM now matched %"IVdf" times, len=%"IVdf"...\n",
5197 (int)(REPORT_CODE_OFF+(depth*2)), "",
5198 (IV) ST.count, (IV)ST.alen)
5201 locinput = PL_reginput;
5203 if (cur_eval && cur_eval->u.eval.close_paren &&
5204 cur_eval->u.eval.close_paren == (U32)ST.me->flags)
5208 I32 max = (ST.minmod ? ARG1(ST.me) : ARG2(ST.me));
5209 if ( max == REG_INFTY || ST.count < max )
5210 goto curlym_do_A; /* try to match another A */
5212 goto curlym_do_B; /* try to match B */
5214 case CURLYM_A_fail: /* just failed to match an A */
5215 REGCP_UNWIND(ST.cp);
5217 if (ST.minmod || ST.count < ARG1(ST.me) /* min*/
5218 || (cur_eval && cur_eval->u.eval.close_paren &&
5219 cur_eval->u.eval.close_paren == (U32)ST.me->flags))
5222 curlym_do_B: /* execute the B in /A{m,n}B/ */
5223 PL_reginput = locinput;
5224 if (ST.c1 == CHRTEST_UNINIT) {
5225 /* calculate c1 and c2 for possible match of 1st char
5226 * following curly */
5227 ST.c1 = ST.c2 = CHRTEST_VOID;
5228 if (HAS_TEXT(ST.B) || JUMPABLE(ST.B)) {
5229 regnode *text_node = ST.B;
5230 if (! HAS_TEXT(text_node))
5231 FIND_NEXT_IMPT(text_node);
5234 (HAS_TEXT(text_node) && PL_regkind[OP(text_node)] == EXACT)
5236 But the former is redundant in light of the latter.
5238 if this changes back then the macro for
5239 IS_TEXT and friends need to change.
5241 if (PL_regkind[OP(text_node)] == EXACT)
5244 ST.c1 = (U8)*STRING(text_node);
5245 switch (OP(text_node)) {
5246 case EXACTF: ST.c2 = PL_fold[ST.c1]; break;
5249 case EXACTFU_TRICKYFOLD:
5250 case EXACTFU: ST.c2 = PL_fold_latin1[ST.c1]; break;
5251 case EXACTFL: ST.c2 = PL_fold_locale[ST.c1]; break;
5252 default: ST.c2 = ST.c1;
5259 PerlIO_printf(Perl_debug_log,
5260 "%*s CURLYM trying tail with matches=%"IVdf"...\n",
5261 (int)(REPORT_CODE_OFF+(depth*2)),
5264 if (ST.c1 != CHRTEST_VOID
5265 && UCHARAT(PL_reginput) != ST.c1
5266 && UCHARAT(PL_reginput) != ST.c2)
5268 /* simulate B failing */
5270 PerlIO_printf(Perl_debug_log,
5271 "%*s CURLYM Fast bail c1=%"IVdf" c2=%"IVdf"\n",
5272 (int)(REPORT_CODE_OFF+(depth*2)),"",
5275 state_num = CURLYM_B_fail;
5276 goto reenter_switch;
5280 /* emulate CLOSE: mark current A as captured */
5281 I32 paren = ST.me->flags;
5283 rex->offs[paren].start
5284 = HOPc(PL_reginput, -ST.alen) - PL_bostr;
5285 rex->offs[paren].end = PL_reginput - PL_bostr;
5286 if ((U32)paren > rex->lastparen)
5287 rex->lastparen = paren;
5288 rex->lastcloseparen = paren;
5291 rex->offs[paren].end = -1;
5292 if (cur_eval && cur_eval->u.eval.close_paren &&
5293 cur_eval->u.eval.close_paren == (U32)ST.me->flags)
5302 PUSH_STATE_GOTO(CURLYM_B, ST.B); /* match B */
5303 assert(0); /* NOTREACHED */
5305 case CURLYM_B_fail: /* just failed to match a B */
5306 REGCP_UNWIND(ST.cp);
5307 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
5309 I32 max = ARG2(ST.me);
5310 if (max != REG_INFTY && ST.count == max)
5312 goto curlym_do_A; /* try to match a further A */
5314 /* backtrack one A */
5315 if (ST.count == ARG1(ST.me) /* min */)
5318 locinput = HOPc(locinput, -ST.alen);
5319 goto curlym_do_B; /* try to match B */
5322 #define ST st->u.curly
5324 #define CURLY_SETPAREN(paren, success) \
5327 rex->offs[paren].start = HOPc(locinput, -1) - PL_bostr; \
5328 rex->offs[paren].end = locinput - PL_bostr; \
5329 if (paren > rex->lastparen) \
5330 rex->lastparen = paren; \
5331 rex->lastcloseparen = paren; \
5334 rex->offs[paren].end = -1; \
5335 rex->lastparen = ST.lastparen; \
5336 rex->lastcloseparen = ST.lastcloseparen; \
5340 case STAR: /* /A*B/ where A is width 1 */
5344 scan = NEXTOPER(scan);
5346 case PLUS: /* /A+B/ where A is width 1 */
5350 scan = NEXTOPER(scan);
5352 case CURLYN: /* /(A){m,n}B/ where A is width 1 */
5353 ST.paren = scan->flags; /* Which paren to set */
5354 ST.lastparen = rex->lastparen;
5355 ST.lastcloseparen = rex->lastcloseparen;
5356 if (ST.paren > PL_regsize)
5357 PL_regsize = ST.paren;
5358 ST.min = ARG1(scan); /* min to match */
5359 ST.max = ARG2(scan); /* max to match */
5360 if (cur_eval && cur_eval->u.eval.close_paren &&
5361 cur_eval->u.eval.close_paren == (U32)ST.paren) {
5365 scan = regnext(NEXTOPER(scan) + NODE_STEP_REGNODE);
5367 case CURLY: /* /A{m,n}B/ where A is width 1 */
5369 ST.min = ARG1(scan); /* min to match */
5370 ST.max = ARG2(scan); /* max to match */
5371 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
5374 * Lookahead to avoid useless match attempts
5375 * when we know what character comes next.
5377 * Used to only do .*x and .*?x, but now it allows
5378 * for )'s, ('s and (?{ ... })'s to be in the way
5379 * of the quantifier and the EXACT-like node. -- japhy
5382 if (ST.min > ST.max) /* XXX make this a compile-time check? */
5384 if (HAS_TEXT(next) || JUMPABLE(next)) {
5386 regnode *text_node = next;
5388 if (! HAS_TEXT(text_node))
5389 FIND_NEXT_IMPT(text_node);
5391 if (! HAS_TEXT(text_node))
5392 ST.c1 = ST.c2 = CHRTEST_VOID;
5394 if ( PL_regkind[OP(text_node)] != EXACT ) {
5395 ST.c1 = ST.c2 = CHRTEST_VOID;
5396 goto assume_ok_easy;
5399 s = (U8*)STRING(text_node);
5401 /* Currently we only get here when
5403 PL_rekind[OP(text_node)] == EXACT
5405 if this changes back then the macro for IS_TEXT and
5406 friends need to change. */
5409 switch (OP(text_node)) {
5410 case EXACTF: ST.c2 = PL_fold[ST.c1]; break;
5413 case EXACTFU_TRICKYFOLD:
5414 case EXACTFU: ST.c2 = PL_fold_latin1[ST.c1]; break;
5415 case EXACTFL: ST.c2 = PL_fold_locale[ST.c1]; break;
5416 default: ST.c2 = ST.c1; break;
5419 else { /* UTF_PATTERN */
5420 if (IS_TEXTFU(text_node) || IS_TEXTF(text_node)) {
5422 U8 tmpbuf[UTF8_MAXBYTES_CASE+1];
5424 to_utf8_fold((U8*)s, tmpbuf, &ulen);
5425 ST.c1 = ST.c2 = utf8n_to_uvchr(tmpbuf, UTF8_MAXLEN, 0,
5429 ST.c2 = ST.c1 = utf8n_to_uvchr(s, UTF8_MAXBYTES, 0,
5436 ST.c1 = ST.c2 = CHRTEST_VOID;
5441 PL_reginput = locinput;
5444 if (ST.min && regrepeat(rex, ST.A, ST.min, depth) < ST.min)
5447 locinput = PL_reginput;
5449 if (ST.c1 == CHRTEST_VOID)
5450 goto curly_try_B_min;
5452 ST.oldloc = locinput;
5454 /* set ST.maxpos to the furthest point along the
5455 * string that could possibly match */
5456 if (ST.max == REG_INFTY) {
5457 ST.maxpos = PL_regeol - 1;
5459 while (UTF8_IS_CONTINUATION(*(U8*)ST.maxpos))
5462 else if (utf8_target) {
5463 int m = ST.max - ST.min;
5464 for (ST.maxpos = locinput;
5465 m >0 && ST.maxpos + UTF8SKIP(ST.maxpos) <= PL_regeol; m--)
5466 ST.maxpos += UTF8SKIP(ST.maxpos);
5469 ST.maxpos = locinput + ST.max - ST.min;
5470 if (ST.maxpos >= PL_regeol)
5471 ST.maxpos = PL_regeol - 1;
5473 goto curly_try_B_min_known;
5477 ST.count = regrepeat(rex, ST.A, ST.max, depth);
5478 locinput = PL_reginput;
5479 if (ST.count < ST.min)
5481 if ((ST.count > ST.min)
5482 && (PL_regkind[OP(ST.B)] == EOL) && (OP(ST.B) != MEOL))
5484 /* A{m,n} must come at the end of the string, there's
5485 * no point in backing off ... */
5487 /* ...except that $ and \Z can match before *and* after
5488 newline at the end. Consider "\n\n" =~ /\n+\Z\n/.
5489 We may back off by one in this case. */
5490 if (UCHARAT(PL_reginput - 1) == '\n' && OP(ST.B) != EOS)
5494 goto curly_try_B_max;
5496 assert(0); /* NOTREACHED */
5499 case CURLY_B_min_known_fail:
5500 /* failed to find B in a non-greedy match where c1,c2 valid */
5502 PL_reginput = locinput; /* Could be reset... */
5503 REGCP_UNWIND(ST.cp);
5505 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
5507 /* Couldn't or didn't -- move forward. */
5508 ST.oldloc = locinput;
5510 locinput += UTF8SKIP(locinput);
5514 curly_try_B_min_known:
5515 /* find the next place where 'B' could work, then call B */
5519 n = (ST.oldloc == locinput) ? 0 : 1;
5520 if (ST.c1 == ST.c2) {
5522 /* set n to utf8_distance(oldloc, locinput) */
5523 while (locinput <= ST.maxpos &&
5524 utf8n_to_uvchr((U8*)locinput,
5525 UTF8_MAXBYTES, &len,
5526 uniflags) != (UV)ST.c1) {
5532 /* set n to utf8_distance(oldloc, locinput) */
5533 while (locinput <= ST.maxpos) {
5535 const UV c = utf8n_to_uvchr((U8*)locinput,
5536 UTF8_MAXBYTES, &len,
5538 if (c == (UV)ST.c1 || c == (UV)ST.c2)
5546 if (ST.c1 == ST.c2) {
5547 while (locinput <= ST.maxpos &&
5548 UCHARAT(locinput) != ST.c1)
5552 while (locinput <= ST.maxpos
5553 && UCHARAT(locinput) != ST.c1
5554 && UCHARAT(locinput) != ST.c2)
5557 n = locinput - ST.oldloc;
5559 if (locinput > ST.maxpos)
5561 /* PL_reginput == oldloc now */
5564 if (regrepeat(rex, ST.A, n, depth) < n)
5567 PL_reginput = locinput;
5568 CURLY_SETPAREN(ST.paren, ST.count);
5569 if (cur_eval && cur_eval->u.eval.close_paren &&
5570 cur_eval->u.eval.close_paren == (U32)ST.paren) {
5573 PUSH_STATE_GOTO(CURLY_B_min_known, ST.B);
5575 assert(0); /* NOTREACHED */
5578 case CURLY_B_min_fail:
5579 /* failed to find B in a non-greedy match where c1,c2 invalid */
5581 REGCP_UNWIND(ST.cp);
5583 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
5585 /* failed -- move forward one */
5586 PL_reginput = locinput;
5587 if (regrepeat(rex, ST.A, 1, depth)) {
5589 locinput = PL_reginput;
5590 if (ST.count <= ST.max || (ST.max == REG_INFTY &&
5591 ST.count > 0)) /* count overflow ? */
5594 CURLY_SETPAREN(ST.paren, ST.count);
5595 if (cur_eval && cur_eval->u.eval.close_paren &&
5596 cur_eval->u.eval.close_paren == (U32)ST.paren) {
5599 PUSH_STATE_GOTO(CURLY_B_min, ST.B);
5603 assert(0); /* NOTREACHED */
5607 /* a successful greedy match: now try to match B */
5608 if (cur_eval && cur_eval->u.eval.close_paren &&
5609 cur_eval->u.eval.close_paren == (U32)ST.paren) {
5614 if (ST.c1 != CHRTEST_VOID)
5615 c = utf8_target ? utf8n_to_uvchr((U8*)PL_reginput,
5616 UTF8_MAXBYTES, 0, uniflags)
5617 : (UV) UCHARAT(PL_reginput);
5618 /* If it could work, try it. */
5619 if (ST.c1 == CHRTEST_VOID || c == (UV)ST.c1 || c == (UV)ST.c2) {
5620 CURLY_SETPAREN(ST.paren, ST.count);
5621 PUSH_STATE_GOTO(CURLY_B_max, ST.B);
5622 assert(0); /* NOTREACHED */
5626 case CURLY_B_max_fail:
5627 /* failed to find B in a greedy match */
5629 REGCP_UNWIND(ST.cp);
5631 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
5634 if (--ST.count < ST.min)
5636 PL_reginput = locinput = HOPc(locinput, -1);
5637 goto curly_try_B_max;
5644 /* we've just finished A in /(??{A})B/; now continue with B */
5645 st->u.eval.toggle_reg_flags
5646 = cur_eval->u.eval.toggle_reg_flags;
5647 PL_reg_flags ^= st->u.eval.toggle_reg_flags;
5649 st->u.eval.prev_rex = rex_sv; /* inner */
5650 st->u.eval.cp = regcppush(rex, 0); /* Save *all* the positions. */
5651 rex_sv = cur_eval->u.eval.prev_rex;
5652 SET_reg_curpm(rex_sv);
5653 rex = (struct regexp *)SvANY(rex_sv);
5654 rexi = RXi_GET(rex);
5655 cur_curlyx = cur_eval->u.eval.prev_curlyx;
5657 REGCP_SET(st->u.eval.lastcp);
5658 PL_reginput = locinput;
5660 /* Restore parens of the outer rex without popping the
5662 S_regcp_restore(aTHX_ rex, cur_eval->u.eval.lastcp);
5664 st->u.eval.prev_eval = cur_eval;
5665 cur_eval = cur_eval->u.eval.prev_eval;
5667 PerlIO_printf(Perl_debug_log, "%*s EVAL trying tail ... %"UVxf"\n",
5668 REPORT_CODE_OFF+depth*2, "",PTR2UV(cur_eval)););
5669 if ( nochange_depth )
5672 PUSH_YES_STATE_GOTO(EVAL_AB,
5673 st->u.eval.prev_eval->u.eval.B); /* match B */
5676 if (locinput < reginfo->till) {
5677 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
5678 "%sMatch possible, but length=%ld is smaller than requested=%ld, failing!%s\n",
5680 (long)(locinput - PL_reg_starttry),
5681 (long)(reginfo->till - PL_reg_starttry),
5684 sayNO_SILENT; /* Cannot match: too short. */
5686 PL_reginput = locinput; /* put where regtry can find it */
5687 sayYES; /* Success! */
5689 case SUCCEED: /* successful SUSPEND/UNLESSM/IFMATCH/CURLYM */
5691 PerlIO_printf(Perl_debug_log,
5692 "%*s %ssubpattern success...%s\n",
5693 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5]));
5694 PL_reginput = locinput; /* put where regtry can find it */
5695 sayYES; /* Success! */
5698 #define ST st->u.ifmatch
5700 case SUSPEND: /* (?>A) */
5702 PL_reginput = locinput;
5705 case UNLESSM: /* -ve lookaround: (?!A), or with flags, (?<!A) */
5707 goto ifmatch_trivial_fail_test;
5709 case IFMATCH: /* +ve lookaround: (?=A), or with flags, (?<=A) */
5711 ifmatch_trivial_fail_test:
5713 char * const s = HOPBACKc(locinput, scan->flags);
5718 sw = 1 - cBOOL(ST.wanted);
5722 next = scan + ARG(scan);
5730 PL_reginput = locinput;
5734 ST.logical = logical;
5735 logical = 0; /* XXX: reset state of logical once it has been saved into ST */
5737 /* execute body of (?...A) */
5738 PUSH_YES_STATE_GOTO(IFMATCH_A, NEXTOPER(NEXTOPER(scan)));
5739 assert(0); /* NOTREACHED */
5741 case IFMATCH_A_fail: /* body of (?...A) failed */
5742 ST.wanted = !ST.wanted;
5745 case IFMATCH_A: /* body of (?...A) succeeded */
5747 sw = cBOOL(ST.wanted);
5749 else if (!ST.wanted)
5752 if (OP(ST.me) == SUSPEND)
5753 locinput = PL_reginput;
5755 locinput = PL_reginput = st->locinput;
5756 nextchr = UCHARAT(locinput);
5758 scan = ST.me + ARG(ST.me);
5761 continue; /* execute B */
5766 next = scan + ARG(scan);
5771 reginfo->cutpoint = PL_regeol;
5774 PL_reginput = locinput;
5776 sv_yes_mark = sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
5777 PUSH_STATE_GOTO(COMMIT_next,next);
5778 assert(0); /* NOTREACHED */
5779 case COMMIT_next_fail:
5784 assert(0); /* NOTREACHED */
5786 #define ST st->u.mark
5788 ST.prev_mark = mark_state;
5789 ST.mark_name = sv_commit = sv_yes_mark
5790 = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
5792 ST.mark_loc = PL_reginput = locinput;
5793 PUSH_YES_STATE_GOTO(MARKPOINT_next,next);
5794 assert(0); /* NOTREACHED */
5795 case MARKPOINT_next:
5796 mark_state = ST.prev_mark;
5798 assert(0); /* NOTREACHED */
5799 case MARKPOINT_next_fail:
5800 if (popmark && sv_eq(ST.mark_name,popmark))
5802 if (ST.mark_loc > startpoint)
5803 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
5804 popmark = NULL; /* we found our mark */
5805 sv_commit = ST.mark_name;
5808 PerlIO_printf(Perl_debug_log,
5809 "%*s %ssetting cutpoint to mark:%"SVf"...%s\n",
5810 REPORT_CODE_OFF+depth*2, "",
5811 PL_colors[4], SVfARG(sv_commit), PL_colors[5]);
5814 mark_state = ST.prev_mark;
5815 sv_yes_mark = mark_state ?
5816 mark_state->u.mark.mark_name : NULL;
5818 assert(0); /* NOTREACHED */
5820 PL_reginput = locinput;
5822 /* (*SKIP) : if we fail we cut here*/
5823 ST.mark_name = NULL;
5824 ST.mark_loc = locinput;
5825 PUSH_STATE_GOTO(SKIP_next,next);
5827 /* (*SKIP:NAME) : if there is a (*MARK:NAME) fail where it was,
5828 otherwise do nothing. Meaning we need to scan
5830 regmatch_state *cur = mark_state;
5831 SV *find = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
5834 if ( sv_eq( cur->u.mark.mark_name,
5837 ST.mark_name = find;
5838 PUSH_STATE_GOTO( SKIP_next, next );
5840 cur = cur->u.mark.prev_mark;
5843 /* Didn't find our (*MARK:NAME) so ignore this (*SKIP:NAME) */
5845 case SKIP_next_fail:
5847 /* (*CUT:NAME) - Set up to search for the name as we
5848 collapse the stack*/
5849 popmark = ST.mark_name;
5851 /* (*CUT) - No name, we cut here.*/
5852 if (ST.mark_loc > startpoint)
5853 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
5854 /* but we set sv_commit to latest mark_name if there
5855 is one so they can test to see how things lead to this
5858 sv_commit=mark_state->u.mark.mark_name;
5862 assert(0); /* NOTREACHED */
5865 if ((n=is_LNBREAK(locinput,utf8_target))) {
5867 nextchr = UCHARAT(locinput);
5872 #define CASE_CLASS(nAmE) \
5874 if (locinput >= PL_regeol) \
5876 if ((n=is_##nAmE(locinput,utf8_target))) { \
5878 nextchr = UCHARAT(locinput); \
5883 if (locinput >= PL_regeol) \
5885 if ((n=is_##nAmE(locinput,utf8_target))) { \
5888 locinput += UTF8SKIP(locinput); \
5889 nextchr = UCHARAT(locinput); \
5894 CASE_CLASS(HORIZWS);
5898 PerlIO_printf(Perl_error_log, "%"UVxf" %d\n",
5899 PTR2UV(scan), OP(scan));
5900 Perl_croak(aTHX_ "regexp memory corruption");
5904 /* switch break jumps here */
5905 scan = next; /* prepare to execute the next op and ... */
5906 continue; /* ... jump back to the top, reusing st */
5907 assert(0); /* NOTREACHED */
5910 /* push a state that backtracks on success */
5911 st->u.yes.prev_yes_state = yes_state;
5915 /* push a new regex state, then continue at scan */
5917 regmatch_state *newst;
5920 regmatch_state *cur = st;
5921 regmatch_state *curyes = yes_state;
5923 regmatch_slab *slab = PL_regmatch_slab;
5924 for (;curd > -1;cur--,curd--) {
5925 if (cur < SLAB_FIRST(slab)) {
5927 cur = SLAB_LAST(slab);
5929 PerlIO_printf(Perl_error_log, "%*s#%-3d %-10s %s\n",
5930 REPORT_CODE_OFF + 2 + depth * 2,"",
5931 curd, PL_reg_name[cur->resume_state],
5932 (curyes == cur) ? "yes" : ""
5935 curyes = cur->u.yes.prev_yes_state;
5938 DEBUG_STATE_pp("push")
5941 st->locinput = locinput;
5943 if (newst > SLAB_LAST(PL_regmatch_slab))
5944 newst = S_push_slab(aTHX);
5945 PL_regmatch_state = newst;
5947 locinput = PL_reginput;
5948 nextchr = UCHARAT(locinput);
5951 assert(0); /* NOTREACHED */
5956 * We get here only if there's trouble -- normally "case END" is
5957 * the terminating point.
5959 Perl_croak(aTHX_ "corrupted regexp pointers");
5965 /* we have successfully completed a subexpression, but we must now
5966 * pop to the state marked by yes_state and continue from there */
5967 assert(st != yes_state);
5969 while (st != yes_state) {
5971 if (st < SLAB_FIRST(PL_regmatch_slab)) {
5972 PL_regmatch_slab = PL_regmatch_slab->prev;
5973 st = SLAB_LAST(PL_regmatch_slab);
5977 DEBUG_STATE_pp("pop (no final)");
5979 DEBUG_STATE_pp("pop (yes)");
5985 while (yes_state < SLAB_FIRST(PL_regmatch_slab)
5986 || yes_state > SLAB_LAST(PL_regmatch_slab))
5988 /* not in this slab, pop slab */
5989 depth -= (st - SLAB_FIRST(PL_regmatch_slab) + 1);
5990 PL_regmatch_slab = PL_regmatch_slab->prev;
5991 st = SLAB_LAST(PL_regmatch_slab);
5993 depth -= (st - yes_state);
5996 yes_state = st->u.yes.prev_yes_state;
5997 PL_regmatch_state = st;
6000 locinput= st->locinput;
6001 nextchr = UCHARAT(locinput);
6003 state_num = st->resume_state + no_final;
6004 goto reenter_switch;
6007 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch successful!%s\n",
6008 PL_colors[4], PL_colors[5]));
6010 if (PL_reg_state.re_state_eval_setup_done) {
6011 /* each successfully executed (?{...}) block does the equivalent of
6012 * local $^R = do {...}
6013 * When popping the save stack, all these locals would be undone;
6014 * bypass this by setting the outermost saved $^R to the latest
6016 if (oreplsv != GvSV(PL_replgv))
6017 sv_setsv(oreplsv, GvSV(PL_replgv));
6024 PerlIO_printf(Perl_debug_log,
6025 "%*s %sfailed...%s\n",
6026 REPORT_CODE_OFF+depth*2, "",
6027 PL_colors[4], PL_colors[5])
6039 /* there's a previous state to backtrack to */
6041 if (st < SLAB_FIRST(PL_regmatch_slab)) {
6042 PL_regmatch_slab = PL_regmatch_slab->prev;
6043 st = SLAB_LAST(PL_regmatch_slab);
6045 PL_regmatch_state = st;
6046 locinput= st->locinput;
6047 nextchr = UCHARAT(locinput);
6049 DEBUG_STATE_pp("pop");
6051 if (yes_state == st)
6052 yes_state = st->u.yes.prev_yes_state;
6054 state_num = st->resume_state + 1; /* failure = success + 1 */
6055 goto reenter_switch;
6060 if (rex->intflags & PREGf_VERBARG_SEEN) {
6061 SV *sv_err = get_sv("REGERROR", 1);
6062 SV *sv_mrk = get_sv("REGMARK", 1);
6064 sv_commit = &PL_sv_no;
6066 sv_yes_mark = &PL_sv_yes;
6069 sv_commit = &PL_sv_yes;
6070 sv_yes_mark = &PL_sv_no;
6072 sv_setsv(sv_err, sv_commit);
6073 sv_setsv(sv_mrk, sv_yes_mark);
6077 if (last_pushed_cv) {
6080 PERL_UNUSED_VAR(SP);
6083 /* clean up; in particular, free all slabs above current one */
6084 LEAVE_SCOPE(oldsave);
6090 - regrepeat - repeatedly match something simple, report how many
6093 * [This routine now assumes that it will only match on things of length 1.
6094 * That was true before, but now we assume scan - reginput is the count,
6095 * rather than incrementing count on every character. [Er, except utf8.]]
6098 S_regrepeat(pTHX_ const regexp *prog, const regnode *p, I32 max, int depth)
6103 char *loceol = PL_regeol;
6105 bool utf8_target = PL_reg_match_utf8;
6108 PERL_UNUSED_ARG(depth);
6111 PERL_ARGS_ASSERT_REGREPEAT;
6114 if (max == REG_INFTY)
6116 else if (max < loceol - scan)
6117 loceol = scan + max;
6122 while (scan < loceol && hardcount < max && *scan != '\n') {
6123 scan += UTF8SKIP(scan);
6127 while (scan < loceol && *scan != '\n')
6134 while (scan < loceol && hardcount < max) {
6135 scan += UTF8SKIP(scan);
6146 /* To get here, EXACTish nodes must have *byte* length == 1. That
6147 * means they match only characters in the string that can be expressed
6148 * as a single byte. For non-utf8 strings, that means a simple match.
6149 * For utf8 strings, the character matched must be an invariant, or
6150 * downgradable to a single byte. The pattern's utf8ness is
6151 * irrelevant, as since it's a single byte, it either isn't utf8, or if
6152 * it is, it's an invariant */
6155 assert(! UTF_PATTERN || UNI_IS_INVARIANT(c));
6157 if (! utf8_target || UNI_IS_INVARIANT(c)) {
6158 while (scan < loceol && UCHARAT(scan) == c) {
6164 /* Here, the string is utf8, and the pattern char is different
6165 * in utf8 than not, so can't compare them directly. Outside the
6166 * loop, find the two utf8 bytes that represent c, and then
6167 * look for those in sequence in the utf8 string */
6168 U8 high = UTF8_TWO_BYTE_HI(c);
6169 U8 low = UTF8_TWO_BYTE_LO(c);
6172 while (hardcount < max
6173 && scan + 1 < loceol
6174 && UCHARAT(scan) == high
6175 && UCHARAT(scan + 1) == low)
6183 utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
6187 PL_reg_flags |= RF_tainted;
6188 utf8_flags = FOLDEQ_UTF8_LOCALE;
6196 case EXACTFU_TRICKYFOLD:
6198 utf8_flags = (UTF_PATTERN) ? FOLDEQ_S2_ALREADY_FOLDED : 0;
6200 /* The comments for the EXACT case above apply as well to these fold
6205 assert(! UTF_PATTERN || UNI_IS_INVARIANT(c));
6207 if (utf8_target || OP(p) == EXACTFU_SS) { /* Use full Unicode fold matching */
6208 char *tmpeol = loceol;
6209 while (hardcount < max
6210 && foldEQ_utf8_flags(scan, &tmpeol, 0, utf8_target,
6211 STRING(p), NULL, 1, cBOOL(UTF_PATTERN), utf8_flags))
6218 /* XXX Note that the above handles properly the German sharp s in
6219 * the pattern matching ss in the string. But it doesn't handle
6220 * properly cases where the string contains say 'LIGATURE ff' and
6221 * the pattern is 'f+'. This would require, say, a new function or
6222 * revised interface to foldEQ_utf8(), in which the maximum number
6223 * of characters to match could be passed and it would return how
6224 * many actually did. This is just one of many cases where
6225 * multi-char folds don't work properly, and so the fix is being
6231 /* Here, the string isn't utf8 and c is a single byte; and either
6232 * the pattern isn't utf8 or c is an invariant, so its utf8ness
6233 * doesn't affect c. Can just do simple comparisons for exact or
6236 case EXACTF: folded = PL_fold[c]; break;
6238 case EXACTFU_TRICKYFOLD:
6239 case EXACTFU: folded = PL_fold_latin1[c]; break;
6240 case EXACTFL: folded = PL_fold_locale[c]; break;
6241 default: Perl_croak(aTHX_ "panic: Unexpected op %u", OP(p));
6243 while (scan < loceol &&
6244 (UCHARAT(scan) == c || UCHARAT(scan) == folded))
6252 if (utf8_target || OP(p) == ANYOFV) {
6255 inclasslen = loceol - scan;
6256 while (hardcount < max
6257 && ((inclasslen = loceol - scan) > 0)
6258 && reginclass(prog, p, (U8*)scan, &inclasslen, utf8_target))
6264 while (scan < loceol && REGINCLASS(prog, p, (U8*)scan))
6272 LOAD_UTF8_CHARCLASS_ALNUM();
6273 while (hardcount < max && scan < loceol &&
6274 swash_fetch(PL_utf8_alnum, (U8*)scan, utf8_target))
6276 scan += UTF8SKIP(scan);
6280 while (scan < loceol && isWORDCHAR_L1((U8) *scan)) {
6288 while (scan < loceol && isALNUM((U8) *scan)) {
6293 while (scan < loceol && isWORDCHAR_A((U8) *scan)) {
6298 PL_reg_flags |= RF_tainted;
6301 while (hardcount < max && scan < loceol &&
6302 isALNUM_LC_utf8((U8*)scan)) {
6303 scan += UTF8SKIP(scan);
6307 while (scan < loceol && isALNUM_LC(*scan))
6317 LOAD_UTF8_CHARCLASS_ALNUM();
6318 while (hardcount < max && scan < loceol &&
6319 ! swash_fetch(PL_utf8_alnum, (U8*)scan, utf8_target))
6321 scan += UTF8SKIP(scan);
6325 while (scan < loceol && ! isWORDCHAR_L1((U8) *scan)) {
6332 goto utf8_Nwordchar;
6333 while (scan < loceol && ! isALNUM((U8) *scan)) {
6339 while (scan < loceol && _generic_isCC_A((U8) *scan, FLAGS(p))) {
6345 while (scan < loceol && ! _generic_isCC_A((U8) *scan, FLAGS(p))) {
6346 scan += UTF8SKIP(scan);
6350 while (scan < loceol && ! _generic_isCC_A((U8) *scan, FLAGS(p))) {
6357 while (scan < loceol && ! isWORDCHAR_A((U8) *scan)) {
6358 scan += UTF8SKIP(scan);
6362 while (scan < loceol && ! isWORDCHAR_A((U8) *scan)) {
6368 PL_reg_flags |= RF_tainted;
6371 while (hardcount < max && scan < loceol &&
6372 !isALNUM_LC_utf8((U8*)scan)) {
6373 scan += UTF8SKIP(scan);
6377 while (scan < loceol && !isALNUM_LC(*scan))
6387 LOAD_UTF8_CHARCLASS_SPACE();
6388 while (hardcount < max && scan < loceol &&
6390 swash_fetch(PL_utf8_space,(U8*)scan, utf8_target)))
6392 scan += UTF8SKIP(scan);
6398 while (scan < loceol && isSPACE_L1((U8) *scan)) {
6407 while (scan < loceol && isSPACE((U8) *scan)) {
6412 while (scan < loceol && isSPACE_A((U8) *scan)) {
6417 PL_reg_flags |= RF_tainted;
6420 while (hardcount < max && scan < loceol &&
6421 isSPACE_LC_utf8((U8*)scan)) {
6422 scan += UTF8SKIP(scan);
6426 while (scan < loceol && isSPACE_LC(*scan))
6436 LOAD_UTF8_CHARCLASS_SPACE();
6437 while (hardcount < max && scan < loceol &&
6439 swash_fetch(PL_utf8_space,(U8*)scan, utf8_target)))
6441 scan += UTF8SKIP(scan);
6447 while (scan < loceol && ! isSPACE_L1((U8) *scan)) {
6456 while (scan < loceol && ! isSPACE((U8) *scan)) {
6462 while (scan < loceol && ! isSPACE_A((U8) *scan)) {
6463 scan += UTF8SKIP(scan);
6467 while (scan < loceol && ! isSPACE_A((U8) *scan)) {
6473 PL_reg_flags |= RF_tainted;
6476 while (hardcount < max && scan < loceol &&
6477 !isSPACE_LC_utf8((U8*)scan)) {
6478 scan += UTF8SKIP(scan);
6482 while (scan < loceol && !isSPACE_LC(*scan))
6489 LOAD_UTF8_CHARCLASS_DIGIT();
6490 while (hardcount < max && scan < loceol &&
6491 swash_fetch(PL_utf8_digit, (U8*)scan, utf8_target)) {
6492 scan += UTF8SKIP(scan);
6496 while (scan < loceol && isDIGIT(*scan))
6501 while (scan < loceol && isDIGIT_A((U8) *scan)) {
6506 PL_reg_flags |= RF_tainted;
6509 while (hardcount < max && scan < loceol &&
6510 isDIGIT_LC_utf8((U8*)scan)) {
6511 scan += UTF8SKIP(scan);
6515 while (scan < loceol && isDIGIT_LC(*scan))
6522 LOAD_UTF8_CHARCLASS_DIGIT();
6523 while (hardcount < max && scan < loceol &&
6524 !swash_fetch(PL_utf8_digit, (U8*)scan, utf8_target)) {
6525 scan += UTF8SKIP(scan);
6529 while (scan < loceol && !isDIGIT(*scan))
6535 while (scan < loceol && ! isDIGIT_A((U8) *scan)) {
6536 scan += UTF8SKIP(scan);
6540 while (scan < loceol && ! isDIGIT_A((U8) *scan)) {
6546 PL_reg_flags |= RF_tainted;
6549 while (hardcount < max && scan < loceol &&
6550 !isDIGIT_LC_utf8((U8*)scan)) {
6551 scan += UTF8SKIP(scan);
6555 while (scan < loceol && !isDIGIT_LC(*scan))
6562 while (hardcount < max && scan < loceol && (c=is_LNBREAK_utf8(scan))) {
6568 LNBREAK can match two latin chars, which is ok,
6569 because we have a null terminated string, but we
6570 have to use hardcount in this situation
6572 while (scan < loceol && (c=is_LNBREAK_latin1(scan))) {
6581 while (hardcount < max && scan < loceol && (c=is_HORIZWS_utf8(scan))) {
6586 while (scan < loceol && is_HORIZWS_latin1(scan))
6593 while (hardcount < max && scan < loceol && !is_HORIZWS_utf8(scan)) {
6594 scan += UTF8SKIP(scan);
6598 while (scan < loceol && !is_HORIZWS_latin1(scan))
6606 while (hardcount < max && scan < loceol && (c=is_VERTWS_utf8(scan))) {
6611 while (scan < loceol && is_VERTWS_latin1(scan))
6619 while (hardcount < max && scan < loceol && !is_VERTWS_utf8(scan)) {
6620 scan += UTF8SKIP(scan);
6624 while (scan < loceol && !is_VERTWS_latin1(scan))
6630 default: /* Called on something of 0 width. */
6631 break; /* So match right here or not at all. */
6637 c = scan - PL_reginput;
6641 GET_RE_DEBUG_FLAGS_DECL;
6643 SV * const prop = sv_newmortal();
6644 regprop(prog, prop, p);
6645 PerlIO_printf(Perl_debug_log,
6646 "%*s %s can match %"IVdf" times out of %"IVdf"...\n",
6647 REPORT_CODE_OFF + depth*2, "", SvPVX_const(prop),(IV)c,(IV)max);
6655 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
6657 - regclass_swash - prepare the utf8 swash. Wraps the shared core version to
6658 create a copy so that changes the caller makes won't change the shared one
6661 Perl_regclass_swash(pTHX_ const regexp *prog, register const regnode* node, bool doinit, SV** listsvp, SV **altsvp)
6663 PERL_ARGS_ASSERT_REGCLASS_SWASH;
6664 return newSVsv(core_regclass_swash(prog, node, doinit, listsvp, altsvp));
6669 S_core_regclass_swash(pTHX_ const regexp *prog, register const regnode* node, bool doinit, SV** listsvp, SV **altsvp)
6671 /* Returns the swash for the input 'node' in the regex 'prog'.
6672 * If <doinit> is true, will attempt to create the swash if not already
6674 * If <listsvp> is non-null, will return the swash initialization string in
6676 * If <altsvp> is non-null, will return the alternates to the regular swash
6678 * Tied intimately to how regcomp.c sets up the data structure */
6686 RXi_GET_DECL(prog,progi);
6687 const struct reg_data * const data = prog ? progi->data : NULL;
6689 PERL_ARGS_ASSERT_CORE_REGCLASS_SWASH;
6691 assert(ANYOF_NONBITMAP(node));
6693 if (data && data->count) {
6694 const U32 n = ARG(node);
6696 if (data->what[n] == 's') {
6697 SV * const rv = MUTABLE_SV(data->data[n]);
6698 AV * const av = MUTABLE_AV(SvRV(rv));
6699 SV **const ary = AvARRAY(av);
6700 bool invlist_has_user_defined_property;
6702 si = *ary; /* ary[0] = the string to initialize the swash with */
6704 /* Elements 3 and 4 are either both present or both absent. [3] is
6705 * any inversion list generated at compile time; [4] indicates if
6706 * that inversion list has any user-defined properties in it. */
6707 if (av_len(av) >= 3) {
6709 invlist_has_user_defined_property = cBOOL(SvUV(ary[4]));
6713 invlist_has_user_defined_property = FALSE;
6716 /* Element [1] is reserved for the set-up swash. If already there,
6717 * return it; if not, create it and store it there */
6718 if (SvROK(ary[1])) {
6721 else if (si && doinit) {
6723 sw = _core_swash_init("utf8", /* the utf8 package */
6727 0, /* not from tr/// */
6728 FALSE, /* is error if can't find
6731 invlist_has_user_defined_property);
6732 (void)av_store(av, 1, sw);
6735 /* Element [2] is for any multi-char folds. Note that is a
6736 * fundamentally flawed design, because can't backtrack and try
6737 * again. See [perl #89774] */
6738 if (SvTYPE(ary[2]) == SVt_PVAV) {
6745 SV* matches_string = newSVpvn("", 0);
6748 /* Use the swash, if any, which has to have incorporated into it all
6752 && SvTYPE(SvRV(sw)) == SVt_PVHV
6753 && (invlistsvp = hv_fetchs(MUTABLE_HV(SvRV(sw)), "INVLIST", FALSE)))
6755 invlist = *invlistsvp;
6757 else if (si && si != &PL_sv_undef) {
6759 /* If no swash, use the input nitialization string, if available */
6760 sv_catsv(matches_string, si);
6763 /* Add the inversion list to whatever we have. This may have come from
6764 * the swash, or from an input parameter */
6766 sv_catsv(matches_string, _invlist_contents(invlist));
6768 *listsvp = matches_string;
6778 - reginclass - determine if a character falls into a character class
6780 n is the ANYOF regnode
6781 p is the target string
6782 lenp is pointer to the maximum number of bytes of how far to go in p
6783 (This is assumed wthout checking to always be at least the current
6785 utf8_target tells whether p is in UTF-8.
6787 Returns true if matched; false otherwise. If lenp is not NULL, on return
6788 from a successful match, the value it points to will be updated to how many
6789 bytes in p were matched. If there was no match, the value is undefined,
6790 possibly changed from the input.
6792 Note that this can be a synthetic start class, a combination of various
6793 nodes, so things you think might be mutually exclusive, such as locale,
6794 aren't. It can match both locale and non-locale
6799 S_reginclass(pTHX_ const regexp * const prog, register const regnode * const n, register const U8* const p, STRLEN* lenp, register const bool utf8_target)
6802 const char flags = ANYOF_FLAGS(n);
6808 PERL_ARGS_ASSERT_REGINCLASS;
6810 /* If c is not already the code point, get it */
6811 if (utf8_target && !UTF8_IS_INVARIANT(c)) {
6812 c = utf8n_to_uvchr(p, UTF8_MAXBYTES, &c_len,
6813 (UTF8_ALLOW_DEFAULT & UTF8_ALLOW_ANYUV)
6814 | UTF8_ALLOW_FFFF | UTF8_CHECK_ONLY);
6815 /* see [perl #37836] for UTF8_ALLOW_ANYUV; [perl #38293] for
6816 * UTF8_ALLOW_FFFF */
6817 if (c_len == (STRLEN)-1)
6818 Perl_croak(aTHX_ "Malformed UTF-8 character (fatal)");
6824 /* Use passed in max length, or one character if none passed in or less
6825 * than one character. And assume will match just one character. This is
6826 * overwritten later if matched more. */
6828 maxlen = (*lenp > c_len) ? *lenp : c_len;
6836 /* If this character is potentially in the bitmap, check it */
6838 if (ANYOF_BITMAP_TEST(n, c))
6840 else if (flags & ANYOF_NON_UTF8_LATIN1_ALL
6847 else if (flags & ANYOF_LOCALE) {
6848 PL_reg_flags |= RF_tainted;
6850 if ((flags & ANYOF_LOC_NONBITMAP_FOLD)
6851 && ANYOF_BITMAP_TEST(n, PL_fold_locale[c]))
6855 else if (ANYOF_CLASS_TEST_ANY_SET(n) &&
6856 ((ANYOF_CLASS_TEST(n, ANYOF_ALNUM) && isALNUM_LC(c)) ||
6857 (ANYOF_CLASS_TEST(n, ANYOF_NALNUM) && !isALNUM_LC(c)) ||
6858 (ANYOF_CLASS_TEST(n, ANYOF_SPACE) && isSPACE_LC(c)) ||
6859 (ANYOF_CLASS_TEST(n, ANYOF_NSPACE) && !isSPACE_LC(c)) ||
6860 (ANYOF_CLASS_TEST(n, ANYOF_DIGIT) && isDIGIT_LC(c)) ||
6861 (ANYOF_CLASS_TEST(n, ANYOF_NDIGIT) && !isDIGIT_LC(c)) ||
6862 (ANYOF_CLASS_TEST(n, ANYOF_ALNUMC) && isALNUMC_LC(c)) ||
6863 (ANYOF_CLASS_TEST(n, ANYOF_NALNUMC) && !isALNUMC_LC(c)) ||
6864 (ANYOF_CLASS_TEST(n, ANYOF_ALPHA) && isALPHA_LC(c)) ||
6865 (ANYOF_CLASS_TEST(n, ANYOF_NALPHA) && !isALPHA_LC(c)) ||
6866 (ANYOF_CLASS_TEST(n, ANYOF_ASCII) && isASCII_LC(c)) ||
6867 (ANYOF_CLASS_TEST(n, ANYOF_NASCII) && !isASCII_LC(c)) ||
6868 (ANYOF_CLASS_TEST(n, ANYOF_CNTRL) && isCNTRL_LC(c)) ||
6869 (ANYOF_CLASS_TEST(n, ANYOF_NCNTRL) && !isCNTRL_LC(c)) ||
6870 (ANYOF_CLASS_TEST(n, ANYOF_GRAPH) && isGRAPH_LC(c)) ||
6871 (ANYOF_CLASS_TEST(n, ANYOF_NGRAPH) && !isGRAPH_LC(c)) ||
6872 (ANYOF_CLASS_TEST(n, ANYOF_LOWER) && isLOWER_LC(c)) ||
6873 (ANYOF_CLASS_TEST(n, ANYOF_NLOWER) && !isLOWER_LC(c)) ||
6874 (ANYOF_CLASS_TEST(n, ANYOF_PRINT) && isPRINT_LC(c)) ||
6875 (ANYOF_CLASS_TEST(n, ANYOF_NPRINT) && !isPRINT_LC(c)) ||
6876 (ANYOF_CLASS_TEST(n, ANYOF_PUNCT) && isPUNCT_LC(c)) ||
6877 (ANYOF_CLASS_TEST(n, ANYOF_NPUNCT) && !isPUNCT_LC(c)) ||
6878 (ANYOF_CLASS_TEST(n, ANYOF_UPPER) && isUPPER_LC(c)) ||
6879 (ANYOF_CLASS_TEST(n, ANYOF_NUPPER) && !isUPPER_LC(c)) ||
6880 (ANYOF_CLASS_TEST(n, ANYOF_XDIGIT) && isXDIGIT(c)) ||
6881 (ANYOF_CLASS_TEST(n, ANYOF_NXDIGIT) && !isXDIGIT(c)) ||
6882 (ANYOF_CLASS_TEST(n, ANYOF_PSXSPC) && isPSXSPC(c)) ||
6883 (ANYOF_CLASS_TEST(n, ANYOF_NPSXSPC) && !isPSXSPC(c)) ||
6884 (ANYOF_CLASS_TEST(n, ANYOF_BLANK) && isBLANK_LC(c)) ||
6885 (ANYOF_CLASS_TEST(n, ANYOF_NBLANK) && !isBLANK_LC(c))
6886 ) /* How's that for a conditional? */
6893 /* If the bitmap didn't (or couldn't) match, and something outside the
6894 * bitmap could match, try that. Locale nodes specifiy completely the
6895 * behavior of code points in the bit map (otherwise, a utf8 target would
6896 * cause them to be treated as Unicode and not locale), except in
6897 * the very unlikely event when this node is a synthetic start class, which
6898 * could be a combination of locale and non-locale nodes. So allow locale
6899 * to match for the synthetic start class, which will give a false
6900 * positive that will be resolved when the match is done again as not part
6901 * of the synthetic start class */
6903 if (utf8_target && (flags & ANYOF_UNICODE_ALL) && c >= 256) {
6904 match = TRUE; /* Everything above 255 matches */
6906 else if (ANYOF_NONBITMAP(n)
6907 && ((flags & ANYOF_NONBITMAP_NON_UTF8)
6910 || (! (flags & ANYOF_LOCALE))
6911 || (flags & ANYOF_IS_SYNTHETIC)))))
6914 SV * const sw = core_regclass_swash(prog, n, TRUE, 0, (SV**)&av);
6922 /* Not utf8. Convert as much of the string as available up
6923 * to the limit of how far the (single) character in the
6924 * pattern can possibly match (no need to go further). If
6925 * the node is a straight ANYOF or not folding, it can't
6926 * match more than one. Otherwise, It can match up to how
6927 * far a single char can fold to. Since not utf8, each
6928 * character is a single byte, so the max it can be in
6929 * bytes is the same as the max it can be in characters */
6930 STRLEN len = (OP(n) == ANYOF
6931 || ! (flags & ANYOF_LOC_NONBITMAP_FOLD))
6933 : (maxlen < UTF8_MAX_FOLD_CHAR_EXPAND)
6935 : UTF8_MAX_FOLD_CHAR_EXPAND;
6936 utf8_p = bytes_to_utf8(p, &len);
6939 if (swash_fetch(sw, utf8_p, TRUE))
6941 else if (flags & ANYOF_LOC_NONBITMAP_FOLD) {
6943 /* Here, we need to test if the fold of the target string
6944 * matches. The non-multi char folds have all been moved to
6945 * the compilation phase, and the multi-char folds have
6946 * been stored by regcomp into 'av'; we linearly check to
6947 * see if any match the target string (folded). We know
6948 * that the originals were each one character, but we don't
6949 * currently know how many characters/bytes each folded to,
6950 * except we do know that there are small limits imposed by
6951 * Unicode. XXX A performance enhancement would be to have
6952 * regcomp.c store the max number of chars/bytes that are
6953 * in an av entry, as, say the 0th element. Even better
6954 * would be to have a hash of the few characters that can
6955 * start a multi-char fold to the max number of chars of
6958 * If there is a match, we will need to advance (if lenp is
6959 * specified) the match pointer in the target string. But
6960 * what we are comparing here isn't that string directly,
6961 * but its fold, whose length may differ from the original.
6962 * As we go along in constructing the fold, therefore, we
6963 * create a map so that we know how many bytes in the
6964 * source to advance given that we have matched a certain
6965 * number of bytes in the fold. This map is stored in
6966 * 'map_fold_len_back'. Let n mean the number of bytes in
6967 * the fold of the first character that we are folding.
6968 * Then map_fold_len_back[n] is set to the number of bytes
6969 * in that first character. Similarly let m be the
6970 * corresponding number for the second character to be
6971 * folded. Then map_fold_len_back[n+m] is set to the
6972 * number of bytes occupied by the first two source
6973 * characters. ... */
6974 U8 map_fold_len_back[UTF8_MAXBYTES_CASE+1] = { 0 };
6975 U8 folded[UTF8_MAXBYTES_CASE+1];
6976 STRLEN foldlen = 0; /* num bytes in fold of 1st char */
6977 STRLEN total_foldlen = 0; /* num bytes in fold of all
6980 if (OP(n) == ANYOF || maxlen == 1 || ! lenp || ! av) {
6982 /* Here, only need to fold the first char of the target
6983 * string. It the source wasn't utf8, is 1 byte long */
6984 to_utf8_fold(utf8_p, folded, &foldlen);
6985 total_foldlen = foldlen;
6986 map_fold_len_back[foldlen] = (utf8_target)
6992 /* Here, need to fold more than the first char. Do so
6993 * up to the limits */
6994 U8* source_ptr = utf8_p; /* The source for the fold
6997 U8* folded_ptr = folded;
6998 U8* e = utf8_p + maxlen; /* Can't go beyond last
6999 available byte in the
7003 i < UTF8_MAX_FOLD_CHAR_EXPAND && source_ptr < e;
7007 /* Fold the next character */
7008 U8 this_char_folded[UTF8_MAXBYTES_CASE+1];
7009 STRLEN this_char_foldlen;
7010 to_utf8_fold(source_ptr,
7012 &this_char_foldlen);
7014 /* Bail if it would exceed the byte limit for
7015 * folding a single char. */
7016 if (this_char_foldlen + folded_ptr - folded >
7022 /* Add the fold of this character */
7023 Copy(this_char_folded,
7027 source_ptr += UTF8SKIP(source_ptr);
7028 folded_ptr += this_char_foldlen;
7029 total_foldlen = folded_ptr - folded;
7031 /* Create map from the number of bytes in the fold
7032 * back to the number of bytes in the source. If
7033 * the source isn't utf8, the byte count is just
7034 * the number of characters so far */
7035 map_fold_len_back[total_foldlen]
7037 ? source_ptr - utf8_p
7044 /* Do the linear search to see if the fold is in the list
7045 * of multi-char folds. */
7048 for (i = 0; i <= av_len(av); i++) {
7049 SV* const sv = *av_fetch(av, i, FALSE);
7051 const char * const s = SvPV_const(sv, len);
7053 if (len <= total_foldlen
7054 && memEQ(s, (char*)folded, len)
7056 /* If 0, means matched a partial char. See
7058 && map_fold_len_back[len])
7061 /* Advance the target string ptr to account for
7062 * this fold, but have to translate from the
7063 * folded length to the corresponding source
7066 *lenp = map_fold_len_back[len];
7075 /* If we allocated a string above, free it */
7076 if (! utf8_target) Safefree(utf8_p);
7080 if (UNICODE_IS_SUPER(c)
7081 && (flags & ANYOF_WARN_SUPER)
7082 && ckWARN_d(WARN_NON_UNICODE))
7084 Perl_warner(aTHX_ packWARN(WARN_NON_UNICODE),
7085 "Code point 0x%04"UVXf" is not Unicode, all \\p{} matches fail; all \\P{} matches succeed", c);
7089 return (flags & ANYOF_INVERT) ? !match : match;
7093 S_reghop3(U8 *s, I32 off, const U8* lim)
7095 /* return the position 'off' UTF-8 characters away from 's', forward if
7096 * 'off' >= 0, backwards if negative. But don't go outside of position
7097 * 'lim', which better be < s if off < 0 */
7101 PERL_ARGS_ASSERT_REGHOP3;
7104 while (off-- && s < lim) {
7105 /* XXX could check well-formedness here */
7110 while (off++ && s > lim) {
7112 if (UTF8_IS_CONTINUED(*s)) {
7113 while (s > lim && UTF8_IS_CONTINUATION(*s))
7116 /* XXX could check well-formedness here */
7123 /* there are a bunch of places where we use two reghop3's that should
7124 be replaced with this routine. but since thats not done yet
7125 we ifdef it out - dmq
7128 S_reghop4(U8 *s, I32 off, const U8* llim, const U8* rlim)
7132 PERL_ARGS_ASSERT_REGHOP4;
7135 while (off-- && s < rlim) {
7136 /* XXX could check well-formedness here */
7141 while (off++ && s > llim) {
7143 if (UTF8_IS_CONTINUED(*s)) {
7144 while (s > llim && UTF8_IS_CONTINUATION(*s))
7147 /* XXX could check well-formedness here */
7155 S_reghopmaybe3(U8* s, I32 off, const U8* lim)
7159 PERL_ARGS_ASSERT_REGHOPMAYBE3;
7162 while (off-- && s < lim) {
7163 /* XXX could check well-formedness here */
7170 while (off++ && s > lim) {
7172 if (UTF8_IS_CONTINUED(*s)) {
7173 while (s > lim && UTF8_IS_CONTINUATION(*s))
7176 /* XXX could check well-formedness here */
7185 restore_pos(pTHX_ void *arg)
7188 regexp * const rex = (regexp *)arg;
7189 if (PL_reg_state.re_state_eval_setup_done) {
7190 if (PL_reg_oldsaved) {
7191 rex->subbeg = PL_reg_oldsaved;
7192 rex->sublen = PL_reg_oldsavedlen;
7193 #ifdef PERL_OLD_COPY_ON_WRITE
7194 rex->saved_copy = PL_nrs;
7196 RXp_MATCH_COPIED_on(rex);
7198 PL_reg_magic->mg_len = PL_reg_oldpos;
7199 PL_reg_state.re_state_eval_setup_done = FALSE;
7200 PL_curpm = PL_reg_oldcurpm;
7205 S_to_utf8_substr(pTHX_ register regexp *prog)
7209 PERL_ARGS_ASSERT_TO_UTF8_SUBSTR;
7212 if (prog->substrs->data[i].substr
7213 && !prog->substrs->data[i].utf8_substr) {
7214 SV* const sv = newSVsv(prog->substrs->data[i].substr);
7215 prog->substrs->data[i].utf8_substr = sv;
7216 sv_utf8_upgrade(sv);
7217 if (SvVALID(prog->substrs->data[i].substr)) {
7218 if (SvTAIL(prog->substrs->data[i].substr)) {
7219 /* Trim the trailing \n that fbm_compile added last
7221 SvCUR_set(sv, SvCUR(sv) - 1);
7222 /* Whilst this makes the SV technically "invalid" (as its
7223 buffer is no longer followed by "\0") when fbm_compile()
7224 adds the "\n" back, a "\0" is restored. */
7225 fbm_compile(sv, FBMcf_TAIL);
7229 if (prog->substrs->data[i].substr == prog->check_substr)
7230 prog->check_utf8 = sv;
7236 S_to_byte_substr(pTHX_ register regexp *prog)
7241 PERL_ARGS_ASSERT_TO_BYTE_SUBSTR;
7244 if (prog->substrs->data[i].utf8_substr
7245 && !prog->substrs->data[i].substr) {
7246 SV* sv = newSVsv(prog->substrs->data[i].utf8_substr);
7247 if (sv_utf8_downgrade(sv, TRUE)) {
7248 if (SvVALID(prog->substrs->data[i].utf8_substr)) {
7249 if (SvTAIL(prog->substrs->data[i].utf8_substr)) {
7250 /* Trim the trailing \n that fbm_compile added last
7252 SvCUR_set(sv, SvCUR(sv) - 1);
7253 fbm_compile(sv, FBMcf_TAIL);
7261 prog->substrs->data[i].substr = sv;
7262 if (prog->substrs->data[i].utf8_substr == prog->check_utf8)
7263 prog->check_substr = sv;
7270 * c-indentation-style: bsd
7272 * indent-tabs-mode: nil
7275 * ex: set ts=8 sts=4 sw=4 et: