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
77 #ifdef PERL_IN_XSUB_RE
83 #include "inline_invlist.c"
85 #define RF_tainted 1 /* tainted information used? e.g. locale */
86 #define RF_warned 2 /* warned about big count? */
88 #define RF_utf8 8 /* Pattern contains multibyte chars? */
90 #define UTF_PATTERN ((PL_reg_flags & RF_utf8) != 0)
96 /* Valid for non-utf8 strings, non-ANYOFV nodes only: avoids the reginclass
97 * call if there are no complications: i.e., if everything matchable is
98 * straight forward in the bitmap */
99 #define REGINCLASS(prog,p,c) (ANYOF_FLAGS(p) ? reginclass(prog,p,c,0,0) \
100 : ANYOF_BITMAP_TEST(p,*(c)))
106 #define CHR_SVLEN(sv) (utf8_target ? sv_len_utf8(sv) : SvCUR(sv))
107 #define CHR_DIST(a,b) (PL_reg_match_utf8 ? utf8_distance(a,b) : a - b)
109 #define HOPc(pos,off) \
110 (char *)(PL_reg_match_utf8 \
111 ? reghop3((U8*)pos, off, (U8*)(off >= 0 ? PL_regeol : PL_bostr)) \
113 #define HOPBACKc(pos, off) \
114 (char*)(PL_reg_match_utf8\
115 ? reghopmaybe3((U8*)pos, -off, (U8*)PL_bostr) \
116 : (pos - off >= PL_bostr) \
120 #define HOP3(pos,off,lim) (PL_reg_match_utf8 ? reghop3((U8*)(pos), off, (U8*)(lim)) : (U8*)(pos + off))
121 #define HOP3c(pos,off,lim) ((char*)HOP3(pos,off,lim))
123 /* these are unrolled below in the CCC_TRY_XXX defined */
125 /* Often 'str' is a hard-coded utf8 string instead of utfebcdic. so just
126 * skip the check on EBCDIC platforms */
127 # define LOAD_UTF8_CHARCLASS(class,str) LOAD_UTF8_CHARCLASS_NO_CHECK(class)
129 # define LOAD_UTF8_CHARCLASS(class,str) STMT_START { \
130 if (!CAT2(PL_utf8_,class)) { \
132 ENTER; save_re_context(); \
133 ok=CAT2(is_utf8_,class)((const U8*)str); \
134 PERL_UNUSED_VAR(ok); \
135 assert(ok); assert(CAT2(PL_utf8_,class)); LEAVE; } } STMT_END
138 /* Doesn't do an assert to verify that is correct */
139 #define LOAD_UTF8_CHARCLASS_NO_CHECK(class) STMT_START { \
140 if (!CAT2(PL_utf8_,class)) { \
141 bool throw_away PERL_UNUSED_DECL; \
142 ENTER; save_re_context(); \
143 throw_away = CAT2(is_utf8_,class)((const U8*)" "); \
146 #define LOAD_UTF8_CHARCLASS_ALNUM() LOAD_UTF8_CHARCLASS(alnum,"a")
147 #define LOAD_UTF8_CHARCLASS_DIGIT() LOAD_UTF8_CHARCLASS(digit,"0")
148 #define LOAD_UTF8_CHARCLASS_SPACE() LOAD_UTF8_CHARCLASS(space," ")
150 #define LOAD_UTF8_CHARCLASS_GCB() /* Grapheme cluster boundaries */ \
151 LOAD_UTF8_CHARCLASS(X_begin, " "); \
152 LOAD_UTF8_CHARCLASS(X_non_hangul, "A"); \
153 /* These are utf8 constants, and not utf-ebcdic constants, so the \
154 * assert should likely and hopefully fail on an EBCDIC machine */ \
155 LOAD_UTF8_CHARCLASS(X_extend, "\xcc\x80"); /* U+0300 */ \
157 /* No asserts are done for these, in case called on an early \
158 * Unicode version in which they map to nothing */ \
159 LOAD_UTF8_CHARCLASS_NO_CHECK(X_prepend);/* U+0E40 "\xe0\xb9\x80" */ \
160 LOAD_UTF8_CHARCLASS_NO_CHECK(X_L); /* U+1100 "\xe1\x84\x80" */ \
161 LOAD_UTF8_CHARCLASS_NO_CHECK(X_LV_LVT_V);/* U+AC01 "\xea\xb0\x81" */\
162 LOAD_UTF8_CHARCLASS_NO_CHECK(X_T); /* U+11A8 "\xe1\x86\xa8" */ \
163 LOAD_UTF8_CHARCLASS_NO_CHECK(X_V) /* U+1160 "\xe1\x85\xa0" */
165 #define PLACEHOLDER /* Something for the preprocessor to grab onto */
167 /* The actual code for CCC_TRY, which uses several variables from the routine
168 * it's callable from. It is designed to be the bulk of a case statement.
169 * FUNC is the macro or function to call on non-utf8 targets that indicate if
170 * nextchr matches the class.
171 * UTF8_TEST is the whole test string to use for utf8 targets
172 * LOAD is what to use to test, and if not present to load in the swash for the
174 * POS_OR_NEG is either empty or ! to complement the results of FUNC or
176 * The logic is: Fail if we're at the end-of-string; otherwise if the target is
177 * utf8 and a variant, load the swash if necessary and test using the utf8
178 * test. Advance to the next character if test is ok, otherwise fail; If not
179 * utf8 or an invariant under utf8, use the non-utf8 test, and fail if it
180 * fails, or advance to the next character */
182 #define _CCC_TRY_CODE(POS_OR_NEG, FUNC, UTF8_TEST, CLASS, STR) \
183 if (locinput >= PL_regeol) { \
186 if (utf8_target && UTF8_IS_CONTINUED(nextchr)) { \
187 LOAD_UTF8_CHARCLASS(CLASS, STR); \
188 if (POS_OR_NEG (UTF8_TEST)) { \
191 locinput += PL_utf8skip[nextchr]; \
192 nextchr = UCHARAT(locinput); \
195 if (POS_OR_NEG (FUNC(nextchr))) { \
198 nextchr = UCHARAT(++locinput); \
201 /* Handle the non-locale cases for a character class and its complement. It
202 * calls _CCC_TRY_CODE with a ! to complement the test for the character class.
203 * This is because that code fails when the test succeeds, so we want to have
204 * the test fail so that the code succeeds. The swash is stored in a
205 * predictable PL_ place */
206 #define _CCC_TRY_NONLOCALE(NAME, NNAME, FUNC, \
209 _CCC_TRY_CODE( !, FUNC, \
210 cBOOL(swash_fetch(CAT2(PL_utf8_,CLASS), \
211 (U8*)locinput, TRUE)), \
214 _CCC_TRY_CODE( PLACEHOLDER , FUNC, \
215 cBOOL(swash_fetch(CAT2(PL_utf8_,CLASS), \
216 (U8*)locinput, TRUE)), \
219 /* Generate the case statements for both locale and non-locale character
220 * classes in regmatch for classes that don't have special unicode semantics.
221 * Locales don't use an immediate swash, but an intermediary special locale
222 * function that is called on the pointer to the current place in the input
223 * string. That function will resolve to needing the same swash. One might
224 * think that because we don't know what the locale will match, we shouldn't
225 * check with the swash loading function that it loaded properly; ie, that we
226 * should use LOAD_UTF8_CHARCLASS_NO_CHECK for those, but what is passed to the
227 * regular LOAD_UTF8_CHARCLASS is in non-locale terms, and so locale is
229 #define CCC_TRY(NAME, NNAME, FUNC, \
230 NAMEL, NNAMEL, LCFUNC, LCFUNC_utf8, \
231 NAMEA, NNAMEA, FUNCA, \
234 PL_reg_flags |= RF_tainted; \
235 _CCC_TRY_CODE( !, LCFUNC, LCFUNC_utf8((U8*)locinput), CLASS, STR) \
237 PL_reg_flags |= RF_tainted; \
238 _CCC_TRY_CODE( PLACEHOLDER, LCFUNC, LCFUNC_utf8((U8*)locinput), \
241 if (locinput >= PL_regeol || ! FUNCA(nextchr)) { \
244 /* Matched a utf8-invariant, so don't have to worry about utf8 */ \
245 nextchr = UCHARAT(++locinput); \
248 if (locinput >= PL_regeol || FUNCA(nextchr)) { \
252 locinput += PL_utf8skip[nextchr]; \
253 nextchr = UCHARAT(locinput); \
256 nextchr = UCHARAT(++locinput); \
259 /* Generate the non-locale cases */ \
260 _CCC_TRY_NONLOCALE(NAME, NNAME, FUNC, CLASS, STR)
262 /* This is like CCC_TRY, but has an extra set of parameters for generating case
263 * statements to handle separate Unicode semantics nodes */
264 #define CCC_TRY_U(NAME, NNAME, FUNC, \
265 NAMEL, NNAMEL, LCFUNC, LCFUNC_utf8, \
266 NAMEU, NNAMEU, FUNCU, \
267 NAMEA, NNAMEA, FUNCA, \
269 CCC_TRY(NAME, NNAME, FUNC, \
270 NAMEL, NNAMEL, LCFUNC, LCFUNC_utf8, \
271 NAMEA, NNAMEA, FUNCA, \
273 _CCC_TRY_NONLOCALE(NAMEU, NNAMEU, FUNCU, CLASS, STR)
275 /* TODO: Combine JUMPABLE and HAS_TEXT to cache OP(rn) */
277 /* for use after a quantifier and before an EXACT-like node -- japhy */
278 /* it would be nice to rework regcomp.sym to generate this stuff. sigh
280 * NOTE that *nothing* that affects backtracking should be in here, specifically
281 * VERBS must NOT be included. JUMPABLE is used to determine if we can ignore a
282 * node that is in between two EXACT like nodes when ascertaining what the required
283 * "follow" character is. This should probably be moved to regex compile time
284 * although it may be done at run time beause of the REF possibility - more
285 * investigation required. -- demerphq
287 #define JUMPABLE(rn) ( \
289 (OP(rn) == CLOSE && (!cur_eval || cur_eval->u.eval.close_paren != ARG(rn))) || \
291 OP(rn) == SUSPEND || OP(rn) == IFMATCH || \
292 OP(rn) == PLUS || OP(rn) == MINMOD || \
294 (PL_regkind[OP(rn)] == CURLY && ARG1(rn) > 0) \
296 #define IS_EXACT(rn) (PL_regkind[OP(rn)] == EXACT)
298 #define HAS_TEXT(rn) ( IS_EXACT(rn) || PL_regkind[OP(rn)] == REF )
301 /* Currently these are only used when PL_regkind[OP(rn)] == EXACT so
302 we don't need this definition. */
303 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==REF || OP(rn)==NREF )
304 #define IS_TEXTF(rn) ( OP(rn)==EXACTFU || OP(rn)==EXACTFU_SS || OP(rn)==EXACTFU_TRICKYFOLD || OP(rn)==EXACTFA || OP(rn)==EXACTF || OP(rn)==REFF || OP(rn)==NREFF )
305 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL || OP(rn)==REFFL || OP(rn)==NREFFL )
308 /* ... so we use this as its faster. */
309 #define IS_TEXT(rn) ( OP(rn)==EXACT )
310 #define IS_TEXTFU(rn) ( OP(rn)==EXACTFU || OP(rn)==EXACTFU_SS || OP(rn)==EXACTFU_TRICKYFOLD || OP(rn) == EXACTFA)
311 #define IS_TEXTF(rn) ( OP(rn)==EXACTF )
312 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL )
317 Search for mandatory following text node; for lookahead, the text must
318 follow but for lookbehind (rn->flags != 0) we skip to the next step.
320 #define FIND_NEXT_IMPT(rn) STMT_START { \
321 while (JUMPABLE(rn)) { \
322 const OPCODE type = OP(rn); \
323 if (type == SUSPEND || PL_regkind[type] == CURLY) \
324 rn = NEXTOPER(NEXTOPER(rn)); \
325 else if (type == PLUS) \
327 else if (type == IFMATCH) \
328 rn = (rn->flags == 0) ? NEXTOPER(NEXTOPER(rn)) : rn + ARG(rn); \
329 else rn += NEXT_OFF(rn); \
334 static void restore_pos(pTHX_ void *arg);
336 #define REGCP_PAREN_ELEMS 3
337 #define REGCP_OTHER_ELEMS 3
338 #define REGCP_FRAME_ELEMS 1
339 /* REGCP_FRAME_ELEMS are not part of the REGCP_OTHER_ELEMS and
340 * are needed for the regexp context stack bookkeeping. */
343 S_regcppush(pTHX_ const regexp *rex, I32 parenfloor)
346 const int retval = PL_savestack_ix;
347 const int paren_elems_to_push = (PL_regsize - parenfloor) * REGCP_PAREN_ELEMS;
348 const UV total_elems = paren_elems_to_push + REGCP_OTHER_ELEMS;
349 const UV elems_shifted = total_elems << SAVE_TIGHT_SHIFT;
351 GET_RE_DEBUG_FLAGS_DECL;
353 PERL_ARGS_ASSERT_REGCPPUSH;
355 if (paren_elems_to_push < 0)
356 Perl_croak(aTHX_ "panic: paren_elems_to_push, %i < 0",
357 paren_elems_to_push);
359 if ((elems_shifted >> SAVE_TIGHT_SHIFT) != total_elems)
360 Perl_croak(aTHX_ "panic: paren_elems_to_push offset %"UVuf
361 " out of range (%lu-%ld)",
362 total_elems, (unsigned long)PL_regsize, (long)parenfloor);
364 SSGROW(total_elems + REGCP_FRAME_ELEMS);
367 if ((int)PL_regsize > (int)parenfloor)
368 PerlIO_printf(Perl_debug_log,
369 "rex=0x%"UVxf" offs=0x%"UVxf": saving capture indices:\n",
374 for (p = parenfloor+1; p <= (I32)PL_regsize; p++) {
375 /* REGCP_PARENS_ELEMS are pushed per pairs of parentheses. */
376 SSPUSHINT(rex->offs[p].end);
377 SSPUSHINT(rex->offs[p].start);
378 SSPUSHINT(rex->offs[p].start_tmp);
379 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
380 " \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"\n",
382 (IV)rex->offs[p].start,
383 (IV)rex->offs[p].start_tmp,
387 /* REGCP_OTHER_ELEMS are pushed in any case, parentheses or no. */
388 SSPUSHINT(PL_regsize);
389 SSPUSHINT(rex->lastparen);
390 SSPUSHINT(rex->lastcloseparen);
391 SSPUSHUV(SAVEt_REGCONTEXT | elems_shifted); /* Magic cookie. */
396 /* These are needed since we do not localize EVAL nodes: */
397 #define REGCP_SET(cp) \
399 PerlIO_printf(Perl_debug_log, \
400 " Setting an EVAL scope, savestack=%"IVdf"\n", \
401 (IV)PL_savestack_ix)); \
404 #define REGCP_UNWIND(cp) \
406 if (cp != PL_savestack_ix) \
407 PerlIO_printf(Perl_debug_log, \
408 " Clearing an EVAL scope, savestack=%"IVdf"..%"IVdf"\n", \
409 (IV)(cp), (IV)PL_savestack_ix)); \
412 #define UNWIND_PAREN(lp, lcp) \
413 for (n = rex->lastparen; n > lp; n--) \
414 rex->offs[n].end = -1; \
415 rex->lastparen = n; \
416 rex->lastcloseparen = lcp;
420 S_regcppop(pTHX_ regexp *rex)
425 GET_RE_DEBUG_FLAGS_DECL;
427 PERL_ARGS_ASSERT_REGCPPOP;
429 /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
431 assert((i & SAVE_MASK) == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
432 i >>= SAVE_TIGHT_SHIFT; /* Parentheses elements to pop. */
433 rex->lastcloseparen = SSPOPINT;
434 rex->lastparen = SSPOPINT;
435 PL_regsize = SSPOPINT;
437 i -= REGCP_OTHER_ELEMS;
438 /* Now restore the parentheses context. */
440 if (i || rex->lastparen + 1 <= rex->nparens)
441 PerlIO_printf(Perl_debug_log,
442 "rex=0x%"UVxf" offs=0x%"UVxf": restoring capture indices to:\n",
448 for ( ; i > 0; i -= REGCP_PAREN_ELEMS) {
450 rex->offs[paren].start_tmp = SSPOPINT;
451 rex->offs[paren].start = SSPOPINT;
453 if (paren <= rex->lastparen)
454 rex->offs[paren].end = tmps;
455 DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
456 " \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"%s\n",
458 (IV)rex->offs[paren].start,
459 (IV)rex->offs[paren].start_tmp,
460 (IV)rex->offs[paren].end,
461 (paren > rex->lastparen ? "(skipped)" : ""));
466 /* It would seem that the similar code in regtry()
467 * already takes care of this, and in fact it is in
468 * a better location to since this code can #if 0-ed out
469 * but the code in regtry() is needed or otherwise tests
470 * requiring null fields (pat.t#187 and split.t#{13,14}
471 * (as of patchlevel 7877) will fail. Then again,
472 * this code seems to be necessary or otherwise
473 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
474 * --jhi updated by dapm */
475 for (i = rex->lastparen + 1; i <= rex->nparens; i++) {
477 rex->offs[i].start = -1;
478 rex->offs[i].end = -1;
479 DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
480 " \\%"UVuf": %s ..-1 undeffing\n",
482 (i > PL_regsize) ? "-1" : " "
488 /* restore the parens and associated vars at savestack position ix,
489 * but without popping the stack */
492 S_regcp_restore(pTHX_ regexp *rex, I32 ix)
494 I32 tmpix = PL_savestack_ix;
495 PL_savestack_ix = ix;
497 PL_savestack_ix = tmpix;
500 #define regcpblow(cp) LEAVE_SCOPE(cp) /* Ignores regcppush()ed data. */
503 * pregexec and friends
506 #ifndef PERL_IN_XSUB_RE
508 - pregexec - match a regexp against a string
511 Perl_pregexec(pTHX_ REGEXP * const prog, char* stringarg, register char *strend,
512 char *strbeg, I32 minend, SV *screamer, U32 nosave)
513 /* strend: pointer to null at end of string */
514 /* strbeg: real beginning of string */
515 /* minend: end of match must be >=minend after stringarg. */
516 /* nosave: For optimizations. */
518 PERL_ARGS_ASSERT_PREGEXEC;
521 regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
522 nosave ? 0 : REXEC_COPY_STR);
527 * Need to implement the following flags for reg_anch:
529 * USE_INTUIT_NOML - Useful to call re_intuit_start() first
531 * INTUIT_AUTORITATIVE_NOML - Can trust a positive answer
532 * INTUIT_AUTORITATIVE_ML
533 * INTUIT_ONCE_NOML - Intuit can match in one location only.
536 * Another flag for this function: SECOND_TIME (so that float substrs
537 * with giant delta may be not rechecked).
540 /* Assumptions: if ANCH_GPOS, then strpos is anchored. XXXX Check GPOS logic */
542 /* If SCREAM, then SvPVX_const(sv) should be compatible with strpos and strend.
543 Otherwise, only SvCUR(sv) is used to get strbeg. */
545 /* XXXX We assume that strpos is strbeg unless sv. */
547 /* XXXX Some places assume that there is a fixed substring.
548 An update may be needed if optimizer marks as "INTUITable"
549 RExen without fixed substrings. Similarly, it is assumed that
550 lengths of all the strings are no more than minlen, thus they
551 cannot come from lookahead.
552 (Or minlen should take into account lookahead.)
553 NOTE: Some of this comment is not correct. minlen does now take account
554 of lookahead/behind. Further research is required. -- demerphq
558 /* A failure to find a constant substring means that there is no need to make
559 an expensive call to REx engine, thus we celebrate a failure. Similarly,
560 finding a substring too deep into the string means that less calls to
561 regtry() should be needed.
563 REx compiler's optimizer found 4 possible hints:
564 a) Anchored substring;
566 c) Whether we are anchored (beginning-of-line or \G);
567 d) First node (of those at offset 0) which may distinguish positions;
568 We use a)b)d) and multiline-part of c), and try to find a position in the
569 string which does not contradict any of them.
572 /* Most of decisions we do here should have been done at compile time.
573 The nodes of the REx which we used for the search should have been
574 deleted from the finite automaton. */
577 Perl_re_intuit_start(pTHX_ REGEXP * const rx, SV *sv, char *strpos,
578 char *strend, const U32 flags, re_scream_pos_data *data)
581 struct regexp *const prog = (struct regexp *)SvANY(rx);
583 /* Should be nonnegative! */
589 const bool utf8_target = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
591 char *other_last = NULL; /* other substr checked before this */
592 char *check_at = NULL; /* check substr found at this pos */
593 char *checked_upto = NULL; /* how far into the string we have already checked using find_byclass*/
594 const I32 multiline = prog->extflags & RXf_PMf_MULTILINE;
595 RXi_GET_DECL(prog,progi);
597 const char * const i_strpos = strpos;
599 GET_RE_DEBUG_FLAGS_DECL;
601 PERL_ARGS_ASSERT_RE_INTUIT_START;
602 PERL_UNUSED_ARG(flags);
603 PERL_UNUSED_ARG(data);
605 RX_MATCH_UTF8_set(rx,utf8_target);
608 PL_reg_flags |= RF_utf8;
611 debug_start_match(rx, utf8_target, strpos, strend,
612 sv ? "Guessing start of match in sv for"
613 : "Guessing start of match in string for");
616 /* CHR_DIST() would be more correct here but it makes things slow. */
617 if (prog->minlen > strend - strpos) {
618 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
619 "String too short... [re_intuit_start]\n"));
623 strbeg = (sv && SvPOK(sv)) ? strend - SvCUR(sv) : strpos;
626 if (!prog->check_utf8 && prog->check_substr)
627 to_utf8_substr(prog);
628 check = prog->check_utf8;
630 if (!prog->check_substr && prog->check_utf8)
631 to_byte_substr(prog);
632 check = prog->check_substr;
634 if (check == &PL_sv_undef) {
635 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
636 "Non-utf8 string cannot match utf8 check string\n"));
639 if (prog->extflags & RXf_ANCH) { /* Match at beg-of-str or after \n */
640 ml_anch = !( (prog->extflags & RXf_ANCH_SINGLE)
641 || ( (prog->extflags & RXf_ANCH_BOL)
642 && !multiline ) ); /* Check after \n? */
645 if ( !(prog->extflags & RXf_ANCH_GPOS) /* Checked by the caller */
646 && !(prog->intflags & PREGf_IMPLICIT) /* not a real BOL */
647 /* SvCUR is not set on references: SvRV and SvPVX_const overlap */
649 && (strpos != strbeg)) {
650 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Not at start...\n"));
653 if (prog->check_offset_min == prog->check_offset_max &&
654 !(prog->extflags & RXf_CANY_SEEN)) {
655 /* Substring at constant offset from beg-of-str... */
658 s = HOP3c(strpos, prog->check_offset_min, strend);
661 slen = SvCUR(check); /* >= 1 */
663 if ( strend - s > slen || strend - s < slen - 1
664 || (strend - s == slen && strend[-1] != '\n')) {
665 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "String too long...\n"));
668 /* Now should match s[0..slen-2] */
670 if (slen && (*SvPVX_const(check) != *s
672 && memNE(SvPVX_const(check), s, slen)))) {
674 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "String not equal...\n"));
678 else if (*SvPVX_const(check) != *s
679 || ((slen = SvCUR(check)) > 1
680 && memNE(SvPVX_const(check), s, slen)))
683 goto success_at_start;
686 /* Match is anchored, but substr is not anchored wrt beg-of-str. */
688 start_shift = prog->check_offset_min; /* okay to underestimate on CC */
689 end_shift = prog->check_end_shift;
692 const I32 end = prog->check_offset_max + CHR_SVLEN(check)
693 - (SvTAIL(check) != 0);
694 const I32 eshift = CHR_DIST((U8*)strend, (U8*)s) - end;
696 if (end_shift < eshift)
700 else { /* Can match at random position */
703 start_shift = prog->check_offset_min; /* okay to underestimate on CC */
704 end_shift = prog->check_end_shift;
706 /* end shift should be non negative here */
709 #ifdef QDEBUGGING /* 7/99: reports of failure (with the older version) */
711 Perl_croak(aTHX_ "panic: end_shift: %"IVdf" pattern:\n%s\n ",
712 (IV)end_shift, RX_PRECOMP(prog));
716 /* Find a possible match in the region s..strend by looking for
717 the "check" substring in the region corrected by start/end_shift. */
720 I32 srch_start_shift = start_shift;
721 I32 srch_end_shift = end_shift;
724 if (srch_start_shift < 0 && strbeg - s > srch_start_shift) {
725 srch_end_shift -= ((strbeg - s) - srch_start_shift);
726 srch_start_shift = strbeg - s;
728 DEBUG_OPTIMISE_MORE_r({
729 PerlIO_printf(Perl_debug_log, "Check offset min: %"IVdf" Start shift: %"IVdf" End shift %"IVdf" Real End Shift: %"IVdf"\n",
730 (IV)prog->check_offset_min,
731 (IV)srch_start_shift,
733 (IV)prog->check_end_shift);
736 if (prog->extflags & RXf_CANY_SEEN) {
737 start_point= (U8*)(s + srch_start_shift);
738 end_point= (U8*)(strend - srch_end_shift);
740 start_point= HOP3(s, srch_start_shift, srch_start_shift < 0 ? strbeg : strend);
741 end_point= HOP3(strend, -srch_end_shift, strbeg);
743 DEBUG_OPTIMISE_MORE_r({
744 PerlIO_printf(Perl_debug_log, "fbm_instr len=%d str=<%.*s>\n",
745 (int)(end_point - start_point),
746 (int)(end_point - start_point) > 20 ? 20 : (int)(end_point - start_point),
750 s = fbm_instr( start_point, end_point,
751 check, multiline ? FBMrf_MULTILINE : 0);
753 /* Update the count-of-usability, remove useless subpatterns,
757 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
758 SvPVX_const(check), RE_SV_DUMPLEN(check), 30);
759 PerlIO_printf(Perl_debug_log, "%s %s substr %s%s%s",
760 (s ? "Found" : "Did not find"),
761 (check == (utf8_target ? prog->anchored_utf8 : prog->anchored_substr)
762 ? "anchored" : "floating"),
765 (s ? " at offset " : "...\n") );
770 /* Finish the diagnostic message */
771 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%ld...\n", (long)(s - i_strpos)) );
773 /* XXX dmq: first branch is for positive lookbehind...
774 Our check string is offset from the beginning of the pattern.
775 So we need to do any stclass tests offset forward from that
784 /* Got a candidate. Check MBOL anchoring, and the *other* substr.
785 Start with the other substr.
786 XXXX no SCREAM optimization yet - and a very coarse implementation
787 XXXX /ttx+/ results in anchored="ttx", floating="x". floating will
788 *always* match. Probably should be marked during compile...
789 Probably it is right to do no SCREAM here...
792 if (utf8_target ? (prog->float_utf8 && prog->anchored_utf8)
793 : (prog->float_substr && prog->anchored_substr))
795 /* Take into account the "other" substring. */
796 /* XXXX May be hopelessly wrong for UTF... */
799 if (check == (utf8_target ? prog->float_utf8 : prog->float_substr)) {
802 char * const last = HOP3c(s, -start_shift, strbeg);
804 char * const saved_s = s;
807 t = s - prog->check_offset_max;
808 if (s - strpos > prog->check_offset_max /* signed-corrected t > strpos */
810 || ((t = (char*)reghopmaybe3((U8*)s, -(prog->check_offset_max), (U8*)strpos))
815 t = HOP3c(t, prog->anchored_offset, strend);
816 if (t < other_last) /* These positions already checked */
818 last2 = last1 = HOP3c(strend, -prog->minlen, strbeg);
821 /* XXXX It is not documented what units *_offsets are in.
822 We assume bytes, but this is clearly wrong.
823 Meaning this code needs to be carefully reviewed for errors.
827 /* On end-of-str: see comment below. */
828 must = utf8_target ? prog->anchored_utf8 : prog->anchored_substr;
829 if (must == &PL_sv_undef) {
831 DEBUG_r(must = prog->anchored_utf8); /* for debug */
836 HOP3(HOP3(last1, prog->anchored_offset, strend)
837 + SvCUR(must), -(SvTAIL(must)!=0), strbeg),
839 multiline ? FBMrf_MULTILINE : 0
842 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
843 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
844 PerlIO_printf(Perl_debug_log, "%s anchored substr %s%s",
845 (s ? "Found" : "Contradicts"),
846 quoted, RE_SV_TAIL(must));
851 if (last1 >= last2) {
852 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
853 ", giving up...\n"));
856 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
857 ", trying floating at offset %ld...\n",
858 (long)(HOP3c(saved_s, 1, strend) - i_strpos)));
859 other_last = HOP3c(last1, prog->anchored_offset+1, strend);
860 s = HOP3c(last, 1, strend);
864 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " at offset %ld...\n",
865 (long)(s - i_strpos)));
866 t = HOP3c(s, -prog->anchored_offset, strbeg);
867 other_last = HOP3c(s, 1, strend);
875 else { /* Take into account the floating substring. */
877 char * const saved_s = s;
880 t = HOP3c(s, -start_shift, strbeg);
882 HOP3c(strend, -prog->minlen + prog->float_min_offset, strbeg);
883 if (CHR_DIST((U8*)last, (U8*)t) > prog->float_max_offset)
884 last = HOP3c(t, prog->float_max_offset, strend);
885 s = HOP3c(t, prog->float_min_offset, strend);
888 /* XXXX It is not documented what units *_offsets are in. Assume bytes. */
889 must = utf8_target ? prog->float_utf8 : prog->float_substr;
890 /* fbm_instr() takes into account exact value of end-of-str
891 if the check is SvTAIL(ed). Since false positives are OK,
892 and end-of-str is not later than strend we are OK. */
893 if (must == &PL_sv_undef) {
895 DEBUG_r(must = prog->float_utf8); /* for debug message */
898 s = fbm_instr((unsigned char*)s,
899 (unsigned char*)last + SvCUR(must)
901 must, multiline ? FBMrf_MULTILINE : 0);
903 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
904 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
905 PerlIO_printf(Perl_debug_log, "%s floating substr %s%s",
906 (s ? "Found" : "Contradicts"),
907 quoted, RE_SV_TAIL(must));
911 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
912 ", giving up...\n"));
915 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
916 ", trying anchored starting at offset %ld...\n",
917 (long)(saved_s + 1 - i_strpos)));
919 s = HOP3c(t, 1, strend);
923 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " at offset %ld...\n",
924 (long)(s - i_strpos)));
925 other_last = s; /* Fix this later. --Hugo */
935 t= (char*)HOP3( s, -prog->check_offset_max, (prog->check_offset_max<0) ? strend : strpos);
937 DEBUG_OPTIMISE_MORE_r(
938 PerlIO_printf(Perl_debug_log,
939 "Check offset min:%"IVdf" max:%"IVdf" S:%"IVdf" t:%"IVdf" D:%"IVdf" end:%"IVdf"\n",
940 (IV)prog->check_offset_min,
941 (IV)prog->check_offset_max,
949 if (s - strpos > prog->check_offset_max /* signed-corrected t > strpos */
951 || ((t = (char*)reghopmaybe3((U8*)s, -prog->check_offset_max, (U8*) ((prog->check_offset_max<0) ? strend : strpos)))
954 /* Fixed substring is found far enough so that the match
955 cannot start at strpos. */
957 if (ml_anch && t[-1] != '\n') {
958 /* Eventually fbm_*() should handle this, but often
959 anchored_offset is not 0, so this check will not be wasted. */
960 /* XXXX In the code below we prefer to look for "^" even in
961 presence of anchored substrings. And we search even
962 beyond the found float position. These pessimizations
963 are historical artefacts only. */
965 while (t < strend - prog->minlen) {
967 if (t < check_at - prog->check_offset_min) {
968 if (utf8_target ? prog->anchored_utf8 : prog->anchored_substr) {
969 /* Since we moved from the found position,
970 we definitely contradict the found anchored
971 substr. Due to the above check we do not
972 contradict "check" substr.
973 Thus we can arrive here only if check substr
974 is float. Redo checking for "other"=="fixed".
977 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Found /%s^%s/m at offset %ld, rescanning for anchored from offset %ld...\n",
978 PL_colors[0], PL_colors[1], (long)(strpos - i_strpos), (long)(strpos - i_strpos + prog->anchored_offset)));
979 goto do_other_anchored;
981 /* We don't contradict the found floating substring. */
982 /* XXXX Why not check for STCLASS? */
984 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Found /%s^%s/m at offset %ld...\n",
985 PL_colors[0], PL_colors[1], (long)(s - i_strpos)));
988 /* Position contradicts check-string */
989 /* XXXX probably better to look for check-string
990 than for "\n", so one should lower the limit for t? */
991 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Found /%s^%s/m, restarting lookup for check-string at offset %ld...\n",
992 PL_colors[0], PL_colors[1], (long)(t + 1 - i_strpos)));
993 other_last = strpos = s = t + 1;
998 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Did not find /%s^%s/m...\n",
999 PL_colors[0], PL_colors[1]));
1003 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Starting position does not contradict /%s^%s/m...\n",
1004 PL_colors[0], PL_colors[1]));
1008 ++BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr); /* hooray/5 */
1011 /* The found string does not prohibit matching at strpos,
1012 - no optimization of calling REx engine can be performed,
1013 unless it was an MBOL and we are not after MBOL,
1014 or a future STCLASS check will fail this. */
1016 /* Even in this situation we may use MBOL flag if strpos is offset
1017 wrt the start of the string. */
1018 if (ml_anch && sv && !SvROK(sv) /* See prev comment on SvROK */
1019 && (strpos != strbeg) && strpos[-1] != '\n'
1020 /* May be due to an implicit anchor of m{.*foo} */
1021 && !(prog->intflags & PREGf_IMPLICIT))
1026 DEBUG_EXECUTE_r( if (ml_anch)
1027 PerlIO_printf(Perl_debug_log, "Position at offset %ld does not contradict /%s^%s/m...\n",
1028 (long)(strpos - i_strpos), PL_colors[0], PL_colors[1]);
1031 if (!(prog->intflags & PREGf_NAUGHTY) /* XXXX If strpos moved? */
1033 prog->check_utf8 /* Could be deleted already */
1034 && --BmUSEFUL(prog->check_utf8) < 0
1035 && (prog->check_utf8 == prog->float_utf8)
1037 prog->check_substr /* Could be deleted already */
1038 && --BmUSEFUL(prog->check_substr) < 0
1039 && (prog->check_substr == prog->float_substr)
1042 /* If flags & SOMETHING - do not do it many times on the same match */
1043 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "... Disabling check substring...\n"));
1044 /* XXX Does the destruction order has to change with utf8_target? */
1045 SvREFCNT_dec(utf8_target ? prog->check_utf8 : prog->check_substr);
1046 SvREFCNT_dec(utf8_target ? prog->check_substr : prog->check_utf8);
1047 prog->check_substr = prog->check_utf8 = NULL; /* disable */
1048 prog->float_substr = prog->float_utf8 = NULL; /* clear */
1049 check = NULL; /* abort */
1051 /* XXXX If the check string was an implicit check MBOL, then we need to unset the relevant flag
1052 see http://bugs.activestate.com/show_bug.cgi?id=87173 */
1053 if (prog->intflags & PREGf_IMPLICIT)
1054 prog->extflags &= ~RXf_ANCH_MBOL;
1055 /* XXXX This is a remnant of the old implementation. It
1056 looks wasteful, since now INTUIT can use many
1057 other heuristics. */
1058 prog->extflags &= ~RXf_USE_INTUIT;
1059 /* XXXX What other flags might need to be cleared in this branch? */
1065 /* Last resort... */
1066 /* XXXX BmUSEFUL already changed, maybe multiple change is meaningful... */
1067 /* trie stclasses are too expensive to use here, we are better off to
1068 leave it to regmatch itself */
1069 if (progi->regstclass && PL_regkind[OP(progi->regstclass)]!=TRIE) {
1070 /* minlen == 0 is possible if regstclass is \b or \B,
1071 and the fixed substr is ''$.
1072 Since minlen is already taken into account, s+1 is before strend;
1073 accidentally, minlen >= 1 guaranties no false positives at s + 1
1074 even for \b or \B. But (minlen? 1 : 0) below assumes that
1075 regstclass does not come from lookahead... */
1076 /* If regstclass takes bytelength more than 1: If charlength==1, OK.
1077 This leaves EXACTF-ish only, which are dealt with in find_byclass(). */
1078 const U8* const str = (U8*)STRING(progi->regstclass);
1079 const int cl_l = (PL_regkind[OP(progi->regstclass)] == EXACT
1080 ? CHR_DIST(str+STR_LEN(progi->regstclass), str)
1083 if (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
1084 endpos= HOP3c(s, (prog->minlen ? cl_l : 0), strend);
1085 else if (prog->float_substr || prog->float_utf8)
1086 endpos= HOP3c(HOP3c(check_at, -start_shift, strbeg), cl_l, strend);
1090 if (checked_upto < s)
1092 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "start_shift: %"IVdf" check_at: %"IVdf" s: %"IVdf" endpos: %"IVdf" checked_upto: %"IVdf"\n",
1093 (IV)start_shift, (IV)(check_at - strbeg), (IV)(s - strbeg), (IV)(endpos - strbeg), (IV)(checked_upto- strbeg)));
1096 s = find_byclass(prog, progi->regstclass, checked_upto, endpos, NULL);
1101 const char *what = NULL;
1103 if (endpos == strend) {
1104 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1105 "Could not match STCLASS...\n") );
1108 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1109 "This position contradicts STCLASS...\n") );
1110 if ((prog->extflags & RXf_ANCH) && !ml_anch)
1112 checked_upto = HOPBACKc(endpos, start_shift);
1113 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "start_shift: %"IVdf" check_at: %"IVdf" endpos: %"IVdf" checked_upto: %"IVdf"\n",
1114 (IV)start_shift, (IV)(check_at - strbeg), (IV)(endpos - strbeg), (IV)(checked_upto- strbeg)));
1115 /* Contradict one of substrings */
1116 if (prog->anchored_substr || prog->anchored_utf8) {
1117 if ((utf8_target ? prog->anchored_utf8 : prog->anchored_substr) == check) {
1118 DEBUG_EXECUTE_r( what = "anchored" );
1120 s = HOP3c(t, 1, strend);
1121 if (s + start_shift + end_shift > strend) {
1122 /* XXXX Should be taken into account earlier? */
1123 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1124 "Could not match STCLASS...\n") );
1129 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1130 "Looking for %s substr starting at offset %ld...\n",
1131 what, (long)(s + start_shift - i_strpos)) );
1134 /* Have both, check_string is floating */
1135 if (t + start_shift >= check_at) /* Contradicts floating=check */
1136 goto retry_floating_check;
1137 /* Recheck anchored substring, but not floating... */
1141 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1142 "Looking for anchored substr starting at offset %ld...\n",
1143 (long)(other_last - i_strpos)) );
1144 goto do_other_anchored;
1146 /* Another way we could have checked stclass at the
1147 current position only: */
1152 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1153 "Looking for /%s^%s/m starting at offset %ld...\n",
1154 PL_colors[0], PL_colors[1], (long)(t - i_strpos)) );
1157 if (!(utf8_target ? prog->float_utf8 : prog->float_substr)) /* Could have been deleted */
1159 /* Check is floating substring. */
1160 retry_floating_check:
1161 t = check_at - start_shift;
1162 DEBUG_EXECUTE_r( what = "floating" );
1163 goto hop_and_restart;
1166 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1167 "By STCLASS: moving %ld --> %ld\n",
1168 (long)(t - i_strpos), (long)(s - i_strpos))
1172 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1173 "Does not contradict STCLASS...\n");
1178 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%s%s:%s match at offset %ld\n",
1179 PL_colors[4], (check ? "Guessed" : "Giving up"),
1180 PL_colors[5], (long)(s - i_strpos)) );
1183 fail_finish: /* Substring not found */
1184 if (prog->check_substr || prog->check_utf8) /* could be removed already */
1185 BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
1187 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch rejected by optimizer%s\n",
1188 PL_colors[4], PL_colors[5]));
1192 #define DECL_TRIE_TYPE(scan) \
1193 const enum { trie_plain, trie_utf8, trie_utf8_fold, trie_latin_utf8_fold } \
1194 trie_type = ((scan->flags == EXACT) \
1195 ? (utf8_target ? trie_utf8 : trie_plain) \
1196 : (utf8_target ? trie_utf8_fold : trie_latin_utf8_fold))
1198 #define REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc, uscan, len, \
1199 uvc, charid, foldlen, foldbuf, uniflags) STMT_START { \
1201 switch (trie_type) { \
1202 case trie_utf8_fold: \
1203 if ( foldlen>0 ) { \
1204 uvc = utf8n_to_uvuni( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1209 uvc = to_utf8_fold( (const U8*) uc, foldbuf, &foldlen ); \
1210 len = UTF8SKIP(uc); \
1211 skiplen = UNISKIP( uvc ); \
1212 foldlen -= skiplen; \
1213 uscan = foldbuf + skiplen; \
1216 case trie_latin_utf8_fold: \
1217 if ( foldlen>0 ) { \
1218 uvc = utf8n_to_uvuni( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1224 uvc = _to_fold_latin1( (U8) *uc, foldbuf, &foldlen, 1); \
1225 skiplen = UNISKIP( uvc ); \
1226 foldlen -= skiplen; \
1227 uscan = foldbuf + skiplen; \
1231 uvc = utf8n_to_uvuni( (const U8*) uc, UTF8_MAXLEN, &len, uniflags ); \
1238 charid = trie->charmap[ uvc ]; \
1242 if (widecharmap) { \
1243 SV** const svpp = hv_fetch(widecharmap, \
1244 (char*)&uvc, sizeof(UV), 0); \
1246 charid = (U16)SvIV(*svpp); \
1251 #define REXEC_FBC_EXACTISH_SCAN(CoNd) \
1255 && (ln == 1 || folder(s, pat_string, ln)) \
1256 && (!reginfo || regtry(reginfo, &s)) ) \
1262 #define REXEC_FBC_UTF8_SCAN(CoDe) \
1264 while (s + (uskip = UTF8SKIP(s)) <= strend) { \
1270 #define REXEC_FBC_SCAN(CoDe) \
1272 while (s < strend) { \
1278 #define REXEC_FBC_UTF8_CLASS_SCAN(CoNd) \
1279 REXEC_FBC_UTF8_SCAN( \
1281 if (tmp && (!reginfo || regtry(reginfo, &s))) \
1290 #define REXEC_FBC_CLASS_SCAN(CoNd) \
1293 if (tmp && (!reginfo || regtry(reginfo, &s))) \
1302 #define REXEC_FBC_TRYIT \
1303 if ((!reginfo || regtry(reginfo, &s))) \
1306 #define REXEC_FBC_CSCAN(CoNdUtF8,CoNd) \
1307 if (utf8_target) { \
1308 REXEC_FBC_UTF8_CLASS_SCAN(CoNdUtF8); \
1311 REXEC_FBC_CLASS_SCAN(CoNd); \
1314 #define REXEC_FBC_CSCAN_PRELOAD(UtFpReLoAd,CoNdUtF8,CoNd) \
1315 if (utf8_target) { \
1317 REXEC_FBC_UTF8_CLASS_SCAN(CoNdUtF8); \
1320 REXEC_FBC_CLASS_SCAN(CoNd); \
1323 #define REXEC_FBC_CSCAN_TAINT(CoNdUtF8,CoNd) \
1324 PL_reg_flags |= RF_tainted; \
1325 if (utf8_target) { \
1326 REXEC_FBC_UTF8_CLASS_SCAN(CoNdUtF8); \
1329 REXEC_FBC_CLASS_SCAN(CoNd); \
1332 #define DUMP_EXEC_POS(li,s,doutf8) \
1333 dump_exec_pos(li,s,(PL_regeol),(PL_bostr),(PL_reg_starttry),doutf8)
1336 #define UTF8_NOLOAD(TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1337 tmp = (s != PL_bostr) ? UCHARAT(s - 1) : '\n'; \
1338 tmp = TEST_NON_UTF8(tmp); \
1339 REXEC_FBC_UTF8_SCAN( \
1340 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1349 #define UTF8_LOAD(TeSt1_UtF8, TeSt2_UtF8, IF_SUCCESS, IF_FAIL) \
1350 if (s == PL_bostr) { \
1354 U8 * const r = reghop3((U8*)s, -1, (U8*)PL_bostr); \
1355 tmp = utf8n_to_uvchr(r, UTF8SKIP(r), 0, UTF8_ALLOW_DEFAULT); \
1358 LOAD_UTF8_CHARCLASS_ALNUM(); \
1359 REXEC_FBC_UTF8_SCAN( \
1360 if (tmp == ! (TeSt2_UtF8)) { \
1369 /* The only difference between the BOUND and NBOUND cases is that
1370 * REXEC_FBC_TRYIT is called when matched in BOUND, and when non-matched in
1371 * NBOUND. This is accomplished by passing it in either the if or else clause,
1372 * with the other one being empty */
1373 #define FBC_BOUND(TEST_NON_UTF8, TEST1_UTF8, TEST2_UTF8) \
1374 FBC_BOUND_COMMON(UTF8_LOAD(TEST1_UTF8, TEST2_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1376 #define FBC_BOUND_NOLOAD(TEST_NON_UTF8, TEST1_UTF8, TEST2_UTF8) \
1377 FBC_BOUND_COMMON(UTF8_NOLOAD(TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1379 #define FBC_NBOUND(TEST_NON_UTF8, TEST1_UTF8, TEST2_UTF8) \
1380 FBC_BOUND_COMMON(UTF8_LOAD(TEST1_UTF8, TEST2_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1382 #define FBC_NBOUND_NOLOAD(TEST_NON_UTF8, TEST1_UTF8, TEST2_UTF8) \
1383 FBC_BOUND_COMMON(UTF8_NOLOAD(TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1386 /* Common to the BOUND and NBOUND cases. Unfortunately the UTF8 tests need to
1387 * be passed in completely with the variable name being tested, which isn't
1388 * such a clean interface, but this is easier to read than it was before. We
1389 * are looking for the boundary (or non-boundary between a word and non-word
1390 * character. The utf8 and non-utf8 cases have the same logic, but the details
1391 * must be different. Find the "wordness" of the character just prior to this
1392 * one, and compare it with the wordness of this one. If they differ, we have
1393 * a boundary. At the beginning of the string, pretend that the previous
1394 * character was a new-line */
1395 #define FBC_BOUND_COMMON(UTF8_CODE, TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1396 if (utf8_target) { \
1399 else { /* Not utf8 */ \
1400 tmp = (s != PL_bostr) ? UCHARAT(s - 1) : '\n'; \
1401 tmp = TEST_NON_UTF8(tmp); \
1403 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1412 if ((!prog->minlen && tmp) && (!reginfo || regtry(reginfo, &s))) \
1415 /* We know what class REx starts with. Try to find this position... */
1416 /* if reginfo is NULL, its a dryrun */
1417 /* annoyingly all the vars in this routine have different names from their counterparts
1418 in regmatch. /grrr */
1421 S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
1422 const char *strend, regmatch_info *reginfo)
1425 const I32 doevery = (prog->intflags & PREGf_SKIP) == 0;
1426 char *pat_string; /* The pattern's exactish string */
1427 char *pat_end; /* ptr to end char of pat_string */
1428 re_fold_t folder; /* Function for computing non-utf8 folds */
1429 const U8 *fold_array; /* array for folding ords < 256 */
1436 I32 tmp = 1; /* Scratch variable? */
1437 const bool utf8_target = PL_reg_match_utf8;
1438 UV utf8_fold_flags = 0;
1439 RXi_GET_DECL(prog,progi);
1441 PERL_ARGS_ASSERT_FIND_BYCLASS;
1443 /* We know what class it must start with. */
1447 if (utf8_target || OP(c) == ANYOFV) {
1448 STRLEN inclasslen = strend - s;
1449 REXEC_FBC_UTF8_CLASS_SCAN(
1450 reginclass(prog, c, (U8*)s, &inclasslen, utf8_target));
1453 REXEC_FBC_CLASS_SCAN(REGINCLASS(prog, c, (U8*)s));
1458 if (tmp && (!reginfo || regtry(reginfo, &s)))
1466 if (UTF_PATTERN || utf8_target) {
1467 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
1468 goto do_exactf_utf8;
1470 fold_array = PL_fold_latin1; /* Latin1 folds are not affected by */
1471 folder = foldEQ_latin1; /* /a, except the sharp s one which */
1472 goto do_exactf_non_utf8; /* isn't dealt with by these */
1477 /* regcomp.c already folded this if pattern is in UTF-8 */
1478 utf8_fold_flags = 0;
1479 goto do_exactf_utf8;
1481 fold_array = PL_fold;
1483 goto do_exactf_non_utf8;
1486 if (UTF_PATTERN || utf8_target) {
1487 utf8_fold_flags = FOLDEQ_UTF8_LOCALE;
1488 goto do_exactf_utf8;
1490 fold_array = PL_fold_locale;
1491 folder = foldEQ_locale;
1492 goto do_exactf_non_utf8;
1496 utf8_fold_flags = FOLDEQ_S2_ALREADY_FOLDED;
1498 goto do_exactf_utf8;
1500 case EXACTFU_TRICKYFOLD:
1502 if (UTF_PATTERN || utf8_target) {
1503 utf8_fold_flags = (UTF_PATTERN) ? FOLDEQ_S2_ALREADY_FOLDED : 0;
1504 goto do_exactf_utf8;
1507 /* Any 'ss' in the pattern should have been replaced by regcomp,
1508 * so we don't have to worry here about this single special case
1509 * in the Latin1 range */
1510 fold_array = PL_fold_latin1;
1511 folder = foldEQ_latin1;
1515 do_exactf_non_utf8: /* Neither pattern nor string are UTF8, and there
1516 are no glitches with fold-length differences
1517 between the target string and pattern */
1519 /* The idea in the non-utf8 EXACTF* cases is to first find the
1520 * first character of the EXACTF* node and then, if necessary,
1521 * case-insensitively compare the full text of the node. c1 is the
1522 * first character. c2 is its fold. This logic will not work for
1523 * Unicode semantics and the german sharp ss, which hence should
1524 * not be compiled into a node that gets here. */
1525 pat_string = STRING(c);
1526 ln = STR_LEN(c); /* length to match in octets/bytes */
1528 /* We know that we have to match at least 'ln' bytes (which is the
1529 * same as characters, since not utf8). If we have to match 3
1530 * characters, and there are only 2 availabe, we know without
1531 * trying that it will fail; so don't start a match past the
1532 * required minimum number from the far end */
1533 e = HOP3c(strend, -((I32)ln), s);
1535 if (!reginfo && e < s) {
1536 e = s; /* Due to minlen logic of intuit() */
1540 c2 = fold_array[c1];
1541 if (c1 == c2) { /* If char and fold are the same */
1542 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1);
1545 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1 || *(U8*)s == c2);
1554 /* If one of the operands is in utf8, we can't use the simpler
1555 * folding above, due to the fact that many different characters
1556 * can have the same fold, or portion of a fold, or different-
1558 pat_string = STRING(c);
1559 ln = STR_LEN(c); /* length to match in octets/bytes */
1560 pat_end = pat_string + ln;
1561 lnc = (UTF_PATTERN) /* length to match in characters */
1562 ? utf8_length((U8 *) pat_string, (U8 *) pat_end)
1565 /* We have 'lnc' characters to match in the pattern, but because of
1566 * multi-character folding, each character in the target can match
1567 * up to 3 characters (Unicode guarantees it will never exceed
1568 * this) if it is utf8-encoded; and up to 2 if not (based on the
1569 * fact that the Latin 1 folds are already determined, and the
1570 * only multi-char fold in that range is the sharp-s folding to
1571 * 'ss'. Thus, a pattern character can match as little as 1/3 of a
1572 * string character. Adjust lnc accordingly, rounding up, so that
1573 * if we need to match at least 4+1/3 chars, that really is 5. */
1574 expansion = (utf8_target) ? UTF8_MAX_FOLD_CHAR_EXPAND : 2;
1575 lnc = (lnc + expansion - 1) / expansion;
1577 /* As in the non-UTF8 case, if we have to match 3 characters, and
1578 * only 2 are left, it's guaranteed to fail, so don't start a
1579 * match that would require us to go beyond the end of the string
1581 e = HOP3c(strend, -((I32)lnc), s);
1583 if (!reginfo && e < s) {
1584 e = s; /* Due to minlen logic of intuit() */
1587 /* XXX Note that we could recalculate e to stop the loop earlier,
1588 * as the worst case expansion above will rarely be met, and as we
1589 * go along we would usually find that e moves further to the left.
1590 * This would happen only after we reached the point in the loop
1591 * where if there were no expansion we should fail. Unclear if
1592 * worth the expense */
1595 char *my_strend= (char *)strend;
1596 if (foldEQ_utf8_flags(s, &my_strend, 0, utf8_target,
1597 pat_string, NULL, ln, cBOOL(UTF_PATTERN), utf8_fold_flags)
1598 && (!reginfo || regtry(reginfo, &s)) )
1602 s += (utf8_target) ? UTF8SKIP(s) : 1;
1607 PL_reg_flags |= RF_tainted;
1608 FBC_BOUND(isALNUM_LC,
1609 isALNUM_LC_uvchr(UNI_TO_NATIVE(tmp)),
1610 isALNUM_LC_utf8((U8*)s));
1613 PL_reg_flags |= RF_tainted;
1614 FBC_NBOUND(isALNUM_LC,
1615 isALNUM_LC_uvchr(UNI_TO_NATIVE(tmp)),
1616 isALNUM_LC_utf8((U8*)s));
1619 FBC_BOUND(isWORDCHAR,
1621 cBOOL(swash_fetch(PL_utf8_alnum, (U8*)s, utf8_target)));
1624 FBC_BOUND_NOLOAD(isWORDCHAR_A,
1626 isWORDCHAR_A((U8*)s));
1629 FBC_NBOUND(isWORDCHAR,
1631 cBOOL(swash_fetch(PL_utf8_alnum, (U8*)s, utf8_target)));
1634 FBC_NBOUND_NOLOAD(isWORDCHAR_A,
1636 isWORDCHAR_A((U8*)s));
1639 FBC_BOUND(isWORDCHAR_L1,
1641 cBOOL(swash_fetch(PL_utf8_alnum, (U8*)s, utf8_target)));
1644 FBC_NBOUND(isWORDCHAR_L1,
1646 cBOOL(swash_fetch(PL_utf8_alnum, (U8*)s, utf8_target)));
1649 REXEC_FBC_CSCAN_TAINT(
1650 isALNUM_LC_utf8((U8*)s),
1655 REXEC_FBC_CSCAN_PRELOAD(
1656 LOAD_UTF8_CHARCLASS_ALNUM(),
1657 swash_fetch(PL_utf8_alnum,(U8*)s, utf8_target),
1658 isWORDCHAR_L1((U8) *s)
1662 REXEC_FBC_CSCAN_PRELOAD(
1663 LOAD_UTF8_CHARCLASS_ALNUM(),
1664 swash_fetch(PL_utf8_alnum,(U8*)s, utf8_target),
1669 /* Don't need to worry about utf8, as it can match only a single
1670 * byte invariant character */
1671 REXEC_FBC_CLASS_SCAN( isWORDCHAR_A(*s));
1674 REXEC_FBC_CSCAN_PRELOAD(
1675 LOAD_UTF8_CHARCLASS_ALNUM(),
1676 !swash_fetch(PL_utf8_alnum,(U8*)s, utf8_target),
1677 ! isWORDCHAR_L1((U8) *s)
1681 REXEC_FBC_CSCAN_PRELOAD(
1682 LOAD_UTF8_CHARCLASS_ALNUM(),
1683 !swash_fetch(PL_utf8_alnum, (U8*)s, utf8_target),
1694 REXEC_FBC_CSCAN_TAINT(
1695 !isALNUM_LC_utf8((U8*)s),
1700 REXEC_FBC_CSCAN_PRELOAD(
1701 LOAD_UTF8_CHARCLASS_SPACE(),
1702 *s == ' ' || swash_fetch(PL_utf8_space,(U8*)s, utf8_target),
1707 REXEC_FBC_CSCAN_PRELOAD(
1708 LOAD_UTF8_CHARCLASS_SPACE(),
1709 *s == ' ' || swash_fetch(PL_utf8_space,(U8*)s, utf8_target),
1714 /* Don't need to worry about utf8, as it can match only a single
1715 * byte invariant character */
1716 REXEC_FBC_CLASS_SCAN( isSPACE_A(*s));
1719 REXEC_FBC_CSCAN_TAINT(
1720 isSPACE_LC_utf8((U8*)s),
1725 REXEC_FBC_CSCAN_PRELOAD(
1726 LOAD_UTF8_CHARCLASS_SPACE(),
1727 !( *s == ' ' || swash_fetch(PL_utf8_space,(U8*)s, utf8_target)),
1728 ! isSPACE_L1((U8) *s)
1732 REXEC_FBC_CSCAN_PRELOAD(
1733 LOAD_UTF8_CHARCLASS_SPACE(),
1734 !(*s == ' ' || swash_fetch(PL_utf8_space,(U8*)s, utf8_target)),
1745 REXEC_FBC_CSCAN_TAINT(
1746 !isSPACE_LC_utf8((U8*)s),
1751 REXEC_FBC_CSCAN_PRELOAD(
1752 LOAD_UTF8_CHARCLASS_DIGIT(),
1753 swash_fetch(PL_utf8_digit,(U8*)s, utf8_target),
1758 /* Don't need to worry about utf8, as it can match only a single
1759 * byte invariant character */
1760 REXEC_FBC_CLASS_SCAN( isDIGIT_A(*s));
1763 REXEC_FBC_CSCAN_TAINT(
1764 isDIGIT_LC_utf8((U8*)s),
1769 REXEC_FBC_CSCAN_PRELOAD(
1770 LOAD_UTF8_CHARCLASS_DIGIT(),
1771 !swash_fetch(PL_utf8_digit,(U8*)s, utf8_target),
1782 REXEC_FBC_CSCAN_TAINT(
1783 !isDIGIT_LC_utf8((U8*)s),
1790 is_LNBREAK_latin1(s)
1802 !is_VERTWS_latin1(s)
1808 is_HORIZWS_latin1(s)
1813 !is_HORIZWS_utf8(s),
1814 !is_HORIZWS_latin1(s)
1818 /* Don't need to worry about utf8, as it can match only a single
1819 * byte invariant character. The flag in this node type is the
1820 * class number to pass to _generic_isCC() to build a mask for
1821 * searching in PL_charclass[] */
1822 REXEC_FBC_CLASS_SCAN( _generic_isCC_A(*s, FLAGS(c)));
1826 !_generic_isCC_A(*s, FLAGS(c)),
1827 !_generic_isCC_A(*s, FLAGS(c))
1835 /* what trie are we using right now */
1837 = (reg_ac_data*)progi->data->data[ ARG( c ) ];
1839 = (reg_trie_data*)progi->data->data[ aho->trie ];
1840 HV *widecharmap = MUTABLE_HV(progi->data->data[ aho->trie + 1 ]);
1842 const char *last_start = strend - trie->minlen;
1844 const char *real_start = s;
1846 STRLEN maxlen = trie->maxlen;
1848 U8 **points; /* map of where we were in the input string
1849 when reading a given char. For ASCII this
1850 is unnecessary overhead as the relationship
1851 is always 1:1, but for Unicode, especially
1852 case folded Unicode this is not true. */
1853 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1857 GET_RE_DEBUG_FLAGS_DECL;
1859 /* We can't just allocate points here. We need to wrap it in
1860 * an SV so it gets freed properly if there is a croak while
1861 * running the match */
1864 sv_points=newSV(maxlen * sizeof(U8 *));
1865 SvCUR_set(sv_points,
1866 maxlen * sizeof(U8 *));
1867 SvPOK_on(sv_points);
1868 sv_2mortal(sv_points);
1869 points=(U8**)SvPV_nolen(sv_points );
1870 if ( trie_type != trie_utf8_fold
1871 && (trie->bitmap || OP(c)==AHOCORASICKC) )
1874 bitmap=(U8*)trie->bitmap;
1876 bitmap=(U8*)ANYOF_BITMAP(c);
1878 /* this is the Aho-Corasick algorithm modified a touch
1879 to include special handling for long "unknown char"
1880 sequences. The basic idea being that we use AC as long
1881 as we are dealing with a possible matching char, when
1882 we encounter an unknown char (and we have not encountered
1883 an accepting state) we scan forward until we find a legal
1885 AC matching is basically that of trie matching, except
1886 that when we encounter a failing transition, we fall back
1887 to the current states "fail state", and try the current char
1888 again, a process we repeat until we reach the root state,
1889 state 1, or a legal transition. If we fail on the root state
1890 then we can either terminate if we have reached an accepting
1891 state previously, or restart the entire process from the beginning
1895 while (s <= last_start) {
1896 const U32 uniflags = UTF8_ALLOW_DEFAULT;
1904 U8 *uscan = (U8*)NULL;
1905 U8 *leftmost = NULL;
1907 U32 accepted_word= 0;
1911 while ( state && uc <= (U8*)strend ) {
1913 U32 word = aho->states[ state ].wordnum;
1917 DEBUG_TRIE_EXECUTE_r(
1918 if ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
1919 dump_exec_pos( (char *)uc, c, strend, real_start,
1920 (char *)uc, utf8_target );
1921 PerlIO_printf( Perl_debug_log,
1922 " Scanning for legal start char...\n");
1926 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
1930 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
1936 if (uc >(U8*)last_start) break;
1940 U8 *lpos= points[ (pointpos - trie->wordinfo[word].len) % maxlen ];
1941 if (!leftmost || lpos < leftmost) {
1942 DEBUG_r(accepted_word=word);
1948 points[pointpos++ % maxlen]= uc;
1949 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
1950 uscan, len, uvc, charid, foldlen,
1952 DEBUG_TRIE_EXECUTE_r({
1953 dump_exec_pos( (char *)uc, c, strend, real_start,
1955 PerlIO_printf(Perl_debug_log,
1956 " Charid:%3u CP:%4"UVxf" ",
1962 word = aho->states[ state ].wordnum;
1964 base = aho->states[ state ].trans.base;
1966 DEBUG_TRIE_EXECUTE_r({
1968 dump_exec_pos( (char *)uc, c, strend, real_start,
1970 PerlIO_printf( Perl_debug_log,
1971 "%sState: %4"UVxf", word=%"UVxf,
1972 failed ? " Fail transition to " : "",
1973 (UV)state, (UV)word);
1979 ( ((offset = base + charid
1980 - 1 - trie->uniquecharcount)) >= 0)
1981 && ((U32)offset < trie->lasttrans)
1982 && trie->trans[offset].check == state
1983 && (tmp=trie->trans[offset].next))
1985 DEBUG_TRIE_EXECUTE_r(
1986 PerlIO_printf( Perl_debug_log," - legal\n"));
1991 DEBUG_TRIE_EXECUTE_r(
1992 PerlIO_printf( Perl_debug_log," - fail\n"));
1994 state = aho->fail[state];
1998 /* we must be accepting here */
1999 DEBUG_TRIE_EXECUTE_r(
2000 PerlIO_printf( Perl_debug_log," - accepting\n"));
2009 if (!state) state = 1;
2012 if ( aho->states[ state ].wordnum ) {
2013 U8 *lpos = points[ (pointpos - trie->wordinfo[aho->states[ state ].wordnum].len) % maxlen ];
2014 if (!leftmost || lpos < leftmost) {
2015 DEBUG_r(accepted_word=aho->states[ state ].wordnum);
2020 s = (char*)leftmost;
2021 DEBUG_TRIE_EXECUTE_r({
2023 Perl_debug_log,"Matches word #%"UVxf" at position %"IVdf". Trying full pattern...\n",
2024 (UV)accepted_word, (IV)(s - real_start)
2027 if (!reginfo || regtry(reginfo, &s)) {
2033 DEBUG_TRIE_EXECUTE_r({
2034 PerlIO_printf( Perl_debug_log,"Pattern failed. Looking for new start point...\n");
2037 DEBUG_TRIE_EXECUTE_r(
2038 PerlIO_printf( Perl_debug_log,"No match.\n"));
2047 Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
2057 - regexec_flags - match a regexp against a string
2060 Perl_regexec_flags(pTHX_ REGEXP * const rx, char *stringarg, register char *strend,
2061 char *strbeg, I32 minend, SV *sv, void *data, U32 flags)
2062 /* strend: pointer to null at end of string */
2063 /* strbeg: real beginning of string */
2064 /* minend: end of match must be >=minend after stringarg. */
2065 /* data: May be used for some additional optimizations.
2066 Currently its only used, with a U32 cast, for transmitting
2067 the ganch offset when doing a /g match. This will change */
2068 /* nosave: For optimizations. */
2071 struct regexp *const prog = (struct regexp *)SvANY(rx);
2072 /*register*/ char *s;
2074 /*register*/ char *startpos = stringarg;
2075 I32 minlen; /* must match at least this many chars */
2076 I32 dontbother = 0; /* how many characters not to try at end */
2077 I32 end_shift = 0; /* Same for the end. */ /* CC */
2078 I32 scream_pos = -1; /* Internal iterator of scream. */
2079 char *scream_olds = NULL;
2080 const bool utf8_target = cBOOL(DO_UTF8(sv));
2082 RXi_GET_DECL(prog,progi);
2083 regmatch_info reginfo; /* create some info to pass to regtry etc */
2084 regexp_paren_pair *swap = NULL;
2085 GET_RE_DEBUG_FLAGS_DECL;
2087 PERL_ARGS_ASSERT_REGEXEC_FLAGS;
2088 PERL_UNUSED_ARG(data);
2090 /* Be paranoid... */
2091 if (prog == NULL || startpos == NULL) {
2092 Perl_croak(aTHX_ "NULL regexp parameter");
2096 multiline = prog->extflags & RXf_PMf_MULTILINE;
2097 reginfo.prog = rx; /* Yes, sorry that this is confusing. */
2099 RX_MATCH_UTF8_set(rx, utf8_target);
2101 debug_start_match(rx, utf8_target, startpos, strend,
2105 minlen = prog->minlen;
2107 if (strend - startpos < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
2108 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
2109 "String too short [regexec_flags]...\n"));
2114 /* Check validity of program. */
2115 if (UCHARAT(progi->program) != REG_MAGIC) {
2116 Perl_croak(aTHX_ "corrupted regexp program");
2120 PL_reg_state.re_state_eval_setup_done = FALSE;
2124 PL_reg_flags |= RF_utf8;
2126 /* Mark beginning of line for ^ and lookbehind. */
2127 reginfo.bol = startpos; /* XXX not used ??? */
2131 /* Mark end of line for $ (and such) */
2134 /* see how far we have to get to not match where we matched before */
2135 reginfo.till = startpos+minend;
2137 /* If there is a "must appear" string, look for it. */
2140 if (prog->extflags & RXf_GPOS_SEEN) { /* Need to set reginfo->ganch */
2142 if (flags & REXEC_IGNOREPOS){ /* Means: check only at start */
2143 reginfo.ganch = startpos + prog->gofs;
2144 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
2145 "GPOS IGNOREPOS: reginfo.ganch = startpos + %"UVxf"\n",(UV)prog->gofs));
2146 } else if (sv && SvTYPE(sv) >= SVt_PVMG
2148 && (mg = mg_find(sv, PERL_MAGIC_regex_global))
2149 && mg->mg_len >= 0) {
2150 reginfo.ganch = strbeg + mg->mg_len; /* Defined pos() */
2151 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
2152 "GPOS MAGIC: reginfo.ganch = strbeg + %"IVdf"\n",(IV)mg->mg_len));
2154 if (prog->extflags & RXf_ANCH_GPOS) {
2155 if (s > reginfo.ganch)
2157 s = reginfo.ganch - prog->gofs;
2158 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
2159 "GPOS ANCH_GPOS: s = ganch - %"UVxf"\n",(UV)prog->gofs));
2165 reginfo.ganch = strbeg + PTR2UV(data);
2166 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
2167 "GPOS DATA: reginfo.ganch= strbeg + %"UVxf"\n",PTR2UV(data)));
2169 } else { /* pos() not defined */
2170 reginfo.ganch = strbeg;
2171 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
2172 "GPOS: reginfo.ganch = strbeg\n"));
2175 if (PL_curpm && (PM_GETRE(PL_curpm) == rx)) {
2176 /* We have to be careful. If the previous successful match
2177 was from this regex we don't want a subsequent partially
2178 successful match to clobber the old results.
2179 So when we detect this possibility we add a swap buffer
2180 to the re, and switch the buffer each match. If we fail
2181 we switch it back, otherwise we leave it swapped.
2184 /* do we need a save destructor here for eval dies? */
2185 Newxz(prog->offs, (prog->nparens + 1), regexp_paren_pair);
2186 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
2187 "rex=0x%"UVxf" saving offs: orig=0x%"UVxf" new=0x%"UVxf"\n",
2193 if (!(flags & REXEC_CHECKED) && (prog->check_substr != NULL || prog->check_utf8 != NULL)) {
2194 re_scream_pos_data d;
2196 d.scream_olds = &scream_olds;
2197 d.scream_pos = &scream_pos;
2198 s = re_intuit_start(rx, sv, s, strend, flags, &d);
2200 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Not present...\n"));
2201 goto phooey; /* not present */
2207 /* Simplest case: anchored match need be tried only once. */
2208 /* [unless only anchor is BOL and multiline is set] */
2209 if (prog->extflags & (RXf_ANCH & ~RXf_ANCH_GPOS)) {
2210 if (s == startpos && regtry(®info, &startpos))
2212 else if (multiline || (prog->intflags & PREGf_IMPLICIT)
2213 || (prog->extflags & RXf_ANCH_MBOL)) /* XXXX SBOL? */
2218 dontbother = minlen - 1;
2219 end = HOP3c(strend, -dontbother, strbeg) - 1;
2220 /* for multiline we only have to try after newlines */
2221 if (prog->check_substr || prog->check_utf8) {
2222 /* because of the goto we can not easily reuse the macros for bifurcating the
2223 unicode/non-unicode match modes here like we do elsewhere - demerphq */
2226 goto after_try_utf8;
2228 if (regtry(®info, &s)) {
2235 if (prog->extflags & RXf_USE_INTUIT) {
2236 s = re_intuit_start(rx, sv, s + UTF8SKIP(s), strend, flags, NULL);
2245 } /* end search for check string in unicode */
2247 if (s == startpos) {
2248 goto after_try_latin;
2251 if (regtry(®info, &s)) {
2258 if (prog->extflags & RXf_USE_INTUIT) {
2259 s = re_intuit_start(rx, sv, s + 1, strend, flags, NULL);
2268 } /* end search for check string in latin*/
2269 } /* end search for check string */
2270 else { /* search for newline */
2272 /*XXX: The s-- is almost definitely wrong here under unicode - demeprhq*/
2275 /* We can use a more efficient search as newlines are the same in unicode as they are in latin */
2276 while (s <= end) { /* note it could be possible to match at the end of the string */
2277 if (*s++ == '\n') { /* don't need PL_utf8skip here */
2278 if (regtry(®info, &s))
2282 } /* end search for newline */
2283 } /* end anchored/multiline check string search */
2285 } else if (RXf_GPOS_CHECK == (prog->extflags & RXf_GPOS_CHECK))
2287 /* the warning about reginfo.ganch being used without initialization
2288 is bogus -- we set it above, when prog->extflags & RXf_GPOS_SEEN
2289 and we only enter this block when the same bit is set. */
2290 char *tmp_s = reginfo.ganch - prog->gofs;
2292 if (tmp_s >= strbeg && regtry(®info, &tmp_s))
2297 /* Messy cases: unanchored match. */
2298 if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
2299 /* we have /x+whatever/ */
2300 /* it must be a one character string (XXXX Except UTF_PATTERN?) */
2305 if (!(utf8_target ? prog->anchored_utf8 : prog->anchored_substr))
2306 utf8_target ? to_utf8_substr(prog) : to_byte_substr(prog);
2307 ch = SvPVX_const(utf8_target ? prog->anchored_utf8 : prog->anchored_substr)[0];
2312 DEBUG_EXECUTE_r( did_match = 1 );
2313 if (regtry(®info, &s)) goto got_it;
2315 while (s < strend && *s == ch)
2323 DEBUG_EXECUTE_r( did_match = 1 );
2324 if (regtry(®info, &s)) goto got_it;
2326 while (s < strend && *s == ch)
2331 DEBUG_EXECUTE_r(if (!did_match)
2332 PerlIO_printf(Perl_debug_log,
2333 "Did not find anchored character...\n")
2336 else if (prog->anchored_substr != NULL
2337 || prog->anchored_utf8 != NULL
2338 || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
2339 && prog->float_max_offset < strend - s)) {
2344 char *last1; /* Last position checked before */
2348 if (prog->anchored_substr || prog->anchored_utf8) {
2349 if (!(utf8_target ? prog->anchored_utf8 : prog->anchored_substr))
2350 utf8_target ? to_utf8_substr(prog) : to_byte_substr(prog);
2351 must = utf8_target ? prog->anchored_utf8 : prog->anchored_substr;
2352 back_max = back_min = prog->anchored_offset;
2354 if (!(utf8_target ? prog->float_utf8 : prog->float_substr))
2355 utf8_target ? to_utf8_substr(prog) : to_byte_substr(prog);
2356 must = utf8_target ? prog->float_utf8 : prog->float_substr;
2357 back_max = prog->float_max_offset;
2358 back_min = prog->float_min_offset;
2362 if (must == &PL_sv_undef)
2363 /* could not downgrade utf8 check substring, so must fail */
2369 last = HOP3c(strend, /* Cannot start after this */
2370 -(I32)(CHR_SVLEN(must)
2371 - (SvTAIL(must) != 0) + back_min), strbeg);
2374 last1 = HOPc(s, -1);
2376 last1 = s - 1; /* bogus */
2378 /* XXXX check_substr already used to find "s", can optimize if
2379 check_substr==must. */
2381 dontbother = end_shift;
2382 strend = HOPc(strend, -dontbother);
2383 while ( (s <= last) &&
2384 (s = fbm_instr((unsigned char*)HOP3(s, back_min, (back_min<0 ? strbeg : strend)),
2385 (unsigned char*)strend, must,
2386 multiline ? FBMrf_MULTILINE : 0)) ) {
2387 DEBUG_EXECUTE_r( did_match = 1 );
2388 if (HOPc(s, -back_max) > last1) {
2389 last1 = HOPc(s, -back_min);
2390 s = HOPc(s, -back_max);
2393 char * const t = (last1 >= PL_bostr) ? HOPc(last1, 1) : last1 + 1;
2395 last1 = HOPc(s, -back_min);
2399 while (s <= last1) {
2400 if (regtry(®info, &s))
2406 while (s <= last1) {
2407 if (regtry(®info, &s))
2413 DEBUG_EXECUTE_r(if (!did_match) {
2414 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
2415 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
2416 PerlIO_printf(Perl_debug_log, "Did not find %s substr %s%s...\n",
2417 ((must == prog->anchored_substr || must == prog->anchored_utf8)
2418 ? "anchored" : "floating"),
2419 quoted, RE_SV_TAIL(must));
2423 else if ( (c = progi->regstclass) ) {
2425 const OPCODE op = OP(progi->regstclass);
2426 /* don't bother with what can't match */
2427 if (PL_regkind[op] != EXACT && op != CANY && PL_regkind[op] != TRIE)
2428 strend = HOPc(strend, -(minlen - 1));
2431 SV * const prop = sv_newmortal();
2432 regprop(prog, prop, c);
2434 RE_PV_QUOTED_DECL(quoted,utf8_target,PERL_DEBUG_PAD_ZERO(1),
2436 PerlIO_printf(Perl_debug_log,
2437 "Matching stclass %.*s against %s (%d bytes)\n",
2438 (int)SvCUR(prop), SvPVX_const(prop),
2439 quoted, (int)(strend - s));
2442 if (find_byclass(prog, c, s, strend, ®info))
2444 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Contradicts stclass... [regexec_flags]\n"));
2448 if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
2455 if (!(utf8_target ? prog->float_utf8 : prog->float_substr))
2456 utf8_target ? to_utf8_substr(prog) : to_byte_substr(prog);
2457 float_real = utf8_target ? prog->float_utf8 : prog->float_substr;
2459 little = SvPV_const(float_real, len);
2460 if (SvTAIL(float_real)) {
2461 /* This means that float_real contains an artificial \n on the end
2462 * due to the presence of something like this: /foo$/
2463 * where we can match both "foo" and "foo\n" at the end of the string.
2464 * So we have to compare the end of the string first against the float_real
2465 * without the \n and then against the full float_real with the string.
2466 * We have to watch out for cases where the string might be smaller
2467 * than the float_real or the float_real without the \n.
2469 char *checkpos= strend - len;
2471 PerlIO_printf(Perl_debug_log,
2472 "%sChecking for float_real.%s\n",
2473 PL_colors[4], PL_colors[5]));
2474 if (checkpos + 1 < strbeg) {
2475 /* can't match, even if we remove the trailing \n string is too short to match */
2477 PerlIO_printf(Perl_debug_log,
2478 "%sString shorter than required trailing substring, cannot match.%s\n",
2479 PL_colors[4], PL_colors[5]));
2481 } else if (memEQ(checkpos + 1, little, len - 1)) {
2482 /* can match, the end of the string matches without the "\n" */
2483 last = checkpos + 1;
2484 } else if (checkpos < strbeg) {
2485 /* cant match, string is too short when the "\n" is included */
2487 PerlIO_printf(Perl_debug_log,
2488 "%sString does not contain required trailing substring, cannot match.%s\n",
2489 PL_colors[4], PL_colors[5]));
2491 } else if (!multiline) {
2492 /* non multiline match, so compare with the "\n" at the end of the string */
2493 if (memEQ(checkpos, little, len)) {
2497 PerlIO_printf(Perl_debug_log,
2498 "%sString does not contain required trailing substring, cannot match.%s\n",
2499 PL_colors[4], PL_colors[5]));
2503 /* multiline match, so we have to search for a place where the full string is located */
2509 last = rninstr(s, strend, little, little + len);
2511 last = strend; /* matching "$" */
2514 /* at one point this block contained a comment which was probably
2515 * incorrect, which said that this was a "should not happen" case.
2516 * Even if it was true when it was written I am pretty sure it is
2517 * not anymore, so I have removed the comment and replaced it with
2520 PerlIO_printf(Perl_debug_log,
2521 "String does not contain required substring, cannot match.\n"
2525 dontbother = strend - last + prog->float_min_offset;
2527 if (minlen && (dontbother < minlen))
2528 dontbother = minlen - 1;
2529 strend -= dontbother; /* this one's always in bytes! */
2530 /* We don't know much -- general case. */
2533 if (regtry(®info, &s))
2542 if (regtry(®info, &s))
2544 } while (s++ < strend);
2554 PerlIO_printf(Perl_debug_log,
2555 "rex=0x%"UVxf" freeing offs: 0x%"UVxf"\n",
2561 RX_MATCH_TAINTED_set(rx, PL_reg_flags & RF_tainted);
2563 if (PL_reg_state.re_state_eval_setup_done)
2564 restore_pos(aTHX_ prog);
2565 if (RXp_PAREN_NAMES(prog))
2566 (void)hv_iterinit(RXp_PAREN_NAMES(prog));
2568 /* make sure $`, $&, $', and $digit will work later */
2569 if ( !(flags & REXEC_NOT_FIRST) ) {
2570 RX_MATCH_COPY_FREE(rx);
2571 if (flags & REXEC_COPY_STR) {
2572 const I32 i = PL_regeol - startpos + (stringarg - strbeg);
2573 #ifdef PERL_OLD_COPY_ON_WRITE
2575 || (SvFLAGS(sv) & CAN_COW_MASK) == CAN_COW_FLAGS)) {
2577 PerlIO_printf(Perl_debug_log,
2578 "Copy on write: regexp capture, type %d\n",
2581 prog->saved_copy = sv_setsv_cow(prog->saved_copy, sv);
2582 prog->subbeg = (char *)SvPVX_const(prog->saved_copy);
2583 assert (SvPOKp(prog->saved_copy));
2587 RX_MATCH_COPIED_on(rx);
2588 s = savepvn(strbeg, i);
2594 prog->subbeg = strbeg;
2595 prog->sublen = PL_regeol - strbeg; /* strend may have been modified */
2602 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch failed%s\n",
2603 PL_colors[4], PL_colors[5]));
2604 if (PL_reg_state.re_state_eval_setup_done)
2605 restore_pos(aTHX_ prog);
2607 /* we failed :-( roll it back */
2608 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
2609 "rex=0x%"UVxf" rolling back offs: freeing=0x%"UVxf" restoring=0x%"UVxf"\n",
2614 Safefree(prog->offs);
2622 /* Set which rex is pointed to by PL_reg_state, handling ref counting.
2623 * Do inc before dec, in case old and new rex are the same */
2624 #define SET_reg_curpm(Re2) \
2625 if (PL_reg_state.re_state_eval_setup_done) { \
2626 (void)ReREFCNT_inc(Re2); \
2627 ReREFCNT_dec(PM_GETRE(PL_reg_curpm)); \
2628 PM_SETRE((PL_reg_curpm), (Re2)); \
2633 - regtry - try match at specific point
2635 STATIC I32 /* 0 failure, 1 success */
2636 S_regtry(pTHX_ regmatch_info *reginfo, char **startpos)
2640 REGEXP *const rx = reginfo->prog;
2641 regexp *const prog = (struct regexp *)SvANY(rx);
2642 RXi_GET_DECL(prog,progi);
2643 GET_RE_DEBUG_FLAGS_DECL;
2645 PERL_ARGS_ASSERT_REGTRY;
2647 reginfo->cutpoint=NULL;
2649 if ((prog->extflags & RXf_EVAL_SEEN)
2650 && !PL_reg_state.re_state_eval_setup_done)
2654 PL_reg_state.re_state_eval_setup_done = TRUE;
2656 /* Make $_ available to executed code. */
2657 if (reginfo->sv != DEFSV) {
2659 DEFSV_set(reginfo->sv);
2662 if (!(SvTYPE(reginfo->sv) >= SVt_PVMG && SvMAGIC(reginfo->sv)
2663 && (mg = mg_find(reginfo->sv, PERL_MAGIC_regex_global)))) {
2664 /* prepare for quick setting of pos */
2665 #ifdef PERL_OLD_COPY_ON_WRITE
2666 if (SvIsCOW(reginfo->sv))
2667 sv_force_normal_flags(reginfo->sv, 0);
2669 mg = sv_magicext(reginfo->sv, NULL, PERL_MAGIC_regex_global,
2670 &PL_vtbl_mglob, NULL, 0);
2674 PL_reg_oldpos = mg->mg_len;
2675 SAVEDESTRUCTOR_X(restore_pos, prog);
2677 if (!PL_reg_curpm) {
2678 Newxz(PL_reg_curpm, 1, PMOP);
2681 SV* const repointer = &PL_sv_undef;
2682 /* this regexp is also owned by the new PL_reg_curpm, which
2683 will try to free it. */
2684 av_push(PL_regex_padav, repointer);
2685 PL_reg_curpm->op_pmoffset = av_len(PL_regex_padav);
2686 PL_regex_pad = AvARRAY(PL_regex_padav);
2691 PL_reg_oldcurpm = PL_curpm;
2692 PL_curpm = PL_reg_curpm;
2693 if (RXp_MATCH_COPIED(prog)) {
2694 /* Here is a serious problem: we cannot rewrite subbeg,
2695 since it may be needed if this match fails. Thus
2696 $` inside (?{}) could fail... */
2697 PL_reg_oldsaved = prog->subbeg;
2698 PL_reg_oldsavedlen = prog->sublen;
2699 #ifdef PERL_OLD_COPY_ON_WRITE
2700 PL_nrs = prog->saved_copy;
2702 RXp_MATCH_COPIED_off(prog);
2705 PL_reg_oldsaved = NULL;
2706 prog->subbeg = PL_bostr;
2707 prog->sublen = PL_regeol - PL_bostr; /* strend may have been modified */
2710 PL_reg_starttry = *startpos;
2712 prog->offs[0].start = *startpos - PL_bostr;
2713 PL_reginput = *startpos;
2714 prog->lastparen = 0;
2715 prog->lastcloseparen = 0;
2718 /* XXXX What this code is doing here?!!! There should be no need
2719 to do this again and again, prog->lastparen should take care of
2722 /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
2723 * Actually, the code in regcppop() (which Ilya may be meaning by
2724 * prog->lastparen), is not needed at all by the test suite
2725 * (op/regexp, op/pat, op/split), but that code is needed otherwise
2726 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
2727 * Meanwhile, this code *is* needed for the
2728 * above-mentioned test suite tests to succeed. The common theme
2729 * on those tests seems to be returning null fields from matches.
2730 * --jhi updated by dapm */
2732 if (prog->nparens) {
2733 regexp_paren_pair *pp = prog->offs;
2735 for (i = prog->nparens; i > (I32)prog->lastparen; i--) {
2743 if (regmatch(reginfo, progi->program + 1)) {
2744 prog->offs[0].end = PL_reginput - PL_bostr;
2747 if (reginfo->cutpoint)
2748 *startpos= reginfo->cutpoint;
2749 REGCP_UNWIND(lastcp);
2754 #define sayYES goto yes
2755 #define sayNO goto no
2756 #define sayNO_SILENT goto no_silent
2758 /* we dont use STMT_START/END here because it leads to
2759 "unreachable code" warnings, which are bogus, but distracting. */
2760 #define CACHEsayNO \
2761 if (ST.cache_mask) \
2762 PL_reg_poscache[ST.cache_offset] |= ST.cache_mask; \
2765 /* this is used to determine how far from the left messages like
2766 'failed...' are printed. It should be set such that messages
2767 are inline with the regop output that created them.
2769 #define REPORT_CODE_OFF 32
2772 #define CHRTEST_UNINIT -1001 /* c1/c2 haven't been calculated yet */
2773 #define CHRTEST_VOID -1000 /* the c1/c2 "next char" test should be skipped */
2775 #define SLAB_FIRST(s) (&(s)->states[0])
2776 #define SLAB_LAST(s) (&(s)->states[PERL_REGMATCH_SLAB_SLOTS-1])
2778 /* grab a new slab and return the first slot in it */
2780 STATIC regmatch_state *
2783 #if PERL_VERSION < 9 && !defined(PERL_CORE)
2786 regmatch_slab *s = PL_regmatch_slab->next;
2788 Newx(s, 1, regmatch_slab);
2789 s->prev = PL_regmatch_slab;
2791 PL_regmatch_slab->next = s;
2793 PL_regmatch_slab = s;
2794 return SLAB_FIRST(s);
2798 /* push a new state then goto it */
2800 #define PUSH_STATE_GOTO(state, node) \
2802 st->resume_state = state; \
2805 /* push a new state with success backtracking, then goto it */
2807 #define PUSH_YES_STATE_GOTO(state, node) \
2809 st->resume_state = state; \
2810 goto push_yes_state;
2816 regmatch() - main matching routine
2818 This is basically one big switch statement in a loop. We execute an op,
2819 set 'next' to point the next op, and continue. If we come to a point which
2820 we may need to backtrack to on failure such as (A|B|C), we push a
2821 backtrack state onto the backtrack stack. On failure, we pop the top
2822 state, and re-enter the loop at the state indicated. If there are no more
2823 states to pop, we return failure.
2825 Sometimes we also need to backtrack on success; for example /A+/, where
2826 after successfully matching one A, we need to go back and try to
2827 match another one; similarly for lookahead assertions: if the assertion
2828 completes successfully, we backtrack to the state just before the assertion
2829 and then carry on. In these cases, the pushed state is marked as
2830 'backtrack on success too'. This marking is in fact done by a chain of
2831 pointers, each pointing to the previous 'yes' state. On success, we pop to
2832 the nearest yes state, discarding any intermediate failure-only states.
2833 Sometimes a yes state is pushed just to force some cleanup code to be
2834 called at the end of a successful match or submatch; e.g. (??{$re}) uses
2835 it to free the inner regex.
2837 Note that failure backtracking rewinds the cursor position, while
2838 success backtracking leaves it alone.
2840 A pattern is complete when the END op is executed, while a subpattern
2841 such as (?=foo) is complete when the SUCCESS op is executed. Both of these
2842 ops trigger the "pop to last yes state if any, otherwise return true"
2845 A common convention in this function is to use A and B to refer to the two
2846 subpatterns (or to the first nodes thereof) in patterns like /A*B/: so A is
2847 the subpattern to be matched possibly multiple times, while B is the entire
2848 rest of the pattern. Variable and state names reflect this convention.
2850 The states in the main switch are the union of ops and failure/success of
2851 substates associated with with that op. For example, IFMATCH is the op
2852 that does lookahead assertions /(?=A)B/ and so the IFMATCH state means
2853 'execute IFMATCH'; while IFMATCH_A is a state saying that we have just
2854 successfully matched A and IFMATCH_A_fail is a state saying that we have
2855 just failed to match A. Resume states always come in pairs. The backtrack
2856 state we push is marked as 'IFMATCH_A', but when that is popped, we resume
2857 at IFMATCH_A or IFMATCH_A_fail, depending on whether we are backtracking
2858 on success or failure.
2860 The struct that holds a backtracking state is actually a big union, with
2861 one variant for each major type of op. The variable st points to the
2862 top-most backtrack struct. To make the code clearer, within each
2863 block of code we #define ST to alias the relevant union.
2865 Here's a concrete example of a (vastly oversimplified) IFMATCH
2871 #define ST st->u.ifmatch
2873 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
2874 ST.foo = ...; // some state we wish to save
2876 // push a yes backtrack state with a resume value of
2877 // IFMATCH_A/IFMATCH_A_fail, then continue execution at the
2879 PUSH_YES_STATE_GOTO(IFMATCH_A, A);
2882 case IFMATCH_A: // we have successfully executed A; now continue with B
2884 bar = ST.foo; // do something with the preserved value
2887 case IFMATCH_A_fail: // A failed, so the assertion failed
2888 ...; // do some housekeeping, then ...
2889 sayNO; // propagate the failure
2896 For any old-timers reading this who are familiar with the old recursive
2897 approach, the code above is equivalent to:
2899 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
2908 ...; // do some housekeeping, then ...
2909 sayNO; // propagate the failure
2912 The topmost backtrack state, pointed to by st, is usually free. If you
2913 want to claim it, populate any ST.foo fields in it with values you wish to
2914 save, then do one of
2916 PUSH_STATE_GOTO(resume_state, node);
2917 PUSH_YES_STATE_GOTO(resume_state, node);
2919 which sets that backtrack state's resume value to 'resume_state', pushes a
2920 new free entry to the top of the backtrack stack, then goes to 'node'.
2921 On backtracking, the free slot is popped, and the saved state becomes the
2922 new free state. An ST.foo field in this new top state can be temporarily
2923 accessed to retrieve values, but once the main loop is re-entered, it
2924 becomes available for reuse.
2926 Note that the depth of the backtrack stack constantly increases during the
2927 left-to-right execution of the pattern, rather than going up and down with
2928 the pattern nesting. For example the stack is at its maximum at Z at the
2929 end of the pattern, rather than at X in the following:
2931 /(((X)+)+)+....(Y)+....Z/
2933 The only exceptions to this are lookahead/behind assertions and the cut,
2934 (?>A), which pop all the backtrack states associated with A before
2937 Backtrack state structs are allocated in slabs of about 4K in size.
2938 PL_regmatch_state and st always point to the currently active state,
2939 and PL_regmatch_slab points to the slab currently containing
2940 PL_regmatch_state. The first time regmatch() is called, the first slab is
2941 allocated, and is never freed until interpreter destruction. When the slab
2942 is full, a new one is allocated and chained to the end. At exit from
2943 regmatch(), slabs allocated since entry are freed.
2948 #define DEBUG_STATE_pp(pp) \
2950 DUMP_EXEC_POS(locinput, scan, utf8_target); \
2951 PerlIO_printf(Perl_debug_log, \
2952 " %*s"pp" %s%s%s%s%s\n", \
2954 PL_reg_name[st->resume_state], \
2955 ((st==yes_state||st==mark_state) ? "[" : ""), \
2956 ((st==yes_state) ? "Y" : ""), \
2957 ((st==mark_state) ? "M" : ""), \
2958 ((st==yes_state||st==mark_state) ? "]" : "") \
2963 #define REG_NODE_NUM(x) ((x) ? (int)((x)-prog) : -1)
2968 S_debug_start_match(pTHX_ const REGEXP *prog, const bool utf8_target,
2969 const char *start, const char *end, const char *blurb)
2971 const bool utf8_pat = RX_UTF8(prog) ? 1 : 0;
2973 PERL_ARGS_ASSERT_DEBUG_START_MATCH;
2978 RE_PV_QUOTED_DECL(s0, utf8_pat, PERL_DEBUG_PAD_ZERO(0),
2979 RX_PRECOMP_const(prog), RX_PRELEN(prog), 60);
2981 RE_PV_QUOTED_DECL(s1, utf8_target, PERL_DEBUG_PAD_ZERO(1),
2982 start, end - start, 60);
2984 PerlIO_printf(Perl_debug_log,
2985 "%s%s REx%s %s against %s\n",
2986 PL_colors[4], blurb, PL_colors[5], s0, s1);
2988 if (utf8_target||utf8_pat)
2989 PerlIO_printf(Perl_debug_log, "UTF-8 %s%s%s...\n",
2990 utf8_pat ? "pattern" : "",
2991 utf8_pat && utf8_target ? " and " : "",
2992 utf8_target ? "string" : ""
2998 S_dump_exec_pos(pTHX_ const char *locinput,
2999 const regnode *scan,
3000 const char *loc_regeol,
3001 const char *loc_bostr,
3002 const char *loc_reg_starttry,
3003 const bool utf8_target)
3005 const int docolor = *PL_colors[0] || *PL_colors[2] || *PL_colors[4];
3006 const int taill = (docolor ? 10 : 7); /* 3 chars for "> <" */
3007 int l = (loc_regeol - locinput) > taill ? taill : (loc_regeol - locinput);
3008 /* The part of the string before starttry has one color
3009 (pref0_len chars), between starttry and current
3010 position another one (pref_len - pref0_len chars),
3011 after the current position the third one.
3012 We assume that pref0_len <= pref_len, otherwise we
3013 decrease pref0_len. */
3014 int pref_len = (locinput - loc_bostr) > (5 + taill) - l
3015 ? (5 + taill) - l : locinput - loc_bostr;
3018 PERL_ARGS_ASSERT_DUMP_EXEC_POS;
3020 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput - pref_len)))
3022 pref0_len = pref_len - (locinput - loc_reg_starttry);
3023 if (l + pref_len < (5 + taill) && l < loc_regeol - locinput)
3024 l = ( loc_regeol - locinput > (5 + taill) - pref_len
3025 ? (5 + taill) - pref_len : loc_regeol - locinput);
3026 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput + l)))
3030 if (pref0_len > pref_len)
3031 pref0_len = pref_len;
3033 const int is_uni = (utf8_target && OP(scan) != CANY) ? 1 : 0;
3035 RE_PV_COLOR_DECL(s0,len0,is_uni,PERL_DEBUG_PAD(0),
3036 (locinput - pref_len),pref0_len, 60, 4, 5);
3038 RE_PV_COLOR_DECL(s1,len1,is_uni,PERL_DEBUG_PAD(1),
3039 (locinput - pref_len + pref0_len),
3040 pref_len - pref0_len, 60, 2, 3);
3042 RE_PV_COLOR_DECL(s2,len2,is_uni,PERL_DEBUG_PAD(2),
3043 locinput, loc_regeol - locinput, 10, 0, 1);
3045 const STRLEN tlen=len0+len1+len2;
3046 PerlIO_printf(Perl_debug_log,
3047 "%4"IVdf" <%.*s%.*s%s%.*s>%*s|",
3048 (IV)(locinput - loc_bostr),
3051 (docolor ? "" : "> <"),
3053 (int)(tlen > 19 ? 0 : 19 - tlen),
3060 /* reg_check_named_buff_matched()
3061 * Checks to see if a named buffer has matched. The data array of
3062 * buffer numbers corresponding to the buffer is expected to reside
3063 * in the regexp->data->data array in the slot stored in the ARG() of
3064 * node involved. Note that this routine doesn't actually care about the
3065 * name, that information is not preserved from compilation to execution.
3066 * Returns the index of the leftmost defined buffer with the given name
3067 * or 0 if non of the buffers matched.
3070 S_reg_check_named_buff_matched(pTHX_ const regexp *rex, const regnode *scan)
3073 RXi_GET_DECL(rex,rexi);
3074 SV *sv_dat= MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
3075 I32 *nums=(I32*)SvPVX(sv_dat);
3077 PERL_ARGS_ASSERT_REG_CHECK_NAMED_BUFF_MATCHED;
3079 for ( n=0; n<SvIVX(sv_dat); n++ ) {
3080 if ((I32)rex->lastparen >= nums[n] &&
3081 rex->offs[nums[n]].end != -1)
3090 /* free all slabs above current one - called during LEAVE_SCOPE */
3093 S_clear_backtrack_stack(pTHX_ void *p)
3095 regmatch_slab *s = PL_regmatch_slab->next;
3100 PL_regmatch_slab->next = NULL;
3102 regmatch_slab * const osl = s;
3109 STATIC I32 /* 0 failure, 1 success */
3110 S_regmatch(pTHX_ regmatch_info *reginfo, regnode *prog)
3112 #if PERL_VERSION < 9 && !defined(PERL_CORE)
3116 const bool utf8_target = PL_reg_match_utf8;
3117 const U32 uniflags = UTF8_ALLOW_DEFAULT;
3118 REGEXP *rex_sv = reginfo->prog;
3119 regexp *rex = (struct regexp *)SvANY(rex_sv);
3120 RXi_GET_DECL(rex,rexi);
3122 /* the current state. This is a cached copy of PL_regmatch_state */
3124 /* cache heavy used fields of st in registers */
3127 U32 n = 0; /* general value; init to avoid compiler warning */
3128 I32 ln = 0; /* len or last; init to avoid compiler warning */
3129 char *locinput = PL_reginput;
3130 I32 nextchr; /* is always set to UCHARAT(locinput) */
3132 bool result = 0; /* return value of S_regmatch */
3133 int depth = 0; /* depth of backtrack stack */
3134 U32 nochange_depth = 0; /* depth of GOSUB recursion with nochange */
3135 const U32 max_nochange_depth =
3136 (3 * rex->nparens > MAX_RECURSE_EVAL_NOCHANGE_DEPTH) ?
3137 3 * rex->nparens : MAX_RECURSE_EVAL_NOCHANGE_DEPTH;
3138 regmatch_state *yes_state = NULL; /* state to pop to on success of
3140 /* mark_state piggy backs on the yes_state logic so that when we unwind
3141 the stack on success we can update the mark_state as we go */
3142 regmatch_state *mark_state = NULL; /* last mark state we have seen */
3143 regmatch_state *cur_eval = NULL; /* most recent EVAL_AB state */
3144 struct regmatch_state *cur_curlyx = NULL; /* most recent curlyx */
3146 bool no_final = 0; /* prevent failure from backtracking? */
3147 bool do_cutgroup = 0; /* no_final only until next branch/trie entry */
3148 char *startpoint = PL_reginput;
3149 SV *popmark = NULL; /* are we looking for a mark? */
3150 SV *sv_commit = NULL; /* last mark name seen in failure */
3151 SV *sv_yes_mark = NULL; /* last mark name we have seen
3152 during a successful match */
3153 U32 lastopen = 0; /* last open we saw */
3154 bool has_cutgroup = RX_HAS_CUTGROUP(rex) ? 1 : 0;
3155 SV* const oreplsv = GvSV(PL_replgv);
3156 /* these three flags are set by various ops to signal information to
3157 * the very next op. They have a useful lifetime of exactly one loop
3158 * iteration, and are not preserved or restored by state pushes/pops
3160 bool sw = 0; /* the condition value in (?(cond)a|b) */
3161 bool minmod = 0; /* the next "{n,m}" is a "{n,m}?" */
3162 int logical = 0; /* the following EVAL is:
3166 or the following IFMATCH/UNLESSM is:
3167 false: plain (?=foo)
3168 true: used as a condition: (?(?=foo))
3170 PAD* last_pad = NULL;
3172 I32 gimme = G_SCALAR;
3173 CV *caller_cv = NULL; /* who called us */
3174 CV *last_pushed_cv = NULL; /* most recently called (?{}) CV */
3175 CHECKPOINT runops_cp; /* savestack position before executing EVAL */
3178 GET_RE_DEBUG_FLAGS_DECL;
3181 /* shut up 'may be used uninitialized' compiler warnings for dMULTICALL */
3182 multicall_oldcatch = 0;
3183 multicall_cv = NULL;
3185 PERL_UNUSED_VAR(multicall_cop);
3186 PERL_UNUSED_VAR(newsp);
3189 PERL_ARGS_ASSERT_REGMATCH;
3191 DEBUG_OPTIMISE_r( DEBUG_EXECUTE_r({
3192 PerlIO_printf(Perl_debug_log,"regmatch start\n");
3194 /* on first ever call to regmatch, allocate first slab */
3195 if (!PL_regmatch_slab) {
3196 Newx(PL_regmatch_slab, 1, regmatch_slab);
3197 PL_regmatch_slab->prev = NULL;
3198 PL_regmatch_slab->next = NULL;
3199 PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
3202 oldsave = PL_savestack_ix;
3203 SAVEDESTRUCTOR_X(S_clear_backtrack_stack, NULL);
3204 SAVEVPTR(PL_regmatch_slab);
3205 SAVEVPTR(PL_regmatch_state);
3207 /* grab next free state slot */
3208 st = ++PL_regmatch_state;
3209 if (st > SLAB_LAST(PL_regmatch_slab))
3210 st = PL_regmatch_state = S_push_slab(aTHX);
3212 /* Note that nextchr is a byte even in UTF */
3213 nextchr = UCHARAT(locinput);
3215 while (scan != NULL) {
3218 SV * const prop = sv_newmortal();
3219 regnode *rnext=regnext(scan);
3220 DUMP_EXEC_POS( locinput, scan, utf8_target );
3221 regprop(rex, prop, scan);
3223 PerlIO_printf(Perl_debug_log,
3224 "%3"IVdf":%*s%s(%"IVdf")\n",
3225 (IV)(scan - rexi->program), depth*2, "",
3227 (PL_regkind[OP(scan)] == END || !rnext) ?
3228 0 : (IV)(rnext - rexi->program));
3231 next = scan + NEXT_OFF(scan);
3234 state_num = OP(scan);
3238 switch (state_num) {
3240 if (locinput == PL_bostr)
3242 /* reginfo->till = reginfo->bol; */
3247 if (locinput == PL_bostr ||
3248 ((nextchr || locinput < PL_regeol) && locinput[-1] == '\n'))
3254 if (locinput == PL_bostr)
3258 if (locinput == reginfo->ganch)
3263 /* update the startpoint */
3264 st->u.keeper.val = rex->offs[0].start;
3265 PL_reginput = locinput;
3266 rex->offs[0].start = locinput - PL_bostr;
3267 PUSH_STATE_GOTO(KEEPS_next, next);
3269 case KEEPS_next_fail:
3270 /* rollback the start point change */
3271 rex->offs[0].start = st->u.keeper.val;
3277 if ((nextchr || locinput < PL_regeol) && nextchr != '\n')
3282 if ((nextchr || locinput < PL_regeol) && nextchr != '\n')
3284 if (PL_regeol - locinput > 1)
3288 if (PL_regeol != locinput)
3292 if (!nextchr && locinput >= PL_regeol)
3295 locinput += PL_utf8skip[nextchr];
3296 if (locinput > PL_regeol)
3298 nextchr = UCHARAT(locinput);
3301 nextchr = UCHARAT(++locinput);
3304 if (!nextchr && locinput >= PL_regeol)
3306 nextchr = UCHARAT(++locinput);
3309 if ((!nextchr && locinput >= PL_regeol) || nextchr == '\n')
3312 locinput += PL_utf8skip[nextchr];
3313 if (locinput > PL_regeol)
3315 nextchr = UCHARAT(locinput);
3318 nextchr = UCHARAT(++locinput);
3322 #define ST st->u.trie
3324 /* In this case the charclass data is available inline so
3325 we can fail fast without a lot of extra overhead.
3327 if(!ANYOF_BITMAP_TEST(scan, *locinput)) {
3329 PerlIO_printf(Perl_debug_log,
3330 "%*s %sfailed to match trie start class...%s\n",
3331 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
3334 assert(0); /* NOTREACHED */
3338 /* the basic plan of execution of the trie is:
3339 * At the beginning, run though all the states, and
3340 * find the longest-matching word. Also remember the position
3341 * of the shortest matching word. For example, this pattern:
3344 * when matched against the string "abcde", will generate
3345 * accept states for all words except 3, with the longest
3346 * matching word being 4, and the shortest being 1 (with
3347 * the position being after char 1 of the string).
3349 * Then for each matching word, in word order (i.e. 1,2,4,5),
3350 * we run the remainder of the pattern; on each try setting
3351 * the current position to the character following the word,
3352 * returning to try the next word on failure.
3354 * We avoid having to build a list of words at runtime by
3355 * using a compile-time structure, wordinfo[].prev, which
3356 * gives, for each word, the previous accepting word (if any).
3357 * In the case above it would contain the mappings 1->2, 2->0,
3358 * 3->0, 4->5, 5->1. We can use this table to generate, from
3359 * the longest word (4 above), a list of all words, by
3360 * following the list of prev pointers; this gives us the
3361 * unordered list 4,5,1,2. Then given the current word we have
3362 * just tried, we can go through the list and find the
3363 * next-biggest word to try (so if we just failed on word 2,
3364 * the next in the list is 4).
3366 * Since at runtime we don't record the matching position in
3367 * the string for each word, we have to work that out for
3368 * each word we're about to process. The wordinfo table holds
3369 * the character length of each word; given that we recorded
3370 * at the start: the position of the shortest word and its
3371 * length in chars, we just need to move the pointer the
3372 * difference between the two char lengths. Depending on
3373 * Unicode status and folding, that's cheap or expensive.
3375 * This algorithm is optimised for the case where are only a
3376 * small number of accept states, i.e. 0,1, or maybe 2.
3377 * With lots of accepts states, and having to try all of them,
3378 * it becomes quadratic on number of accept states to find all
3383 /* what type of TRIE am I? (utf8 makes this contextual) */
3384 DECL_TRIE_TYPE(scan);
3386 /* what trie are we using right now */
3387 reg_trie_data * const trie
3388 = (reg_trie_data*)rexi->data->data[ ARG( scan ) ];
3389 HV * widecharmap = MUTABLE_HV(rexi->data->data[ ARG( scan ) + 1 ]);
3390 U32 state = trie->startstate;
3392 if (trie->bitmap && !TRIE_BITMAP_TEST(trie,*locinput) ) {
3393 if (trie->states[ state ].wordnum) {
3395 PerlIO_printf(Perl_debug_log,
3396 "%*s %smatched empty string...%s\n",
3397 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
3403 PerlIO_printf(Perl_debug_log,
3404 "%*s %sfailed to match trie start class...%s\n",
3405 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
3412 U8 *uc = ( U8* )locinput;
3416 U8 *uscan = (U8*)NULL;
3417 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
3418 U32 charcount = 0; /* how many input chars we have matched */
3419 U32 accepted = 0; /* have we seen any accepting states? */
3421 ST.jump = trie->jump;
3424 ST.longfold = FALSE; /* char longer if folded => it's harder */
3427 /* fully traverse the TRIE; note the position of the
3428 shortest accept state and the wordnum of the longest
3431 while ( state && uc <= (U8*)PL_regeol ) {
3432 U32 base = trie->states[ state ].trans.base;
3436 wordnum = trie->states[ state ].wordnum;
3438 if (wordnum) { /* it's an accept state */
3441 /* record first match position */
3443 ST.firstpos = (U8*)locinput;
3448 ST.firstchars = charcount;
3451 if (!ST.nextword || wordnum < ST.nextword)
3452 ST.nextword = wordnum;
3453 ST.topword = wordnum;
3456 DEBUG_TRIE_EXECUTE_r({
3457 DUMP_EXEC_POS( (char *)uc, scan, utf8_target );
3458 PerlIO_printf( Perl_debug_log,
3459 "%*s %sState: %4"UVxf" Accepted: %c ",
3460 2+depth * 2, "", PL_colors[4],
3461 (UV)state, (accepted ? 'Y' : 'N'));
3464 /* read a char and goto next state */
3467 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
3468 uscan, len, uvc, charid, foldlen,
3475 base + charid - 1 - trie->uniquecharcount)) >= 0)
3477 && ((U32)offset < trie->lasttrans)
3478 && trie->trans[offset].check == state)
3480 state = trie->trans[offset].next;
3491 DEBUG_TRIE_EXECUTE_r(
3492 PerlIO_printf( Perl_debug_log,
3493 "Charid:%3x CP:%4"UVxf" After State: %4"UVxf"%s\n",
3494 charid, uvc, (UV)state, PL_colors[5] );
3500 /* calculate total number of accept states */
3505 w = trie->wordinfo[w].prev;
3508 ST.accepted = accepted;
3512 PerlIO_printf( Perl_debug_log,
3513 "%*s %sgot %"IVdf" possible matches%s\n",
3514 REPORT_CODE_OFF + depth * 2, "",
3515 PL_colors[4], (IV)ST.accepted, PL_colors[5] );
3517 goto trie_first_try; /* jump into the fail handler */
3519 assert(0); /* NOTREACHED */
3521 case TRIE_next_fail: /* we failed - try next alternative */
3523 REGCP_UNWIND(ST.cp);
3524 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
3526 if (!--ST.accepted) {
3528 PerlIO_printf( Perl_debug_log,
3529 "%*s %sTRIE failed...%s\n",
3530 REPORT_CODE_OFF+depth*2, "",
3537 /* Find next-highest word to process. Note that this code
3538 * is O(N^2) per trie run (O(N) per branch), so keep tight */
3541 U16 const nextword = ST.nextword;
3542 reg_trie_wordinfo * const wordinfo
3543 = ((reg_trie_data*)rexi->data->data[ARG(ST.me)])->wordinfo;
3544 for (word=ST.topword; word; word=wordinfo[word].prev) {
3545 if (word > nextword && (!min || word < min))
3558 ST.lastparen = rex->lastparen;
3559 ST.lastcloseparen = rex->lastcloseparen;
3563 /* find start char of end of current word */
3565 U32 chars; /* how many chars to skip */
3566 U8 *uc = ST.firstpos;
3567 reg_trie_data * const trie
3568 = (reg_trie_data*)rexi->data->data[ARG(ST.me)];
3570 assert((trie->wordinfo[ST.nextword].len - trie->prefixlen)
3572 chars = (trie->wordinfo[ST.nextword].len - trie->prefixlen)
3576 /* the hard option - fold each char in turn and find
3577 * its folded length (which may be different */
3578 U8 foldbuf[UTF8_MAXBYTES_CASE + 1];
3586 uvc = utf8n_to_uvuni((U8*)uc, UTF8_MAXLEN, &len,
3594 uvc = to_uni_fold(uvc, foldbuf, &foldlen);
3599 uvc = utf8n_to_uvuni(uscan, UTF8_MAXLEN, &len,
3613 PL_reginput = (char *)uc;
3616 scan = ST.me + ((ST.jump && ST.jump[ST.nextword])
3617 ? ST.jump[ST.nextword]
3621 PerlIO_printf( Perl_debug_log,
3622 "%*s %sTRIE matched word #%d, continuing%s\n",
3623 REPORT_CODE_OFF+depth*2, "",
3630 if (ST.accepted > 1 || has_cutgroup) {
3631 PUSH_STATE_GOTO(TRIE_next, scan);
3632 assert(0); /* NOTREACHED */
3634 /* only one choice left - just continue */
3636 AV *const trie_words
3637 = MUTABLE_AV(rexi->data->data[ARG(ST.me)+TRIE_WORDS_OFFSET]);
3638 SV ** const tmp = av_fetch( trie_words,
3640 SV *sv= tmp ? sv_newmortal() : NULL;
3642 PerlIO_printf( Perl_debug_log,
3643 "%*s %sonly one match left, short-circuiting: #%d <%s>%s\n",
3644 REPORT_CODE_OFF+depth*2, "", PL_colors[4],
3646 tmp ? pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 0,
3647 PL_colors[0], PL_colors[1],
3648 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)|PERL_PV_ESCAPE_NONASCII
3650 : "not compiled under -Dr",
3654 locinput = PL_reginput;
3655 nextchr = UCHARAT(locinput);
3656 continue; /* execute rest of RE */
3657 assert(0); /* NOTREACHED */
3661 char *s = STRING(scan);
3663 if (utf8_target != UTF_PATTERN) {
3664 /* The target and the pattern have differing utf8ness. */
3666 const char * const e = s + ln;
3669 /* The target is utf8, the pattern is not utf8. */
3674 if (NATIVE_TO_UNI(*(U8*)s) !=
3675 utf8n_to_uvuni((U8*)l, UTF8_MAXBYTES, &ulen,
3683 /* The target is not utf8, the pattern is utf8. */
3688 if (NATIVE_TO_UNI(*((U8*)l)) !=
3689 utf8n_to_uvuni((U8*)s, UTF8_MAXBYTES, &ulen,
3697 nextchr = UCHARAT(locinput);
3700 /* The target and the pattern have the same utf8ness. */
3701 /* Inline the first character, for speed. */
3702 if (UCHARAT(s) != nextchr)
3704 if (PL_regeol - locinput < ln)
3706 if (ln > 1 && memNE(s, locinput, ln))
3709 nextchr = UCHARAT(locinput);
3714 const U8 * fold_array;
3716 U32 fold_utf8_flags;
3718 PL_reg_flags |= RF_tainted;
3719 folder = foldEQ_locale;
3720 fold_array = PL_fold_locale;
3721 fold_utf8_flags = FOLDEQ_UTF8_LOCALE;
3725 case EXACTFU_TRICKYFOLD:
3727 folder = foldEQ_latin1;
3728 fold_array = PL_fold_latin1;
3729 fold_utf8_flags = (UTF_PATTERN) ? FOLDEQ_S1_ALREADY_FOLDED : 0;
3733 folder = foldEQ_latin1;
3734 fold_array = PL_fold_latin1;
3735 fold_utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
3740 fold_array = PL_fold;
3741 fold_utf8_flags = 0;
3747 if (utf8_target || UTF_PATTERN || state_num == EXACTFU_SS) {
3748 /* Either target or the pattern are utf8, or has the issue where
3749 * the fold lengths may differ. */
3750 const char * const l = locinput;
3751 char *e = PL_regeol;
3753 if (! foldEQ_utf8_flags(s, 0, ln, cBOOL(UTF_PATTERN),
3754 l, &e, 0, utf8_target, fold_utf8_flags))
3759 nextchr = UCHARAT(locinput);
3763 /* Neither the target nor the pattern are utf8 */
3764 if (UCHARAT(s) != nextchr &&
3765 UCHARAT(s) != fold_array[nextchr])
3769 if (PL_regeol - locinput < ln)
3771 if (ln > 1 && ! folder(s, locinput, ln))
3774 nextchr = UCHARAT(locinput);
3778 /* XXX Could improve efficiency by separating these all out using a
3779 * macro or in-line function. At that point regcomp.c would no longer
3780 * have to set the FLAGS fields of these */
3783 PL_reg_flags |= RF_tainted;
3791 /* was last char in word? */
3793 && FLAGS(scan) != REGEX_ASCII_RESTRICTED_CHARSET
3794 && FLAGS(scan) != REGEX_ASCII_MORE_RESTRICTED_CHARSET)
3796 if (locinput == PL_bostr)
3799 const U8 * const r = reghop3((U8*)locinput, -1, (U8*)PL_bostr);
3801 ln = utf8n_to_uvchr(r, UTF8SKIP(r), 0, uniflags);
3803 if (FLAGS(scan) != REGEX_LOCALE_CHARSET) {
3804 ln = isALNUM_uni(ln);
3805 LOAD_UTF8_CHARCLASS_ALNUM();
3806 n = swash_fetch(PL_utf8_alnum, (U8*)locinput, utf8_target);
3809 ln = isALNUM_LC_uvchr(UNI_TO_NATIVE(ln));
3810 n = isALNUM_LC_utf8((U8*)locinput);
3815 /* Here the string isn't utf8, or is utf8 and only ascii
3816 * characters are to match \w. In the latter case looking at
3817 * the byte just prior to the current one may be just the final
3818 * byte of a multi-byte character. This is ok. There are two
3820 * 1) it is a single byte character, and then the test is doing
3821 * just what it's supposed to.
3822 * 2) it is a multi-byte character, in which case the final
3823 * byte is never mistakable for ASCII, and so the test
3824 * will say it is not a word character, which is the
3825 * correct answer. */
3826 ln = (locinput != PL_bostr) ?
3827 UCHARAT(locinput - 1) : '\n';
3828 switch (FLAGS(scan)) {
3829 case REGEX_UNICODE_CHARSET:
3830 ln = isWORDCHAR_L1(ln);
3831 n = isWORDCHAR_L1(nextchr);
3833 case REGEX_LOCALE_CHARSET:
3834 ln = isALNUM_LC(ln);
3835 n = isALNUM_LC(nextchr);
3837 case REGEX_DEPENDS_CHARSET:
3839 n = isALNUM(nextchr);
3841 case REGEX_ASCII_RESTRICTED_CHARSET:
3842 case REGEX_ASCII_MORE_RESTRICTED_CHARSET:
3843 ln = isWORDCHAR_A(ln);
3844 n = isWORDCHAR_A(nextchr);
3847 Perl_croak(aTHX_ "panic: Unexpected FLAGS %u in op %u", FLAGS(scan), OP(scan));
3851 /* Note requires that all BOUNDs be lower than all NBOUNDs in
3853 if (((!ln) == (!n)) == (OP(scan) < NBOUND))
3858 if (utf8_target || state_num == ANYOFV) {
3859 STRLEN inclasslen = PL_regeol - locinput;
3860 if (locinput >= PL_regeol)
3863 if (!reginclass(rex, scan, (U8*)locinput, &inclasslen, utf8_target))
3865 locinput += inclasslen;
3866 nextchr = UCHARAT(locinput);
3871 nextchr = UCHARAT(locinput);
3872 if (!nextchr && locinput >= PL_regeol)
3874 if (!REGINCLASS(rex, scan, (U8*)locinput))
3876 nextchr = UCHARAT(++locinput);
3880 /* Special char classes - The defines start on line 129 or so */
3881 CCC_TRY_U(ALNUM, NALNUM, isWORDCHAR,
3882 ALNUML, NALNUML, isALNUM_LC, isALNUM_LC_utf8,
3883 ALNUMU, NALNUMU, isWORDCHAR_L1,
3884 ALNUMA, NALNUMA, isWORDCHAR_A,
3887 CCC_TRY_U(SPACE, NSPACE, isSPACE,
3888 SPACEL, NSPACEL, isSPACE_LC, isSPACE_LC_utf8,
3889 SPACEU, NSPACEU, isSPACE_L1,
3890 SPACEA, NSPACEA, isSPACE_A,
3893 CCC_TRY(DIGIT, NDIGIT, isDIGIT,
3894 DIGITL, NDIGITL, isDIGIT_LC, isDIGIT_LC_utf8,
3895 DIGITA, NDIGITA, isDIGIT_A,
3899 if (locinput >= PL_regeol || ! _generic_isCC_A(nextchr, FLAGS(scan))) {
3902 /* Matched a utf8-invariant, so don't have to worry about utf8 */
3903 nextchr = UCHARAT(++locinput);
3906 if (locinput >= PL_regeol || _generic_isCC_A(nextchr, FLAGS(scan))) {
3910 locinput += PL_utf8skip[nextchr];
3911 nextchr = UCHARAT(locinput);
3914 nextchr = UCHARAT(++locinput);
3918 case CLUMP: /* Match \X: logical Unicode character. This is defined as
3919 a Unicode extended Grapheme Cluster */
3920 /* From http://www.unicode.org/reports/tr29 (5.2 version). An
3921 extended Grapheme Cluster is:
3924 | Prepend* Begin Extend*
3927 Begin is (Hangul-syllable | ! Control)
3928 Extend is (Grapheme_Extend | Spacing_Mark)
3929 Control is [ GCB_Control CR LF ]
3931 The discussion below shows how the code for CLUMP is derived
3932 from this regex. Note that most of these concepts are from
3933 property values of the Grapheme Cluster Boundary (GCB) property.
3934 No code point can have multiple property values for a given
3935 property. Thus a code point in Prepend can't be in Control, but
3936 it must be in !Control. This is why Control above includes
3937 GCB_Control plus CR plus LF. The latter two are used in the GCB
3938 property separately, and so can't be in GCB_Control, even though
3939 they logically are controls. Control is not the same as gc=cc,
3940 but includes format and other characters as well.
3942 The Unicode definition of Hangul-syllable is:
3944 | (L* ( ( V | LV ) V* | LVT ) T*)
3947 Each of these is a value for the GCB property, and hence must be
3948 disjoint, so the order they are tested is immaterial, so the
3949 above can safely be changed to
3952 | (L* ( LVT | ( V | LV ) V*) T*)
3954 The last two terms can be combined like this:
3955 L* ( L | (( LVT | ( V | LV ) V*) T*))
3957 That means that if we have seen any L's at all we can quit
3958 there, but if the next character is an LVT, a V, or an LV we
3961 There is a subtlety with Prepend* which showed up in testing.
3962 Note that the Begin, and only the Begin is required in:
3963 | Prepend* Begin Extend*
3964 Also, Begin contains '! Control'. A Prepend must be a
3965 '! Control', which means it must also be a Begin. What it
3966 comes down to is that if we match Prepend* and then find no
3967 suitable Begin afterwards, that if we backtrack the last
3968 Prepend, that one will be a suitable Begin.
3971 if (locinput >= PL_regeol)
3973 if (! utf8_target) {
3975 /* Match either CR LF or '.', as all the other possibilities
3977 locinput++; /* Match the . or CR */
3978 if (nextchr == '\r' /* And if it was CR, and the next is LF,
3980 && locinput < PL_regeol
3981 && UCHARAT(locinput) == '\n') locinput++;
3985 /* Utf8: See if is ( CR LF ); already know that locinput <
3986 * PL_regeol, so locinput+1 is in bounds */
3987 if (nextchr == '\r' && UCHARAT(locinput + 1) == '\n') {
3991 /* In case have to backtrack to beginning, then match '.' */
3992 char *starting = locinput;
3994 /* In case have to backtrack the last prepend */
3995 char *previous_prepend = 0;
3997 LOAD_UTF8_CHARCLASS_GCB();
3999 /* Match (prepend)* */
4000 while (locinput < PL_regeol
4001 && swash_fetch(PL_utf8_X_prepend,
4002 (U8*)locinput, utf8_target))
4004 previous_prepend = locinput;
4005 locinput += UTF8SKIP(locinput);
4008 /* As noted above, if we matched a prepend character, but
4009 * the next thing won't match, back off the last prepend we
4010 * matched, as it is guaranteed to match the begin */
4011 if (previous_prepend
4012 && (locinput >= PL_regeol
4013 || ! swash_fetch(PL_utf8_X_begin,
4014 (U8*)locinput, utf8_target)))
4016 locinput = previous_prepend;
4019 /* Note that here we know PL_regeol > locinput, as we
4020 * tested that upon input to this switch case, and if we
4021 * moved locinput forward, we tested the result just above
4022 * and it either passed, or we backed off so that it will
4024 if (! swash_fetch(PL_utf8_X_begin, (U8*)locinput, utf8_target)) {
4026 /* Here did not match the required 'Begin' in the
4027 * second term. So just match the very first
4028 * character, the '.' of the final term of the regex */
4029 locinput = starting + UTF8SKIP(starting);
4032 /* Here is the beginning of a character that can have
4033 * an extender. It is either a hangul syllable, or a
4035 if (swash_fetch(PL_utf8_X_non_hangul,
4036 (U8*)locinput, utf8_target))
4039 /* Here not a Hangul syllable, must be a
4040 * ('! * Control') */
4041 locinput += UTF8SKIP(locinput);
4044 /* Here is a Hangul syllable. It can be composed
4045 * of several individual characters. One
4046 * possibility is T+ */
4047 if (swash_fetch(PL_utf8_X_T,
4048 (U8*)locinput, utf8_target))
4050 while (locinput < PL_regeol
4051 && swash_fetch(PL_utf8_X_T,
4052 (U8*)locinput, utf8_target))
4054 locinput += UTF8SKIP(locinput);
4058 /* Here, not T+, but is a Hangul. That means
4059 * it is one of the others: L, LV, LVT or V,
4061 * L* (L | LVT T* | V V* T* | LV V* T*) */
4064 while (locinput < PL_regeol
4065 && swash_fetch(PL_utf8_X_L,
4066 (U8*)locinput, utf8_target))
4068 locinput += UTF8SKIP(locinput);
4071 /* Here, have exhausted L*. If the next
4072 * character is not an LV, LVT nor V, it means
4073 * we had to have at least one L, so matches L+
4074 * in the original equation, we have a complete
4075 * hangul syllable. Are done. */
4077 if (locinput < PL_regeol
4078 && swash_fetch(PL_utf8_X_LV_LVT_V,
4079 (U8*)locinput, utf8_target))
4082 /* Otherwise keep going. Must be LV, LVT
4083 * or V. See if LVT */
4084 if (is_utf8_X_LVT((U8*)locinput)) {
4085 locinput += UTF8SKIP(locinput);
4088 /* Must be V or LV. Take it, then
4090 locinput += UTF8SKIP(locinput);
4091 while (locinput < PL_regeol
4092 && swash_fetch(PL_utf8_X_V,
4093 (U8*)locinput, utf8_target))
4095 locinput += UTF8SKIP(locinput);
4099 /* And any of LV, LVT, or V can be followed
4101 while (locinput < PL_regeol
4102 && swash_fetch(PL_utf8_X_T,
4106 locinput += UTF8SKIP(locinput);
4112 /* Match any extender */
4113 while (locinput < PL_regeol
4114 && swash_fetch(PL_utf8_X_extend,
4115 (U8*)locinput, utf8_target))
4117 locinput += UTF8SKIP(locinput);
4121 if (locinput > PL_regeol) sayNO;
4123 nextchr = UCHARAT(locinput);
4127 { /* The capture buffer cases. The ones beginning with N for the
4128 named buffers just convert to the equivalent numbered and
4129 pretend they were called as the corresponding numbered buffer
4131 /* don't initialize these in the declaration, it makes C++
4136 const U8 *fold_array;
4139 PL_reg_flags |= RF_tainted;
4140 folder = foldEQ_locale;
4141 fold_array = PL_fold_locale;
4143 utf8_fold_flags = FOLDEQ_UTF8_LOCALE;
4147 folder = foldEQ_latin1;
4148 fold_array = PL_fold_latin1;
4150 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
4154 folder = foldEQ_latin1;
4155 fold_array = PL_fold_latin1;
4157 utf8_fold_flags = 0;
4162 fold_array = PL_fold;
4164 utf8_fold_flags = 0;
4171 utf8_fold_flags = 0;
4174 /* For the named back references, find the corresponding buffer
4176 n = reg_check_named_buff_matched(rex,scan);
4181 goto do_nref_ref_common;
4184 PL_reg_flags |= RF_tainted;
4185 folder = foldEQ_locale;
4186 fold_array = PL_fold_locale;
4187 utf8_fold_flags = FOLDEQ_UTF8_LOCALE;
4191 folder = foldEQ_latin1;
4192 fold_array = PL_fold_latin1;
4193 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
4197 folder = foldEQ_latin1;
4198 fold_array = PL_fold_latin1;
4199 utf8_fold_flags = 0;
4204 fold_array = PL_fold;
4205 utf8_fold_flags = 0;
4211 utf8_fold_flags = 0;
4215 n = ARG(scan); /* which paren pair */
4218 ln = rex->offs[n].start;
4219 PL_reg_leftiter = PL_reg_maxiter; /* Void cache */
4220 if (rex->lastparen < n || ln == -1)
4221 sayNO; /* Do not match unless seen CLOSEn. */
4222 if (ln == rex->offs[n].end)
4226 if (type != REF /* REF can do byte comparison */
4227 && (utf8_target || type == REFFU))
4228 { /* XXX handle REFFL better */
4229 char * limit = PL_regeol;
4231 /* This call case insensitively compares the entire buffer
4232 * at s, with the current input starting at locinput, but
4233 * not going off the end given by PL_regeol, and returns in
4234 * limit upon success, how much of the current input was
4236 if (! foldEQ_utf8_flags(s, NULL, rex->offs[n].end - ln, utf8_target,
4237 locinput, &limit, 0, utf8_target, utf8_fold_flags))
4242 nextchr = UCHARAT(locinput);
4246 /* Not utf8: Inline the first character, for speed. */
4247 if (UCHARAT(s) != nextchr &&
4249 UCHARAT(s) != fold_array[nextchr]))
4251 ln = rex->offs[n].end - ln;
4252 if (locinput + ln > PL_regeol)
4254 if (ln > 1 && (type == REF
4255 ? memNE(s, locinput, ln)
4256 : ! folder(s, locinput, ln)))
4259 nextchr = UCHARAT(locinput);
4269 #define ST st->u.eval
4274 regexp_internal *rei;
4275 regnode *startpoint;
4278 case GOSUB: /* /(...(?1))/ /(...(?&foo))/ */
4279 if (cur_eval && cur_eval->locinput==locinput) {
4280 if (cur_eval->u.eval.close_paren == (U32)ARG(scan))
4281 Perl_croak(aTHX_ "Infinite recursion in regex");
4282 if ( ++nochange_depth > max_nochange_depth )
4284 "Pattern subroutine nesting without pos change"
4285 " exceeded limit in regex");
4292 if (OP(scan)==GOSUB) {
4293 startpoint = scan + ARG2L(scan);
4294 ST.close_paren = ARG(scan);
4296 startpoint = rei->program+1;
4299 goto eval_recurse_doit;
4300 assert(0); /* NOTREACHED */
4301 case EVAL: /* /(?{A})B/ /(??{A})B/ and /(?(?{A})X|Y)B/ */
4302 if (cur_eval && cur_eval->locinput==locinput) {
4303 if ( ++nochange_depth > max_nochange_depth )
4304 Perl_croak(aTHX_ "EVAL without pos change exceeded limit in regex");
4309 /* execute the code in the {...} */
4313 OP * const oop = PL_op;
4314 COP * const ocurcop = PL_curcop;
4316 char *saved_regeol = PL_regeol;
4317 struct re_save_state saved_state;
4320 /* save *all* paren positions */
4322 REGCP_SET(runops_cp);
4324 /* To not corrupt the existing regex state while executing the
4325 * eval we would normally put it on the save stack, like with
4326 * save_re_context. However, re-evals have a weird scoping so we
4327 * can't just add ENTER/LEAVE here. With that, things like
4329 * (?{$a=2})(a(?{local$a=$a+1}))*aak*c(?{$b=$a})
4331 * would break, as they expect the localisation to be unwound
4332 * only when the re-engine backtracks through the bit that
4335 * What we do instead is just saving the state in a local c
4338 Copy(&PL_reg_state, &saved_state, 1, struct re_save_state);
4340 PL_reg_state.re_reparsing = FALSE;
4343 caller_cv = find_runcv(NULL);
4347 if (rexi->data->what[n] == 'r') { /* code from an external qr */
4348 newcv = ((struct regexp *)SvANY(
4349 (REGEXP*)(rexi->data->data[n])
4352 nop = (OP*)rexi->data->data[n+1];
4354 else if (rexi->data->what[n] == 'l') { /* literal code */
4356 nop = (OP*)rexi->data->data[n];
4357 assert(CvDEPTH(newcv));
4360 /* literal with own CV */
4361 assert(rexi->data->what[n] == 'L');
4362 newcv = rex->qr_anoncv;
4363 nop = (OP*)rexi->data->data[n];
4366 /* normally if we're about to execute code from the same
4367 * CV that we used previously, we just use the existing
4368 * CX stack entry. However, its possible that in the
4369 * meantime we may have backtracked, popped from the save
4370 * stack, and undone the SAVECOMPPAD(s) associated with
4371 * PUSH_MULTICALL; in which case PL_comppad no longer
4372 * points to newcv's pad. */
4373 if (newcv != last_pushed_cv || PL_comppad != last_pad)
4375 I32 depth = (newcv == caller_cv) ? 0 : 1;
4376 if (last_pushed_cv) {
4377 CHANGE_MULTICALL_WITHDEPTH(newcv, depth);
4380 PUSH_MULTICALL_WITHDEPTH(newcv, depth);
4382 last_pushed_cv = newcv;
4384 last_pad = PL_comppad;
4386 /* the initial nextstate you would normally execute
4387 * at the start of an eval (which would cause error
4388 * messages to come from the eval), may be optimised
4389 * away from the execution path in the regex code blocks;
4390 * so manually set PL_curcop to it initially */
4392 OP *o = cUNOPx(nop)->op_first;
4393 assert(o->op_type == OP_NULL);
4394 if (o->op_targ == OP_SCOPE) {
4395 o = cUNOPo->op_first;
4398 assert(o->op_targ == OP_LEAVE);
4399 o = cUNOPo->op_first;
4400 assert(o->op_type == OP_ENTER);
4404 if (o->op_type != OP_STUB) {
4405 assert( o->op_type == OP_NEXTSTATE
4406 || o->op_type == OP_DBSTATE
4407 || (o->op_type == OP_NULL
4408 && ( o->op_targ == OP_NEXTSTATE
4409 || o->op_targ == OP_DBSTATE
4413 PL_curcop = (COP*)o;
4418 DEBUG_STATE_r( PerlIO_printf(Perl_debug_log,
4419 " re EVAL PL_op=0x%"UVxf"\n", PTR2UV(nop)) );
4421 rex->offs[0].end = PL_reg_magic->mg_len = locinput - PL_bostr;
4424 SV *sv_mrk = get_sv("REGMARK", 1);
4425 sv_setsv(sv_mrk, sv_yes_mark);
4428 /* we don't use MULTICALL here as we want to call the
4429 * first op of the block of interest, rather than the
4430 * first op of the sub */
4433 CALLRUNOPS(aTHX); /* Scalar context. */
4436 ret = &PL_sv_undef; /* protect against empty (?{}) blocks. */
4442 /* before restoring everything, evaluate the returned
4443 * value, so that 'uninit' warnings don't use the wrong
4444 * PL_op or pad. Also need to process any magic vars
4445 * (e.g. $1) *before* parentheses are restored */
4450 if (logical == 0) /* (?{})/ */
4451 sv_setsv(save_scalar(PL_replgv), ret); /* $^R */
4452 else if (logical == 1) { /* /(?(?{...})X|Y)/ */
4453 sw = cBOOL(SvTRUE(ret));
4456 else { /* /(??{}) */
4457 /* if its overloaded, let the regex compiler handle
4458 * it; otherwise extract regex, or stringify */
4459 if (!SvAMAGIC(ret)) {
4463 if (SvTYPE(sv) == SVt_REGEXP)
4464 re_sv = (REGEXP*) sv;
4465 else if (SvSMAGICAL(sv)) {
4466 MAGIC *mg = mg_find(sv, PERL_MAGIC_qr);
4468 re_sv = (REGEXP *) mg->mg_obj;
4471 /* force any magic, undef warnings here */
4473 ret = sv_mortalcopy(ret);
4474 (void) SvPV_force_nolen(ret);
4480 Copy(&saved_state, &PL_reg_state, 1, struct re_save_state);
4482 /* *** Note that at this point we don't restore
4483 * PL_comppad, (or pop the CxSUB) on the assumption it may
4484 * be used again soon. This is safe as long as nothing
4485 * in the regexp code uses the pad ! */
4487 PL_curcop = ocurcop;
4488 PL_regeol = saved_regeol;
4489 S_regcp_restore(aTHX_ rex, runops_cp);
4495 /* only /(??{})/ from now on */
4498 /* extract RE object from returned value; compiling if
4502 re_sv = reg_temp_copy(NULL, re_sv);
4506 const I32 osize = PL_regsize;
4508 if (SvUTF8(ret) && IN_BYTES) {
4509 /* In use 'bytes': make a copy of the octet
4510 * sequence, but without the flag on */
4512 const char *const p = SvPV(ret, len);
4513 ret = newSVpvn_flags(p, len, SVs_TEMP);
4515 if (rex->intflags & PREGf_USE_RE_EVAL)
4516 pm_flags |= PMf_USE_RE_EVAL;
4518 /* if we got here, it should be an engine which
4519 * supports compiling code blocks and stuff */
4520 assert(rex->engine && rex->engine->op_comp);
4521 assert(!(scan->flags & ~RXf_PMf_COMPILETIME));
4522 re_sv = rex->engine->op_comp(aTHX_ &ret, 1, NULL,
4523 rex->engine, NULL, NULL,
4524 /* copy /msix etc to inner pattern */
4529 & (SVs_TEMP | SVs_PADTMP | SVf_READONLY
4531 /* This isn't a first class regexp. Instead, it's
4532 caching a regexp onto an existing, Perl visible
4534 sv_magic(ret, MUTABLE_SV(re_sv), PERL_MAGIC_qr, 0, 0);
4537 /* safe to do now that any $1 etc has been
4538 * interpolated into the new pattern string and
4540 S_regcp_restore(aTHX_ rex, runops_cp);
4542 re = (struct regexp *)SvANY(re_sv);
4544 RXp_MATCH_COPIED_off(re);
4545 re->subbeg = rex->subbeg;
4546 re->sublen = rex->sublen;
4549 debug_start_match(re_sv, utf8_target, locinput, PL_regeol,
4550 "Matching embedded");
4552 startpoint = rei->program + 1;
4553 ST.close_paren = 0; /* only used for GOSUB */
4555 eval_recurse_doit: /* Share code with GOSUB below this line */
4556 /* run the pattern returned from (??{...}) */
4557 ST.cp = regcppush(rex, 0); /* Save *all* the positions. */
4558 REGCP_SET(ST.lastcp);
4561 re->lastcloseparen = 0;
4563 PL_reginput = locinput;
4566 /* XXXX This is too dramatic a measure... */
4569 ST.toggle_reg_flags = PL_reg_flags;
4571 PL_reg_flags |= RF_utf8;
4573 PL_reg_flags &= ~RF_utf8;
4574 ST.toggle_reg_flags ^= PL_reg_flags; /* diff of old and new */
4576 ST.prev_rex = rex_sv;
4577 ST.prev_curlyx = cur_curlyx;
4579 SET_reg_curpm(rex_sv);
4584 ST.prev_eval = cur_eval;
4586 /* now continue from first node in postoned RE */
4587 PUSH_YES_STATE_GOTO(EVAL_AB, startpoint);
4588 assert(0); /* NOTREACHED */
4591 case EVAL_AB: /* cleanup after a successful (??{A})B */
4592 /* note: this is called twice; first after popping B, then A */
4593 PL_reg_flags ^= ST.toggle_reg_flags;
4594 rex_sv = ST.prev_rex;
4595 SET_reg_curpm(rex_sv);
4596 rex = (struct regexp *)SvANY(rex_sv);
4597 rexi = RXi_GET(rex);
4599 cur_eval = ST.prev_eval;
4600 cur_curlyx = ST.prev_curlyx;
4602 /* XXXX This is too dramatic a measure... */
4604 if ( nochange_depth )
4609 case EVAL_AB_fail: /* unsuccessfully ran A or B in (??{A})B */
4610 /* note: this is called twice; first after popping B, then A */
4611 PL_reg_flags ^= ST.toggle_reg_flags;
4612 rex_sv = ST.prev_rex;
4613 SET_reg_curpm(rex_sv);
4614 rex = (struct regexp *)SvANY(rex_sv);
4615 rexi = RXi_GET(rex);
4617 PL_reginput = locinput;
4618 REGCP_UNWIND(ST.lastcp);
4620 cur_eval = ST.prev_eval;
4621 cur_curlyx = ST.prev_curlyx;
4622 /* XXXX This is too dramatic a measure... */
4624 if ( nochange_depth )
4630 n = ARG(scan); /* which paren pair */
4631 rex->offs[n].start_tmp = locinput - PL_bostr;
4634 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
4635 "rex=0x%"UVxf" offs=0x%"UVxf": \\%"UVuf": set %"IVdf" tmp; regsize=%"UVuf"\n",
4639 (IV)rex->offs[n].start_tmp,
4645 /* XXX really need to log other places start/end are set too */
4646 #define CLOSE_CAPTURE \
4647 rex->offs[n].start = rex->offs[n].start_tmp; \
4648 rex->offs[n].end = locinput - PL_bostr; \
4649 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log, \
4650 "rex=0x%"UVxf" offs=0x%"UVxf": \\%"UVuf": set %"IVdf"..%"IVdf"\n", \
4652 PTR2UV(rex->offs), \
4654 (IV)rex->offs[n].start, \
4655 (IV)rex->offs[n].end \
4659 n = ARG(scan); /* which paren pair */
4661 /*if (n > PL_regsize)
4663 if (n > rex->lastparen)
4665 rex->lastcloseparen = n;
4666 if (cur_eval && cur_eval->u.eval.close_paren == n) {
4674 cursor && OP(cursor)!=END;
4675 cursor=regnext(cursor))
4677 if ( OP(cursor)==CLOSE ){
4679 if ( n <= lastopen ) {
4681 /*if (n > PL_regsize)
4683 if (n > rex->lastparen)
4685 rex->lastcloseparen = n;
4686 if ( n == ARG(scan) || (cur_eval &&
4687 cur_eval->u.eval.close_paren == n))
4696 n = ARG(scan); /* which paren pair */
4697 sw = cBOOL(rex->lastparen >= n && rex->offs[n].end != -1);
4700 /* reg_check_named_buff_matched returns 0 for no match */
4701 sw = cBOOL(0 < reg_check_named_buff_matched(rex,scan));
4705 sw = (cur_eval && (!n || cur_eval->u.eval.close_paren == n));
4711 PL_reg_leftiter = PL_reg_maxiter; /* Void cache */
4713 next = NEXTOPER(NEXTOPER(scan));
4715 next = scan + ARG(scan);
4716 if (OP(next) == IFTHEN) /* Fake one. */
4717 next = NEXTOPER(NEXTOPER(next));
4721 logical = scan->flags;
4724 /*******************************************************************
4726 The CURLYX/WHILEM pair of ops handle the most generic case of the /A*B/
4727 pattern, where A and B are subpatterns. (For simple A, CURLYM or
4728 STAR/PLUS/CURLY/CURLYN are used instead.)
4730 A*B is compiled as <CURLYX><A><WHILEM><B>
4732 On entry to the subpattern, CURLYX is called. This pushes a CURLYX
4733 state, which contains the current count, initialised to -1. It also sets
4734 cur_curlyx to point to this state, with any previous value saved in the
4737 CURLYX then jumps straight to the WHILEM op, rather than executing A,
4738 since the pattern may possibly match zero times (i.e. it's a while {} loop
4739 rather than a do {} while loop).
4741 Each entry to WHILEM represents a successful match of A. The count in the
4742 CURLYX block is incremented, another WHILEM state is pushed, and execution
4743 passes to A or B depending on greediness and the current count.
4745 For example, if matching against the string a1a2a3b (where the aN are
4746 substrings that match /A/), then the match progresses as follows: (the
4747 pushed states are interspersed with the bits of strings matched so far):
4750 <CURLYX cnt=0><WHILEM>
4751 <CURLYX cnt=1><WHILEM> a1 <WHILEM>
4752 <CURLYX cnt=2><WHILEM> a1 <WHILEM> a2 <WHILEM>
4753 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM>
4754 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM> b
4756 (Contrast this with something like CURLYM, which maintains only a single
4760 a1 <CURLYM cnt=1> a2
4761 a1 a2 <CURLYM cnt=2> a3
4762 a1 a2 a3 <CURLYM cnt=3> b
4765 Each WHILEM state block marks a point to backtrack to upon partial failure
4766 of A or B, and also contains some minor state data related to that
4767 iteration. The CURLYX block, pointed to by cur_curlyx, contains the
4768 overall state, such as the count, and pointers to the A and B ops.
4770 This is complicated slightly by nested CURLYX/WHILEM's. Since cur_curlyx
4771 must always point to the *current* CURLYX block, the rules are:
4773 When executing CURLYX, save the old cur_curlyx in the CURLYX state block,
4774 and set cur_curlyx to point the new block.
4776 When popping the CURLYX block after a successful or unsuccessful match,
4777 restore the previous cur_curlyx.
4779 When WHILEM is about to execute B, save the current cur_curlyx, and set it
4780 to the outer one saved in the CURLYX block.
4782 When popping the WHILEM block after a successful or unsuccessful B match,
4783 restore the previous cur_curlyx.
4785 Here's an example for the pattern (AI* BI)*BO
4786 I and O refer to inner and outer, C and W refer to CURLYX and WHILEM:
4789 curlyx backtrack stack
4790 ------ ---------------
4792 CO <CO prev=NULL> <WO>
4793 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
4794 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
4795 NULL <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi <WO prev=CO> bo
4797 At this point the pattern succeeds, and we work back down the stack to
4798 clean up, restoring as we go:
4800 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
4801 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
4802 CO <CO prev=NULL> <WO>
4805 *******************************************************************/
4807 #define ST st->u.curlyx
4809 case CURLYX: /* start of /A*B/ (for complex A) */
4811 /* No need to save/restore up to this paren */
4812 I32 parenfloor = scan->flags;
4814 assert(next); /* keep Coverity happy */
4815 if (OP(PREVOPER(next)) == NOTHING) /* LONGJMP */
4818 /* XXXX Probably it is better to teach regpush to support
4819 parenfloor > PL_regsize... */
4820 if (parenfloor > (I32)rex->lastparen)
4821 parenfloor = rex->lastparen; /* Pessimization... */
4823 ST.prev_curlyx= cur_curlyx;
4825 ST.cp = PL_savestack_ix;
4827 /* these fields contain the state of the current curly.
4828 * they are accessed by subsequent WHILEMs */
4829 ST.parenfloor = parenfloor;
4834 ST.count = -1; /* this will be updated by WHILEM */
4835 ST.lastloc = NULL; /* this will be updated by WHILEM */
4837 PL_reginput = locinput;
4838 PUSH_YES_STATE_GOTO(CURLYX_end, PREVOPER(next));
4839 assert(0); /* NOTREACHED */
4842 case CURLYX_end: /* just finished matching all of A*B */
4843 cur_curlyx = ST.prev_curlyx;
4845 assert(0); /* NOTREACHED */
4847 case CURLYX_end_fail: /* just failed to match all of A*B */
4849 cur_curlyx = ST.prev_curlyx;
4851 assert(0); /* NOTREACHED */
4855 #define ST st->u.whilem
4857 case WHILEM: /* just matched an A in /A*B/ (for complex A) */
4859 /* see the discussion above about CURLYX/WHILEM */
4861 int min = ARG1(cur_curlyx->u.curlyx.me);
4862 int max = ARG2(cur_curlyx->u.curlyx.me);
4863 regnode *A = NEXTOPER(cur_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS;
4865 assert(cur_curlyx); /* keep Coverity happy */
4866 n = ++cur_curlyx->u.curlyx.count; /* how many A's matched */
4867 ST.save_lastloc = cur_curlyx->u.curlyx.lastloc;
4868 ST.cache_offset = 0;
4871 PL_reginput = locinput;
4873 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
4874 "%*s whilem: matched %ld out of %d..%d\n",
4875 REPORT_CODE_OFF+depth*2, "", (long)n, min, max)
4878 /* First just match a string of min A's. */
4881 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor);
4882 cur_curlyx->u.curlyx.lastloc = locinput;
4883 REGCP_SET(ST.lastcp);
4885 PUSH_STATE_GOTO(WHILEM_A_pre, A);
4886 assert(0); /* NOTREACHED */
4889 /* If degenerate A matches "", assume A done. */
4891 if (locinput == cur_curlyx->u.curlyx.lastloc) {
4892 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
4893 "%*s whilem: empty match detected, trying continuation...\n",
4894 REPORT_CODE_OFF+depth*2, "")
4896 goto do_whilem_B_max;
4899 /* super-linear cache processing */
4903 if (!PL_reg_maxiter) {
4904 /* start the countdown: Postpone detection until we
4905 * know the match is not *that* much linear. */
4906 PL_reg_maxiter = (PL_regeol - PL_bostr + 1) * (scan->flags>>4);
4907 /* possible overflow for long strings and many CURLYX's */
4908 if (PL_reg_maxiter < 0)
4909 PL_reg_maxiter = I32_MAX;
4910 PL_reg_leftiter = PL_reg_maxiter;
4913 if (PL_reg_leftiter-- == 0) {
4914 /* initialise cache */
4915 const I32 size = (PL_reg_maxiter + 7)/8;
4916 if (PL_reg_poscache) {
4917 if ((I32)PL_reg_poscache_size < size) {
4918 Renew(PL_reg_poscache, size, char);
4919 PL_reg_poscache_size = size;
4921 Zero(PL_reg_poscache, size, char);
4924 PL_reg_poscache_size = size;
4925 Newxz(PL_reg_poscache, size, char);
4927 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
4928 "%swhilem: Detected a super-linear match, switching on caching%s...\n",
4929 PL_colors[4], PL_colors[5])
4933 if (PL_reg_leftiter < 0) {
4934 /* have we already failed at this position? */
4936 offset = (scan->flags & 0xf) - 1
4937 + (locinput - PL_bostr) * (scan->flags>>4);
4938 mask = 1 << (offset % 8);
4940 if (PL_reg_poscache[offset] & mask) {
4941 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
4942 "%*s whilem: (cache) already tried at this position...\n",
4943 REPORT_CODE_OFF+depth*2, "")
4945 sayNO; /* cache records failure */
4947 ST.cache_offset = offset;
4948 ST.cache_mask = mask;
4952 /* Prefer B over A for minimal matching. */
4954 if (cur_curlyx->u.curlyx.minmod) {
4955 ST.save_curlyx = cur_curlyx;
4956 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
4957 ST.cp = regcppush(rex, ST.save_curlyx->u.curlyx.parenfloor);
4958 REGCP_SET(ST.lastcp);
4959 PUSH_YES_STATE_GOTO(WHILEM_B_min, ST.save_curlyx->u.curlyx.B);
4960 assert(0); /* NOTREACHED */
4963 /* Prefer A over B for maximal matching. */
4965 if (n < max) { /* More greed allowed? */
4966 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor);
4967 cur_curlyx->u.curlyx.lastloc = locinput;
4968 REGCP_SET(ST.lastcp);
4969 PUSH_STATE_GOTO(WHILEM_A_max, A);
4970 assert(0); /* NOTREACHED */
4972 goto do_whilem_B_max;
4974 assert(0); /* NOTREACHED */
4976 case WHILEM_B_min: /* just matched B in a minimal match */
4977 case WHILEM_B_max: /* just matched B in a maximal match */
4978 cur_curlyx = ST.save_curlyx;
4980 assert(0); /* NOTREACHED */
4982 case WHILEM_B_max_fail: /* just failed to match B in a maximal match */
4983 cur_curlyx = ST.save_curlyx;
4984 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
4985 cur_curlyx->u.curlyx.count--;
4987 assert(0); /* NOTREACHED */
4989 case WHILEM_A_min_fail: /* just failed to match A in a minimal match */
4991 case WHILEM_A_pre_fail: /* just failed to match even minimal A */
4992 REGCP_UNWIND(ST.lastcp);
4994 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
4995 cur_curlyx->u.curlyx.count--;
4997 assert(0); /* NOTREACHED */
4999 case WHILEM_A_max_fail: /* just failed to match A in a maximal match */
5000 REGCP_UNWIND(ST.lastcp);
5001 regcppop(rex); /* Restore some previous $<digit>s? */
5002 PL_reginput = locinput;
5003 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
5004 "%*s whilem: failed, trying continuation...\n",
5005 REPORT_CODE_OFF+depth*2, "")
5008 if (cur_curlyx->u.curlyx.count >= REG_INFTY
5009 && ckWARN(WARN_REGEXP)
5010 && !(PL_reg_flags & RF_warned))
5012 PL_reg_flags |= RF_warned;
5013 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
5014 "Complex regular subexpression recursion limit (%d) "
5020 ST.save_curlyx = cur_curlyx;
5021 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
5022 PUSH_YES_STATE_GOTO(WHILEM_B_max, ST.save_curlyx->u.curlyx.B);
5023 assert(0); /* NOTREACHED */
5025 case WHILEM_B_min_fail: /* just failed to match B in a minimal match */
5026 cur_curlyx = ST.save_curlyx;
5027 REGCP_UNWIND(ST.lastcp);
5030 if (cur_curlyx->u.curlyx.count >= /*max*/ARG2(cur_curlyx->u.curlyx.me)) {
5031 /* Maximum greed exceeded */
5032 if (cur_curlyx->u.curlyx.count >= REG_INFTY
5033 && ckWARN(WARN_REGEXP)
5034 && !(PL_reg_flags & RF_warned))
5036 PL_reg_flags |= RF_warned;
5037 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
5038 "Complex regular subexpression recursion "
5039 "limit (%d) exceeded",
5042 cur_curlyx->u.curlyx.count--;
5046 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
5047 "%*s trying longer...\n", REPORT_CODE_OFF+depth*2, "")
5049 /* Try grabbing another A and see if it helps. */
5050 PL_reginput = locinput;
5051 cur_curlyx->u.curlyx.lastloc = locinput;
5052 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor);
5053 REGCP_SET(ST.lastcp);
5054 PUSH_STATE_GOTO(WHILEM_A_min,
5055 /*A*/ NEXTOPER(ST.save_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS);
5056 assert(0); /* NOTREACHED */
5059 #define ST st->u.branch
5061 case BRANCHJ: /* /(...|A|...)/ with long next pointer */
5062 next = scan + ARG(scan);
5065 scan = NEXTOPER(scan);
5068 case BRANCH: /* /(...|A|...)/ */
5069 scan = NEXTOPER(scan); /* scan now points to inner node */
5070 ST.lastparen = rex->lastparen;
5071 ST.lastcloseparen = rex->lastcloseparen;
5072 ST.next_branch = next;
5074 PL_reginput = locinput;
5076 /* Now go into the branch */
5078 PUSH_YES_STATE_GOTO(BRANCH_next, scan);
5080 PUSH_STATE_GOTO(BRANCH_next, scan);
5082 assert(0); /* NOTREACHED */
5084 PL_reginput = locinput;
5085 sv_yes_mark = st->u.mark.mark_name = scan->flags ? NULL :
5086 MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
5087 PUSH_STATE_GOTO(CUTGROUP_next,next);
5088 assert(0); /* NOTREACHED */
5089 case CUTGROUP_next_fail:
5092 if (st->u.mark.mark_name)
5093 sv_commit = st->u.mark.mark_name;
5095 assert(0); /* NOTREACHED */
5098 assert(0); /* NOTREACHED */
5099 case BRANCH_next_fail: /* that branch failed; try the next, if any */
5104 REGCP_UNWIND(ST.cp);
5105 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
5106 scan = ST.next_branch;
5107 /* no more branches? */
5108 if (!scan || (OP(scan) != BRANCH && OP(scan) != BRANCHJ)) {
5110 PerlIO_printf( Perl_debug_log,
5111 "%*s %sBRANCH failed...%s\n",
5112 REPORT_CODE_OFF+depth*2, "",
5118 continue; /* execute next BRANCH[J] op */
5119 assert(0); /* NOTREACHED */
5126 #define ST st->u.curlym
5128 case CURLYM: /* /A{m,n}B/ where A is fixed-length */
5130 /* This is an optimisation of CURLYX that enables us to push
5131 * only a single backtracking state, no matter how many matches
5132 * there are in {m,n}. It relies on the pattern being constant
5133 * length, with no parens to influence future backrefs
5137 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
5139 ST.lastparen = rex->lastparen;
5140 ST.lastcloseparen = rex->lastcloseparen;
5142 /* if paren positive, emulate an OPEN/CLOSE around A */
5144 U32 paren = ST.me->flags;
5145 if (paren > PL_regsize)
5147 scan += NEXT_OFF(scan); /* Skip former OPEN. */
5155 ST.c1 = CHRTEST_UNINIT;
5158 if (!(ST.minmod ? ARG1(ST.me) : ARG2(ST.me))) /* min/max */
5161 curlym_do_A: /* execute the A in /A{m,n}B/ */
5162 PL_reginput = locinput;
5163 PUSH_YES_STATE_GOTO(CURLYM_A, ST.A); /* match A */
5164 assert(0); /* NOTREACHED */
5166 case CURLYM_A: /* we've just matched an A */
5167 locinput = st->locinput;
5168 nextchr = UCHARAT(locinput);
5171 /* after first match, determine A's length: u.curlym.alen */
5172 if (ST.count == 1) {
5173 if (PL_reg_match_utf8) {
5175 while (s < PL_reginput) {
5181 ST.alen = PL_reginput - locinput;
5184 ST.count = ST.minmod ? ARG1(ST.me) : ARG2(ST.me);
5187 PerlIO_printf(Perl_debug_log,
5188 "%*s CURLYM now matched %"IVdf" times, len=%"IVdf"...\n",
5189 (int)(REPORT_CODE_OFF+(depth*2)), "",
5190 (IV) ST.count, (IV)ST.alen)
5193 locinput = PL_reginput;
5195 if (cur_eval && cur_eval->u.eval.close_paren &&
5196 cur_eval->u.eval.close_paren == (U32)ST.me->flags)
5200 I32 max = (ST.minmod ? ARG1(ST.me) : ARG2(ST.me));
5201 if ( max == REG_INFTY || ST.count < max )
5202 goto curlym_do_A; /* try to match another A */
5204 goto curlym_do_B; /* try to match B */
5206 case CURLYM_A_fail: /* just failed to match an A */
5207 REGCP_UNWIND(ST.cp);
5209 if (ST.minmod || ST.count < ARG1(ST.me) /* min*/
5210 || (cur_eval && cur_eval->u.eval.close_paren &&
5211 cur_eval->u.eval.close_paren == (U32)ST.me->flags))
5214 curlym_do_B: /* execute the B in /A{m,n}B/ */
5215 PL_reginput = locinput;
5216 if (ST.c1 == CHRTEST_UNINIT) {
5217 /* calculate c1 and c2 for possible match of 1st char
5218 * following curly */
5219 ST.c1 = ST.c2 = CHRTEST_VOID;
5220 if (HAS_TEXT(ST.B) || JUMPABLE(ST.B)) {
5221 regnode *text_node = ST.B;
5222 if (! HAS_TEXT(text_node))
5223 FIND_NEXT_IMPT(text_node);
5226 (HAS_TEXT(text_node) && PL_regkind[OP(text_node)] == EXACT)
5228 But the former is redundant in light of the latter.
5230 if this changes back then the macro for
5231 IS_TEXT and friends need to change.
5233 if (PL_regkind[OP(text_node)] == EXACT)
5236 ST.c1 = (U8)*STRING(text_node);
5237 switch (OP(text_node)) {
5238 case EXACTF: ST.c2 = PL_fold[ST.c1]; break;
5241 case EXACTFU_TRICKYFOLD:
5242 case EXACTFU: ST.c2 = PL_fold_latin1[ST.c1]; break;
5243 case EXACTFL: ST.c2 = PL_fold_locale[ST.c1]; break;
5244 default: ST.c2 = ST.c1;
5251 PerlIO_printf(Perl_debug_log,
5252 "%*s CURLYM trying tail with matches=%"IVdf"...\n",
5253 (int)(REPORT_CODE_OFF+(depth*2)),
5256 if (ST.c1 != CHRTEST_VOID
5257 && UCHARAT(PL_reginput) != ST.c1
5258 && UCHARAT(PL_reginput) != ST.c2)
5260 /* simulate B failing */
5262 PerlIO_printf(Perl_debug_log,
5263 "%*s CURLYM Fast bail c1=%"IVdf" c2=%"IVdf"\n",
5264 (int)(REPORT_CODE_OFF+(depth*2)),"",
5267 state_num = CURLYM_B_fail;
5268 goto reenter_switch;
5272 /* emulate CLOSE: mark current A as captured */
5273 I32 paren = ST.me->flags;
5275 rex->offs[paren].start
5276 = HOPc(PL_reginput, -ST.alen) - PL_bostr;
5277 rex->offs[paren].end = PL_reginput - PL_bostr;
5278 if ((U32)paren > rex->lastparen)
5279 rex->lastparen = paren;
5280 rex->lastcloseparen = paren;
5283 rex->offs[paren].end = -1;
5284 if (cur_eval && cur_eval->u.eval.close_paren &&
5285 cur_eval->u.eval.close_paren == (U32)ST.me->flags)
5294 PUSH_STATE_GOTO(CURLYM_B, ST.B); /* match B */
5295 assert(0); /* NOTREACHED */
5297 case CURLYM_B_fail: /* just failed to match a B */
5298 REGCP_UNWIND(ST.cp);
5299 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
5301 I32 max = ARG2(ST.me);
5302 if (max != REG_INFTY && ST.count == max)
5304 goto curlym_do_A; /* try to match a further A */
5306 /* backtrack one A */
5307 if (ST.count == ARG1(ST.me) /* min */)
5310 locinput = HOPc(locinput, -ST.alen);
5311 goto curlym_do_B; /* try to match B */
5314 #define ST st->u.curly
5316 #define CURLY_SETPAREN(paren, success) \
5319 rex->offs[paren].start = HOPc(locinput, -1) - PL_bostr; \
5320 rex->offs[paren].end = locinput - PL_bostr; \
5321 if (paren > rex->lastparen) \
5322 rex->lastparen = paren; \
5323 rex->lastcloseparen = paren; \
5326 rex->offs[paren].end = -1; \
5327 rex->lastparen = ST.lastparen; \
5328 rex->lastcloseparen = ST.lastcloseparen; \
5332 case STAR: /* /A*B/ where A is width 1 */
5336 scan = NEXTOPER(scan);
5338 case PLUS: /* /A+B/ where A is width 1 */
5342 scan = NEXTOPER(scan);
5344 case CURLYN: /* /(A){m,n}B/ where A is width 1 */
5345 ST.paren = scan->flags; /* Which paren to set */
5346 ST.lastparen = rex->lastparen;
5347 ST.lastcloseparen = rex->lastcloseparen;
5348 if (ST.paren > PL_regsize)
5349 PL_regsize = ST.paren;
5350 ST.min = ARG1(scan); /* min to match */
5351 ST.max = ARG2(scan); /* max to match */
5352 if (cur_eval && cur_eval->u.eval.close_paren &&
5353 cur_eval->u.eval.close_paren == (U32)ST.paren) {
5357 scan = regnext(NEXTOPER(scan) + NODE_STEP_REGNODE);
5359 case CURLY: /* /A{m,n}B/ where A is width 1 */
5361 ST.min = ARG1(scan); /* min to match */
5362 ST.max = ARG2(scan); /* max to match */
5363 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
5366 * Lookahead to avoid useless match attempts
5367 * when we know what character comes next.
5369 * Used to only do .*x and .*?x, but now it allows
5370 * for )'s, ('s and (?{ ... })'s to be in the way
5371 * of the quantifier and the EXACT-like node. -- japhy
5374 if (ST.min > ST.max) /* XXX make this a compile-time check? */
5376 if (HAS_TEXT(next) || JUMPABLE(next)) {
5378 regnode *text_node = next;
5380 if (! HAS_TEXT(text_node))
5381 FIND_NEXT_IMPT(text_node);
5383 if (! HAS_TEXT(text_node))
5384 ST.c1 = ST.c2 = CHRTEST_VOID;
5386 if ( PL_regkind[OP(text_node)] != EXACT ) {
5387 ST.c1 = ST.c2 = CHRTEST_VOID;
5388 goto assume_ok_easy;
5391 s = (U8*)STRING(text_node);
5393 /* Currently we only get here when
5395 PL_rekind[OP(text_node)] == EXACT
5397 if this changes back then the macro for IS_TEXT and
5398 friends need to change. */
5401 switch (OP(text_node)) {
5402 case EXACTF: ST.c2 = PL_fold[ST.c1]; break;
5405 case EXACTFU_TRICKYFOLD:
5406 case EXACTFU: ST.c2 = PL_fold_latin1[ST.c1]; break;
5407 case EXACTFL: ST.c2 = PL_fold_locale[ST.c1]; break;
5408 default: ST.c2 = ST.c1; break;
5411 else { /* UTF_PATTERN */
5412 if (IS_TEXTFU(text_node) || IS_TEXTF(text_node)) {
5414 U8 tmpbuf[UTF8_MAXBYTES_CASE+1];
5416 to_utf8_fold((U8*)s, tmpbuf, &ulen);
5417 ST.c1 = ST.c2 = utf8n_to_uvchr(tmpbuf, UTF8_MAXLEN, 0,
5421 ST.c2 = ST.c1 = utf8n_to_uvchr(s, UTF8_MAXBYTES, 0,
5428 ST.c1 = ST.c2 = CHRTEST_VOID;
5433 PL_reginput = locinput;
5436 if (ST.min && regrepeat(rex, ST.A, ST.min, depth) < ST.min)
5439 locinput = PL_reginput;
5441 if (ST.c1 == CHRTEST_VOID)
5442 goto curly_try_B_min;
5444 ST.oldloc = locinput;
5446 /* set ST.maxpos to the furthest point along the
5447 * string that could possibly match */
5448 if (ST.max == REG_INFTY) {
5449 ST.maxpos = PL_regeol - 1;
5451 while (UTF8_IS_CONTINUATION(*(U8*)ST.maxpos))
5454 else if (utf8_target) {
5455 int m = ST.max - ST.min;
5456 for (ST.maxpos = locinput;
5457 m >0 && ST.maxpos + UTF8SKIP(ST.maxpos) <= PL_regeol; m--)
5458 ST.maxpos += UTF8SKIP(ST.maxpos);
5461 ST.maxpos = locinput + ST.max - ST.min;
5462 if (ST.maxpos >= PL_regeol)
5463 ST.maxpos = PL_regeol - 1;
5465 goto curly_try_B_min_known;
5469 ST.count = regrepeat(rex, ST.A, ST.max, depth);
5470 locinput = PL_reginput;
5471 if (ST.count < ST.min)
5473 if ((ST.count > ST.min)
5474 && (PL_regkind[OP(ST.B)] == EOL) && (OP(ST.B) != MEOL))
5476 /* A{m,n} must come at the end of the string, there's
5477 * no point in backing off ... */
5479 /* ...except that $ and \Z can match before *and* after
5480 newline at the end. Consider "\n\n" =~ /\n+\Z\n/.
5481 We may back off by one in this case. */
5482 if (UCHARAT(PL_reginput - 1) == '\n' && OP(ST.B) != EOS)
5486 goto curly_try_B_max;
5488 assert(0); /* NOTREACHED */
5491 case CURLY_B_min_known_fail:
5492 /* failed to find B in a non-greedy match where c1,c2 valid */
5494 PL_reginput = locinput; /* Could be reset... */
5495 REGCP_UNWIND(ST.cp);
5497 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
5499 /* Couldn't or didn't -- move forward. */
5500 ST.oldloc = locinput;
5502 locinput += UTF8SKIP(locinput);
5506 curly_try_B_min_known:
5507 /* find the next place where 'B' could work, then call B */
5511 n = (ST.oldloc == locinput) ? 0 : 1;
5512 if (ST.c1 == ST.c2) {
5514 /* set n to utf8_distance(oldloc, locinput) */
5515 while (locinput <= ST.maxpos &&
5516 utf8n_to_uvchr((U8*)locinput,
5517 UTF8_MAXBYTES, &len,
5518 uniflags) != (UV)ST.c1) {
5524 /* set n to utf8_distance(oldloc, locinput) */
5525 while (locinput <= ST.maxpos) {
5527 const UV c = utf8n_to_uvchr((U8*)locinput,
5528 UTF8_MAXBYTES, &len,
5530 if (c == (UV)ST.c1 || c == (UV)ST.c2)
5538 if (ST.c1 == ST.c2) {
5539 while (locinput <= ST.maxpos &&
5540 UCHARAT(locinput) != ST.c1)
5544 while (locinput <= ST.maxpos
5545 && UCHARAT(locinput) != ST.c1
5546 && UCHARAT(locinput) != ST.c2)
5549 n = locinput - ST.oldloc;
5551 if (locinput > ST.maxpos)
5553 /* PL_reginput == oldloc now */
5556 if (regrepeat(rex, ST.A, n, depth) < n)
5559 PL_reginput = locinput;
5560 CURLY_SETPAREN(ST.paren, ST.count);
5561 if (cur_eval && cur_eval->u.eval.close_paren &&
5562 cur_eval->u.eval.close_paren == (U32)ST.paren) {
5565 PUSH_STATE_GOTO(CURLY_B_min_known, ST.B);
5567 assert(0); /* NOTREACHED */
5570 case CURLY_B_min_fail:
5571 /* failed to find B in a non-greedy match where c1,c2 invalid */
5573 REGCP_UNWIND(ST.cp);
5575 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
5577 /* failed -- move forward one */
5578 PL_reginput = locinput;
5579 if (regrepeat(rex, ST.A, 1, depth)) {
5581 locinput = PL_reginput;
5582 if (ST.count <= ST.max || (ST.max == REG_INFTY &&
5583 ST.count > 0)) /* count overflow ? */
5586 CURLY_SETPAREN(ST.paren, ST.count);
5587 if (cur_eval && cur_eval->u.eval.close_paren &&
5588 cur_eval->u.eval.close_paren == (U32)ST.paren) {
5591 PUSH_STATE_GOTO(CURLY_B_min, ST.B);
5595 assert(0); /* NOTREACHED */
5599 /* a successful greedy match: now try to match B */
5600 if (cur_eval && cur_eval->u.eval.close_paren &&
5601 cur_eval->u.eval.close_paren == (U32)ST.paren) {
5606 if (ST.c1 != CHRTEST_VOID)
5607 c = utf8_target ? utf8n_to_uvchr((U8*)PL_reginput,
5608 UTF8_MAXBYTES, 0, uniflags)
5609 : (UV) UCHARAT(PL_reginput);
5610 /* If it could work, try it. */
5611 if (ST.c1 == CHRTEST_VOID || c == (UV)ST.c1 || c == (UV)ST.c2) {
5612 CURLY_SETPAREN(ST.paren, ST.count);
5613 PUSH_STATE_GOTO(CURLY_B_max, ST.B);
5614 assert(0); /* NOTREACHED */
5618 case CURLY_B_max_fail:
5619 /* failed to find B in a greedy match */
5621 REGCP_UNWIND(ST.cp);
5623 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
5626 if (--ST.count < ST.min)
5628 PL_reginput = locinput = HOPc(locinput, -1);
5629 goto curly_try_B_max;
5636 /* we've just finished A in /(??{A})B/; now continue with B */
5637 st->u.eval.toggle_reg_flags
5638 = cur_eval->u.eval.toggle_reg_flags;
5639 PL_reg_flags ^= st->u.eval.toggle_reg_flags;
5641 st->u.eval.prev_rex = rex_sv; /* inner */
5642 st->u.eval.cp = regcppush(rex, 0); /* Save *all* the positions. */
5643 rex_sv = cur_eval->u.eval.prev_rex;
5644 SET_reg_curpm(rex_sv);
5645 rex = (struct regexp *)SvANY(rex_sv);
5646 rexi = RXi_GET(rex);
5647 cur_curlyx = cur_eval->u.eval.prev_curlyx;
5649 REGCP_SET(st->u.eval.lastcp);
5650 PL_reginput = locinput;
5652 /* Restore parens of the outer rex without popping the
5654 S_regcp_restore(aTHX_ rex, cur_eval->u.eval.lastcp);
5656 st->u.eval.prev_eval = cur_eval;
5657 cur_eval = cur_eval->u.eval.prev_eval;
5659 PerlIO_printf(Perl_debug_log, "%*s EVAL trying tail ... %"UVxf"\n",
5660 REPORT_CODE_OFF+depth*2, "",PTR2UV(cur_eval)););
5661 if ( nochange_depth )
5664 PUSH_YES_STATE_GOTO(EVAL_AB,
5665 st->u.eval.prev_eval->u.eval.B); /* match B */
5668 if (locinput < reginfo->till) {
5669 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
5670 "%sMatch possible, but length=%ld is smaller than requested=%ld, failing!%s\n",
5672 (long)(locinput - PL_reg_starttry),
5673 (long)(reginfo->till - PL_reg_starttry),
5676 sayNO_SILENT; /* Cannot match: too short. */
5678 PL_reginput = locinput; /* put where regtry can find it */
5679 sayYES; /* Success! */
5681 case SUCCEED: /* successful SUSPEND/UNLESSM/IFMATCH/CURLYM */
5683 PerlIO_printf(Perl_debug_log,
5684 "%*s %ssubpattern success...%s\n",
5685 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5]));
5686 PL_reginput = locinput; /* put where regtry can find it */
5687 sayYES; /* Success! */
5690 #define ST st->u.ifmatch
5692 case SUSPEND: /* (?>A) */
5694 PL_reginput = locinput;
5697 case UNLESSM: /* -ve lookaround: (?!A), or with flags, (?<!A) */
5699 goto ifmatch_trivial_fail_test;
5701 case IFMATCH: /* +ve lookaround: (?=A), or with flags, (?<=A) */
5703 ifmatch_trivial_fail_test:
5705 char * const s = HOPBACKc(locinput, scan->flags);
5710 sw = 1 - cBOOL(ST.wanted);
5714 next = scan + ARG(scan);
5722 PL_reginput = locinput;
5726 ST.logical = logical;
5727 logical = 0; /* XXX: reset state of logical once it has been saved into ST */
5729 /* execute body of (?...A) */
5730 PUSH_YES_STATE_GOTO(IFMATCH_A, NEXTOPER(NEXTOPER(scan)));
5731 assert(0); /* NOTREACHED */
5733 case IFMATCH_A_fail: /* body of (?...A) failed */
5734 ST.wanted = !ST.wanted;
5737 case IFMATCH_A: /* body of (?...A) succeeded */
5739 sw = cBOOL(ST.wanted);
5741 else if (!ST.wanted)
5744 if (OP(ST.me) == SUSPEND)
5745 locinput = PL_reginput;
5747 locinput = PL_reginput = st->locinput;
5748 nextchr = UCHARAT(locinput);
5750 scan = ST.me + ARG(ST.me);
5753 continue; /* execute B */
5758 next = scan + ARG(scan);
5763 reginfo->cutpoint = PL_regeol;
5766 PL_reginput = locinput;
5768 sv_yes_mark = sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
5769 PUSH_STATE_GOTO(COMMIT_next,next);
5770 assert(0); /* NOTREACHED */
5771 case COMMIT_next_fail:
5776 assert(0); /* NOTREACHED */
5778 #define ST st->u.mark
5780 ST.prev_mark = mark_state;
5781 ST.mark_name = sv_commit = sv_yes_mark
5782 = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
5784 ST.mark_loc = PL_reginput = locinput;
5785 PUSH_YES_STATE_GOTO(MARKPOINT_next,next);
5786 assert(0); /* NOTREACHED */
5787 case MARKPOINT_next:
5788 mark_state = ST.prev_mark;
5790 assert(0); /* NOTREACHED */
5791 case MARKPOINT_next_fail:
5792 if (popmark && sv_eq(ST.mark_name,popmark))
5794 if (ST.mark_loc > startpoint)
5795 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
5796 popmark = NULL; /* we found our mark */
5797 sv_commit = ST.mark_name;
5800 PerlIO_printf(Perl_debug_log,
5801 "%*s %ssetting cutpoint to mark:%"SVf"...%s\n",
5802 REPORT_CODE_OFF+depth*2, "",
5803 PL_colors[4], SVfARG(sv_commit), PL_colors[5]);
5806 mark_state = ST.prev_mark;
5807 sv_yes_mark = mark_state ?
5808 mark_state->u.mark.mark_name : NULL;
5810 assert(0); /* NOTREACHED */
5812 PL_reginput = locinput;
5814 /* (*SKIP) : if we fail we cut here*/
5815 ST.mark_name = NULL;
5816 ST.mark_loc = locinput;
5817 PUSH_STATE_GOTO(SKIP_next,next);
5819 /* (*SKIP:NAME) : if there is a (*MARK:NAME) fail where it was,
5820 otherwise do nothing. Meaning we need to scan
5822 regmatch_state *cur = mark_state;
5823 SV *find = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
5826 if ( sv_eq( cur->u.mark.mark_name,
5829 ST.mark_name = find;
5830 PUSH_STATE_GOTO( SKIP_next, next );
5832 cur = cur->u.mark.prev_mark;
5835 /* Didn't find our (*MARK:NAME) so ignore this (*SKIP:NAME) */
5837 case SKIP_next_fail:
5839 /* (*CUT:NAME) - Set up to search for the name as we
5840 collapse the stack*/
5841 popmark = ST.mark_name;
5843 /* (*CUT) - No name, we cut here.*/
5844 if (ST.mark_loc > startpoint)
5845 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
5846 /* but we set sv_commit to latest mark_name if there
5847 is one so they can test to see how things lead to this
5850 sv_commit=mark_state->u.mark.mark_name;
5854 assert(0); /* NOTREACHED */
5857 if ((n=is_LNBREAK(locinput,utf8_target))) {
5859 nextchr = UCHARAT(locinput);
5864 #define CASE_CLASS(nAmE) \
5866 if (locinput >= PL_regeol) \
5868 if ((n=is_##nAmE(locinput,utf8_target))) { \
5870 nextchr = UCHARAT(locinput); \
5875 if (locinput >= PL_regeol) \
5877 if ((n=is_##nAmE(locinput,utf8_target))) { \
5880 locinput += UTF8SKIP(locinput); \
5881 nextchr = UCHARAT(locinput); \
5886 CASE_CLASS(HORIZWS);
5890 PerlIO_printf(Perl_error_log, "%"UVxf" %d\n",
5891 PTR2UV(scan), OP(scan));
5892 Perl_croak(aTHX_ "regexp memory corruption");
5896 /* switch break jumps here */
5897 scan = next; /* prepare to execute the next op and ... */
5898 continue; /* ... jump back to the top, reusing st */
5899 assert(0); /* NOTREACHED */
5902 /* push a state that backtracks on success */
5903 st->u.yes.prev_yes_state = yes_state;
5907 /* push a new regex state, then continue at scan */
5909 regmatch_state *newst;
5912 regmatch_state *cur = st;
5913 regmatch_state *curyes = yes_state;
5915 regmatch_slab *slab = PL_regmatch_slab;
5916 for (;curd > -1;cur--,curd--) {
5917 if (cur < SLAB_FIRST(slab)) {
5919 cur = SLAB_LAST(slab);
5921 PerlIO_printf(Perl_error_log, "%*s#%-3d %-10s %s\n",
5922 REPORT_CODE_OFF + 2 + depth * 2,"",
5923 curd, PL_reg_name[cur->resume_state],
5924 (curyes == cur) ? "yes" : ""
5927 curyes = cur->u.yes.prev_yes_state;
5930 DEBUG_STATE_pp("push")
5933 st->locinput = locinput;
5935 if (newst > SLAB_LAST(PL_regmatch_slab))
5936 newst = S_push_slab(aTHX);
5937 PL_regmatch_state = newst;
5939 locinput = PL_reginput;
5940 nextchr = UCHARAT(locinput);
5943 assert(0); /* NOTREACHED */
5948 * We get here only if there's trouble -- normally "case END" is
5949 * the terminating point.
5951 Perl_croak(aTHX_ "corrupted regexp pointers");
5957 /* we have successfully completed a subexpression, but we must now
5958 * pop to the state marked by yes_state and continue from there */
5959 assert(st != yes_state);
5961 while (st != yes_state) {
5963 if (st < SLAB_FIRST(PL_regmatch_slab)) {
5964 PL_regmatch_slab = PL_regmatch_slab->prev;
5965 st = SLAB_LAST(PL_regmatch_slab);
5969 DEBUG_STATE_pp("pop (no final)");
5971 DEBUG_STATE_pp("pop (yes)");
5977 while (yes_state < SLAB_FIRST(PL_regmatch_slab)
5978 || yes_state > SLAB_LAST(PL_regmatch_slab))
5980 /* not in this slab, pop slab */
5981 depth -= (st - SLAB_FIRST(PL_regmatch_slab) + 1);
5982 PL_regmatch_slab = PL_regmatch_slab->prev;
5983 st = SLAB_LAST(PL_regmatch_slab);
5985 depth -= (st - yes_state);
5988 yes_state = st->u.yes.prev_yes_state;
5989 PL_regmatch_state = st;
5992 locinput= st->locinput;
5993 nextchr = UCHARAT(locinput);
5995 state_num = st->resume_state + no_final;
5996 goto reenter_switch;
5999 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch successful!%s\n",
6000 PL_colors[4], PL_colors[5]));
6002 if (PL_reg_state.re_state_eval_setup_done) {
6003 /* each successfully executed (?{...}) block does the equivalent of
6004 * local $^R = do {...}
6005 * When popping the save stack, all these locals would be undone;
6006 * bypass this by setting the outermost saved $^R to the latest
6008 if (oreplsv != GvSV(PL_replgv))
6009 sv_setsv(oreplsv, GvSV(PL_replgv));
6016 PerlIO_printf(Perl_debug_log,
6017 "%*s %sfailed...%s\n",
6018 REPORT_CODE_OFF+depth*2, "",
6019 PL_colors[4], PL_colors[5])
6031 /* there's a previous state to backtrack to */
6033 if (st < SLAB_FIRST(PL_regmatch_slab)) {
6034 PL_regmatch_slab = PL_regmatch_slab->prev;
6035 st = SLAB_LAST(PL_regmatch_slab);
6037 PL_regmatch_state = st;
6038 locinput= st->locinput;
6039 nextchr = UCHARAT(locinput);
6041 DEBUG_STATE_pp("pop");
6043 if (yes_state == st)
6044 yes_state = st->u.yes.prev_yes_state;
6046 state_num = st->resume_state + 1; /* failure = success + 1 */
6047 goto reenter_switch;
6052 if (rex->intflags & PREGf_VERBARG_SEEN) {
6053 SV *sv_err = get_sv("REGERROR", 1);
6054 SV *sv_mrk = get_sv("REGMARK", 1);
6056 sv_commit = &PL_sv_no;
6058 sv_yes_mark = &PL_sv_yes;
6061 sv_commit = &PL_sv_yes;
6062 sv_yes_mark = &PL_sv_no;
6064 sv_setsv(sv_err, sv_commit);
6065 sv_setsv(sv_mrk, sv_yes_mark);
6069 if (last_pushed_cv) {
6072 PERL_UNUSED_VAR(SP);
6075 /* clean up; in particular, free all slabs above current one */
6076 LEAVE_SCOPE(oldsave);
6082 - regrepeat - repeatedly match something simple, report how many
6085 * [This routine now assumes that it will only match on things of length 1.
6086 * That was true before, but now we assume scan - reginput is the count,
6087 * rather than incrementing count on every character. [Er, except utf8.]]
6090 S_regrepeat(pTHX_ const regexp *prog, const regnode *p, I32 max, int depth)
6095 char *loceol = PL_regeol;
6097 bool utf8_target = PL_reg_match_utf8;
6100 PERL_UNUSED_ARG(depth);
6103 PERL_ARGS_ASSERT_REGREPEAT;
6106 if (max == REG_INFTY)
6108 else if (max < loceol - scan)
6109 loceol = scan + max;
6114 while (scan < loceol && hardcount < max && *scan != '\n') {
6115 scan += UTF8SKIP(scan);
6119 while (scan < loceol && *scan != '\n')
6126 while (scan < loceol && hardcount < max) {
6127 scan += UTF8SKIP(scan);
6138 /* To get here, EXACTish nodes must have *byte* length == 1. That
6139 * means they match only characters in the string that can be expressed
6140 * as a single byte. For non-utf8 strings, that means a simple match.
6141 * For utf8 strings, the character matched must be an invariant, or
6142 * downgradable to a single byte. The pattern's utf8ness is
6143 * irrelevant, as since it's a single byte, it either isn't utf8, or if
6144 * it is, it's an invariant */
6147 assert(! UTF_PATTERN || UNI_IS_INVARIANT(c));
6149 if (! utf8_target || UNI_IS_INVARIANT(c)) {
6150 while (scan < loceol && UCHARAT(scan) == c) {
6156 /* Here, the string is utf8, and the pattern char is different
6157 * in utf8 than not, so can't compare them directly. Outside the
6158 * loop, find the two utf8 bytes that represent c, and then
6159 * look for those in sequence in the utf8 string */
6160 U8 high = UTF8_TWO_BYTE_HI(c);
6161 U8 low = UTF8_TWO_BYTE_LO(c);
6164 while (hardcount < max
6165 && scan + 1 < loceol
6166 && UCHARAT(scan) == high
6167 && UCHARAT(scan + 1) == low)
6175 utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
6179 PL_reg_flags |= RF_tainted;
6180 utf8_flags = FOLDEQ_UTF8_LOCALE;
6188 case EXACTFU_TRICKYFOLD:
6190 utf8_flags = (UTF_PATTERN) ? FOLDEQ_S2_ALREADY_FOLDED : 0;
6192 /* The comments for the EXACT case above apply as well to these fold
6197 assert(! UTF_PATTERN || UNI_IS_INVARIANT(c));
6199 if (utf8_target || OP(p) == EXACTFU_SS) { /* Use full Unicode fold matching */
6200 char *tmpeol = loceol;
6201 while (hardcount < max
6202 && foldEQ_utf8_flags(scan, &tmpeol, 0, utf8_target,
6203 STRING(p), NULL, 1, cBOOL(UTF_PATTERN), utf8_flags))
6210 /* XXX Note that the above handles properly the German sharp s in
6211 * the pattern matching ss in the string. But it doesn't handle
6212 * properly cases where the string contains say 'LIGATURE ff' and
6213 * the pattern is 'f+'. This would require, say, a new function or
6214 * revised interface to foldEQ_utf8(), in which the maximum number
6215 * of characters to match could be passed and it would return how
6216 * many actually did. This is just one of many cases where
6217 * multi-char folds don't work properly, and so the fix is being
6223 /* Here, the string isn't utf8 and c is a single byte; and either
6224 * the pattern isn't utf8 or c is an invariant, so its utf8ness
6225 * doesn't affect c. Can just do simple comparisons for exact or
6228 case EXACTF: folded = PL_fold[c]; break;
6230 case EXACTFU_TRICKYFOLD:
6231 case EXACTFU: folded = PL_fold_latin1[c]; break;
6232 case EXACTFL: folded = PL_fold_locale[c]; break;
6233 default: Perl_croak(aTHX_ "panic: Unexpected op %u", OP(p));
6235 while (scan < loceol &&
6236 (UCHARAT(scan) == c || UCHARAT(scan) == folded))
6244 if (utf8_target || OP(p) == ANYOFV) {
6247 inclasslen = loceol - scan;
6248 while (hardcount < max
6249 && ((inclasslen = loceol - scan) > 0)
6250 && reginclass(prog, p, (U8*)scan, &inclasslen, utf8_target))
6256 while (scan < loceol && REGINCLASS(prog, p, (U8*)scan))
6264 LOAD_UTF8_CHARCLASS_ALNUM();
6265 while (hardcount < max && scan < loceol &&
6266 swash_fetch(PL_utf8_alnum, (U8*)scan, utf8_target))
6268 scan += UTF8SKIP(scan);
6272 while (scan < loceol && isWORDCHAR_L1((U8) *scan)) {
6280 while (scan < loceol && isALNUM((U8) *scan)) {
6285 while (scan < loceol && isWORDCHAR_A((U8) *scan)) {
6290 PL_reg_flags |= RF_tainted;
6293 while (hardcount < max && scan < loceol &&
6294 isALNUM_LC_utf8((U8*)scan)) {
6295 scan += UTF8SKIP(scan);
6299 while (scan < loceol && isALNUM_LC(*scan))
6309 LOAD_UTF8_CHARCLASS_ALNUM();
6310 while (hardcount < max && scan < loceol &&
6311 ! swash_fetch(PL_utf8_alnum, (U8*)scan, utf8_target))
6313 scan += UTF8SKIP(scan);
6317 while (scan < loceol && ! isWORDCHAR_L1((U8) *scan)) {
6324 goto utf8_Nwordchar;
6325 while (scan < loceol && ! isALNUM((U8) *scan)) {
6331 while (scan < loceol && _generic_isCC_A((U8) *scan, FLAGS(p))) {
6337 while (scan < loceol && ! _generic_isCC_A((U8) *scan, FLAGS(p))) {
6338 scan += UTF8SKIP(scan);
6342 while (scan < loceol && ! _generic_isCC_A((U8) *scan, FLAGS(p))) {
6349 while (scan < loceol && ! isWORDCHAR_A((U8) *scan)) {
6350 scan += UTF8SKIP(scan);
6354 while (scan < loceol && ! isWORDCHAR_A((U8) *scan)) {
6360 PL_reg_flags |= RF_tainted;
6363 while (hardcount < max && scan < loceol &&
6364 !isALNUM_LC_utf8((U8*)scan)) {
6365 scan += UTF8SKIP(scan);
6369 while (scan < loceol && !isALNUM_LC(*scan))
6379 LOAD_UTF8_CHARCLASS_SPACE();
6380 while (hardcount < max && scan < loceol &&
6382 swash_fetch(PL_utf8_space,(U8*)scan, utf8_target)))
6384 scan += UTF8SKIP(scan);
6390 while (scan < loceol && isSPACE_L1((U8) *scan)) {
6399 while (scan < loceol && isSPACE((U8) *scan)) {
6404 while (scan < loceol && isSPACE_A((U8) *scan)) {
6409 PL_reg_flags |= RF_tainted;
6412 while (hardcount < max && scan < loceol &&
6413 isSPACE_LC_utf8((U8*)scan)) {
6414 scan += UTF8SKIP(scan);
6418 while (scan < loceol && isSPACE_LC(*scan))
6428 LOAD_UTF8_CHARCLASS_SPACE();
6429 while (hardcount < max && scan < loceol &&
6431 swash_fetch(PL_utf8_space,(U8*)scan, utf8_target)))
6433 scan += UTF8SKIP(scan);
6439 while (scan < loceol && ! isSPACE_L1((U8) *scan)) {
6448 while (scan < loceol && ! isSPACE((U8) *scan)) {
6454 while (scan < loceol && ! isSPACE_A((U8) *scan)) {
6455 scan += UTF8SKIP(scan);
6459 while (scan < loceol && ! isSPACE_A((U8) *scan)) {
6465 PL_reg_flags |= RF_tainted;
6468 while (hardcount < max && scan < loceol &&
6469 !isSPACE_LC_utf8((U8*)scan)) {
6470 scan += UTF8SKIP(scan);
6474 while (scan < loceol && !isSPACE_LC(*scan))
6481 LOAD_UTF8_CHARCLASS_DIGIT();
6482 while (hardcount < max && scan < loceol &&
6483 swash_fetch(PL_utf8_digit, (U8*)scan, utf8_target)) {
6484 scan += UTF8SKIP(scan);
6488 while (scan < loceol && isDIGIT(*scan))
6493 while (scan < loceol && isDIGIT_A((U8) *scan)) {
6498 PL_reg_flags |= RF_tainted;
6501 while (hardcount < max && scan < loceol &&
6502 isDIGIT_LC_utf8((U8*)scan)) {
6503 scan += UTF8SKIP(scan);
6507 while (scan < loceol && isDIGIT_LC(*scan))
6514 LOAD_UTF8_CHARCLASS_DIGIT();
6515 while (hardcount < max && scan < loceol &&
6516 !swash_fetch(PL_utf8_digit, (U8*)scan, utf8_target)) {
6517 scan += UTF8SKIP(scan);
6521 while (scan < loceol && !isDIGIT(*scan))
6527 while (scan < loceol && ! isDIGIT_A((U8) *scan)) {
6528 scan += UTF8SKIP(scan);
6532 while (scan < loceol && ! isDIGIT_A((U8) *scan)) {
6538 PL_reg_flags |= RF_tainted;
6541 while (hardcount < max && scan < loceol &&
6542 !isDIGIT_LC_utf8((U8*)scan)) {
6543 scan += UTF8SKIP(scan);
6547 while (scan < loceol && !isDIGIT_LC(*scan))
6554 while (hardcount < max && scan < loceol && (c=is_LNBREAK_utf8(scan))) {
6560 LNBREAK can match two latin chars, which is ok,
6561 because we have a null terminated string, but we
6562 have to use hardcount in this situation
6564 while (scan < loceol && (c=is_LNBREAK_latin1(scan))) {
6573 while (hardcount < max && scan < loceol && (c=is_HORIZWS_utf8(scan))) {
6578 while (scan < loceol && is_HORIZWS_latin1(scan))
6585 while (hardcount < max && scan < loceol && !is_HORIZWS_utf8(scan)) {
6586 scan += UTF8SKIP(scan);
6590 while (scan < loceol && !is_HORIZWS_latin1(scan))
6598 while (hardcount < max && scan < loceol && (c=is_VERTWS_utf8(scan))) {
6603 while (scan < loceol && is_VERTWS_latin1(scan))
6611 while (hardcount < max && scan < loceol && !is_VERTWS_utf8(scan)) {
6612 scan += UTF8SKIP(scan);
6616 while (scan < loceol && !is_VERTWS_latin1(scan))
6622 default: /* Called on something of 0 width. */
6623 break; /* So match right here or not at all. */
6629 c = scan - PL_reginput;
6633 GET_RE_DEBUG_FLAGS_DECL;
6635 SV * const prop = sv_newmortal();
6636 regprop(prog, prop, p);
6637 PerlIO_printf(Perl_debug_log,
6638 "%*s %s can match %"IVdf" times out of %"IVdf"...\n",
6639 REPORT_CODE_OFF + depth*2, "", SvPVX_const(prop),(IV)c,(IV)max);
6647 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
6649 - regclass_swash - prepare the utf8 swash. Wraps the shared core version to
6650 create a copy so that changes the caller makes won't change the shared one
6653 Perl_regclass_swash(pTHX_ const regexp *prog, register const regnode* node, bool doinit, SV** listsvp, SV **altsvp)
6655 PERL_ARGS_ASSERT_REGCLASS_SWASH;
6656 return newSVsv(core_regclass_swash(prog, node, doinit, listsvp, altsvp));
6661 S_core_regclass_swash(pTHX_ const regexp *prog, register const regnode* node, bool doinit, SV** listsvp, SV **altsvp)
6663 /* Returns the swash for the input 'node' in the regex 'prog'.
6664 * If <doinit> is true, will attempt to create the swash if not already
6666 * If <listsvp> is non-null, will return the swash initialization string in
6668 * If <altsvp> is non-null, will return the alternates to the regular swash
6670 * Tied intimately to how regcomp.c sets up the data structure */
6678 RXi_GET_DECL(prog,progi);
6679 const struct reg_data * const data = prog ? progi->data : NULL;
6681 PERL_ARGS_ASSERT_CORE_REGCLASS_SWASH;
6683 assert(ANYOF_NONBITMAP(node));
6685 if (data && data->count) {
6686 const U32 n = ARG(node);
6688 if (data->what[n] == 's') {
6689 SV * const rv = MUTABLE_SV(data->data[n]);
6690 AV * const av = MUTABLE_AV(SvRV(rv));
6691 SV **const ary = AvARRAY(av);
6692 U8 swash_init_flags = 0;
6694 si = *ary; /* ary[0] = the string to initialize the swash with */
6696 /* Elements 3 and 4 are either both present or both absent. [3] is
6697 * any inversion list generated at compile time; [4] indicates if
6698 * that inversion list has any user-defined properties in it. */
6699 if (av_len(av) >= 3) {
6702 swash_init_flags |= _CORE_SWASH_INIT_USER_DEFINED_PROPERTY;
6709 /* Element [1] is reserved for the set-up swash. If already there,
6710 * return it; if not, create it and store it there */
6711 if (SvROK(ary[1])) {
6714 else if (si && doinit) {
6716 sw = _core_swash_init("utf8", /* the utf8 package */
6720 0, /* not from tr/// */
6723 (void)av_store(av, 1, sw);
6726 /* Element [2] is for any multi-char folds. Note that is a
6727 * fundamentally flawed design, because can't backtrack and try
6728 * again. See [perl #89774] */
6729 if (SvTYPE(ary[2]) == SVt_PVAV) {
6736 SV* matches_string = newSVpvn("", 0);
6738 /* Use the swash, if any, which has to have incorporated into it all
6740 if ((! sw || (invlist = _get_swash_invlist(sw)) == NULL)
6741 && (si && si != &PL_sv_undef))
6744 /* If no swash, use the input initialization string, if available */
6745 sv_catsv(matches_string, si);
6748 /* Add the inversion list to whatever we have. This may have come from
6749 * the swash, or from an input parameter */
6751 sv_catsv(matches_string, _invlist_contents(invlist));
6753 *listsvp = matches_string;
6763 - reginclass - determine if a character falls into a character class
6765 n is the ANYOF regnode
6766 p is the target string
6767 lenp is pointer to the maximum number of bytes of how far to go in p
6768 (This is assumed wthout checking to always be at least the current
6770 utf8_target tells whether p is in UTF-8.
6772 Returns true if matched; false otherwise. If lenp is not NULL, on return
6773 from a successful match, the value it points to will be updated to how many
6774 bytes in p were matched. If there was no match, the value is undefined,
6775 possibly changed from the input.
6777 Note that this can be a synthetic start class, a combination of various
6778 nodes, so things you think might be mutually exclusive, such as locale,
6779 aren't. It can match both locale and non-locale
6784 S_reginclass(pTHX_ const regexp * const prog, register const regnode * const n, register const U8* const p, STRLEN* lenp, register const bool utf8_target)
6787 const char flags = ANYOF_FLAGS(n);
6793 PERL_ARGS_ASSERT_REGINCLASS;
6795 /* If c is not already the code point, get it */
6796 if (utf8_target && !UTF8_IS_INVARIANT(c)) {
6797 c = utf8n_to_uvchr(p, UTF8_MAXBYTES, &c_len,
6798 (UTF8_ALLOW_DEFAULT & UTF8_ALLOW_ANYUV)
6799 | UTF8_ALLOW_FFFF | UTF8_CHECK_ONLY);
6800 /* see [perl #37836] for UTF8_ALLOW_ANYUV; [perl #38293] for
6801 * UTF8_ALLOW_FFFF */
6802 if (c_len == (STRLEN)-1)
6803 Perl_croak(aTHX_ "Malformed UTF-8 character (fatal)");
6809 /* Use passed in max length, or one character if none passed in or less
6810 * than one character. And assume will match just one character. This is
6811 * overwritten later if matched more. */
6813 maxlen = (*lenp > c_len) ? *lenp : c_len;
6821 /* If this character is potentially in the bitmap, check it */
6823 if (ANYOF_BITMAP_TEST(n, c))
6825 else if (flags & ANYOF_NON_UTF8_LATIN1_ALL
6832 else if (flags & ANYOF_LOCALE) {
6833 PL_reg_flags |= RF_tainted;
6835 if ((flags & ANYOF_LOC_NONBITMAP_FOLD)
6836 && ANYOF_BITMAP_TEST(n, PL_fold_locale[c]))
6840 else if (ANYOF_CLASS_TEST_ANY_SET(n) &&
6841 ((ANYOF_CLASS_TEST(n, ANYOF_ALNUM) && isALNUM_LC(c)) ||
6842 (ANYOF_CLASS_TEST(n, ANYOF_NALNUM) && !isALNUM_LC(c)) ||
6843 (ANYOF_CLASS_TEST(n, ANYOF_SPACE) && isSPACE_LC(c)) ||
6844 (ANYOF_CLASS_TEST(n, ANYOF_NSPACE) && !isSPACE_LC(c)) ||
6845 (ANYOF_CLASS_TEST(n, ANYOF_DIGIT) && isDIGIT_LC(c)) ||
6846 (ANYOF_CLASS_TEST(n, ANYOF_NDIGIT) && !isDIGIT_LC(c)) ||
6847 (ANYOF_CLASS_TEST(n, ANYOF_ALNUMC) && isALNUMC_LC(c)) ||
6848 (ANYOF_CLASS_TEST(n, ANYOF_NALNUMC) && !isALNUMC_LC(c)) ||
6849 (ANYOF_CLASS_TEST(n, ANYOF_ALPHA) && isALPHA_LC(c)) ||
6850 (ANYOF_CLASS_TEST(n, ANYOF_NALPHA) && !isALPHA_LC(c)) ||
6851 (ANYOF_CLASS_TEST(n, ANYOF_ASCII) && isASCII_LC(c)) ||
6852 (ANYOF_CLASS_TEST(n, ANYOF_NASCII) && !isASCII_LC(c)) ||
6853 (ANYOF_CLASS_TEST(n, ANYOF_CNTRL) && isCNTRL_LC(c)) ||
6854 (ANYOF_CLASS_TEST(n, ANYOF_NCNTRL) && !isCNTRL_LC(c)) ||
6855 (ANYOF_CLASS_TEST(n, ANYOF_GRAPH) && isGRAPH_LC(c)) ||
6856 (ANYOF_CLASS_TEST(n, ANYOF_NGRAPH) && !isGRAPH_LC(c)) ||
6857 (ANYOF_CLASS_TEST(n, ANYOF_LOWER) && isLOWER_LC(c)) ||
6858 (ANYOF_CLASS_TEST(n, ANYOF_NLOWER) && !isLOWER_LC(c)) ||
6859 (ANYOF_CLASS_TEST(n, ANYOF_PRINT) && isPRINT_LC(c)) ||
6860 (ANYOF_CLASS_TEST(n, ANYOF_NPRINT) && !isPRINT_LC(c)) ||
6861 (ANYOF_CLASS_TEST(n, ANYOF_PUNCT) && isPUNCT_LC(c)) ||
6862 (ANYOF_CLASS_TEST(n, ANYOF_NPUNCT) && !isPUNCT_LC(c)) ||
6863 (ANYOF_CLASS_TEST(n, ANYOF_UPPER) && isUPPER_LC(c)) ||
6864 (ANYOF_CLASS_TEST(n, ANYOF_NUPPER) && !isUPPER_LC(c)) ||
6865 (ANYOF_CLASS_TEST(n, ANYOF_XDIGIT) && isXDIGIT(c)) ||
6866 (ANYOF_CLASS_TEST(n, ANYOF_NXDIGIT) && !isXDIGIT(c)) ||
6867 (ANYOF_CLASS_TEST(n, ANYOF_PSXSPC) && isPSXSPC(c)) ||
6868 (ANYOF_CLASS_TEST(n, ANYOF_NPSXSPC) && !isPSXSPC(c)) ||
6869 (ANYOF_CLASS_TEST(n, ANYOF_BLANK) && isBLANK_LC(c)) ||
6870 (ANYOF_CLASS_TEST(n, ANYOF_NBLANK) && !isBLANK_LC(c))
6871 ) /* How's that for a conditional? */
6878 /* If the bitmap didn't (or couldn't) match, and something outside the
6879 * bitmap could match, try that. Locale nodes specifiy completely the
6880 * behavior of code points in the bit map (otherwise, a utf8 target would
6881 * cause them to be treated as Unicode and not locale), except in
6882 * the very unlikely event when this node is a synthetic start class, which
6883 * could be a combination of locale and non-locale nodes. So allow locale
6884 * to match for the synthetic start class, which will give a false
6885 * positive that will be resolved when the match is done again as not part
6886 * of the synthetic start class */
6888 if (utf8_target && (flags & ANYOF_UNICODE_ALL) && c >= 256) {
6889 match = TRUE; /* Everything above 255 matches */
6891 else if (ANYOF_NONBITMAP(n)
6892 && ((flags & ANYOF_NONBITMAP_NON_UTF8)
6895 || (! (flags & ANYOF_LOCALE))
6896 || (flags & ANYOF_IS_SYNTHETIC)))))
6899 SV * const sw = core_regclass_swash(prog, n, TRUE, 0, (SV**)&av);
6907 /* Not utf8. Convert as much of the string as available up
6908 * to the limit of how far the (single) character in the
6909 * pattern can possibly match (no need to go further). If
6910 * the node is a straight ANYOF or not folding, it can't
6911 * match more than one. Otherwise, It can match up to how
6912 * far a single char can fold to. Since not utf8, each
6913 * character is a single byte, so the max it can be in
6914 * bytes is the same as the max it can be in characters */
6915 STRLEN len = (OP(n) == ANYOF
6916 || ! (flags & ANYOF_LOC_NONBITMAP_FOLD))
6918 : (maxlen < UTF8_MAX_FOLD_CHAR_EXPAND)
6920 : UTF8_MAX_FOLD_CHAR_EXPAND;
6921 utf8_p = bytes_to_utf8(p, &len);
6924 if (swash_fetch(sw, utf8_p, TRUE))
6926 else if (flags & ANYOF_LOC_NONBITMAP_FOLD) {
6928 /* Here, we need to test if the fold of the target string
6929 * matches. The non-multi char folds have all been moved to
6930 * the compilation phase, and the multi-char folds have
6931 * been stored by regcomp into 'av'; we linearly check to
6932 * see if any match the target string (folded). We know
6933 * that the originals were each one character, but we don't
6934 * currently know how many characters/bytes each folded to,
6935 * except we do know that there are small limits imposed by
6936 * Unicode. XXX A performance enhancement would be to have
6937 * regcomp.c store the max number of chars/bytes that are
6938 * in an av entry, as, say the 0th element. Even better
6939 * would be to have a hash of the few characters that can
6940 * start a multi-char fold to the max number of chars of
6943 * If there is a match, we will need to advance (if lenp is
6944 * specified) the match pointer in the target string. But
6945 * what we are comparing here isn't that string directly,
6946 * but its fold, whose length may differ from the original.
6947 * As we go along in constructing the fold, therefore, we
6948 * create a map so that we know how many bytes in the
6949 * source to advance given that we have matched a certain
6950 * number of bytes in the fold. This map is stored in
6951 * 'map_fold_len_back'. Let n mean the number of bytes in
6952 * the fold of the first character that we are folding.
6953 * Then map_fold_len_back[n] is set to the number of bytes
6954 * in that first character. Similarly let m be the
6955 * corresponding number for the second character to be
6956 * folded. Then map_fold_len_back[n+m] is set to the
6957 * number of bytes occupied by the first two source
6958 * characters. ... */
6959 U8 map_fold_len_back[UTF8_MAXBYTES_CASE+1] = { 0 };
6960 U8 folded[UTF8_MAXBYTES_CASE+1];
6961 STRLEN foldlen = 0; /* num bytes in fold of 1st char */
6962 STRLEN total_foldlen = 0; /* num bytes in fold of all
6965 if (OP(n) == ANYOF || maxlen == 1 || ! lenp || ! av) {
6967 /* Here, only need to fold the first char of the target
6968 * string. It the source wasn't utf8, is 1 byte long */
6969 to_utf8_fold(utf8_p, folded, &foldlen);
6970 total_foldlen = foldlen;
6971 map_fold_len_back[foldlen] = (utf8_target)
6977 /* Here, need to fold more than the first char. Do so
6978 * up to the limits */
6979 U8* source_ptr = utf8_p; /* The source for the fold
6982 U8* folded_ptr = folded;
6983 U8* e = utf8_p + maxlen; /* Can't go beyond last
6984 available byte in the
6988 i < UTF8_MAX_FOLD_CHAR_EXPAND && source_ptr < e;
6992 /* Fold the next character */
6993 U8 this_char_folded[UTF8_MAXBYTES_CASE+1];
6994 STRLEN this_char_foldlen;
6995 to_utf8_fold(source_ptr,
6997 &this_char_foldlen);
6999 /* Bail if it would exceed the byte limit for
7000 * folding a single char. */
7001 if (this_char_foldlen + folded_ptr - folded >
7007 /* Add the fold of this character */
7008 Copy(this_char_folded,
7012 source_ptr += UTF8SKIP(source_ptr);
7013 folded_ptr += this_char_foldlen;
7014 total_foldlen = folded_ptr - folded;
7016 /* Create map from the number of bytes in the fold
7017 * back to the number of bytes in the source. If
7018 * the source isn't utf8, the byte count is just
7019 * the number of characters so far */
7020 map_fold_len_back[total_foldlen]
7022 ? source_ptr - utf8_p
7029 /* Do the linear search to see if the fold is in the list
7030 * of multi-char folds. */
7033 for (i = 0; i <= av_len(av); i++) {
7034 SV* const sv = *av_fetch(av, i, FALSE);
7036 const char * const s = SvPV_const(sv, len);
7038 if (len <= total_foldlen
7039 && memEQ(s, (char*)folded, len)
7041 /* If 0, means matched a partial char. See
7043 && map_fold_len_back[len])
7046 /* Advance the target string ptr to account for
7047 * this fold, but have to translate from the
7048 * folded length to the corresponding source
7051 *lenp = map_fold_len_back[len];
7060 /* If we allocated a string above, free it */
7061 if (! utf8_target) Safefree(utf8_p);
7065 if (UNICODE_IS_SUPER(c)
7066 && (flags & ANYOF_WARN_SUPER)
7067 && ckWARN_d(WARN_NON_UNICODE))
7069 Perl_warner(aTHX_ packWARN(WARN_NON_UNICODE),
7070 "Code point 0x%04"UVXf" is not Unicode, all \\p{} matches fail; all \\P{} matches succeed", c);
7074 /* The xor complements the return if to invert: 1^1 = 0, 1^0 = 1 */
7075 return cBOOL(flags & ANYOF_INVERT) ^ match;
7079 S_reghop3(U8 *s, I32 off, const U8* lim)
7081 /* return the position 'off' UTF-8 characters away from 's', forward if
7082 * 'off' >= 0, backwards if negative. But don't go outside of position
7083 * 'lim', which better be < s if off < 0 */
7087 PERL_ARGS_ASSERT_REGHOP3;
7090 while (off-- && s < lim) {
7091 /* XXX could check well-formedness here */
7096 while (off++ && s > lim) {
7098 if (UTF8_IS_CONTINUED(*s)) {
7099 while (s > lim && UTF8_IS_CONTINUATION(*s))
7102 /* XXX could check well-formedness here */
7109 /* there are a bunch of places where we use two reghop3's that should
7110 be replaced with this routine. but since thats not done yet
7111 we ifdef it out - dmq
7114 S_reghop4(U8 *s, I32 off, const U8* llim, const U8* rlim)
7118 PERL_ARGS_ASSERT_REGHOP4;
7121 while (off-- && s < rlim) {
7122 /* XXX could check well-formedness here */
7127 while (off++ && s > llim) {
7129 if (UTF8_IS_CONTINUED(*s)) {
7130 while (s > llim && UTF8_IS_CONTINUATION(*s))
7133 /* XXX could check well-formedness here */
7141 S_reghopmaybe3(U8* s, I32 off, const U8* lim)
7145 PERL_ARGS_ASSERT_REGHOPMAYBE3;
7148 while (off-- && s < lim) {
7149 /* XXX could check well-formedness here */
7156 while (off++ && s > lim) {
7158 if (UTF8_IS_CONTINUED(*s)) {
7159 while (s > lim && UTF8_IS_CONTINUATION(*s))
7162 /* XXX could check well-formedness here */
7171 restore_pos(pTHX_ void *arg)
7174 regexp * const rex = (regexp *)arg;
7175 if (PL_reg_state.re_state_eval_setup_done) {
7176 if (PL_reg_oldsaved) {
7177 rex->subbeg = PL_reg_oldsaved;
7178 rex->sublen = PL_reg_oldsavedlen;
7179 #ifdef PERL_OLD_COPY_ON_WRITE
7180 rex->saved_copy = PL_nrs;
7182 RXp_MATCH_COPIED_on(rex);
7184 PL_reg_magic->mg_len = PL_reg_oldpos;
7185 PL_reg_state.re_state_eval_setup_done = FALSE;
7186 PL_curpm = PL_reg_oldcurpm;
7191 S_to_utf8_substr(pTHX_ register regexp *prog)
7195 PERL_ARGS_ASSERT_TO_UTF8_SUBSTR;
7198 if (prog->substrs->data[i].substr
7199 && !prog->substrs->data[i].utf8_substr) {
7200 SV* const sv = newSVsv(prog->substrs->data[i].substr);
7201 prog->substrs->data[i].utf8_substr = sv;
7202 sv_utf8_upgrade(sv);
7203 if (SvVALID(prog->substrs->data[i].substr)) {
7204 if (SvTAIL(prog->substrs->data[i].substr)) {
7205 /* Trim the trailing \n that fbm_compile added last
7207 SvCUR_set(sv, SvCUR(sv) - 1);
7208 /* Whilst this makes the SV technically "invalid" (as its
7209 buffer is no longer followed by "\0") when fbm_compile()
7210 adds the "\n" back, a "\0" is restored. */
7211 fbm_compile(sv, FBMcf_TAIL);
7215 if (prog->substrs->data[i].substr == prog->check_substr)
7216 prog->check_utf8 = sv;
7222 S_to_byte_substr(pTHX_ register regexp *prog)
7227 PERL_ARGS_ASSERT_TO_BYTE_SUBSTR;
7230 if (prog->substrs->data[i].utf8_substr
7231 && !prog->substrs->data[i].substr) {
7232 SV* sv = newSVsv(prog->substrs->data[i].utf8_substr);
7233 if (sv_utf8_downgrade(sv, TRUE)) {
7234 if (SvVALID(prog->substrs->data[i].utf8_substr)) {
7235 if (SvTAIL(prog->substrs->data[i].utf8_substr)) {
7236 /* Trim the trailing \n that fbm_compile added last
7238 SvCUR_set(sv, SvCUR(sv) - 1);
7239 fbm_compile(sv, FBMcf_TAIL);
7247 prog->substrs->data[i].substr = sv;
7248 if (prog->substrs->data[i].utf8_substr == prog->check_utf8)
7249 prog->check_substr = sv;
7256 * c-indentation-style: bsd
7258 * indent-tabs-mode: nil
7261 * ex: set ts=8 sts=4 sw=4 et: