5 * One Ring to rule them all, One Ring to find them
7 * [p.v of _The Lord of the Rings_, opening poem]
8 * [p.50 of _The Lord of the Rings_, I/iii: "The Shadow of the Past"]
9 * [p.254 of _The Lord of the Rings_, II/ii: "The Council of Elrond"]
12 /* This file contains functions for executing a regular expression. See
13 * also regcomp.c which funnily enough, contains functions for compiling
14 * a regular expression.
16 * This file is also copied at build time to ext/re/re_exec.c, where
17 * it's built with -DPERL_EXT_RE_BUILD -DPERL_EXT_RE_DEBUG -DPERL_EXT.
18 * This causes the main functions to be compiled under new names and with
19 * debugging support added, which makes "use re 'debug'" work.
22 /* NOTE: this is derived from Henry Spencer's regexp code, and should not
23 * confused with the original package (see point 3 below). Thanks, Henry!
26 /* Additional note: this code is very heavily munged from Henry's version
27 * in places. In some spots I've traded clarity for efficiency, so don't
28 * blame Henry for some of the lack of readability.
31 /* The names of the functions have been changed from regcomp and
32 * regexec to pregcomp and pregexec in order to avoid conflicts
33 * with the POSIX routines of the same names.
36 #ifdef PERL_EXT_RE_BUILD
41 * pregcomp and pregexec -- regsub and regerror are not used in perl
43 * Copyright (c) 1986 by University of Toronto.
44 * Written by Henry Spencer. Not derived from licensed software.
46 * Permission is granted to anyone to use this software for any
47 * purpose on any computer system, and to redistribute it freely,
48 * subject to the following restrictions:
50 * 1. The author is not responsible for the consequences of use of
51 * this software, no matter how awful, even if they arise
54 * 2. The origin of this software must not be misrepresented, either
55 * by explicit claim or by omission.
57 * 3. Altered versions must be plainly marked as such, and must not
58 * be misrepresented as being the original software.
60 **** Alterations to Henry's code are...
62 **** Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
63 **** 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
64 **** by Larry Wall and others
66 **** You may distribute under the terms of either the GNU General Public
67 **** License or the Artistic License, as specified in the README file.
69 * Beware that some of this code is subtly aware of the way operator
70 * precedence is structured in regular expressions. Serious changes in
71 * regular-expression syntax might require a total rethink.
74 #define PERL_IN_REGEXEC_C
78 #ifdef PERL_IN_XSUB_RE
84 #define RF_tainted 1 /* tainted information used? e.g. locale */
85 #define RF_warned 2 /* warned about big count? */
87 #define RF_utf8 8 /* Pattern contains multibyte chars? */
89 #define UTF_PATTERN ((PL_reg_flags & RF_utf8) != 0)
91 #define RS_init 1 /* eval environment created */
92 #define RS_set 2 /* replsv value is set */
98 /* Valid for non-utf8 strings, non-ANYOFV nodes only: avoids the reginclass
99 * call if there are no complications: i.e., if everything matchable is
100 * straight forward in the bitmap */
101 #define REGINCLASS(prog,p,c) (ANYOF_FLAGS(p) ? reginclass(prog,p,c,0,0) \
102 : ANYOF_BITMAP_TEST(p,*(c)))
108 #define CHR_SVLEN(sv) (utf8_target ? sv_len_utf8(sv) : SvCUR(sv))
109 #define CHR_DIST(a,b) (PL_reg_match_utf8 ? utf8_distance(a,b) : a - b)
111 #define HOPc(pos,off) \
112 (char *)(PL_reg_match_utf8 \
113 ? reghop3((U8*)pos, off, (U8*)(off >= 0 ? PL_regeol : PL_bostr)) \
115 #define HOPBACKc(pos, off) \
116 (char*)(PL_reg_match_utf8\
117 ? reghopmaybe3((U8*)pos, -off, (U8*)PL_bostr) \
118 : (pos - off >= PL_bostr) \
122 #define HOP3(pos,off,lim) (PL_reg_match_utf8 ? reghop3((U8*)(pos), off, (U8*)(lim)) : (U8*)(pos + off))
123 #define HOP3c(pos,off,lim) ((char*)HOP3(pos,off,lim))
125 /* these are unrolled below in the CCC_TRY_XXX defined */
126 #define LOAD_UTF8_CHARCLASS(class,str) STMT_START { \
127 if (!CAT2(PL_utf8_,class)) { \
129 ENTER; save_re_context(); \
130 ok=CAT2(is_utf8_,class)((const U8*)str); \
131 assert(ok); LEAVE; } } STMT_END
133 /* Doesn't do an assert to verify that is correct */
134 #define LOAD_UTF8_CHARCLASS_NO_CHECK(class) STMT_START { \
135 if (!CAT2(PL_utf8_,class)) { \
136 bool throw_away __attribute__unused__; \
137 ENTER; save_re_context(); \
138 throw_away = CAT2(is_utf8_,class)((const U8*)" "); \
141 #define LOAD_UTF8_CHARCLASS_ALNUM() LOAD_UTF8_CHARCLASS(alnum,"a")
142 #define LOAD_UTF8_CHARCLASS_DIGIT() LOAD_UTF8_CHARCLASS(digit,"0")
143 #define LOAD_UTF8_CHARCLASS_SPACE() LOAD_UTF8_CHARCLASS(space," ")
145 #define LOAD_UTF8_CHARCLASS_GCB() /* Grapheme cluster boundaries */ \
146 LOAD_UTF8_CHARCLASS(X_begin, " "); \
147 LOAD_UTF8_CHARCLASS(X_non_hangul, "A"); \
148 /* These are utf8 constants, and not utf-ebcdic constants, so the \
149 * assert should likely and hopefully fail on an EBCDIC machine */ \
150 LOAD_UTF8_CHARCLASS(X_extend, "\xcc\x80"); /* U+0300 */ \
152 /* No asserts are done for these, in case called on an early \
153 * Unicode version in which they map to nothing */ \
154 LOAD_UTF8_CHARCLASS_NO_CHECK(X_prepend);/* U+0E40 "\xe0\xb9\x80" */ \
155 LOAD_UTF8_CHARCLASS_NO_CHECK(X_L); /* U+1100 "\xe1\x84\x80" */ \
156 LOAD_UTF8_CHARCLASS_NO_CHECK(X_LV); /* U+AC00 "\xea\xb0\x80" */ \
157 LOAD_UTF8_CHARCLASS_NO_CHECK(X_LVT); /* U+AC01 "\xea\xb0\x81" */ \
158 LOAD_UTF8_CHARCLASS_NO_CHECK(X_LV_LVT_V);/* U+AC01 "\xea\xb0\x81" */\
159 LOAD_UTF8_CHARCLASS_NO_CHECK(X_T); /* U+11A8 "\xe1\x86\xa8" */ \
160 LOAD_UTF8_CHARCLASS_NO_CHECK(X_V) /* U+1160 "\xe1\x85\xa0" */
162 #define PLACEHOLDER /* Something for the preprocessor to grab onto */
164 /* The actual code for CCC_TRY, which uses several variables from the routine
165 * it's callable from. It is designed to be the bulk of a case statement.
166 * FUNC is the macro or function to call on non-utf8 targets that indicate if
167 * nextchr matches the class.
168 * UTF8_TEST is the whole test string to use for utf8 targets
169 * LOAD is what to use to test, and if not present to load in the swash for the
171 * POS_OR_NEG is either empty or ! to complement the results of FUNC or
173 * The logic is: Fail if we're at the end-of-string; otherwise if the target is
174 * utf8 and a variant, load the swash if necessary and test using the utf8
175 * test. Advance to the next character if test is ok, otherwise fail; If not
176 * utf8 or an invariant under utf8, use the non-utf8 test, and fail if it
177 * fails, or advance to the next character */
179 #define _CCC_TRY_CODE(POS_OR_NEG, FUNC, UTF8_TEST, CLASS, STR) \
180 if (locinput >= PL_regeol) { \
183 if (utf8_target && UTF8_IS_CONTINUED(nextchr)) { \
184 LOAD_UTF8_CHARCLASS(CLASS, STR); \
185 if (POS_OR_NEG (UTF8_TEST)) { \
188 locinput += PL_utf8skip[nextchr]; \
189 nextchr = UCHARAT(locinput); \
192 if (POS_OR_NEG (FUNC(nextchr))) { \
195 nextchr = UCHARAT(++locinput); \
198 /* Handle the non-locale cases for a character class and its complement. It
199 * calls _CCC_TRY_CODE with a ! to complement the test for the character class.
200 * This is because that code fails when the test succeeds, so we want to have
201 * the test fail so that the code succeeds. The swash is stored in a
202 * predictable PL_ place */
203 #define _CCC_TRY_NONLOCALE(NAME, NNAME, FUNC, \
206 _CCC_TRY_CODE( !, FUNC, \
207 cBOOL(swash_fetch(CAT2(PL_utf8_,CLASS), \
208 (U8*)locinput, TRUE)), \
211 _CCC_TRY_CODE( PLACEHOLDER , FUNC, \
212 cBOOL(swash_fetch(CAT2(PL_utf8_,CLASS), \
213 (U8*)locinput, TRUE)), \
216 /* Generate the case statements for both locale and non-locale character
217 * classes in regmatch for classes that don't have special unicode semantics.
218 * Locales don't use an immediate swash, but an intermediary special locale
219 * function that is called on the pointer to the current place in the input
220 * string. That function will resolve to needing the same swash. One might
221 * think that because we don't know what the locale will match, we shouldn't
222 * check with the swash loading function that it loaded properly; ie, that we
223 * should use LOAD_UTF8_CHARCLASS_NO_CHECK for those, but what is passed to the
224 * regular LOAD_UTF8_CHARCLASS is in non-locale terms, and so locale is
226 #define CCC_TRY(NAME, NNAME, FUNC, \
227 NAMEL, NNAMEL, LCFUNC, LCFUNC_utf8, \
228 NAMEA, NNAMEA, FUNCA, \
231 PL_reg_flags |= RF_tainted; \
232 _CCC_TRY_CODE( !, LCFUNC, LCFUNC_utf8((U8*)locinput), CLASS, STR) \
234 PL_reg_flags |= RF_tainted; \
235 _CCC_TRY_CODE( PLACEHOLDER, LCFUNC, LCFUNC_utf8((U8*)locinput), \
238 if (locinput >= PL_regeol || ! FUNCA(nextchr)) { \
241 /* Matched a utf8-invariant, so don't have to worry about utf8 */ \
242 nextchr = UCHARAT(++locinput); \
245 if (locinput >= PL_regeol || FUNCA(nextchr)) { \
249 locinput += PL_utf8skip[nextchr]; \
250 nextchr = UCHARAT(locinput); \
253 nextchr = UCHARAT(++locinput); \
256 /* Generate the non-locale cases */ \
257 _CCC_TRY_NONLOCALE(NAME, NNAME, FUNC, CLASS, STR)
259 /* This is like CCC_TRY, but has an extra set of parameters for generating case
260 * statements to handle separate Unicode semantics nodes */
261 #define CCC_TRY_U(NAME, NNAME, FUNC, \
262 NAMEL, NNAMEL, LCFUNC, LCFUNC_utf8, \
263 NAMEU, NNAMEU, FUNCU, \
264 NAMEA, NNAMEA, FUNCA, \
266 CCC_TRY(NAME, NNAME, FUNC, \
267 NAMEL, NNAMEL, LCFUNC, LCFUNC_utf8, \
268 NAMEA, NNAMEA, FUNCA, \
270 _CCC_TRY_NONLOCALE(NAMEU, NNAMEU, FUNCU, CLASS, STR)
272 /* TODO: Combine JUMPABLE and HAS_TEXT to cache OP(rn) */
274 /* for use after a quantifier and before an EXACT-like node -- japhy */
275 /* it would be nice to rework regcomp.sym to generate this stuff. sigh
277 * NOTE that *nothing* that affects backtracking should be in here, specifically
278 * VERBS must NOT be included. JUMPABLE is used to determine if we can ignore a
279 * node that is in between two EXACT like nodes when ascertaining what the required
280 * "follow" character is. This should probably be moved to regex compile time
281 * although it may be done at run time beause of the REF possibility - more
282 * investigation required. -- demerphq
284 #define JUMPABLE(rn) ( \
286 (OP(rn) == CLOSE && (!cur_eval || cur_eval->u.eval.close_paren != ARG(rn))) || \
288 OP(rn) == SUSPEND || OP(rn) == IFMATCH || \
289 OP(rn) == PLUS || OP(rn) == MINMOD || \
291 (PL_regkind[OP(rn)] == CURLY && ARG1(rn) > 0) \
293 #define IS_EXACT(rn) (PL_regkind[OP(rn)] == EXACT)
295 #define HAS_TEXT(rn) ( IS_EXACT(rn) || PL_regkind[OP(rn)] == REF )
298 /* Currently these are only used when PL_regkind[OP(rn)] == EXACT so
299 we don't need this definition. */
300 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==REF || OP(rn)==NREF )
301 #define IS_TEXTF(rn) ( (OP(rn)==EXACTFU || OP(rn)==EXACTFA || OP(rn)==EXACTF) || OP(rn)==REFF || OP(rn)==NREFF )
302 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL || OP(rn)==REFFL || OP(rn)==NREFFL )
305 /* ... so we use this as its faster. */
306 #define IS_TEXT(rn) ( OP(rn)==EXACT )
307 #define IS_TEXTFU(rn) ( OP(rn)==EXACTFU || OP(rn) == EXACTFA)
308 #define IS_TEXTF(rn) ( OP(rn)==EXACTF )
309 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL )
314 Search for mandatory following text node; for lookahead, the text must
315 follow but for lookbehind (rn->flags != 0) we skip to the next step.
317 #define FIND_NEXT_IMPT(rn) STMT_START { \
318 while (JUMPABLE(rn)) { \
319 const OPCODE type = OP(rn); \
320 if (type == SUSPEND || PL_regkind[type] == CURLY) \
321 rn = NEXTOPER(NEXTOPER(rn)); \
322 else if (type == PLUS) \
324 else if (type == IFMATCH) \
325 rn = (rn->flags == 0) ? NEXTOPER(NEXTOPER(rn)) : rn + ARG(rn); \
326 else rn += NEXT_OFF(rn); \
331 static void restore_pos(pTHX_ void *arg);
333 #define REGCP_PAREN_ELEMS 4
334 #define REGCP_OTHER_ELEMS 5
335 #define REGCP_FRAME_ELEMS 1
336 /* REGCP_FRAME_ELEMS are not part of the REGCP_OTHER_ELEMS and
337 * are needed for the regexp context stack bookkeeping. */
340 S_regcppush(pTHX_ I32 parenfloor)
343 const int retval = PL_savestack_ix;
344 const int paren_elems_to_push = (PL_regsize - parenfloor) * REGCP_PAREN_ELEMS;
345 const UV total_elems = paren_elems_to_push + REGCP_OTHER_ELEMS;
346 const UV elems_shifted = total_elems << SAVE_TIGHT_SHIFT;
348 GET_RE_DEBUG_FLAGS_DECL;
350 if (paren_elems_to_push < 0)
351 Perl_croak(aTHX_ "panic: paren_elems_to_push < 0");
353 if ((elems_shifted >> SAVE_TIGHT_SHIFT) != total_elems)
354 Perl_croak(aTHX_ "panic: paren_elems_to_push offset %"UVuf
355 " out of range (%lu-%ld)",
356 total_elems, (unsigned long)PL_regsize, (long)parenfloor);
358 SSGROW(total_elems + REGCP_FRAME_ELEMS);
360 for (p = PL_regsize; p > parenfloor; p--) {
361 /* REGCP_PARENS_ELEMS are pushed per pairs of parentheses. */
362 SSPUSHINT(PL_regoffs[p].end);
363 SSPUSHINT(PL_regoffs[p].start);
364 SSPUSHPTR(PL_reg_start_tmp[p]);
366 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
367 " saving \\%"UVuf" %"IVdf"(%"IVdf")..%"IVdf"\n",
368 (UV)p, (IV)PL_regoffs[p].start,
369 (IV)(PL_reg_start_tmp[p] - PL_bostr),
370 (IV)PL_regoffs[p].end
373 /* REGCP_OTHER_ELEMS are pushed in any case, parentheses or no. */
374 SSPUSHPTR(PL_regoffs);
375 SSPUSHINT(PL_regsize);
376 SSPUSHINT(*PL_reglastparen);
377 SSPUSHINT(*PL_reglastcloseparen);
378 SSPUSHPTR(PL_reginput);
379 SSPUSHUV(SAVEt_REGCONTEXT | elems_shifted); /* Magic cookie. */
384 /* These are needed since we do not localize EVAL nodes: */
385 #define REGCP_SET(cp) \
387 PerlIO_printf(Perl_debug_log, \
388 " Setting an EVAL scope, savestack=%"IVdf"\n", \
389 (IV)PL_savestack_ix)); \
392 #define REGCP_UNWIND(cp) \
394 if (cp != PL_savestack_ix) \
395 PerlIO_printf(Perl_debug_log, \
396 " Clearing an EVAL scope, savestack=%"IVdf"..%"IVdf"\n", \
397 (IV)(cp), (IV)PL_savestack_ix)); \
401 S_regcppop(pTHX_ const regexp *rex)
406 GET_RE_DEBUG_FLAGS_DECL;
408 PERL_ARGS_ASSERT_REGCPPOP;
410 /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
412 assert((i & SAVE_MASK) == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
413 i >>= SAVE_TIGHT_SHIFT; /* Parentheses elements to pop. */
414 input = (char *) SSPOPPTR;
415 *PL_reglastcloseparen = SSPOPINT;
416 *PL_reglastparen = SSPOPINT;
417 PL_regsize = SSPOPINT;
418 PL_regoffs=(regexp_paren_pair *) SSPOPPTR;
420 i -= REGCP_OTHER_ELEMS;
421 /* Now restore the parentheses context. */
422 for ( ; i > 0; i -= REGCP_PAREN_ELEMS) {
424 U32 paren = (U32)SSPOPINT;
425 PL_reg_start_tmp[paren] = (char *) SSPOPPTR;
426 PL_regoffs[paren].start = SSPOPINT;
428 if (paren <= *PL_reglastparen)
429 PL_regoffs[paren].end = tmps;
431 PerlIO_printf(Perl_debug_log,
432 " restoring \\%"UVuf" to %"IVdf"(%"IVdf")..%"IVdf"%s\n",
433 (UV)paren, (IV)PL_regoffs[paren].start,
434 (IV)(PL_reg_start_tmp[paren] - PL_bostr),
435 (IV)PL_regoffs[paren].end,
436 (paren > *PL_reglastparen ? "(no)" : ""));
440 if (*PL_reglastparen + 1 <= rex->nparens) {
441 PerlIO_printf(Perl_debug_log,
442 " restoring \\%"IVdf"..\\%"IVdf" to undef\n",
443 (IV)(*PL_reglastparen + 1), (IV)rex->nparens);
447 /* It would seem that the similar code in regtry()
448 * already takes care of this, and in fact it is in
449 * a better location to since this code can #if 0-ed out
450 * but the code in regtry() is needed or otherwise tests
451 * requiring null fields (pat.t#187 and split.t#{13,14}
452 * (as of patchlevel 7877) will fail. Then again,
453 * this code seems to be necessary or otherwise
454 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
455 * --jhi updated by dapm */
456 for (i = *PL_reglastparen + 1; i <= rex->nparens; i++) {
458 PL_regoffs[i].start = -1;
459 PL_regoffs[i].end = -1;
465 #define regcpblow(cp) LEAVE_SCOPE(cp) /* Ignores regcppush()ed data. */
468 * pregexec and friends
471 #ifndef PERL_IN_XSUB_RE
473 - pregexec - match a regexp against a string
476 Perl_pregexec(pTHX_ REGEXP * const prog, char* stringarg, register char *strend,
477 char *strbeg, I32 minend, SV *screamer, U32 nosave)
478 /* strend: pointer to null at end of string */
479 /* strbeg: real beginning of string */
480 /* minend: end of match must be >=minend after stringarg. */
481 /* nosave: For optimizations. */
483 PERL_ARGS_ASSERT_PREGEXEC;
486 regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
487 nosave ? 0 : REXEC_COPY_STR);
492 * Need to implement the following flags for reg_anch:
494 * USE_INTUIT_NOML - Useful to call re_intuit_start() first
496 * INTUIT_AUTORITATIVE_NOML - Can trust a positive answer
497 * INTUIT_AUTORITATIVE_ML
498 * INTUIT_ONCE_NOML - Intuit can match in one location only.
501 * Another flag for this function: SECOND_TIME (so that float substrs
502 * with giant delta may be not rechecked).
505 /* Assumptions: if ANCH_GPOS, then strpos is anchored. XXXX Check GPOS logic */
507 /* If SCREAM, then SvPVX_const(sv) should be compatible with strpos and strend.
508 Otherwise, only SvCUR(sv) is used to get strbeg. */
510 /* XXXX We assume that strpos is strbeg unless sv. */
512 /* XXXX Some places assume that there is a fixed substring.
513 An update may be needed if optimizer marks as "INTUITable"
514 RExen without fixed substrings. Similarly, it is assumed that
515 lengths of all the strings are no more than minlen, thus they
516 cannot come from lookahead.
517 (Or minlen should take into account lookahead.)
518 NOTE: Some of this comment is not correct. minlen does now take account
519 of lookahead/behind. Further research is required. -- demerphq
523 /* A failure to find a constant substring means that there is no need to make
524 an expensive call to REx engine, thus we celebrate a failure. Similarly,
525 finding a substring too deep into the string means that less calls to
526 regtry() should be needed.
528 REx compiler's optimizer found 4 possible hints:
529 a) Anchored substring;
531 c) Whether we are anchored (beginning-of-line or \G);
532 d) First node (of those at offset 0) which may distinguish positions;
533 We use a)b)d) and multiline-part of c), and try to find a position in the
534 string which does not contradict any of them.
537 /* Most of decisions we do here should have been done at compile time.
538 The nodes of the REx which we used for the search should have been
539 deleted from the finite automaton. */
542 Perl_re_intuit_start(pTHX_ REGEXP * const rx, SV *sv, char *strpos,
543 char *strend, const U32 flags, re_scream_pos_data *data)
546 struct regexp *const prog = (struct regexp *)SvANY(rx);
547 register I32 start_shift = 0;
548 /* Should be nonnegative! */
549 register I32 end_shift = 0;
554 const bool utf8_target = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
556 register char *other_last = NULL; /* other substr checked before this */
557 char *check_at = NULL; /* check substr found at this pos */
558 const I32 multiline = prog->extflags & RXf_PMf_MULTILINE;
559 RXi_GET_DECL(prog,progi);
561 const char * const i_strpos = strpos;
563 GET_RE_DEBUG_FLAGS_DECL;
565 PERL_ARGS_ASSERT_RE_INTUIT_START;
567 RX_MATCH_UTF8_set(rx,utf8_target);
570 PL_reg_flags |= RF_utf8;
573 debug_start_match(rx, utf8_target, strpos, strend,
574 sv ? "Guessing start of match in sv for"
575 : "Guessing start of match in string for");
578 /* CHR_DIST() would be more correct here but it makes things slow. */
579 if (prog->minlen > strend - strpos) {
580 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
581 "String too short... [re_intuit_start]\n"));
585 strbeg = (sv && SvPOK(sv)) ? strend - SvCUR(sv) : strpos;
588 if (!prog->check_utf8 && prog->check_substr)
589 to_utf8_substr(prog);
590 check = prog->check_utf8;
592 if (!prog->check_substr && prog->check_utf8)
593 to_byte_substr(prog);
594 check = prog->check_substr;
596 if (check == &PL_sv_undef) {
597 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
598 "Non-utf8 string cannot match utf8 check string\n"));
601 if (prog->extflags & RXf_ANCH) { /* Match at beg-of-str or after \n */
602 ml_anch = !( (prog->extflags & RXf_ANCH_SINGLE)
603 || ( (prog->extflags & RXf_ANCH_BOL)
604 && !multiline ) ); /* Check after \n? */
607 if ( !(prog->extflags & RXf_ANCH_GPOS) /* Checked by the caller */
608 && !(prog->intflags & PREGf_IMPLICIT) /* not a real BOL */
609 /* SvCUR is not set on references: SvRV and SvPVX_const overlap */
611 && (strpos != strbeg)) {
612 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Not at start...\n"));
615 if (prog->check_offset_min == prog->check_offset_max &&
616 !(prog->extflags & RXf_CANY_SEEN)) {
617 /* Substring at constant offset from beg-of-str... */
620 s = HOP3c(strpos, prog->check_offset_min, strend);
623 slen = SvCUR(check); /* >= 1 */
625 if ( strend - s > slen || strend - s < slen - 1
626 || (strend - s == slen && strend[-1] != '\n')) {
627 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "String too long...\n"));
630 /* Now should match s[0..slen-2] */
632 if (slen && (*SvPVX_const(check) != *s
634 && memNE(SvPVX_const(check), s, slen)))) {
636 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "String not equal...\n"));
640 else if (*SvPVX_const(check) != *s
641 || ((slen = SvCUR(check)) > 1
642 && memNE(SvPVX_const(check), s, slen)))
645 goto success_at_start;
648 /* Match is anchored, but substr is not anchored wrt beg-of-str. */
650 start_shift = prog->check_offset_min; /* okay to underestimate on CC */
651 end_shift = prog->check_end_shift;
654 const I32 end = prog->check_offset_max + CHR_SVLEN(check)
655 - (SvTAIL(check) != 0);
656 const I32 eshift = CHR_DIST((U8*)strend, (U8*)s) - end;
658 if (end_shift < eshift)
662 else { /* Can match at random position */
665 start_shift = prog->check_offset_min; /* okay to underestimate on CC */
666 end_shift = prog->check_end_shift;
668 /* end shift should be non negative here */
671 #ifdef QDEBUGGING /* 7/99: reports of failure (with the older version) */
673 Perl_croak(aTHX_ "panic: end_shift: %"IVdf" pattern:\n%s\n ",
674 (IV)end_shift, RX_PRECOMP(prog));
678 /* Find a possible match in the region s..strend by looking for
679 the "check" substring in the region corrected by start/end_shift. */
682 I32 srch_start_shift = start_shift;
683 I32 srch_end_shift = end_shift;
684 if (srch_start_shift < 0 && strbeg - s > srch_start_shift) {
685 srch_end_shift -= ((strbeg - s) - srch_start_shift);
686 srch_start_shift = strbeg - s;
688 DEBUG_OPTIMISE_MORE_r({
689 PerlIO_printf(Perl_debug_log, "Check offset min: %"IVdf" Start shift: %"IVdf" End shift %"IVdf" Real End Shift: %"IVdf"\n",
690 (IV)prog->check_offset_min,
691 (IV)srch_start_shift,
693 (IV)prog->check_end_shift);
696 if ((flags & REXEC_SCREAM) && SvSCREAM(sv)) {
697 I32 p = -1; /* Internal iterator of scream. */
698 I32 * const pp = data ? data->scream_pos : &p;
702 assert(SvMAGICAL(sv));
703 mg = mg_find(sv, PERL_MAGIC_study);
706 if (mg->mg_private == 1) {
707 found = ((U8 *)mg->mg_ptr)[BmRARE(check)] != (U8)~0;
708 } else if (mg->mg_private == 2) {
709 found = ((U16 *)mg->mg_ptr)[BmRARE(check)] != (U16)~0;
711 assert (mg->mg_private == 4);
712 found = ((U32 *)mg->mg_ptr)[BmRARE(check)] != (U32)~0;
716 || ( BmRARE(check) == '\n'
717 && (BmPREVIOUS(check) == SvCUR(check) - 1)
719 s = screaminstr(sv, check,
720 srch_start_shift + (s - strbeg), srch_end_shift, pp, 0);
723 /* we may be pointing at the wrong string */
724 if (s && RXp_MATCH_COPIED(prog))
725 s = strbeg + (s - SvPVX_const(sv));
727 *data->scream_olds = s;
732 if (prog->extflags & RXf_CANY_SEEN) {
733 start_point= (U8*)(s + srch_start_shift);
734 end_point= (U8*)(strend - srch_end_shift);
736 start_point= HOP3(s, srch_start_shift, srch_start_shift < 0 ? strbeg : strend);
737 end_point= HOP3(strend, -srch_end_shift, strbeg);
739 DEBUG_OPTIMISE_MORE_r({
740 PerlIO_printf(Perl_debug_log, "fbm_instr len=%d str=<%.*s>\n",
741 (int)(end_point - start_point),
742 (int)(end_point - start_point) > 20 ? 20 : (int)(end_point - start_point),
746 s = fbm_instr( start_point, end_point,
747 check, multiline ? FBMrf_MULTILINE : 0);
750 /* Update the count-of-usability, remove useless subpatterns,
754 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
755 SvPVX_const(check), RE_SV_DUMPLEN(check), 30);
756 PerlIO_printf(Perl_debug_log, "%s %s substr %s%s%s",
757 (s ? "Found" : "Did not find"),
758 (check == (utf8_target ? prog->anchored_utf8 : prog->anchored_substr)
759 ? "anchored" : "floating"),
762 (s ? " at offset " : "...\n") );
767 /* Finish the diagnostic message */
768 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%ld...\n", (long)(s - i_strpos)) );
770 /* XXX dmq: first branch is for positive lookbehind...
771 Our check string is offset from the beginning of the pattern.
772 So we need to do any stclass tests offset forward from that
781 /* Got a candidate. Check MBOL anchoring, and the *other* substr.
782 Start with the other substr.
783 XXXX no SCREAM optimization yet - and a very coarse implementation
784 XXXX /ttx+/ results in anchored="ttx", floating="x". floating will
785 *always* match. Probably should be marked during compile...
786 Probably it is right to do no SCREAM here...
789 if (utf8_target ? (prog->float_utf8 && prog->anchored_utf8)
790 : (prog->float_substr && prog->anchored_substr))
792 /* Take into account the "other" substring. */
793 /* XXXX May be hopelessly wrong for UTF... */
796 if (check == (utf8_target ? prog->float_utf8 : prog->float_substr)) {
799 char * const last = HOP3c(s, -start_shift, strbeg);
801 char * const saved_s = s;
804 t = s - prog->check_offset_max;
805 if (s - strpos > prog->check_offset_max /* signed-corrected t > strpos */
807 || ((t = (char*)reghopmaybe3((U8*)s, -(prog->check_offset_max), (U8*)strpos))
812 t = HOP3c(t, prog->anchored_offset, strend);
813 if (t < other_last) /* These positions already checked */
815 last2 = last1 = HOP3c(strend, -prog->minlen, strbeg);
818 /* XXXX It is not documented what units *_offsets are in.
819 We assume bytes, but this is clearly wrong.
820 Meaning this code needs to be carefully reviewed for errors.
824 /* On end-of-str: see comment below. */
825 must = utf8_target ? prog->anchored_utf8 : prog->anchored_substr;
826 if (must == &PL_sv_undef) {
828 DEBUG_r(must = prog->anchored_utf8); /* for debug */
833 HOP3(HOP3(last1, prog->anchored_offset, strend)
834 + SvCUR(must), -(SvTAIL(must)!=0), strbeg),
836 multiline ? FBMrf_MULTILINE : 0
839 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
840 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
841 PerlIO_printf(Perl_debug_log, "%s anchored substr %s%s",
842 (s ? "Found" : "Contradicts"),
843 quoted, RE_SV_TAIL(must));
848 if (last1 >= last2) {
849 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
850 ", giving up...\n"));
853 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
854 ", trying floating at offset %ld...\n",
855 (long)(HOP3c(saved_s, 1, strend) - i_strpos)));
856 other_last = HOP3c(last1, prog->anchored_offset+1, strend);
857 s = HOP3c(last, 1, strend);
861 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " at offset %ld...\n",
862 (long)(s - i_strpos)));
863 t = HOP3c(s, -prog->anchored_offset, strbeg);
864 other_last = HOP3c(s, 1, strend);
872 else { /* Take into account the floating substring. */
874 char * const saved_s = s;
877 t = HOP3c(s, -start_shift, strbeg);
879 HOP3c(strend, -prog->minlen + prog->float_min_offset, strbeg);
880 if (CHR_DIST((U8*)last, (U8*)t) > prog->float_max_offset)
881 last = HOP3c(t, prog->float_max_offset, strend);
882 s = HOP3c(t, prog->float_min_offset, strend);
885 /* XXXX It is not documented what units *_offsets are in. Assume bytes. */
886 must = utf8_target ? prog->float_utf8 : prog->float_substr;
887 /* fbm_instr() takes into account exact value of end-of-str
888 if the check is SvTAIL(ed). Since false positives are OK,
889 and end-of-str is not later than strend we are OK. */
890 if (must == &PL_sv_undef) {
892 DEBUG_r(must = prog->float_utf8); /* for debug message */
895 s = fbm_instr((unsigned char*)s,
896 (unsigned char*)last + SvCUR(must)
898 must, multiline ? FBMrf_MULTILINE : 0);
900 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
901 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
902 PerlIO_printf(Perl_debug_log, "%s floating substr %s%s",
903 (s ? "Found" : "Contradicts"),
904 quoted, RE_SV_TAIL(must));
908 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
909 ", giving up...\n"));
912 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
913 ", trying anchored starting at offset %ld...\n",
914 (long)(saved_s + 1 - i_strpos)));
916 s = HOP3c(t, 1, strend);
920 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " at offset %ld...\n",
921 (long)(s - i_strpos)));
922 other_last = s; /* Fix this later. --Hugo */
932 t= (char*)HOP3( s, -prog->check_offset_max, (prog->check_offset_max<0) ? strend : strpos);
934 DEBUG_OPTIMISE_MORE_r(
935 PerlIO_printf(Perl_debug_log,
936 "Check offset min:%"IVdf" max:%"IVdf" S:%"IVdf" t:%"IVdf" D:%"IVdf" end:%"IVdf"\n",
937 (IV)prog->check_offset_min,
938 (IV)prog->check_offset_max,
946 if (s - strpos > prog->check_offset_max /* signed-corrected t > strpos */
948 || ((t = (char*)reghopmaybe3((U8*)s, -prog->check_offset_max, (U8*) ((prog->check_offset_max<0) ? strend : strpos)))
951 /* Fixed substring is found far enough so that the match
952 cannot start at strpos. */
954 if (ml_anch && t[-1] != '\n') {
955 /* Eventually fbm_*() should handle this, but often
956 anchored_offset is not 0, so this check will not be wasted. */
957 /* XXXX In the code below we prefer to look for "^" even in
958 presence of anchored substrings. And we search even
959 beyond the found float position. These pessimizations
960 are historical artefacts only. */
962 while (t < strend - prog->minlen) {
964 if (t < check_at - prog->check_offset_min) {
965 if (utf8_target ? prog->anchored_utf8 : prog->anchored_substr) {
966 /* Since we moved from the found position,
967 we definitely contradict the found anchored
968 substr. Due to the above check we do not
969 contradict "check" substr.
970 Thus we can arrive here only if check substr
971 is float. Redo checking for "other"=="fixed".
974 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Found /%s^%s/m at offset %ld, rescanning for anchored from offset %ld...\n",
975 PL_colors[0], PL_colors[1], (long)(strpos - i_strpos), (long)(strpos - i_strpos + prog->anchored_offset)));
976 goto do_other_anchored;
978 /* We don't contradict the found floating substring. */
979 /* XXXX Why not check for STCLASS? */
981 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Found /%s^%s/m at offset %ld...\n",
982 PL_colors[0], PL_colors[1], (long)(s - i_strpos)));
985 /* Position contradicts check-string */
986 /* XXXX probably better to look for check-string
987 than for "\n", so one should lower the limit for t? */
988 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Found /%s^%s/m, restarting lookup for check-string at offset %ld...\n",
989 PL_colors[0], PL_colors[1], (long)(t + 1 - i_strpos)));
990 other_last = strpos = s = t + 1;
995 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Did not find /%s^%s/m...\n",
996 PL_colors[0], PL_colors[1]));
1000 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Starting position does not contradict /%s^%s/m...\n",
1001 PL_colors[0], PL_colors[1]));
1005 ++BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr); /* hooray/5 */
1008 /* The found string does not prohibit matching at strpos,
1009 - no optimization of calling REx engine can be performed,
1010 unless it was an MBOL and we are not after MBOL,
1011 or a future STCLASS check will fail this. */
1013 /* Even in this situation we may use MBOL flag if strpos is offset
1014 wrt the start of the string. */
1015 if (ml_anch && sv && !SvROK(sv) /* See prev comment on SvROK */
1016 && (strpos != strbeg) && strpos[-1] != '\n'
1017 /* May be due to an implicit anchor of m{.*foo} */
1018 && !(prog->intflags & PREGf_IMPLICIT))
1023 DEBUG_EXECUTE_r( if (ml_anch)
1024 PerlIO_printf(Perl_debug_log, "Position at offset %ld does not contradict /%s^%s/m...\n",
1025 (long)(strpos - i_strpos), PL_colors[0], PL_colors[1]);
1028 if (!(prog->intflags & PREGf_NAUGHTY) /* XXXX If strpos moved? */
1030 prog->check_utf8 /* Could be deleted already */
1031 && --BmUSEFUL(prog->check_utf8) < 0
1032 && (prog->check_utf8 == prog->float_utf8)
1034 prog->check_substr /* Could be deleted already */
1035 && --BmUSEFUL(prog->check_substr) < 0
1036 && (prog->check_substr == prog->float_substr)
1039 /* If flags & SOMETHING - do not do it many times on the same match */
1040 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "... Disabling check substring...\n"));
1041 /* XXX Does the destruction order has to change with utf8_target? */
1042 SvREFCNT_dec(utf8_target ? prog->check_utf8 : prog->check_substr);
1043 SvREFCNT_dec(utf8_target ? prog->check_substr : prog->check_utf8);
1044 prog->check_substr = prog->check_utf8 = NULL; /* disable */
1045 prog->float_substr = prog->float_utf8 = NULL; /* clear */
1046 check = NULL; /* abort */
1048 /* XXXX If the check string was an implicit check MBOL, then we need to unset the relevant flag
1049 see http://bugs.activestate.com/show_bug.cgi?id=87173 */
1050 if (prog->intflags & PREGf_IMPLICIT)
1051 prog->extflags &= ~RXf_ANCH_MBOL;
1052 /* XXXX This is a remnant of the old implementation. It
1053 looks wasteful, since now INTUIT can use many
1054 other heuristics. */
1055 prog->extflags &= ~RXf_USE_INTUIT;
1056 /* XXXX What other flags might need to be cleared in this branch? */
1062 /* Last resort... */
1063 /* XXXX BmUSEFUL already changed, maybe multiple change is meaningful... */
1064 /* trie stclasses are too expensive to use here, we are better off to
1065 leave it to regmatch itself */
1066 if (progi->regstclass && PL_regkind[OP(progi->regstclass)]!=TRIE) {
1067 /* minlen == 0 is possible if regstclass is \b or \B,
1068 and the fixed substr is ''$.
1069 Since minlen is already taken into account, s+1 is before strend;
1070 accidentally, minlen >= 1 guaranties no false positives at s + 1
1071 even for \b or \B. But (minlen? 1 : 0) below assumes that
1072 regstclass does not come from lookahead... */
1073 /* If regstclass takes bytelength more than 1: If charlength==1, OK.
1074 This leaves EXACTF-ish only, which are dealt with in find_byclass(). */
1075 const U8* const str = (U8*)STRING(progi->regstclass);
1076 const int cl_l = (PL_regkind[OP(progi->regstclass)] == EXACT
1077 ? CHR_DIST(str+STR_LEN(progi->regstclass), str)
1080 if (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
1081 endpos= HOP3c(s, (prog->minlen ? cl_l : 0), strend);
1082 else if (prog->float_substr || prog->float_utf8)
1083 endpos= HOP3c(HOP3c(check_at, -start_shift, strbeg), cl_l, strend);
1087 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "start_shift: %"IVdf" check_at: %"IVdf" s: %"IVdf" endpos: %"IVdf"\n",
1088 (IV)start_shift, (IV)(check_at - strbeg), (IV)(s - strbeg), (IV)(endpos - strbeg)));
1091 s = find_byclass(prog, progi->regstclass, s, endpos, NULL);
1094 const char *what = NULL;
1096 if (endpos == strend) {
1097 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1098 "Could not match STCLASS...\n") );
1101 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1102 "This position contradicts STCLASS...\n") );
1103 if ((prog->extflags & RXf_ANCH) && !ml_anch)
1105 /* Contradict one of substrings */
1106 if (prog->anchored_substr || prog->anchored_utf8) {
1107 if ((utf8_target ? prog->anchored_utf8 : prog->anchored_substr) == check) {
1108 DEBUG_EXECUTE_r( what = "anchored" );
1110 s = HOP3c(t, 1, strend);
1111 if (s + start_shift + end_shift > strend) {
1112 /* XXXX Should be taken into account earlier? */
1113 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1114 "Could not match STCLASS...\n") );
1119 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1120 "Looking for %s substr starting at offset %ld...\n",
1121 what, (long)(s + start_shift - i_strpos)) );
1124 /* Have both, check_string is floating */
1125 if (t + start_shift >= check_at) /* Contradicts floating=check */
1126 goto retry_floating_check;
1127 /* Recheck anchored substring, but not floating... */
1131 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1132 "Looking for anchored substr starting at offset %ld...\n",
1133 (long)(other_last - i_strpos)) );
1134 goto do_other_anchored;
1136 /* Another way we could have checked stclass at the
1137 current position only: */
1142 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1143 "Looking for /%s^%s/m starting at offset %ld...\n",
1144 PL_colors[0], PL_colors[1], (long)(t - i_strpos)) );
1147 if (!(utf8_target ? prog->float_utf8 : prog->float_substr)) /* Could have been deleted */
1149 /* Check is floating substring. */
1150 retry_floating_check:
1151 t = check_at - start_shift;
1152 DEBUG_EXECUTE_r( what = "floating" );
1153 goto hop_and_restart;
1156 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1157 "By STCLASS: moving %ld --> %ld\n",
1158 (long)(t - i_strpos), (long)(s - i_strpos))
1162 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1163 "Does not contradict STCLASS...\n");
1168 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%s%s:%s match at offset %ld\n",
1169 PL_colors[4], (check ? "Guessed" : "Giving up"),
1170 PL_colors[5], (long)(s - i_strpos)) );
1173 fail_finish: /* Substring not found */
1174 if (prog->check_substr || prog->check_utf8) /* could be removed already */
1175 BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
1177 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch rejected by optimizer%s\n",
1178 PL_colors[4], PL_colors[5]));
1182 #define DECL_TRIE_TYPE(scan) \
1183 const enum { trie_plain, trie_utf8, trie_utf8_fold, trie_latin_utf8_fold } \
1184 trie_type = (scan->flags != EXACT) \
1185 ? (utf8_target ? trie_utf8_fold : (UTF_PATTERN ? trie_latin_utf8_fold : trie_plain)) \
1186 : (utf8_target ? trie_utf8 : trie_plain)
1188 #define REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc, uscan, len, \
1189 uvc, charid, foldlen, foldbuf, uniflags) STMT_START { \
1190 switch (trie_type) { \
1191 case trie_utf8_fold: \
1192 if ( foldlen>0 ) { \
1193 uvc = utf8n_to_uvuni( uscan, UTF8_MAXLEN, &len, uniflags ); \
1198 uvc = utf8n_to_uvuni( (U8*)uc, UTF8_MAXLEN, &len, uniflags ); \
1199 uvc = to_uni_fold( uvc, foldbuf, &foldlen ); \
1200 foldlen -= UNISKIP( uvc ); \
1201 uscan = foldbuf + UNISKIP( uvc ); \
1204 case trie_latin_utf8_fold: \
1205 if ( foldlen>0 ) { \
1206 uvc = utf8n_to_uvuni( uscan, UTF8_MAXLEN, &len, uniflags ); \
1212 uvc = to_uni_fold( *(U8*)uc, foldbuf, &foldlen ); \
1213 foldlen -= UNISKIP( uvc ); \
1214 uscan = foldbuf + UNISKIP( uvc ); \
1218 uvc = utf8n_to_uvuni( (U8*)uc, UTF8_MAXLEN, &len, uniflags ); \
1225 charid = trie->charmap[ uvc ]; \
1229 if (widecharmap) { \
1230 SV** const svpp = hv_fetch(widecharmap, \
1231 (char*)&uvc, sizeof(UV), 0); \
1233 charid = (U16)SvIV(*svpp); \
1238 #define REXEC_FBC_EXACTISH_SCAN(CoNd) \
1242 && (ln == 1 || folder(s, pat_string, ln)) \
1243 && (!reginfo || regtry(reginfo, &s)) ) \
1249 #define REXEC_FBC_UTF8_SCAN(CoDe) \
1251 while (s + (uskip = UTF8SKIP(s)) <= strend) { \
1257 #define REXEC_FBC_SCAN(CoDe) \
1259 while (s < strend) { \
1265 #define REXEC_FBC_UTF8_CLASS_SCAN(CoNd) \
1266 REXEC_FBC_UTF8_SCAN( \
1268 if (tmp && (!reginfo || regtry(reginfo, &s))) \
1277 #define REXEC_FBC_CLASS_SCAN(CoNd) \
1280 if (tmp && (!reginfo || regtry(reginfo, &s))) \
1289 #define REXEC_FBC_TRYIT \
1290 if ((!reginfo || regtry(reginfo, &s))) \
1293 #define REXEC_FBC_CSCAN(CoNdUtF8,CoNd) \
1294 if (utf8_target) { \
1295 REXEC_FBC_UTF8_CLASS_SCAN(CoNdUtF8); \
1298 REXEC_FBC_CLASS_SCAN(CoNd); \
1301 #define REXEC_FBC_CSCAN_PRELOAD(UtFpReLoAd,CoNdUtF8,CoNd) \
1302 if (utf8_target) { \
1304 REXEC_FBC_UTF8_CLASS_SCAN(CoNdUtF8); \
1307 REXEC_FBC_CLASS_SCAN(CoNd); \
1310 #define REXEC_FBC_CSCAN_TAINT(CoNdUtF8,CoNd) \
1311 PL_reg_flags |= RF_tainted; \
1312 if (utf8_target) { \
1313 REXEC_FBC_UTF8_CLASS_SCAN(CoNdUtF8); \
1316 REXEC_FBC_CLASS_SCAN(CoNd); \
1319 #define DUMP_EXEC_POS(li,s,doutf8) \
1320 dump_exec_pos(li,s,(PL_regeol),(PL_bostr),(PL_reg_starttry),doutf8)
1323 #define UTF8_NOLOAD(TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1324 tmp = (s != PL_bostr) ? UCHARAT(s - 1) : '\n'; \
1325 tmp = TEST_NON_UTF8(tmp); \
1326 REXEC_FBC_UTF8_SCAN( \
1327 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1336 #define UTF8_LOAD(TeSt1_UtF8, TeSt2_UtF8, IF_SUCCESS, IF_FAIL) \
1337 if (s == PL_bostr) { \
1341 U8 * const r = reghop3((U8*)s, -1, (U8*)PL_bostr); \
1342 tmp = utf8n_to_uvchr(r, UTF8SKIP(r), 0, UTF8_ALLOW_DEFAULT); \
1345 LOAD_UTF8_CHARCLASS_ALNUM(); \
1346 REXEC_FBC_UTF8_SCAN( \
1347 if (tmp == ! (TeSt2_UtF8)) { \
1356 /* The only difference between the BOUND and NBOUND cases is that
1357 * REXEC_FBC_TRYIT is called when matched in BOUND, and when non-matched in
1358 * NBOUND. This is accomplished by passing it in either the if or else clause,
1359 * with the other one being empty */
1360 #define FBC_BOUND(TEST_NON_UTF8, TEST1_UTF8, TEST2_UTF8) \
1361 FBC_BOUND_COMMON(UTF8_LOAD(TEST1_UTF8, TEST2_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1363 #define FBC_BOUND_NOLOAD(TEST_NON_UTF8, TEST1_UTF8, TEST2_UTF8) \
1364 FBC_BOUND_COMMON(UTF8_NOLOAD(TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1366 #define FBC_NBOUND(TEST_NON_UTF8, TEST1_UTF8, TEST2_UTF8) \
1367 FBC_BOUND_COMMON(UTF8_LOAD(TEST1_UTF8, TEST2_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1369 #define FBC_NBOUND_NOLOAD(TEST_NON_UTF8, TEST1_UTF8, TEST2_UTF8) \
1370 FBC_BOUND_COMMON(UTF8_NOLOAD(TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1373 /* Common to the BOUND and NBOUND cases. Unfortunately the UTF8 tests need to
1374 * be passed in completely with the variable name being tested, which isn't
1375 * such a clean interface, but this is easier to read than it was before. We
1376 * are looking for the boundary (or non-boundary between a word and non-word
1377 * character. The utf8 and non-utf8 cases have the same logic, but the details
1378 * must be different. Find the "wordness" of the character just prior to this
1379 * one, and compare it with the wordness of this one. If they differ, we have
1380 * a boundary. At the beginning of the string, pretend that the previous
1381 * character was a new-line */
1382 #define FBC_BOUND_COMMON(UTF8_CODE, TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1383 if (utf8_target) { \
1386 else { /* Not utf8 */ \
1387 tmp = (s != PL_bostr) ? UCHARAT(s - 1) : '\n'; \
1388 tmp = TEST_NON_UTF8(tmp); \
1390 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1399 if ((!prog->minlen && tmp) && (!reginfo || regtry(reginfo, &s))) \
1402 /* We know what class REx starts with. Try to find this position... */
1403 /* if reginfo is NULL, its a dryrun */
1404 /* annoyingly all the vars in this routine have different names from their counterparts
1405 in regmatch. /grrr */
1408 S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
1409 const char *strend, regmatch_info *reginfo)
1412 const I32 doevery = (prog->intflags & PREGf_SKIP) == 0;
1413 char *pat_string; /* The pattern's exactish string */
1414 char *pat_end; /* ptr to end char of pat_string */
1415 re_fold_t folder; /* Function for computing non-utf8 folds */
1416 const U8 *fold_array; /* array for folding ords < 256 */
1419 register STRLEN uskip;
1423 register I32 tmp = 1; /* Scratch variable? */
1424 register const bool utf8_target = PL_reg_match_utf8;
1425 UV utf8_fold_flags = 0;
1426 RXi_GET_DECL(prog,progi);
1428 PERL_ARGS_ASSERT_FIND_BYCLASS;
1430 /* We know what class it must start with. */
1434 if (utf8_target || OP(c) == ANYOFV) {
1435 STRLEN inclasslen = strend - s;
1436 REXEC_FBC_UTF8_CLASS_SCAN(
1437 reginclass(prog, c, (U8*)s, &inclasslen, utf8_target));
1440 REXEC_FBC_CLASS_SCAN(REGINCLASS(prog, c, (U8*)s));
1445 if (tmp && (!reginfo || regtry(reginfo, &s)))
1453 if (UTF_PATTERN || utf8_target) {
1454 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
1455 goto do_exactf_utf8;
1457 fold_array = PL_fold_latin1; /* Latin1 folds are not affected by */
1458 folder = foldEQ_latin1; /* /a, except the sharp s one which */
1459 goto do_exactf_non_utf8; /* isn't dealt with by these */
1462 if (UTF_PATTERN || utf8_target) {
1463 utf8_fold_flags = 0;
1464 goto do_exactf_utf8;
1467 /* Any 'ss' in the pattern should have been replaced by regcomp,
1468 * so we don't have to worry here about this single special case
1469 * in the Latin1 range */
1470 fold_array = PL_fold_latin1;
1471 folder = foldEQ_latin1;
1472 goto do_exactf_non_utf8;
1475 if (UTF_PATTERN || utf8_target) {
1476 utf8_fold_flags = 0;
1477 goto do_exactf_utf8;
1479 fold_array = PL_fold;
1481 goto do_exactf_non_utf8;
1484 if (UTF_PATTERN || utf8_target) {
1485 utf8_fold_flags = FOLDEQ_UTF8_LOCALE;
1486 goto do_exactf_utf8;
1488 fold_array = PL_fold_locale;
1489 folder = foldEQ_locale;
1493 do_exactf_non_utf8: /* Neither pattern nor string are UTF8 */
1495 /* The idea in the non-utf8 EXACTF* cases is to first find the
1496 * first character of the EXACTF* node and then, if necessary,
1497 * case-insensitively compare the full text of the node. c1 is the
1498 * first character. c2 is its fold. This logic will not work for
1499 * Unicode semantics and the german sharp ss, which hence should
1500 * not be compiled into a node that gets here. */
1501 pat_string = STRING(c);
1502 ln = STR_LEN(c); /* length to match in octets/bytes */
1504 e = HOP3c(strend, -((I32)ln), s);
1506 if (!reginfo && e < s) {
1507 e = s; /* Due to minlen logic of intuit() */
1511 c2 = fold_array[c1];
1512 if (c1 == c2) { /* If char and fold are the same */
1513 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1);
1516 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1 || *(U8*)s == c2);
1522 /* If one of the operands is in utf8, we can't use the simpler
1523 * folding above, due to the fact that many different characters
1524 * can have the same fold, or portion of a fold, or different-
1526 pat_string = STRING(c);
1527 ln = STR_LEN(c); /* length to match in octets/bytes */
1528 pat_end = pat_string + ln;
1529 lnc = (UTF_PATTERN) /* length to match in characters */
1530 ? utf8_length((U8 *) pat_string, (U8 *) pat_end)
1533 e = HOP3c(strend, -((I32)lnc), s);
1535 if (!reginfo && e < s) {
1536 e = s; /* Due to minlen logic of intuit() */
1540 char *my_strend= (char *)strend;
1541 if (foldEQ_utf8_flags(s, &my_strend, 0, utf8_target,
1542 pat_string, NULL, ln, cBOOL(UTF_PATTERN), utf8_fold_flags)
1543 && (!reginfo || regtry(reginfo, &s)) )
1551 PL_reg_flags |= RF_tainted;
1552 FBC_BOUND(isALNUM_LC,
1553 isALNUM_LC_uvchr(UNI_TO_NATIVE(tmp)),
1554 isALNUM_LC_utf8((U8*)s));
1557 PL_reg_flags |= RF_tainted;
1558 FBC_NBOUND(isALNUM_LC,
1559 isALNUM_LC_uvchr(UNI_TO_NATIVE(tmp)),
1560 isALNUM_LC_utf8((U8*)s));
1563 FBC_BOUND(isWORDCHAR,
1565 cBOOL(swash_fetch(PL_utf8_alnum, (U8*)s, utf8_target)));
1568 FBC_BOUND_NOLOAD(isWORDCHAR_A,
1570 isWORDCHAR_A((U8*)s));
1573 FBC_NBOUND(isWORDCHAR,
1575 cBOOL(swash_fetch(PL_utf8_alnum, (U8*)s, utf8_target)));
1578 FBC_NBOUND_NOLOAD(isWORDCHAR_A,
1580 isWORDCHAR_A((U8*)s));
1583 FBC_BOUND(isWORDCHAR_L1,
1585 cBOOL(swash_fetch(PL_utf8_alnum, (U8*)s, utf8_target)));
1588 FBC_NBOUND(isWORDCHAR_L1,
1590 cBOOL(swash_fetch(PL_utf8_alnum, (U8*)s, utf8_target)));
1593 REXEC_FBC_CSCAN_TAINT(
1594 isALNUM_LC_utf8((U8*)s),
1599 REXEC_FBC_CSCAN_PRELOAD(
1600 LOAD_UTF8_CHARCLASS_ALNUM(),
1601 swash_fetch(PL_utf8_alnum,(U8*)s, utf8_target),
1602 isWORDCHAR_L1((U8) *s)
1606 REXEC_FBC_CSCAN_PRELOAD(
1607 LOAD_UTF8_CHARCLASS_ALNUM(),
1608 swash_fetch(PL_utf8_alnum,(U8*)s, utf8_target),
1613 /* Don't need to worry about utf8, as it can match only a single
1614 * byte invariant character */
1615 REXEC_FBC_CLASS_SCAN( isWORDCHAR_A(*s));
1618 REXEC_FBC_CSCAN_PRELOAD(
1619 LOAD_UTF8_CHARCLASS_ALNUM(),
1620 !swash_fetch(PL_utf8_alnum,(U8*)s, utf8_target),
1621 ! isWORDCHAR_L1((U8) *s)
1625 REXEC_FBC_CSCAN_PRELOAD(
1626 LOAD_UTF8_CHARCLASS_ALNUM(),
1627 !swash_fetch(PL_utf8_alnum, (U8*)s, utf8_target),
1638 REXEC_FBC_CSCAN_TAINT(
1639 !isALNUM_LC_utf8((U8*)s),
1644 REXEC_FBC_CSCAN_PRELOAD(
1645 LOAD_UTF8_CHARCLASS_SPACE(),
1646 *s == ' ' || swash_fetch(PL_utf8_space,(U8*)s, utf8_target),
1651 REXEC_FBC_CSCAN_PRELOAD(
1652 LOAD_UTF8_CHARCLASS_SPACE(),
1653 *s == ' ' || swash_fetch(PL_utf8_space,(U8*)s, utf8_target),
1658 /* Don't need to worry about utf8, as it can match only a single
1659 * byte invariant character */
1660 REXEC_FBC_CLASS_SCAN( isSPACE_A(*s));
1663 REXEC_FBC_CSCAN_TAINT(
1664 isSPACE_LC_utf8((U8*)s),
1669 REXEC_FBC_CSCAN_PRELOAD(
1670 LOAD_UTF8_CHARCLASS_SPACE(),
1671 !( *s == ' ' || swash_fetch(PL_utf8_space,(U8*)s, utf8_target)),
1672 ! isSPACE_L1((U8) *s)
1676 REXEC_FBC_CSCAN_PRELOAD(
1677 LOAD_UTF8_CHARCLASS_SPACE(),
1678 !(*s == ' ' || swash_fetch(PL_utf8_space,(U8*)s, utf8_target)),
1689 REXEC_FBC_CSCAN_TAINT(
1690 !isSPACE_LC_utf8((U8*)s),
1695 REXEC_FBC_CSCAN_PRELOAD(
1696 LOAD_UTF8_CHARCLASS_DIGIT(),
1697 swash_fetch(PL_utf8_digit,(U8*)s, utf8_target),
1702 /* Don't need to worry about utf8, as it can match only a single
1703 * byte invariant character */
1704 REXEC_FBC_CLASS_SCAN( isDIGIT_A(*s));
1707 REXEC_FBC_CSCAN_TAINT(
1708 isDIGIT_LC_utf8((U8*)s),
1713 REXEC_FBC_CSCAN_PRELOAD(
1714 LOAD_UTF8_CHARCLASS_DIGIT(),
1715 !swash_fetch(PL_utf8_digit,(U8*)s, utf8_target),
1726 REXEC_FBC_CSCAN_TAINT(
1727 !isDIGIT_LC_utf8((U8*)s),
1734 is_LNBREAK_latin1(s)
1746 !is_VERTWS_latin1(s)
1752 is_HORIZWS_latin1(s)
1757 !is_HORIZWS_utf8(s),
1758 !is_HORIZWS_latin1(s)
1765 /* what trie are we using right now */
1767 = (reg_ac_data*)progi->data->data[ ARG( c ) ];
1769 = (reg_trie_data*)progi->data->data[ aho->trie ];
1770 HV *widecharmap = MUTABLE_HV(progi->data->data[ aho->trie + 1 ]);
1772 const char *last_start = strend - trie->minlen;
1774 const char *real_start = s;
1776 STRLEN maxlen = trie->maxlen;
1778 U8 **points; /* map of where we were in the input string
1779 when reading a given char. For ASCII this
1780 is unnecessary overhead as the relationship
1781 is always 1:1, but for Unicode, especially
1782 case folded Unicode this is not true. */
1783 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
1787 GET_RE_DEBUG_FLAGS_DECL;
1789 /* We can't just allocate points here. We need to wrap it in
1790 * an SV so it gets freed properly if there is a croak while
1791 * running the match */
1794 sv_points=newSV(maxlen * sizeof(U8 *));
1795 SvCUR_set(sv_points,
1796 maxlen * sizeof(U8 *));
1797 SvPOK_on(sv_points);
1798 sv_2mortal(sv_points);
1799 points=(U8**)SvPV_nolen(sv_points );
1800 if ( trie_type != trie_utf8_fold
1801 && (trie->bitmap || OP(c)==AHOCORASICKC) )
1804 bitmap=(U8*)trie->bitmap;
1806 bitmap=(U8*)ANYOF_BITMAP(c);
1808 /* this is the Aho-Corasick algorithm modified a touch
1809 to include special handling for long "unknown char"
1810 sequences. The basic idea being that we use AC as long
1811 as we are dealing with a possible matching char, when
1812 we encounter an unknown char (and we have not encountered
1813 an accepting state) we scan forward until we find a legal
1815 AC matching is basically that of trie matching, except
1816 that when we encounter a failing transition, we fall back
1817 to the current states "fail state", and try the current char
1818 again, a process we repeat until we reach the root state,
1819 state 1, or a legal transition. If we fail on the root state
1820 then we can either terminate if we have reached an accepting
1821 state previously, or restart the entire process from the beginning
1825 while (s <= last_start) {
1826 const U32 uniflags = UTF8_ALLOW_DEFAULT;
1834 U8 *uscan = (U8*)NULL;
1835 U8 *leftmost = NULL;
1837 U32 accepted_word= 0;
1841 while ( state && uc <= (U8*)strend ) {
1843 U32 word = aho->states[ state ].wordnum;
1847 DEBUG_TRIE_EXECUTE_r(
1848 if ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
1849 dump_exec_pos( (char *)uc, c, strend, real_start,
1850 (char *)uc, utf8_target );
1851 PerlIO_printf( Perl_debug_log,
1852 " Scanning for legal start char...\n");
1856 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
1860 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
1866 if (uc >(U8*)last_start) break;
1870 U8 *lpos= points[ (pointpos - trie->wordinfo[word].len) % maxlen ];
1871 if (!leftmost || lpos < leftmost) {
1872 DEBUG_r(accepted_word=word);
1878 points[pointpos++ % maxlen]= uc;
1879 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
1880 uscan, len, uvc, charid, foldlen,
1882 DEBUG_TRIE_EXECUTE_r({
1883 dump_exec_pos( (char *)uc, c, strend, real_start,
1885 PerlIO_printf(Perl_debug_log,
1886 " Charid:%3u CP:%4"UVxf" ",
1892 word = aho->states[ state ].wordnum;
1894 base = aho->states[ state ].trans.base;
1896 DEBUG_TRIE_EXECUTE_r({
1898 dump_exec_pos( (char *)uc, c, strend, real_start,
1900 PerlIO_printf( Perl_debug_log,
1901 "%sState: %4"UVxf", word=%"UVxf,
1902 failed ? " Fail transition to " : "",
1903 (UV)state, (UV)word);
1909 ( ((offset = base + charid
1910 - 1 - trie->uniquecharcount)) >= 0)
1911 && ((U32)offset < trie->lasttrans)
1912 && trie->trans[offset].check == state
1913 && (tmp=trie->trans[offset].next))
1915 DEBUG_TRIE_EXECUTE_r(
1916 PerlIO_printf( Perl_debug_log," - legal\n"));
1921 DEBUG_TRIE_EXECUTE_r(
1922 PerlIO_printf( Perl_debug_log," - fail\n"));
1924 state = aho->fail[state];
1928 /* we must be accepting here */
1929 DEBUG_TRIE_EXECUTE_r(
1930 PerlIO_printf( Perl_debug_log," - accepting\n"));
1939 if (!state) state = 1;
1942 if ( aho->states[ state ].wordnum ) {
1943 U8 *lpos = points[ (pointpos - trie->wordinfo[aho->states[ state ].wordnum].len) % maxlen ];
1944 if (!leftmost || lpos < leftmost) {
1945 DEBUG_r(accepted_word=aho->states[ state ].wordnum);
1950 s = (char*)leftmost;
1951 DEBUG_TRIE_EXECUTE_r({
1953 Perl_debug_log,"Matches word #%"UVxf" at position %"IVdf". Trying full pattern...\n",
1954 (UV)accepted_word, (IV)(s - real_start)
1957 if (!reginfo || regtry(reginfo, &s)) {
1963 DEBUG_TRIE_EXECUTE_r({
1964 PerlIO_printf( Perl_debug_log,"Pattern failed. Looking for new start point...\n");
1967 DEBUG_TRIE_EXECUTE_r(
1968 PerlIO_printf( Perl_debug_log,"No match.\n"));
1977 Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
1987 - regexec_flags - match a regexp against a string
1990 Perl_regexec_flags(pTHX_ REGEXP * const rx, char *stringarg, register char *strend,
1991 char *strbeg, I32 minend, SV *sv, void *data, U32 flags)
1992 /* strend: pointer to null at end of string */
1993 /* strbeg: real beginning of string */
1994 /* minend: end of match must be >=minend after stringarg. */
1995 /* data: May be used for some additional optimizations.
1996 Currently its only used, with a U32 cast, for transmitting
1997 the ganch offset when doing a /g match. This will change */
1998 /* nosave: For optimizations. */
2001 struct regexp *const prog = (struct regexp *)SvANY(rx);
2002 /*register*/ char *s;
2003 register regnode *c;
2004 /*register*/ char *startpos = stringarg;
2005 I32 minlen; /* must match at least this many chars */
2006 I32 dontbother = 0; /* how many characters not to try at end */
2007 I32 end_shift = 0; /* Same for the end. */ /* CC */
2008 I32 scream_pos = -1; /* Internal iterator of scream. */
2009 char *scream_olds = NULL;
2010 const bool utf8_target = cBOOL(DO_UTF8(sv));
2012 RXi_GET_DECL(prog,progi);
2013 regmatch_info reginfo; /* create some info to pass to regtry etc */
2014 regexp_paren_pair *swap = NULL;
2015 GET_RE_DEBUG_FLAGS_DECL;
2017 PERL_ARGS_ASSERT_REGEXEC_FLAGS;
2018 PERL_UNUSED_ARG(data);
2020 /* Be paranoid... */
2021 if (prog == NULL || startpos == NULL) {
2022 Perl_croak(aTHX_ "NULL regexp parameter");
2026 multiline = prog->extflags & RXf_PMf_MULTILINE;
2027 reginfo.prog = rx; /* Yes, sorry that this is confusing. */
2029 RX_MATCH_UTF8_set(rx, utf8_target);
2031 debug_start_match(rx, utf8_target, startpos, strend,
2035 minlen = prog->minlen;
2037 if (strend - startpos < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
2038 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
2039 "String too short [regexec_flags]...\n"));
2044 /* Check validity of program. */
2045 if (UCHARAT(progi->program) != REG_MAGIC) {
2046 Perl_croak(aTHX_ "corrupted regexp program");
2050 PL_reg_eval_set = 0;
2054 PL_reg_flags |= RF_utf8;
2056 /* Mark beginning of line for ^ and lookbehind. */
2057 reginfo.bol = startpos; /* XXX not used ??? */
2061 /* Mark end of line for $ (and such) */
2064 /* see how far we have to get to not match where we matched before */
2065 reginfo.till = startpos+minend;
2067 /* If there is a "must appear" string, look for it. */
2070 if (prog->extflags & RXf_GPOS_SEEN) { /* Need to set reginfo->ganch */
2072 if (flags & REXEC_IGNOREPOS){ /* Means: check only at start */
2073 reginfo.ganch = startpos + prog->gofs;
2074 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
2075 "GPOS IGNOREPOS: reginfo.ganch = startpos + %"UVxf"\n",(UV)prog->gofs));
2076 } else if (sv && SvTYPE(sv) >= SVt_PVMG
2078 && (mg = mg_find(sv, PERL_MAGIC_regex_global))
2079 && mg->mg_len >= 0) {
2080 reginfo.ganch = strbeg + mg->mg_len; /* Defined pos() */
2081 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
2082 "GPOS MAGIC: reginfo.ganch = strbeg + %"IVdf"\n",(IV)mg->mg_len));
2084 if (prog->extflags & RXf_ANCH_GPOS) {
2085 if (s > reginfo.ganch)
2087 s = reginfo.ganch - prog->gofs;
2088 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
2089 "GPOS ANCH_GPOS: s = ganch - %"UVxf"\n",(UV)prog->gofs));
2095 reginfo.ganch = strbeg + PTR2UV(data);
2096 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
2097 "GPOS DATA: reginfo.ganch= strbeg + %"UVxf"\n",PTR2UV(data)));
2099 } else { /* pos() not defined */
2100 reginfo.ganch = strbeg;
2101 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
2102 "GPOS: reginfo.ganch = strbeg\n"));
2105 if (PL_curpm && (PM_GETRE(PL_curpm) == rx)) {
2106 /* We have to be careful. If the previous successful match
2107 was from this regex we don't want a subsequent partially
2108 successful match to clobber the old results.
2109 So when we detect this possibility we add a swap buffer
2110 to the re, and switch the buffer each match. If we fail
2111 we switch it back, otherwise we leave it swapped.
2114 /* do we need a save destructor here for eval dies? */
2115 Newxz(prog->offs, (prog->nparens + 1), regexp_paren_pair);
2117 if (!(flags & REXEC_CHECKED) && (prog->check_substr != NULL || prog->check_utf8 != NULL)) {
2118 re_scream_pos_data d;
2120 d.scream_olds = &scream_olds;
2121 d.scream_pos = &scream_pos;
2122 s = re_intuit_start(rx, sv, s, strend, flags, &d);
2124 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Not present...\n"));
2125 goto phooey; /* not present */
2131 /* Simplest case: anchored match need be tried only once. */
2132 /* [unless only anchor is BOL and multiline is set] */
2133 if (prog->extflags & (RXf_ANCH & ~RXf_ANCH_GPOS)) {
2134 if (s == startpos && regtry(®info, &startpos))
2136 else if (multiline || (prog->intflags & PREGf_IMPLICIT)
2137 || (prog->extflags & RXf_ANCH_MBOL)) /* XXXX SBOL? */
2142 dontbother = minlen - 1;
2143 end = HOP3c(strend, -dontbother, strbeg) - 1;
2144 /* for multiline we only have to try after newlines */
2145 if (prog->check_substr || prog->check_utf8) {
2146 /* because of the goto we can not easily reuse the macros for bifurcating the
2147 unicode/non-unicode match modes here like we do elsewhere - demerphq */
2150 goto after_try_utf8;
2152 if (regtry(®info, &s)) {
2159 if (prog->extflags & RXf_USE_INTUIT) {
2160 s = re_intuit_start(rx, sv, s + UTF8SKIP(s), strend, flags, NULL);
2169 } /* end search for check string in unicode */
2171 if (s == startpos) {
2172 goto after_try_latin;
2175 if (regtry(®info, &s)) {
2182 if (prog->extflags & RXf_USE_INTUIT) {
2183 s = re_intuit_start(rx, sv, s + 1, strend, flags, NULL);
2192 } /* end search for check string in latin*/
2193 } /* end search for check string */
2194 else { /* search for newline */
2196 /*XXX: The s-- is almost definitely wrong here under unicode - demeprhq*/
2199 /* We can use a more efficient search as newlines are the same in unicode as they are in latin */
2201 if (*s++ == '\n') { /* don't need PL_utf8skip here */
2202 if (regtry(®info, &s))
2206 } /* end search for newline */
2207 } /* end anchored/multiline check string search */
2209 } else if (RXf_GPOS_CHECK == (prog->extflags & RXf_GPOS_CHECK))
2211 /* the warning about reginfo.ganch being used without initialization
2212 is bogus -- we set it above, when prog->extflags & RXf_GPOS_SEEN
2213 and we only enter this block when the same bit is set. */
2214 char *tmp_s = reginfo.ganch - prog->gofs;
2216 if (tmp_s >= strbeg && regtry(®info, &tmp_s))
2221 /* Messy cases: unanchored match. */
2222 if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
2223 /* we have /x+whatever/ */
2224 /* it must be a one character string (XXXX Except UTF_PATTERN?) */
2229 if (!(utf8_target ? prog->anchored_utf8 : prog->anchored_substr))
2230 utf8_target ? to_utf8_substr(prog) : to_byte_substr(prog);
2231 ch = SvPVX_const(utf8_target ? prog->anchored_utf8 : prog->anchored_substr)[0];
2236 DEBUG_EXECUTE_r( did_match = 1 );
2237 if (regtry(®info, &s)) goto got_it;
2239 while (s < strend && *s == ch)
2247 DEBUG_EXECUTE_r( did_match = 1 );
2248 if (regtry(®info, &s)) goto got_it;
2250 while (s < strend && *s == ch)
2255 DEBUG_EXECUTE_r(if (!did_match)
2256 PerlIO_printf(Perl_debug_log,
2257 "Did not find anchored character...\n")
2260 else if (prog->anchored_substr != NULL
2261 || prog->anchored_utf8 != NULL
2262 || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
2263 && prog->float_max_offset < strend - s)) {
2268 char *last1; /* Last position checked before */
2272 if (prog->anchored_substr || prog->anchored_utf8) {
2273 if (!(utf8_target ? prog->anchored_utf8 : prog->anchored_substr))
2274 utf8_target ? to_utf8_substr(prog) : to_byte_substr(prog);
2275 must = utf8_target ? prog->anchored_utf8 : prog->anchored_substr;
2276 back_max = back_min = prog->anchored_offset;
2278 if (!(utf8_target ? prog->float_utf8 : prog->float_substr))
2279 utf8_target ? to_utf8_substr(prog) : to_byte_substr(prog);
2280 must = utf8_target ? prog->float_utf8 : prog->float_substr;
2281 back_max = prog->float_max_offset;
2282 back_min = prog->float_min_offset;
2286 if (must == &PL_sv_undef)
2287 /* could not downgrade utf8 check substring, so must fail */
2293 last = HOP3c(strend, /* Cannot start after this */
2294 -(I32)(CHR_SVLEN(must)
2295 - (SvTAIL(must) != 0) + back_min), strbeg);
2298 last1 = HOPc(s, -1);
2300 last1 = s - 1; /* bogus */
2302 /* XXXX check_substr already used to find "s", can optimize if
2303 check_substr==must. */
2305 dontbother = end_shift;
2306 strend = HOPc(strend, -dontbother);
2307 while ( (s <= last) &&
2308 ((flags & REXEC_SCREAM) && SvSCREAM(sv)
2309 ? (s = screaminstr(sv, must, HOP3c(s, back_min, (back_min<0 ? strbeg : strend)) - strbeg,
2310 end_shift, &scream_pos, 0))
2311 : (s = fbm_instr((unsigned char*)HOP3(s, back_min, (back_min<0 ? strbeg : strend)),
2312 (unsigned char*)strend, must,
2313 multiline ? FBMrf_MULTILINE : 0))) ) {
2314 /* we may be pointing at the wrong string */
2315 if ((flags & REXEC_SCREAM) && RXp_MATCH_COPIED(prog))
2316 s = strbeg + (s - SvPVX_const(sv));
2317 DEBUG_EXECUTE_r( did_match = 1 );
2318 if (HOPc(s, -back_max) > last1) {
2319 last1 = HOPc(s, -back_min);
2320 s = HOPc(s, -back_max);
2323 char * const t = (last1 >= PL_bostr) ? HOPc(last1, 1) : last1 + 1;
2325 last1 = HOPc(s, -back_min);
2329 while (s <= last1) {
2330 if (regtry(®info, &s))
2336 while (s <= last1) {
2337 if (regtry(®info, &s))
2343 DEBUG_EXECUTE_r(if (!did_match) {
2344 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
2345 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
2346 PerlIO_printf(Perl_debug_log, "Did not find %s substr %s%s...\n",
2347 ((must == prog->anchored_substr || must == prog->anchored_utf8)
2348 ? "anchored" : "floating"),
2349 quoted, RE_SV_TAIL(must));
2353 else if ( (c = progi->regstclass) ) {
2355 const OPCODE op = OP(progi->regstclass);
2356 /* don't bother with what can't match */
2357 if (PL_regkind[op] != EXACT && op != CANY && PL_regkind[op] != TRIE)
2358 strend = HOPc(strend, -(minlen - 1));
2361 SV * const prop = sv_newmortal();
2362 regprop(prog, prop, c);
2364 RE_PV_QUOTED_DECL(quoted,utf8_target,PERL_DEBUG_PAD_ZERO(1),
2366 PerlIO_printf(Perl_debug_log,
2367 "Matching stclass %.*s against %s (%d bytes)\n",
2368 (int)SvCUR(prop), SvPVX_const(prop),
2369 quoted, (int)(strend - s));
2372 if (find_byclass(prog, c, s, strend, ®info))
2374 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Contradicts stclass... [regexec_flags]\n"));
2378 if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
2383 if (!(utf8_target ? prog->float_utf8 : prog->float_substr))
2384 utf8_target ? to_utf8_substr(prog) : to_byte_substr(prog);
2385 float_real = utf8_target ? prog->float_utf8 : prog->float_substr;
2387 if ((flags & REXEC_SCREAM) && SvSCREAM(sv)) {
2388 last = screaminstr(sv, float_real, s - strbeg,
2389 end_shift, &scream_pos, 1); /* last one */
2391 last = scream_olds; /* Only one occurrence. */
2392 /* we may be pointing at the wrong string */
2393 else if (RXp_MATCH_COPIED(prog))
2394 s = strbeg + (s - SvPVX_const(sv));
2398 const char * const little = SvPV_const(float_real, len);
2400 if (SvTAIL(float_real)) {
2401 if (memEQ(strend - len + 1, little, len - 1))
2402 last = strend - len + 1;
2403 else if (!multiline)
2404 last = memEQ(strend - len, little, len)
2405 ? strend - len : NULL;
2411 last = rninstr(s, strend, little, little + len);
2413 last = strend; /* matching "$" */
2418 PerlIO_printf(Perl_debug_log,
2419 "%sCan't trim the tail, match fails (should not happen)%s\n",
2420 PL_colors[4], PL_colors[5]));
2421 goto phooey; /* Should not happen! */
2423 dontbother = strend - last + prog->float_min_offset;
2425 if (minlen && (dontbother < minlen))
2426 dontbother = minlen - 1;
2427 strend -= dontbother; /* this one's always in bytes! */
2428 /* We don't know much -- general case. */
2431 if (regtry(®info, &s))
2440 if (regtry(®info, &s))
2442 } while (s++ < strend);
2451 RX_MATCH_TAINTED_set(rx, PL_reg_flags & RF_tainted);
2453 if (PL_reg_eval_set)
2454 restore_pos(aTHX_ prog);
2455 if (RXp_PAREN_NAMES(prog))
2456 (void)hv_iterinit(RXp_PAREN_NAMES(prog));
2458 /* make sure $`, $&, $', and $digit will work later */
2459 if ( !(flags & REXEC_NOT_FIRST) ) {
2460 RX_MATCH_COPY_FREE(rx);
2461 if (flags & REXEC_COPY_STR) {
2462 const I32 i = PL_regeol - startpos + (stringarg - strbeg);
2463 #ifdef PERL_OLD_COPY_ON_WRITE
2465 || (SvFLAGS(sv) & CAN_COW_MASK) == CAN_COW_FLAGS)) {
2467 PerlIO_printf(Perl_debug_log,
2468 "Copy on write: regexp capture, type %d\n",
2471 prog->saved_copy = sv_setsv_cow(prog->saved_copy, sv);
2472 prog->subbeg = (char *)SvPVX_const(prog->saved_copy);
2473 assert (SvPOKp(prog->saved_copy));
2477 RX_MATCH_COPIED_on(rx);
2478 s = savepvn(strbeg, i);
2484 prog->subbeg = strbeg;
2485 prog->sublen = PL_regeol - strbeg; /* strend may have been modified */
2492 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch failed%s\n",
2493 PL_colors[4], PL_colors[5]));
2494 if (PL_reg_eval_set)
2495 restore_pos(aTHX_ prog);
2497 /* we failed :-( roll it back */
2498 Safefree(prog->offs);
2507 - regtry - try match at specific point
2509 STATIC I32 /* 0 failure, 1 success */
2510 S_regtry(pTHX_ regmatch_info *reginfo, char **startpos)
2514 REGEXP *const rx = reginfo->prog;
2515 regexp *const prog = (struct regexp *)SvANY(rx);
2516 RXi_GET_DECL(prog,progi);
2517 GET_RE_DEBUG_FLAGS_DECL;
2519 PERL_ARGS_ASSERT_REGTRY;
2521 reginfo->cutpoint=NULL;
2523 if ((prog->extflags & RXf_EVAL_SEEN) && !PL_reg_eval_set) {
2526 PL_reg_eval_set = RS_init;
2527 DEBUG_EXECUTE_r(DEBUG_s(
2528 PerlIO_printf(Perl_debug_log, " setting stack tmpbase at %"IVdf"\n",
2529 (IV)(PL_stack_sp - PL_stack_base));
2532 cxstack[cxstack_ix].blk_oldsp = PL_stack_sp - PL_stack_base;
2533 /* Otherwise OP_NEXTSTATE will free whatever on stack now. */
2535 /* Apparently this is not needed, judging by wantarray. */
2536 /* SAVEI8(cxstack[cxstack_ix].blk_gimme);
2537 cxstack[cxstack_ix].blk_gimme = G_SCALAR; */
2540 /* Make $_ available to executed code. */
2541 if (reginfo->sv != DEFSV) {
2543 DEFSV_set(reginfo->sv);
2546 if (!(SvTYPE(reginfo->sv) >= SVt_PVMG && SvMAGIC(reginfo->sv)
2547 && (mg = mg_find(reginfo->sv, PERL_MAGIC_regex_global)))) {
2548 /* prepare for quick setting of pos */
2549 #ifdef PERL_OLD_COPY_ON_WRITE
2550 if (SvIsCOW(reginfo->sv))
2551 sv_force_normal_flags(reginfo->sv, 0);
2553 mg = sv_magicext(reginfo->sv, NULL, PERL_MAGIC_regex_global,
2554 &PL_vtbl_mglob, NULL, 0);
2558 PL_reg_oldpos = mg->mg_len;
2559 SAVEDESTRUCTOR_X(restore_pos, prog);
2561 if (!PL_reg_curpm) {
2562 Newxz(PL_reg_curpm, 1, PMOP);
2565 SV* const repointer = &PL_sv_undef;
2566 /* this regexp is also owned by the new PL_reg_curpm, which
2567 will try to free it. */
2568 av_push(PL_regex_padav, repointer);
2569 PL_reg_curpm->op_pmoffset = av_len(PL_regex_padav);
2570 PL_regex_pad = AvARRAY(PL_regex_padav);
2575 /* It seems that non-ithreads works both with and without this code.
2576 So for efficiency reasons it seems best not to have the code
2577 compiled when it is not needed. */
2578 /* This is safe against NULLs: */
2579 ReREFCNT_dec(PM_GETRE(PL_reg_curpm));
2580 /* PM_reg_curpm owns a reference to this regexp. */
2581 (void)ReREFCNT_inc(rx);
2583 PM_SETRE(PL_reg_curpm, rx);
2584 PL_reg_oldcurpm = PL_curpm;
2585 PL_curpm = PL_reg_curpm;
2586 if (RXp_MATCH_COPIED(prog)) {
2587 /* Here is a serious problem: we cannot rewrite subbeg,
2588 since it may be needed if this match fails. Thus
2589 $` inside (?{}) could fail... */
2590 PL_reg_oldsaved = prog->subbeg;
2591 PL_reg_oldsavedlen = prog->sublen;
2592 #ifdef PERL_OLD_COPY_ON_WRITE
2593 PL_nrs = prog->saved_copy;
2595 RXp_MATCH_COPIED_off(prog);
2598 PL_reg_oldsaved = NULL;
2599 prog->subbeg = PL_bostr;
2600 prog->sublen = PL_regeol - PL_bostr; /* strend may have been modified */
2602 DEBUG_EXECUTE_r(PL_reg_starttry = *startpos);
2603 prog->offs[0].start = *startpos - PL_bostr;
2604 PL_reginput = *startpos;
2605 PL_reglastparen = &prog->lastparen;
2606 PL_reglastcloseparen = &prog->lastcloseparen;
2607 prog->lastparen = 0;
2608 prog->lastcloseparen = 0;
2610 PL_regoffs = prog->offs;
2611 if (PL_reg_start_tmpl <= prog->nparens) {
2612 PL_reg_start_tmpl = prog->nparens*3/2 + 3;
2613 if(PL_reg_start_tmp)
2614 Renew(PL_reg_start_tmp, PL_reg_start_tmpl, char*);
2616 Newx(PL_reg_start_tmp, PL_reg_start_tmpl, char*);
2619 /* XXXX What this code is doing here?!!! There should be no need
2620 to do this again and again, PL_reglastparen should take care of
2623 /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
2624 * Actually, the code in regcppop() (which Ilya may be meaning by
2625 * PL_reglastparen), is not needed at all by the test suite
2626 * (op/regexp, op/pat, op/split), but that code is needed otherwise
2627 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
2628 * Meanwhile, this code *is* needed for the
2629 * above-mentioned test suite tests to succeed. The common theme
2630 * on those tests seems to be returning null fields from matches.
2631 * --jhi updated by dapm */
2633 if (prog->nparens) {
2634 regexp_paren_pair *pp = PL_regoffs;
2636 for (i = prog->nparens; i > (I32)*PL_reglastparen; i--) {
2644 if (regmatch(reginfo, progi->program + 1)) {
2645 PL_regoffs[0].end = PL_reginput - PL_bostr;
2648 if (reginfo->cutpoint)
2649 *startpos= reginfo->cutpoint;
2650 REGCP_UNWIND(lastcp);
2655 #define sayYES goto yes
2656 #define sayNO goto no
2657 #define sayNO_SILENT goto no_silent
2659 /* we dont use STMT_START/END here because it leads to
2660 "unreachable code" warnings, which are bogus, but distracting. */
2661 #define CACHEsayNO \
2662 if (ST.cache_mask) \
2663 PL_reg_poscache[ST.cache_offset] |= ST.cache_mask; \
2666 /* this is used to determine how far from the left messages like
2667 'failed...' are printed. It should be set such that messages
2668 are inline with the regop output that created them.
2670 #define REPORT_CODE_OFF 32
2673 #define CHRTEST_UNINIT -1001 /* c1/c2 haven't been calculated yet */
2674 #define CHRTEST_VOID -1000 /* the c1/c2 "next char" test should be skipped */
2676 #define SLAB_FIRST(s) (&(s)->states[0])
2677 #define SLAB_LAST(s) (&(s)->states[PERL_REGMATCH_SLAB_SLOTS-1])
2679 /* grab a new slab and return the first slot in it */
2681 STATIC regmatch_state *
2684 #if PERL_VERSION < 9 && !defined(PERL_CORE)
2687 regmatch_slab *s = PL_regmatch_slab->next;
2689 Newx(s, 1, regmatch_slab);
2690 s->prev = PL_regmatch_slab;
2692 PL_regmatch_slab->next = s;
2694 PL_regmatch_slab = s;
2695 return SLAB_FIRST(s);
2699 /* push a new state then goto it */
2701 #define PUSH_STATE_GOTO(state, node) \
2703 st->resume_state = state; \
2706 /* push a new state with success backtracking, then goto it */
2708 #define PUSH_YES_STATE_GOTO(state, node) \
2710 st->resume_state = state; \
2711 goto push_yes_state;
2717 regmatch() - main matching routine
2719 This is basically one big switch statement in a loop. We execute an op,
2720 set 'next' to point the next op, and continue. If we come to a point which
2721 we may need to backtrack to on failure such as (A|B|C), we push a
2722 backtrack state onto the backtrack stack. On failure, we pop the top
2723 state, and re-enter the loop at the state indicated. If there are no more
2724 states to pop, we return failure.
2726 Sometimes we also need to backtrack on success; for example /A+/, where
2727 after successfully matching one A, we need to go back and try to
2728 match another one; similarly for lookahead assertions: if the assertion
2729 completes successfully, we backtrack to the state just before the assertion
2730 and then carry on. In these cases, the pushed state is marked as
2731 'backtrack on success too'. This marking is in fact done by a chain of
2732 pointers, each pointing to the previous 'yes' state. On success, we pop to
2733 the nearest yes state, discarding any intermediate failure-only states.
2734 Sometimes a yes state is pushed just to force some cleanup code to be
2735 called at the end of a successful match or submatch; e.g. (??{$re}) uses
2736 it to free the inner regex.
2738 Note that failure backtracking rewinds the cursor position, while
2739 success backtracking leaves it alone.
2741 A pattern is complete when the END op is executed, while a subpattern
2742 such as (?=foo) is complete when the SUCCESS op is executed. Both of these
2743 ops trigger the "pop to last yes state if any, otherwise return true"
2746 A common convention in this function is to use A and B to refer to the two
2747 subpatterns (or to the first nodes thereof) in patterns like /A*B/: so A is
2748 the subpattern to be matched possibly multiple times, while B is the entire
2749 rest of the pattern. Variable and state names reflect this convention.
2751 The states in the main switch are the union of ops and failure/success of
2752 substates associated with with that op. For example, IFMATCH is the op
2753 that does lookahead assertions /(?=A)B/ and so the IFMATCH state means
2754 'execute IFMATCH'; while IFMATCH_A is a state saying that we have just
2755 successfully matched A and IFMATCH_A_fail is a state saying that we have
2756 just failed to match A. Resume states always come in pairs. The backtrack
2757 state we push is marked as 'IFMATCH_A', but when that is popped, we resume
2758 at IFMATCH_A or IFMATCH_A_fail, depending on whether we are backtracking
2759 on success or failure.
2761 The struct that holds a backtracking state is actually a big union, with
2762 one variant for each major type of op. The variable st points to the
2763 top-most backtrack struct. To make the code clearer, within each
2764 block of code we #define ST to alias the relevant union.
2766 Here's a concrete example of a (vastly oversimplified) IFMATCH
2772 #define ST st->u.ifmatch
2774 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
2775 ST.foo = ...; // some state we wish to save
2777 // push a yes backtrack state with a resume value of
2778 // IFMATCH_A/IFMATCH_A_fail, then continue execution at the
2780 PUSH_YES_STATE_GOTO(IFMATCH_A, A);
2783 case IFMATCH_A: // we have successfully executed A; now continue with B
2785 bar = ST.foo; // do something with the preserved value
2788 case IFMATCH_A_fail: // A failed, so the assertion failed
2789 ...; // do some housekeeping, then ...
2790 sayNO; // propagate the failure
2797 For any old-timers reading this who are familiar with the old recursive
2798 approach, the code above is equivalent to:
2800 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
2809 ...; // do some housekeeping, then ...
2810 sayNO; // propagate the failure
2813 The topmost backtrack state, pointed to by st, is usually free. If you
2814 want to claim it, populate any ST.foo fields in it with values you wish to
2815 save, then do one of
2817 PUSH_STATE_GOTO(resume_state, node);
2818 PUSH_YES_STATE_GOTO(resume_state, node);
2820 which sets that backtrack state's resume value to 'resume_state', pushes a
2821 new free entry to the top of the backtrack stack, then goes to 'node'.
2822 On backtracking, the free slot is popped, and the saved state becomes the
2823 new free state. An ST.foo field in this new top state can be temporarily
2824 accessed to retrieve values, but once the main loop is re-entered, it
2825 becomes available for reuse.
2827 Note that the depth of the backtrack stack constantly increases during the
2828 left-to-right execution of the pattern, rather than going up and down with
2829 the pattern nesting. For example the stack is at its maximum at Z at the
2830 end of the pattern, rather than at X in the following:
2832 /(((X)+)+)+....(Y)+....Z/
2834 The only exceptions to this are lookahead/behind assertions and the cut,
2835 (?>A), which pop all the backtrack states associated with A before
2838 Backtrack state structs are allocated in slabs of about 4K in size.
2839 PL_regmatch_state and st always point to the currently active state,
2840 and PL_regmatch_slab points to the slab currently containing
2841 PL_regmatch_state. The first time regmatch() is called, the first slab is
2842 allocated, and is never freed until interpreter destruction. When the slab
2843 is full, a new one is allocated and chained to the end. At exit from
2844 regmatch(), slabs allocated since entry are freed.
2849 #define DEBUG_STATE_pp(pp) \
2851 DUMP_EXEC_POS(locinput, scan, utf8_target); \
2852 PerlIO_printf(Perl_debug_log, \
2853 " %*s"pp" %s%s%s%s%s\n", \
2855 PL_reg_name[st->resume_state], \
2856 ((st==yes_state||st==mark_state) ? "[" : ""), \
2857 ((st==yes_state) ? "Y" : ""), \
2858 ((st==mark_state) ? "M" : ""), \
2859 ((st==yes_state||st==mark_state) ? "]" : "") \
2864 #define REG_NODE_NUM(x) ((x) ? (int)((x)-prog) : -1)
2869 S_debug_start_match(pTHX_ const REGEXP *prog, const bool utf8_target,
2870 const char *start, const char *end, const char *blurb)
2872 const bool utf8_pat = RX_UTF8(prog) ? 1 : 0;
2874 PERL_ARGS_ASSERT_DEBUG_START_MATCH;
2879 RE_PV_QUOTED_DECL(s0, utf8_pat, PERL_DEBUG_PAD_ZERO(0),
2880 RX_PRECOMP_const(prog), RX_PRELEN(prog), 60);
2882 RE_PV_QUOTED_DECL(s1, utf8_target, PERL_DEBUG_PAD_ZERO(1),
2883 start, end - start, 60);
2885 PerlIO_printf(Perl_debug_log,
2886 "%s%s REx%s %s against %s\n",
2887 PL_colors[4], blurb, PL_colors[5], s0, s1);
2889 if (utf8_target||utf8_pat)
2890 PerlIO_printf(Perl_debug_log, "UTF-8 %s%s%s...\n",
2891 utf8_pat ? "pattern" : "",
2892 utf8_pat && utf8_target ? " and " : "",
2893 utf8_target ? "string" : ""
2899 S_dump_exec_pos(pTHX_ const char *locinput,
2900 const regnode *scan,
2901 const char *loc_regeol,
2902 const char *loc_bostr,
2903 const char *loc_reg_starttry,
2904 const bool utf8_target)
2906 const int docolor = *PL_colors[0] || *PL_colors[2] || *PL_colors[4];
2907 const int taill = (docolor ? 10 : 7); /* 3 chars for "> <" */
2908 int l = (loc_regeol - locinput) > taill ? taill : (loc_regeol - locinput);
2909 /* The part of the string before starttry has one color
2910 (pref0_len chars), between starttry and current
2911 position another one (pref_len - pref0_len chars),
2912 after the current position the third one.
2913 We assume that pref0_len <= pref_len, otherwise we
2914 decrease pref0_len. */
2915 int pref_len = (locinput - loc_bostr) > (5 + taill) - l
2916 ? (5 + taill) - l : locinput - loc_bostr;
2919 PERL_ARGS_ASSERT_DUMP_EXEC_POS;
2921 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput - pref_len)))
2923 pref0_len = pref_len - (locinput - loc_reg_starttry);
2924 if (l + pref_len < (5 + taill) && l < loc_regeol - locinput)
2925 l = ( loc_regeol - locinput > (5 + taill) - pref_len
2926 ? (5 + taill) - pref_len : loc_regeol - locinput);
2927 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput + l)))
2931 if (pref0_len > pref_len)
2932 pref0_len = pref_len;
2934 const int is_uni = (utf8_target && OP(scan) != CANY) ? 1 : 0;
2936 RE_PV_COLOR_DECL(s0,len0,is_uni,PERL_DEBUG_PAD(0),
2937 (locinput - pref_len),pref0_len, 60, 4, 5);
2939 RE_PV_COLOR_DECL(s1,len1,is_uni,PERL_DEBUG_PAD(1),
2940 (locinput - pref_len + pref0_len),
2941 pref_len - pref0_len, 60, 2, 3);
2943 RE_PV_COLOR_DECL(s2,len2,is_uni,PERL_DEBUG_PAD(2),
2944 locinput, loc_regeol - locinput, 10, 0, 1);
2946 const STRLEN tlen=len0+len1+len2;
2947 PerlIO_printf(Perl_debug_log,
2948 "%4"IVdf" <%.*s%.*s%s%.*s>%*s|",
2949 (IV)(locinput - loc_bostr),
2952 (docolor ? "" : "> <"),
2954 (int)(tlen > 19 ? 0 : 19 - tlen),
2961 /* reg_check_named_buff_matched()
2962 * Checks to see if a named buffer has matched. The data array of
2963 * buffer numbers corresponding to the buffer is expected to reside
2964 * in the regexp->data->data array in the slot stored in the ARG() of
2965 * node involved. Note that this routine doesn't actually care about the
2966 * name, that information is not preserved from compilation to execution.
2967 * Returns the index of the leftmost defined buffer with the given name
2968 * or 0 if non of the buffers matched.
2971 S_reg_check_named_buff_matched(pTHX_ const regexp *rex, const regnode *scan)
2974 RXi_GET_DECL(rex,rexi);
2975 SV *sv_dat= MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
2976 I32 *nums=(I32*)SvPVX(sv_dat);
2978 PERL_ARGS_ASSERT_REG_CHECK_NAMED_BUFF_MATCHED;
2980 for ( n=0; n<SvIVX(sv_dat); n++ ) {
2981 if ((I32)*PL_reglastparen >= nums[n] &&
2982 PL_regoffs[nums[n]].end != -1)
2991 /* free all slabs above current one - called during LEAVE_SCOPE */
2994 S_clear_backtrack_stack(pTHX_ void *p)
2996 regmatch_slab *s = PL_regmatch_slab->next;
3001 PL_regmatch_slab->next = NULL;
3003 regmatch_slab * const osl = s;
3010 #define SETREX(Re1,Re2) \
3011 if (PL_reg_eval_set) PM_SETRE((PL_reg_curpm), (Re2)); \
3014 STATIC I32 /* 0 failure, 1 success */
3015 S_regmatch(pTHX_ regmatch_info *reginfo, regnode *prog)
3017 #if PERL_VERSION < 9 && !defined(PERL_CORE)
3021 register const bool utf8_target = PL_reg_match_utf8;
3022 const U32 uniflags = UTF8_ALLOW_DEFAULT;
3023 REGEXP *rex_sv = reginfo->prog;
3024 regexp *rex = (struct regexp *)SvANY(rex_sv);
3025 RXi_GET_DECL(rex,rexi);
3027 /* the current state. This is a cached copy of PL_regmatch_state */
3028 register regmatch_state *st;
3029 /* cache heavy used fields of st in registers */
3030 register regnode *scan;
3031 register regnode *next;
3032 register U32 n = 0; /* general value; init to avoid compiler warning */
3033 register I32 ln = 0; /* len or last; init to avoid compiler warning */
3034 register char *locinput = PL_reginput;
3035 register I32 nextchr; /* is always set to UCHARAT(locinput) */
3037 bool result = 0; /* return value of S_regmatch */
3038 int depth = 0; /* depth of backtrack stack */
3039 U32 nochange_depth = 0; /* depth of GOSUB recursion with nochange */
3040 const U32 max_nochange_depth =
3041 (3 * rex->nparens > MAX_RECURSE_EVAL_NOCHANGE_DEPTH) ?
3042 3 * rex->nparens : MAX_RECURSE_EVAL_NOCHANGE_DEPTH;
3043 regmatch_state *yes_state = NULL; /* state to pop to on success of
3045 /* mark_state piggy backs on the yes_state logic so that when we unwind
3046 the stack on success we can update the mark_state as we go */
3047 regmatch_state *mark_state = NULL; /* last mark state we have seen */
3048 regmatch_state *cur_eval = NULL; /* most recent EVAL_AB state */
3049 struct regmatch_state *cur_curlyx = NULL; /* most recent curlyx */
3051 bool no_final = 0; /* prevent failure from backtracking? */
3052 bool do_cutgroup = 0; /* no_final only until next branch/trie entry */
3053 char *startpoint = PL_reginput;
3054 SV *popmark = NULL; /* are we looking for a mark? */
3055 SV *sv_commit = NULL; /* last mark name seen in failure */
3056 SV *sv_yes_mark = NULL; /* last mark name we have seen
3057 during a successful match */
3058 U32 lastopen = 0; /* last open we saw */
3059 bool has_cutgroup = RX_HAS_CUTGROUP(rex) ? 1 : 0;
3060 SV* const oreplsv = GvSV(PL_replgv);
3061 /* these three flags are set by various ops to signal information to
3062 * the very next op. They have a useful lifetime of exactly one loop
3063 * iteration, and are not preserved or restored by state pushes/pops
3065 bool sw = 0; /* the condition value in (?(cond)a|b) */
3066 bool minmod = 0; /* the next "{n,m}" is a "{n,m}?" */
3067 int logical = 0; /* the following EVAL is:
3071 or the following IFMATCH/UNLESSM is:
3072 false: plain (?=foo)
3073 true: used as a condition: (?(?=foo))
3076 GET_RE_DEBUG_FLAGS_DECL;
3079 PERL_ARGS_ASSERT_REGMATCH;
3081 DEBUG_OPTIMISE_r( DEBUG_EXECUTE_r({
3082 PerlIO_printf(Perl_debug_log,"regmatch start\n");
3084 /* on first ever call to regmatch, allocate first slab */
3085 if (!PL_regmatch_slab) {
3086 Newx(PL_regmatch_slab, 1, regmatch_slab);
3087 PL_regmatch_slab->prev = NULL;
3088 PL_regmatch_slab->next = NULL;
3089 PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
3092 oldsave = PL_savestack_ix;
3093 SAVEDESTRUCTOR_X(S_clear_backtrack_stack, NULL);
3094 SAVEVPTR(PL_regmatch_slab);
3095 SAVEVPTR(PL_regmatch_state);
3097 /* grab next free state slot */
3098 st = ++PL_regmatch_state;
3099 if (st > SLAB_LAST(PL_regmatch_slab))
3100 st = PL_regmatch_state = S_push_slab(aTHX);
3102 /* Note that nextchr is a byte even in UTF */
3103 nextchr = UCHARAT(locinput);
3105 while (scan != NULL) {
3108 SV * const prop = sv_newmortal();
3109 regnode *rnext=regnext(scan);
3110 DUMP_EXEC_POS( locinput, scan, utf8_target );
3111 regprop(rex, prop, scan);
3113 PerlIO_printf(Perl_debug_log,
3114 "%3"IVdf":%*s%s(%"IVdf")\n",
3115 (IV)(scan - rexi->program), depth*2, "",
3117 (PL_regkind[OP(scan)] == END || !rnext) ?
3118 0 : (IV)(rnext - rexi->program));
3121 next = scan + NEXT_OFF(scan);
3124 state_num = OP(scan);
3126 REH_CALL_EXEC_NODE_HOOK(rex, scan, reginfo, st);
3129 assert(PL_reglastparen == &rex->lastparen);
3130 assert(PL_reglastcloseparen == &rex->lastcloseparen);
3131 assert(PL_regoffs == rex->offs);
3133 switch (state_num) {
3135 if (locinput == PL_bostr)
3137 /* reginfo->till = reginfo->bol; */
3142 if (locinput == PL_bostr ||
3143 ((nextchr || locinput < PL_regeol) && locinput[-1] == '\n'))
3149 if (locinput == PL_bostr)
3153 if (locinput == reginfo->ganch)
3158 /* update the startpoint */
3159 st->u.keeper.val = PL_regoffs[0].start;
3160 PL_reginput = locinput;
3161 PL_regoffs[0].start = locinput - PL_bostr;
3162 PUSH_STATE_GOTO(KEEPS_next, next);
3164 case KEEPS_next_fail:
3165 /* rollback the start point change */
3166 PL_regoffs[0].start = st->u.keeper.val;
3172 if ((nextchr || locinput < PL_regeol) && nextchr != '\n')
3177 if ((nextchr || locinput < PL_regeol) && nextchr != '\n')
3179 if (PL_regeol - locinput > 1)
3183 if (PL_regeol != locinput)
3187 if (!nextchr && locinput >= PL_regeol)
3190 locinput += PL_utf8skip[nextchr];
3191 if (locinput > PL_regeol)
3193 nextchr = UCHARAT(locinput);
3196 nextchr = UCHARAT(++locinput);
3199 if (!nextchr && locinput >= PL_regeol)
3201 nextchr = UCHARAT(++locinput);
3204 if ((!nextchr && locinput >= PL_regeol) || nextchr == '\n')
3207 locinput += PL_utf8skip[nextchr];
3208 if (locinput > PL_regeol)
3210 nextchr = UCHARAT(locinput);
3213 nextchr = UCHARAT(++locinput);
3217 #define ST st->u.trie
3219 /* In this case the charclass data is available inline so
3220 we can fail fast without a lot of extra overhead.
3222 if (scan->flags == EXACT || !utf8_target) {
3223 if(!ANYOF_BITMAP_TEST(scan, *locinput)) {
3225 PerlIO_printf(Perl_debug_log,
3226 "%*s %sfailed to match trie start class...%s\n",
3227 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
3235 /* the basic plan of execution of the trie is:
3236 * At the beginning, run though all the states, and
3237 * find the longest-matching word. Also remember the position
3238 * of the shortest matching word. For example, this pattern:
3241 * when matched against the string "abcde", will generate
3242 * accept states for all words except 3, with the longest
3243 * matching word being 4, and the shortest being 1 (with
3244 * the position being after char 1 of the string).
3246 * Then for each matching word, in word order (i.e. 1,2,4,5),
3247 * we run the remainder of the pattern; on each try setting
3248 * the current position to the character following the word,
3249 * returning to try the next word on failure.
3251 * We avoid having to build a list of words at runtime by
3252 * using a compile-time structure, wordinfo[].prev, which
3253 * gives, for each word, the previous accepting word (if any).
3254 * In the case above it would contain the mappings 1->2, 2->0,
3255 * 3->0, 4->5, 5->1. We can use this table to generate, from
3256 * the longest word (4 above), a list of all words, by
3257 * following the list of prev pointers; this gives us the
3258 * unordered list 4,5,1,2. Then given the current word we have
3259 * just tried, we can go through the list and find the
3260 * next-biggest word to try (so if we just failed on word 2,
3261 * the next in the list is 4).
3263 * Since at runtime we don't record the matching position in
3264 * the string for each word, we have to work that out for
3265 * each word we're about to process. The wordinfo table holds
3266 * the character length of each word; given that we recorded
3267 * at the start: the position of the shortest word and its
3268 * length in chars, we just need to move the pointer the
3269 * difference between the two char lengths. Depending on
3270 * Unicode status and folding, that's cheap or expensive.
3272 * This algorithm is optimised for the case where are only a
3273 * small number of accept states, i.e. 0,1, or maybe 2.
3274 * With lots of accepts states, and having to try all of them,
3275 * it becomes quadratic on number of accept states to find all
3280 /* what type of TRIE am I? (utf8 makes this contextual) */
3281 DECL_TRIE_TYPE(scan);
3283 /* what trie are we using right now */
3284 reg_trie_data * const trie
3285 = (reg_trie_data*)rexi->data->data[ ARG( scan ) ];
3286 HV * widecharmap = MUTABLE_HV(rexi->data->data[ ARG( scan ) + 1 ]);
3287 U32 state = trie->startstate;
3289 if (trie->bitmap && trie_type != trie_utf8_fold &&
3290 !TRIE_BITMAP_TEST(trie,*locinput)
3292 if (trie->states[ state ].wordnum) {
3294 PerlIO_printf(Perl_debug_log,
3295 "%*s %smatched empty string...%s\n",
3296 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
3302 PerlIO_printf(Perl_debug_log,
3303 "%*s %sfailed to match trie start class...%s\n",
3304 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
3311 U8 *uc = ( U8* )locinput;
3315 U8 *uscan = (U8*)NULL;
3316 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
3317 U32 charcount = 0; /* how many input chars we have matched */
3318 U32 accepted = 0; /* have we seen any accepting states? */
3321 ST.jump = trie->jump;
3324 ST.longfold = FALSE; /* char longer if folded => it's harder */
3327 /* fully traverse the TRIE; note the position of the
3328 shortest accept state and the wordnum of the longest
3331 while ( state && uc <= (U8*)PL_regeol ) {
3332 U32 base = trie->states[ state ].trans.base;
3336 wordnum = trie->states[ state ].wordnum;
3338 if (wordnum) { /* it's an accept state */
3341 /* record first match position */
3343 ST.firstpos = (U8*)locinput;
3348 ST.firstchars = charcount;
3351 if (!ST.nextword || wordnum < ST.nextword)
3352 ST.nextword = wordnum;
3353 ST.topword = wordnum;
3356 DEBUG_TRIE_EXECUTE_r({
3357 DUMP_EXEC_POS( (char *)uc, scan, utf8_target );
3358 PerlIO_printf( Perl_debug_log,
3359 "%*s %sState: %4"UVxf" Accepted: %c ",
3360 2+depth * 2, "", PL_colors[4],
3361 (UV)state, (accepted ? 'Y' : 'N'));
3364 /* read a char and goto next state */
3367 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
3368 uscan, len, uvc, charid, foldlen,
3375 base + charid - 1 - trie->uniquecharcount)) >= 0)
3377 && ((U32)offset < trie->lasttrans)
3378 && trie->trans[offset].check == state)
3380 state = trie->trans[offset].next;
3391 DEBUG_TRIE_EXECUTE_r(
3392 PerlIO_printf( Perl_debug_log,
3393 "Charid:%3x CP:%4"UVxf" After State: %4"UVxf"%s\n",
3394 charid, uvc, (UV)state, PL_colors[5] );
3400 /* calculate total number of accept states */
3405 w = trie->wordinfo[w].prev;
3408 ST.accepted = accepted;
3412 PerlIO_printf( Perl_debug_log,
3413 "%*s %sgot %"IVdf" possible matches%s\n",
3414 REPORT_CODE_OFF + depth * 2, "",
3415 PL_colors[4], (IV)ST.accepted, PL_colors[5] );
3417 goto trie_first_try; /* jump into the fail handler */
3421 case TRIE_next_fail: /* we failed - try next alternative */
3423 REGCP_UNWIND(ST.cp);
3424 for (n = *PL_reglastparen; n > ST.lastparen; n--)
3425 PL_regoffs[n].end = -1;
3426 *PL_reglastparen = n;
3428 if (!--ST.accepted) {
3430 PerlIO_printf( Perl_debug_log,
3431 "%*s %sTRIE failed...%s\n",
3432 REPORT_CODE_OFF+depth*2, "",
3439 /* Find next-highest word to process. Note that this code
3440 * is O(N^2) per trie run (O(N) per branch), so keep tight */
3441 register U16 min = 0;
3443 register U16 const nextword = ST.nextword;
3444 register reg_trie_wordinfo * const wordinfo
3445 = ((reg_trie_data*)rexi->data->data[ARG(ST.me)])->wordinfo;
3446 for (word=ST.topword; word; word=wordinfo[word].prev) {
3447 if (word > nextword && (!min || word < min))
3460 ST.lastparen = *PL_reglastparen;
3464 /* find start char of end of current word */
3466 U32 chars; /* how many chars to skip */
3467 U8 *uc = ST.firstpos;
3468 reg_trie_data * const trie
3469 = (reg_trie_data*)rexi->data->data[ARG(ST.me)];
3471 assert((trie->wordinfo[ST.nextword].len - trie->prefixlen)
3473 chars = (trie->wordinfo[ST.nextword].len - trie->prefixlen)
3477 /* the hard option - fold each char in turn and find
3478 * its folded length (which may be different */
3479 U8 foldbuf[UTF8_MAXBYTES_CASE + 1];
3487 uvc = utf8n_to_uvuni((U8*)uc, UTF8_MAXLEN, &len,
3495 uvc = to_uni_fold(uvc, foldbuf, &foldlen);
3500 uvc = utf8n_to_uvuni(uscan, UTF8_MAXLEN, &len,
3514 PL_reginput = (char *)uc;
3517 scan = (ST.jump && ST.jump[ST.nextword])
3518 ? ST.me + ST.jump[ST.nextword]
3522 PerlIO_printf( Perl_debug_log,
3523 "%*s %sTRIE matched word #%d, continuing%s\n",
3524 REPORT_CODE_OFF+depth*2, "",
3531 if (ST.accepted > 1 || has_cutgroup) {
3532 PUSH_STATE_GOTO(TRIE_next, scan);
3535 /* only one choice left - just continue */
3537 AV *const trie_words
3538 = MUTABLE_AV(rexi->data->data[ARG(ST.me)+TRIE_WORDS_OFFSET]);
3539 SV ** const tmp = av_fetch( trie_words,
3541 SV *sv= tmp ? sv_newmortal() : NULL;
3543 PerlIO_printf( Perl_debug_log,
3544 "%*s %sonly one match left, short-circuiting: #%d <%s>%s\n",
3545 REPORT_CODE_OFF+depth*2, "", PL_colors[4],
3547 tmp ? pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 0,
3548 PL_colors[0], PL_colors[1],
3549 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)|PERL_PV_ESCAPE_NONASCII
3551 : "not compiled under -Dr",
3555 locinput = PL_reginput;
3556 nextchr = UCHARAT(locinput);
3557 continue; /* execute rest of RE */
3562 char *s = STRING(scan);
3564 if (utf8_target != UTF_PATTERN) {
3565 /* The target and the pattern have differing utf8ness. */
3567 const char * const e = s + ln;
3570 /* The target is utf8, the pattern is not utf8. */
3575 if (NATIVE_TO_UNI(*(U8*)s) !=
3576 utf8n_to_uvuni((U8*)l, UTF8_MAXBYTES, &ulen,
3584 /* The target is not utf8, the pattern is utf8. */
3589 if (NATIVE_TO_UNI(*((U8*)l)) !=
3590 utf8n_to_uvuni((U8*)s, UTF8_MAXBYTES, &ulen,
3598 nextchr = UCHARAT(locinput);
3601 /* The target and the pattern have the same utf8ness. */
3602 /* Inline the first character, for speed. */
3603 if (UCHARAT(s) != nextchr)
3605 if (PL_regeol - locinput < ln)
3607 if (ln > 1 && memNE(s, locinput, ln))
3610 nextchr = UCHARAT(locinput);
3615 const U8 * fold_array;
3617 U32 fold_utf8_flags;
3619 PL_reg_flags |= RF_tainted;
3620 folder = foldEQ_locale;
3621 fold_array = PL_fold_locale;
3622 fold_utf8_flags = FOLDEQ_UTF8_LOCALE;
3626 folder = foldEQ_latin1;
3627 fold_array = PL_fold_latin1;
3628 fold_utf8_flags = 0;
3632 folder = foldEQ_latin1;
3633 fold_array = PL_fold_latin1;
3634 fold_utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
3639 fold_array = PL_fold;
3640 fold_utf8_flags = 0;
3646 if (utf8_target || UTF_PATTERN) {
3647 /* Either target or the pattern are utf8. */
3648 const char * const l = locinput;
3649 char *e = PL_regeol;
3651 if (! foldEQ_utf8_flags(s, 0, ln, cBOOL(UTF_PATTERN),
3652 l, &e, 0, utf8_target, fold_utf8_flags))
3657 nextchr = UCHARAT(locinput);
3661 /* Neither the target nor the pattern are utf8 */
3662 if (UCHARAT(s) != nextchr &&
3663 UCHARAT(s) != fold_array[nextchr])
3667 if (PL_regeol - locinput < ln)
3669 if (ln > 1 && ! folder(s, locinput, ln))
3672 nextchr = UCHARAT(locinput);
3676 /* XXX Could improve efficiency by separating these all out using a
3677 * macro or in-line function. At that point regcomp.c would no longer
3678 * have to set the FLAGS fields of these */
3681 PL_reg_flags |= RF_tainted;
3689 /* was last char in word? */
3690 if (utf8_target && FLAGS(scan) != REGEX_ASCII_RESTRICTED_CHARSET) {
3691 if (locinput == PL_bostr)
3694 const U8 * const r = reghop3((U8*)locinput, -1, (U8*)PL_bostr);
3696 ln = utf8n_to_uvchr(r, UTF8SKIP(r), 0, uniflags);
3698 if (FLAGS(scan) != REGEX_LOCALE_CHARSET) {
3699 ln = isALNUM_uni(ln);
3700 LOAD_UTF8_CHARCLASS_ALNUM();
3701 n = swash_fetch(PL_utf8_alnum, (U8*)locinput, utf8_target);
3704 ln = isALNUM_LC_uvchr(UNI_TO_NATIVE(ln));
3705 n = isALNUM_LC_utf8((U8*)locinput);
3710 /* Here the string isn't utf8, or is utf8 and only ascii
3711 * characters are to match \w. In the latter case looking at
3712 * the byte just prior to the current one may be just the final
3713 * byte of a multi-byte character. This is ok. There are two
3715 * 1) it is a single byte character, and then the test is doing
3716 * just what it's supposed to.
3717 * 2) it is a multi-byte character, in which case the final
3718 * byte is never mistakable for ASCII, and so the test
3719 * will say it is not a word character, which is the
3720 * correct answer. */
3721 ln = (locinput != PL_bostr) ?
3722 UCHARAT(locinput - 1) : '\n';
3723 switch (FLAGS(scan)) {
3724 case REGEX_UNICODE_CHARSET:
3725 ln = isWORDCHAR_L1(ln);
3726 n = isWORDCHAR_L1(nextchr);
3728 case REGEX_LOCALE_CHARSET:
3729 ln = isALNUM_LC(ln);
3730 n = isALNUM_LC(nextchr);
3732 case REGEX_DEPENDS_CHARSET:
3734 n = isALNUM(nextchr);
3736 case REGEX_ASCII_RESTRICTED_CHARSET:
3737 ln = isWORDCHAR_A(ln);
3738 n = isWORDCHAR_A(nextchr);
3741 Perl_croak(aTHX_ "panic: Unexpected FLAGS %u in op %u", FLAGS(scan), OP(scan));
3745 /* Note requires that all BOUNDs be lower than all NBOUNDs in
3747 if (((!ln) == (!n)) == (OP(scan) < NBOUND))
3752 if (utf8_target || state_num == ANYOFV) {
3753 STRLEN inclasslen = PL_regeol - locinput;
3754 if (locinput >= PL_regeol)
3757 if (!reginclass(rex, scan, (U8*)locinput, &inclasslen, utf8_target))
3759 locinput += inclasslen;
3760 nextchr = UCHARAT(locinput);
3765 nextchr = UCHARAT(locinput);
3766 if (!nextchr && locinput >= PL_regeol)
3768 if (!REGINCLASS(rex, scan, (U8*)locinput))
3770 nextchr = UCHARAT(++locinput);
3774 /* Special char classes - The defines start on line 129 or so */
3775 CCC_TRY_U(ALNUM, NALNUM, isWORDCHAR,
3776 ALNUML, NALNUML, isALNUM_LC, isALNUM_LC_utf8,
3777 ALNUMU, NALNUMU, isWORDCHAR_L1,
3778 ALNUMA, NALNUMA, isWORDCHAR_A,
3781 CCC_TRY_U(SPACE, NSPACE, isSPACE,
3782 SPACEL, NSPACEL, isSPACE_LC, isSPACE_LC_utf8,
3783 SPACEU, NSPACEU, isSPACE_L1,
3784 SPACEA, NSPACEA, isSPACE_A,
3787 CCC_TRY(DIGIT, NDIGIT, isDIGIT,
3788 DIGITL, NDIGITL, isDIGIT_LC, isDIGIT_LC_utf8,
3789 DIGITA, NDIGITA, isDIGIT_A,
3792 case CLUMP: /* Match \X: logical Unicode character. This is defined as
3793 a Unicode extended Grapheme Cluster */
3794 /* From http://www.unicode.org/reports/tr29 (5.2 version). An
3795 extended Grapheme Cluster is:
3798 | Prepend* Begin Extend*
3801 Begin is (Hangul-syllable | ! Control)
3802 Extend is (Grapheme_Extend | Spacing_Mark)
3803 Control is [ GCB_Control CR LF ]
3805 The discussion below shows how the code for CLUMP is derived
3806 from this regex. Note that most of these concepts are from
3807 property values of the Grapheme Cluster Boundary (GCB) property.
3808 No code point can have multiple property values for a given
3809 property. Thus a code point in Prepend can't be in Control, but
3810 it must be in !Control. This is why Control above includes
3811 GCB_Control plus CR plus LF. The latter two are used in the GCB
3812 property separately, and so can't be in GCB_Control, even though
3813 they logically are controls. Control is not the same as gc=cc,
3814 but includes format and other characters as well.
3816 The Unicode definition of Hangul-syllable is:
3818 | (L* ( ( V | LV ) V* | LVT ) T*)
3821 Each of these is a value for the GCB property, and hence must be
3822 disjoint, so the order they are tested is immaterial, so the
3823 above can safely be changed to
3826 | (L* ( LVT | ( V | LV ) V*) T*)
3828 The last two terms can be combined like this:
3830 | (( LVT | ( V | LV ) V*) T*))
3832 And refactored into this:
3833 L* (L | LVT T* | V V* T* | LV V* T*)
3835 That means that if we have seen any L's at all we can quit
3836 there, but if the next character is an LVT, a V, or an LV we
3839 There is a subtlety with Prepend* which showed up in testing.
3840 Note that the Begin, and only the Begin is required in:
3841 | Prepend* Begin Extend*
3842 Also, Begin contains '! Control'. A Prepend must be a
3843 '! Control', which means it must also be a Begin. What it
3844 comes down to is that if we match Prepend* and then find no
3845 suitable Begin afterwards, that if we backtrack the last
3846 Prepend, that one will be a suitable Begin.
3849 if (locinput >= PL_regeol)
3851 if (! utf8_target) {
3853 /* Match either CR LF or '.', as all the other possibilities
3855 locinput++; /* Match the . or CR */
3856 if (nextchr == '\r' /* And if it was CR, and the next is LF,
3858 && locinput < PL_regeol
3859 && UCHARAT(locinput) == '\n') locinput++;
3863 /* Utf8: See if is ( CR LF ); already know that locinput <
3864 * PL_regeol, so locinput+1 is in bounds */
3865 if (nextchr == '\r' && UCHARAT(locinput + 1) == '\n') {
3869 /* In case have to backtrack to beginning, then match '.' */
3870 char *starting = locinput;
3872 /* In case have to backtrack the last prepend */
3873 char *previous_prepend = 0;
3875 LOAD_UTF8_CHARCLASS_GCB();
3877 /* Match (prepend)* */
3878 while (locinput < PL_regeol
3879 && swash_fetch(PL_utf8_X_prepend,
3880 (U8*)locinput, utf8_target))
3882 previous_prepend = locinput;
3883 locinput += UTF8SKIP(locinput);
3886 /* As noted above, if we matched a prepend character, but
3887 * the next thing won't match, back off the last prepend we
3888 * matched, as it is guaranteed to match the begin */
3889 if (previous_prepend
3890 && (locinput >= PL_regeol
3891 || ! swash_fetch(PL_utf8_X_begin,
3892 (U8*)locinput, utf8_target)))
3894 locinput = previous_prepend;
3897 /* Note that here we know PL_regeol > locinput, as we
3898 * tested that upon input to this switch case, and if we
3899 * moved locinput forward, we tested the result just above
3900 * and it either passed, or we backed off so that it will
3902 if (! swash_fetch(PL_utf8_X_begin, (U8*)locinput, utf8_target)) {
3904 /* Here did not match the required 'Begin' in the
3905 * second term. So just match the very first
3906 * character, the '.' of the final term of the regex */
3907 locinput = starting + UTF8SKIP(starting);
3910 /* Here is the beginning of a character that can have
3911 * an extender. It is either a hangul syllable, or a
3913 if (swash_fetch(PL_utf8_X_non_hangul,
3914 (U8*)locinput, utf8_target))
3917 /* Here not a Hangul syllable, must be a
3918 * ('! * Control') */
3919 locinput += UTF8SKIP(locinput);
3922 /* Here is a Hangul syllable. It can be composed
3923 * of several individual characters. One
3924 * possibility is T+ */
3925 if (swash_fetch(PL_utf8_X_T,
3926 (U8*)locinput, utf8_target))
3928 while (locinput < PL_regeol
3929 && swash_fetch(PL_utf8_X_T,
3930 (U8*)locinput, utf8_target))
3932 locinput += UTF8SKIP(locinput);
3936 /* Here, not T+, but is a Hangul. That means
3937 * it is one of the others: L, LV, LVT or V,
3939 * L* (L | LVT T* | V V* T* | LV V* T*) */
3942 while (locinput < PL_regeol
3943 && swash_fetch(PL_utf8_X_L,
3944 (U8*)locinput, utf8_target))
3946 locinput += UTF8SKIP(locinput);
3949 /* Here, have exhausted L*. If the next
3950 * character is not an LV, LVT nor V, it means
3951 * we had to have at least one L, so matches L+
3952 * in the original equation, we have a complete
3953 * hangul syllable. Are done. */
3955 if (locinput < PL_regeol
3956 && swash_fetch(PL_utf8_X_LV_LVT_V,
3957 (U8*)locinput, utf8_target))
3960 /* Otherwise keep going. Must be LV, LVT
3961 * or V. See if LVT */
3962 if (swash_fetch(PL_utf8_X_LVT,
3963 (U8*)locinput, utf8_target))
3965 locinput += UTF8SKIP(locinput);
3968 /* Must be V or LV. Take it, then
3970 locinput += UTF8SKIP(locinput);
3971 while (locinput < PL_regeol
3972 && swash_fetch(PL_utf8_X_V,
3973 (U8*)locinput, utf8_target))
3975 locinput += UTF8SKIP(locinput);
3979 /* And any of LV, LVT, or V can be followed
3981 while (locinput < PL_regeol
3982 && swash_fetch(PL_utf8_X_T,
3986 locinput += UTF8SKIP(locinput);
3992 /* Match any extender */
3993 while (locinput < PL_regeol
3994 && swash_fetch(PL_utf8_X_extend,
3995 (U8*)locinput, utf8_target))
3997 locinput += UTF8SKIP(locinput);
4001 if (locinput > PL_regeol) sayNO;
4003 nextchr = UCHARAT(locinput);
4007 { /* The capture buffer cases. The ones beginning with N for the
4008 named buffers just convert to the equivalent numbered and
4009 pretend they were called as the corresponding numbered buffer
4011 /* don't initialize these in the declaration, it makes C++
4016 const U8 *fold_array;
4019 PL_reg_flags |= RF_tainted;
4020 folder = foldEQ_locale;
4021 fold_array = PL_fold_locale;
4023 utf8_fold_flags = FOLDEQ_UTF8_LOCALE;
4027 folder = foldEQ_latin1;
4028 fold_array = PL_fold_latin1;
4030 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
4034 folder = foldEQ_latin1;
4035 fold_array = PL_fold_latin1;
4037 utf8_fold_flags = 0;
4042 fold_array = PL_fold;
4044 utf8_fold_flags = 0;
4051 utf8_fold_flags = 0;
4054 /* For the named back references, find the corresponding buffer
4056 n = reg_check_named_buff_matched(rex,scan);
4061 goto do_nref_ref_common;
4064 PL_reg_flags |= RF_tainted;
4065 folder = foldEQ_locale;
4066 fold_array = PL_fold_locale;
4067 utf8_fold_flags = FOLDEQ_UTF8_LOCALE;
4071 folder = foldEQ_latin1;
4072 fold_array = PL_fold_latin1;
4073 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
4077 folder = foldEQ_latin1;
4078 fold_array = PL_fold_latin1;
4079 utf8_fold_flags = 0;
4084 fold_array = PL_fold;
4085 utf8_fold_flags = 0;
4091 utf8_fold_flags = 0;
4095 n = ARG(scan); /* which paren pair */
4098 ln = PL_regoffs[n].start;
4099 PL_reg_leftiter = PL_reg_maxiter; /* Void cache */
4100 if (*PL_reglastparen < n || ln == -1)
4101 sayNO; /* Do not match unless seen CLOSEn. */
4102 if (ln == PL_regoffs[n].end)
4106 if (type != REF /* REF can do byte comparison */
4107 && (utf8_target || type == REFFU))
4108 { /* XXX handle REFFL better */
4109 char * limit = PL_regeol;
4111 /* This call case insensitively compares the entire buffer
4112 * at s, with the current input starting at locinput, but
4113 * not going off the end given by PL_regeol, and returns in
4114 * limit upon success, how much of the current input was
4116 if (! foldEQ_utf8_flags(s, NULL, PL_regoffs[n].end - ln, utf8_target,
4117 locinput, &limit, 0, utf8_target, utf8_fold_flags))
4122 nextchr = UCHARAT(locinput);
4126 /* Not utf8: Inline the first character, for speed. */
4127 if (UCHARAT(s) != nextchr &&
4129 UCHARAT(s) != fold_array[nextchr]))
4131 ln = PL_regoffs[n].end - ln;
4132 if (locinput + ln > PL_regeol)
4134 if (ln > 1 && (type == REF
4135 ? memNE(s, locinput, ln)
4136 : ! folder(s, locinput, ln)))
4139 nextchr = UCHARAT(locinput);
4149 #define ST st->u.eval
4154 regexp_internal *rei;
4155 regnode *startpoint;
4158 case GOSUB: /* /(...(?1))/ /(...(?&foo))/ */
4159 if (cur_eval && cur_eval->locinput==locinput) {
4160 if (cur_eval->u.eval.close_paren == (U32)ARG(scan))
4161 Perl_croak(aTHX_ "Infinite recursion in regex");
4162 if ( ++nochange_depth > max_nochange_depth )
4164 "Pattern subroutine nesting without pos change"
4165 " exceeded limit in regex");
4172 (void)ReREFCNT_inc(rex_sv);
4173 if (OP(scan)==GOSUB) {
4174 startpoint = scan + ARG2L(scan);
4175 ST.close_paren = ARG(scan);
4177 startpoint = rei->program+1;
4180 goto eval_recurse_doit;
4182 case EVAL: /* /(?{A})B/ /(??{A})B/ and /(?(?{A})X|Y)B/ */
4183 if (cur_eval && cur_eval->locinput==locinput) {
4184 if ( ++nochange_depth > max_nochange_depth )
4185 Perl_croak(aTHX_ "EVAL without pos change exceeded limit in regex");
4190 /* execute the code in the {...} */
4192 SV ** const before = SP;
4193 OP_4tree * const oop = PL_op;
4194 COP * const ocurcop = PL_curcop;
4196 char *saved_regeol = PL_regeol;
4197 struct re_save_state saved_state;
4199 /* To not corrupt the existing regex state while executing the
4200 * eval we would normally put it on the save stack, like with
4201 * save_re_context. However, re-evals have a weird scoping so we
4202 * can't just add ENTER/LEAVE here. With that, things like
4204 * (?{$a=2})(a(?{local$a=$a+1}))*aak*c(?{$b=$a})
4206 * would break, as they expect the localisation to be unwound
4207 * only when the re-engine backtracks through the bit that
4210 * What we do instead is just saving the state in a local c
4213 Copy(&PL_reg_state, &saved_state, 1, struct re_save_state);
4216 PL_op = (OP_4tree*)rexi->data->data[n];
4217 DEBUG_STATE_r( PerlIO_printf(Perl_debug_log,
4218 " re_eval 0x%"UVxf"\n", PTR2UV(PL_op)) );
4219 /* wrap the call in two SAVECOMPPADs. This ensures that
4220 * when the save stack is eventually unwound, all the
4221 * accumulated SAVEt_CLEARSV's will be processed with
4222 * interspersed SAVEt_COMPPAD's to ensure that lexicals
4223 * are cleared in the right pad */
4225 PAD_SAVE_LOCAL(old_comppad, (PAD*)rexi->data->data[n + 2]);
4226 PL_regoffs[0].end = PL_reg_magic->mg_len = locinput - PL_bostr;
4229 SV *sv_mrk = get_sv("REGMARK", 1);
4230 sv_setsv(sv_mrk, sv_yes_mark);
4233 CALLRUNOPS(aTHX); /* Scalar context. */
4236 ret = &PL_sv_undef; /* protect against empty (?{}) blocks. */
4242 Copy(&saved_state, &PL_reg_state, 1, struct re_save_state);
4246 PAD_RESTORE_LOCAL(old_comppad);
4247 PL_curcop = ocurcop;
4248 PL_regeol = saved_regeol;
4251 sv_setsv(save_scalar(PL_replgv), ret);
4255 if (logical == 2) { /* Postponed subexpression: /(??{...})/ */
4258 /* extract RE object from returned value; compiling if
4264 SV *const sv = SvRV(ret);
4266 if (SvTYPE(sv) == SVt_REGEXP) {
4268 } else if (SvSMAGICAL(sv)) {
4269 mg = mg_find(sv, PERL_MAGIC_qr);
4272 } else if (SvTYPE(ret) == SVt_REGEXP) {
4274 } else if (SvSMAGICAL(ret)) {
4275 if (SvGMAGICAL(ret)) {
4276 /* I don't believe that there is ever qr magic
4278 assert(!mg_find(ret, PERL_MAGIC_qr));
4279 sv_unmagic(ret, PERL_MAGIC_qr);
4282 mg = mg_find(ret, PERL_MAGIC_qr);
4283 /* testing suggests mg only ends up non-NULL for
4284 scalars who were upgraded and compiled in the
4285 else block below. In turn, this is only
4286 triggered in the "postponed utf8 string" tests
4292 rx = (REGEXP *) mg->mg_obj; /*XXX:dmq*/
4296 rx = reg_temp_copy(NULL, rx);
4300 const I32 osize = PL_regsize;
4303 assert (SvUTF8(ret));
4304 } else if (SvUTF8(ret)) {
4305 /* Not doing UTF-8, despite what the SV says. Is
4306 this only if we're trapped in use 'bytes'? */
4307 /* Make a copy of the octet sequence, but without
4308 the flag on, as the compiler now honours the
4309 SvUTF8 flag on ret. */
4311 const char *const p = SvPV(ret, len);
4312 ret = newSVpvn_flags(p, len, SVs_TEMP);
4314 rx = CALLREGCOMP(ret, pm_flags);
4316 & (SVs_TEMP | SVs_PADTMP | SVf_READONLY
4318 /* This isn't a first class regexp. Instead, it's
4319 caching a regexp onto an existing, Perl visible
4321 sv_magic(ret, MUTABLE_SV(rx), PERL_MAGIC_qr, 0, 0);
4326 re = (struct regexp *)SvANY(rx);
4328 RXp_MATCH_COPIED_off(re);
4329 re->subbeg = rex->subbeg;
4330 re->sublen = rex->sublen;
4333 debug_start_match(re_sv, utf8_target, locinput, PL_regeol,
4334 "Matching embedded");
4336 startpoint = rei->program + 1;
4337 ST.close_paren = 0; /* only used for GOSUB */
4338 /* borrowed from regtry */
4339 if (PL_reg_start_tmpl <= re->nparens) {
4340 PL_reg_start_tmpl = re->nparens*3/2 + 3;
4341 if(PL_reg_start_tmp)
4342 Renew(PL_reg_start_tmp, PL_reg_start_tmpl, char*);
4344 Newx(PL_reg_start_tmp, PL_reg_start_tmpl, char*);
4347 eval_recurse_doit: /* Share code with GOSUB below this line */
4348 /* run the pattern returned from (??{...}) */
4349 ST.cp = regcppush(0); /* Save *all* the positions. */
4350 REGCP_SET(ST.lastcp);
4352 PL_regoffs = re->offs; /* essentially NOOP on GOSUB */
4354 /* see regtry, specifically PL_reglast(?:close)?paren is a pointer! (i dont know why) :dmq */
4355 PL_reglastparen = &re->lastparen;
4356 PL_reglastcloseparen = &re->lastcloseparen;
4358 re->lastcloseparen = 0;
4360 PL_reginput = locinput;
4363 /* XXXX This is too dramatic a measure... */
4366 ST.toggle_reg_flags = PL_reg_flags;
4368 PL_reg_flags |= RF_utf8;
4370 PL_reg_flags &= ~RF_utf8;
4371 ST.toggle_reg_flags ^= PL_reg_flags; /* diff of old and new */
4373 ST.prev_rex = rex_sv;
4374 ST.prev_curlyx = cur_curlyx;
4375 SETREX(rex_sv,re_sv);
4380 ST.prev_eval = cur_eval;
4382 /* now continue from first node in postoned RE */
4383 PUSH_YES_STATE_GOTO(EVAL_AB, startpoint);
4386 /* logical is 1, /(?(?{...})X|Y)/ */
4387 sw = cBOOL(SvTRUE(ret));
4392 case EVAL_AB: /* cleanup after a successful (??{A})B */
4393 /* note: this is called twice; first after popping B, then A */
4394 PL_reg_flags ^= ST.toggle_reg_flags;
4395 ReREFCNT_dec(rex_sv);
4396 SETREX(rex_sv,ST.prev_rex);
4397 rex = (struct regexp *)SvANY(rex_sv);
4398 rexi = RXi_GET(rex);
4400 cur_eval = ST.prev_eval;
4401 cur_curlyx = ST.prev_curlyx;
4403 /* rex was changed so update the pointer in PL_reglastparen and PL_reglastcloseparen */
4404 PL_reglastparen = &rex->lastparen;
4405 PL_reglastcloseparen = &rex->lastcloseparen;
4406 /* also update PL_regoffs */
4407 PL_regoffs = rex->offs;
4409 /* XXXX This is too dramatic a measure... */
4411 if ( nochange_depth )
4416 case EVAL_AB_fail: /* unsuccessfully ran A or B in (??{A})B */
4417 /* note: this is called twice; first after popping B, then A */
4418 PL_reg_flags ^= ST.toggle_reg_flags;
4419 ReREFCNT_dec(rex_sv);
4420 SETREX(rex_sv,ST.prev_rex);
4421 rex = (struct regexp *)SvANY(rex_sv);
4422 rexi = RXi_GET(rex);
4423 /* rex was changed so update the pointer in PL_reglastparen and PL_reglastcloseparen */
4424 PL_reglastparen = &rex->lastparen;
4425 PL_reglastcloseparen = &rex->lastcloseparen;
4427 PL_reginput = locinput;
4428 REGCP_UNWIND(ST.lastcp);
4430 cur_eval = ST.prev_eval;
4431 cur_curlyx = ST.prev_curlyx;
4432 /* XXXX This is too dramatic a measure... */
4434 if ( nochange_depth )
4440 n = ARG(scan); /* which paren pair */
4441 PL_reg_start_tmp[n] = locinput;
4447 n = ARG(scan); /* which paren pair */
4448 PL_regoffs[n].start = PL_reg_start_tmp[n] - PL_bostr;
4449 PL_regoffs[n].end = locinput - PL_bostr;
4450 /*if (n > PL_regsize)
4452 if (n > *PL_reglastparen)
4453 *PL_reglastparen = n;
4454 *PL_reglastcloseparen = n;
4455 if (cur_eval && cur_eval->u.eval.close_paren == n) {
4463 cursor && OP(cursor)!=END;
4464 cursor=regnext(cursor))
4466 if ( OP(cursor)==CLOSE ){
4468 if ( n <= lastopen ) {
4470 = PL_reg_start_tmp[n] - PL_bostr;
4471 PL_regoffs[n].end = locinput - PL_bostr;
4472 /*if (n > PL_regsize)
4474 if (n > *PL_reglastparen)
4475 *PL_reglastparen = n;
4476 *PL_reglastcloseparen = n;
4477 if ( n == ARG(scan) || (cur_eval &&
4478 cur_eval->u.eval.close_paren == n))
4487 n = ARG(scan); /* which paren pair */
4488 sw = cBOOL(*PL_reglastparen >= n && PL_regoffs[n].end != -1);
4491 /* reg_check_named_buff_matched returns 0 for no match */
4492 sw = cBOOL(0 < reg_check_named_buff_matched(rex,scan));
4496 sw = (cur_eval && (!n || cur_eval->u.eval.close_paren == n));
4502 PL_reg_leftiter = PL_reg_maxiter; /* Void cache */
4504 next = NEXTOPER(NEXTOPER(scan));
4506 next = scan + ARG(scan);
4507 if (OP(next) == IFTHEN) /* Fake one. */
4508 next = NEXTOPER(NEXTOPER(next));
4512 logical = scan->flags;
4515 /*******************************************************************
4517 The CURLYX/WHILEM pair of ops handle the most generic case of the /A*B/
4518 pattern, where A and B are subpatterns. (For simple A, CURLYM or
4519 STAR/PLUS/CURLY/CURLYN are used instead.)
4521 A*B is compiled as <CURLYX><A><WHILEM><B>
4523 On entry to the subpattern, CURLYX is called. This pushes a CURLYX
4524 state, which contains the current count, initialised to -1. It also sets
4525 cur_curlyx to point to this state, with any previous value saved in the
4528 CURLYX then jumps straight to the WHILEM op, rather than executing A,
4529 since the pattern may possibly match zero times (i.e. it's a while {} loop
4530 rather than a do {} while loop).
4532 Each entry to WHILEM represents a successful match of A. The count in the
4533 CURLYX block is incremented, another WHILEM state is pushed, and execution
4534 passes to A or B depending on greediness and the current count.
4536 For example, if matching against the string a1a2a3b (where the aN are
4537 substrings that match /A/), then the match progresses as follows: (the
4538 pushed states are interspersed with the bits of strings matched so far):
4541 <CURLYX cnt=0><WHILEM>
4542 <CURLYX cnt=1><WHILEM> a1 <WHILEM>
4543 <CURLYX cnt=2><WHILEM> a1 <WHILEM> a2 <WHILEM>
4544 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM>
4545 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM> b
4547 (Contrast this with something like CURLYM, which maintains only a single
4551 a1 <CURLYM cnt=1> a2
4552 a1 a2 <CURLYM cnt=2> a3
4553 a1 a2 a3 <CURLYM cnt=3> b
4556 Each WHILEM state block marks a point to backtrack to upon partial failure
4557 of A or B, and also contains some minor state data related to that
4558 iteration. The CURLYX block, pointed to by cur_curlyx, contains the
4559 overall state, such as the count, and pointers to the A and B ops.
4561 This is complicated slightly by nested CURLYX/WHILEM's. Since cur_curlyx
4562 must always point to the *current* CURLYX block, the rules are:
4564 When executing CURLYX, save the old cur_curlyx in the CURLYX state block,
4565 and set cur_curlyx to point the new block.
4567 When popping the CURLYX block after a successful or unsuccessful match,
4568 restore the previous cur_curlyx.
4570 When WHILEM is about to execute B, save the current cur_curlyx, and set it
4571 to the outer one saved in the CURLYX block.
4573 When popping the WHILEM block after a successful or unsuccessful B match,
4574 restore the previous cur_curlyx.
4576 Here's an example for the pattern (AI* BI)*BO
4577 I and O refer to inner and outer, C and W refer to CURLYX and WHILEM:
4580 curlyx backtrack stack
4581 ------ ---------------
4583 CO <CO prev=NULL> <WO>
4584 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
4585 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
4586 NULL <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi <WO prev=CO> bo
4588 At this point the pattern succeeds, and we work back down the stack to
4589 clean up, restoring as we go:
4591 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
4592 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
4593 CO <CO prev=NULL> <WO>
4596 *******************************************************************/
4598 #define ST st->u.curlyx
4600 case CURLYX: /* start of /A*B/ (for complex A) */
4602 /* No need to save/restore up to this paren */
4603 I32 parenfloor = scan->flags;
4605 assert(next); /* keep Coverity happy */
4606 if (OP(PREVOPER(next)) == NOTHING) /* LONGJMP */
4609 /* XXXX Probably it is better to teach regpush to support
4610 parenfloor > PL_regsize... */
4611 if (parenfloor > (I32)*PL_reglastparen)
4612 parenfloor = *PL_reglastparen; /* Pessimization... */
4614 ST.prev_curlyx= cur_curlyx;
4616 ST.cp = PL_savestack_ix;
4618 /* these fields contain the state of the current curly.
4619 * they are accessed by subsequent WHILEMs */
4620 ST.parenfloor = parenfloor;
4625 ST.count = -1; /* this will be updated by WHILEM */
4626 ST.lastloc = NULL; /* this will be updated by WHILEM */
4628 PL_reginput = locinput;
4629 PUSH_YES_STATE_GOTO(CURLYX_end, PREVOPER(next));
4633 case CURLYX_end: /* just finished matching all of A*B */
4634 cur_curlyx = ST.prev_curlyx;
4638 case CURLYX_end_fail: /* just failed to match all of A*B */
4640 cur_curlyx = ST.prev_curlyx;
4646 #define ST st->u.whilem
4648 case WHILEM: /* just matched an A in /A*B/ (for complex A) */
4650 /* see the discussion above about CURLYX/WHILEM */
4652 int min = ARG1(cur_curlyx->u.curlyx.me);
4653 int max = ARG2(cur_curlyx->u.curlyx.me);
4654 regnode *A = NEXTOPER(cur_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS;
4656 assert(cur_curlyx); /* keep Coverity happy */
4657 n = ++cur_curlyx->u.curlyx.count; /* how many A's matched */
4658 ST.save_lastloc = cur_curlyx->u.curlyx.lastloc;
4659 ST.cache_offset = 0;
4662 PL_reginput = locinput;
4664 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
4665 "%*s whilem: matched %ld out of %d..%d\n",
4666 REPORT_CODE_OFF+depth*2, "", (long)n, min, max)
4669 /* First just match a string of min A's. */
4672 ST.cp = regcppush(cur_curlyx->u.curlyx.parenfloor);
4673 cur_curlyx->u.curlyx.lastloc = locinput;
4674 REGCP_SET(ST.lastcp);
4676 PUSH_STATE_GOTO(WHILEM_A_pre, A);
4680 /* If degenerate A matches "", assume A done. */
4682 if (locinput == cur_curlyx->u.curlyx.lastloc) {
4683 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
4684 "%*s whilem: empty match detected, trying continuation...\n",
4685 REPORT_CODE_OFF+depth*2, "")
4687 goto do_whilem_B_max;
4690 /* super-linear cache processing */
4694 if (!PL_reg_maxiter) {
4695 /* start the countdown: Postpone detection until we
4696 * know the match is not *that* much linear. */
4697 PL_reg_maxiter = (PL_regeol - PL_bostr + 1) * (scan->flags>>4);
4698 /* possible overflow for long strings and many CURLYX's */
4699 if (PL_reg_maxiter < 0)
4700 PL_reg_maxiter = I32_MAX;
4701 PL_reg_leftiter = PL_reg_maxiter;
4704 if (PL_reg_leftiter-- == 0) {
4705 /* initialise cache */
4706 const I32 size = (PL_reg_maxiter + 7)/8;
4707 if (PL_reg_poscache) {
4708 if ((I32)PL_reg_poscache_size < size) {
4709 Renew(PL_reg_poscache, size, char);
4710 PL_reg_poscache_size = size;
4712 Zero(PL_reg_poscache, size, char);
4715 PL_reg_poscache_size = size;
4716 Newxz(PL_reg_poscache, size, char);
4718 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
4719 "%swhilem: Detected a super-linear match, switching on caching%s...\n",
4720 PL_colors[4], PL_colors[5])
4724 if (PL_reg_leftiter < 0) {
4725 /* have we already failed at this position? */
4727 offset = (scan->flags & 0xf) - 1
4728 + (locinput - PL_bostr) * (scan->flags>>4);
4729 mask = 1 << (offset % 8);
4731 if (PL_reg_poscache[offset] & mask) {
4732 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
4733 "%*s whilem: (cache) already tried at this position...\n",
4734 REPORT_CODE_OFF+depth*2, "")
4736 sayNO; /* cache records failure */
4738 ST.cache_offset = offset;
4739 ST.cache_mask = mask;
4743 /* Prefer B over A for minimal matching. */
4745 if (cur_curlyx->u.curlyx.minmod) {
4746 ST.save_curlyx = cur_curlyx;
4747 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
4748 ST.cp = regcppush(ST.save_curlyx->u.curlyx.parenfloor);
4749 REGCP_SET(ST.lastcp);
4750 PUSH_YES_STATE_GOTO(WHILEM_B_min, ST.save_curlyx->u.curlyx.B);
4754 /* Prefer A over B for maximal matching. */
4756 if (n < max) { /* More greed allowed? */
4757 ST.cp = regcppush(cur_curlyx->u.curlyx.parenfloor);
4758 cur_curlyx->u.curlyx.lastloc = locinput;
4759 REGCP_SET(ST.lastcp);
4760 PUSH_STATE_GOTO(WHILEM_A_max, A);
4763 goto do_whilem_B_max;
4767 case WHILEM_B_min: /* just matched B in a minimal match */
4768 case WHILEM_B_max: /* just matched B in a maximal match */
4769 cur_curlyx = ST.save_curlyx;
4773 case WHILEM_B_max_fail: /* just failed to match B in a maximal match */
4774 cur_curlyx = ST.save_curlyx;
4775 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
4776 cur_curlyx->u.curlyx.count--;
4780 case WHILEM_A_min_fail: /* just failed to match A in a minimal match */
4782 case WHILEM_A_pre_fail: /* just failed to match even minimal A */
4783 REGCP_UNWIND(ST.lastcp);
4785 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
4786 cur_curlyx->u.curlyx.count--;
4790 case WHILEM_A_max_fail: /* just failed to match A in a maximal match */
4791 REGCP_UNWIND(ST.lastcp);
4792 regcppop(rex); /* Restore some previous $<digit>s? */
4793 PL_reginput = locinput;
4794 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
4795 "%*s whilem: failed, trying continuation...\n",
4796 REPORT_CODE_OFF+depth*2, "")
4799 if (cur_curlyx->u.curlyx.count >= REG_INFTY
4800 && ckWARN(WARN_REGEXP)
4801 && !(PL_reg_flags & RF_warned))
4803 PL_reg_flags |= RF_warned;
4804 Perl_warner(aTHX_ packWARN(WARN_REGEXP), "%s limit (%d) exceeded",
4805 "Complex regular subexpression recursion",
4810 ST.save_curlyx = cur_curlyx;
4811 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
4812 PUSH_YES_STATE_GOTO(WHILEM_B_max, ST.save_curlyx->u.curlyx.B);
4815 case WHILEM_B_min_fail: /* just failed to match B in a minimal match */
4816 cur_curlyx = ST.save_curlyx;
4817 REGCP_UNWIND(ST.lastcp);
4820 if (cur_curlyx->u.curlyx.count >= /*max*/ARG2(cur_curlyx->u.curlyx.me)) {
4821 /* Maximum greed exceeded */
4822 if (cur_curlyx->u.curlyx.count >= REG_INFTY
4823 && ckWARN(WARN_REGEXP)
4824 && !(PL_reg_flags & RF_warned))
4826 PL_reg_flags |= RF_warned;
4827 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
4828 "%s limit (%d) exceeded",
4829 "Complex regular subexpression recursion",
4832 cur_curlyx->u.curlyx.count--;
4836 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
4837 "%*s trying longer...\n", REPORT_CODE_OFF+depth*2, "")
4839 /* Try grabbing another A and see if it helps. */
4840 PL_reginput = locinput;
4841 cur_curlyx->u.curlyx.lastloc = locinput;
4842 ST.cp = regcppush(cur_curlyx->u.curlyx.parenfloor);
4843 REGCP_SET(ST.lastcp);
4844 PUSH_STATE_GOTO(WHILEM_A_min,
4845 /*A*/ NEXTOPER(ST.save_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS);
4849 #define ST st->u.branch
4851 case BRANCHJ: /* /(...|A|...)/ with long next pointer */
4852 next = scan + ARG(scan);
4855 scan = NEXTOPER(scan);
4858 case BRANCH: /* /(...|A|...)/ */
4859 scan = NEXTOPER(scan); /* scan now points to inner node */
4860 ST.lastparen = *PL_reglastparen;
4861 ST.next_branch = next;
4863 PL_reginput = locinput;
4865 /* Now go into the branch */
4867 PUSH_YES_STATE_GOTO(BRANCH_next, scan);
4869 PUSH_STATE_GOTO(BRANCH_next, scan);
4873 PL_reginput = locinput;
4874 sv_yes_mark = st->u.mark.mark_name = scan->flags ? NULL :
4875 MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
4876 PUSH_STATE_GOTO(CUTGROUP_next,next);
4878 case CUTGROUP_next_fail:
4881 if (st->u.mark.mark_name)
4882 sv_commit = st->u.mark.mark_name;
4888 case BRANCH_next_fail: /* that branch failed; try the next, if any */
4893 REGCP_UNWIND(ST.cp);
4894 for (n = *PL_reglastparen; n > ST.lastparen; n--)
4895 PL_regoffs[n].end = -1;
4896 *PL_reglastparen = n;
4897 /*dmq: *PL_reglastcloseparen = n; */
4898 scan = ST.next_branch;
4899 /* no more branches? */
4900 if (!scan || (OP(scan) != BRANCH && OP(scan) != BRANCHJ)) {
4902 PerlIO_printf( Perl_debug_log,
4903 "%*s %sBRANCH failed...%s\n",
4904 REPORT_CODE_OFF+depth*2, "",
4910 continue; /* execute next BRANCH[J] op */
4918 #define ST st->u.curlym
4920 case CURLYM: /* /A{m,n}B/ where A is fixed-length */
4922 /* This is an optimisation of CURLYX that enables us to push
4923 * only a single backtracking state, no matter how many matches
4924 * there are in {m,n}. It relies on the pattern being constant
4925 * length, with no parens to influence future backrefs
4929 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
4931 /* if paren positive, emulate an OPEN/CLOSE around A */
4933 U32 paren = ST.me->flags;
4934 if (paren > PL_regsize)
4936 if (paren > *PL_reglastparen)
4937 *PL_reglastparen = paren;
4938 scan += NEXT_OFF(scan); /* Skip former OPEN. */
4946 ST.c1 = CHRTEST_UNINIT;
4949 if (!(ST.minmod ? ARG1(ST.me) : ARG2(ST.me))) /* min/max */
4952 curlym_do_A: /* execute the A in /A{m,n}B/ */
4953 PL_reginput = locinput;
4954 PUSH_YES_STATE_GOTO(CURLYM_A, ST.A); /* match A */
4957 case CURLYM_A: /* we've just matched an A */
4958 locinput = st->locinput;
4959 nextchr = UCHARAT(locinput);
4962 /* after first match, determine A's length: u.curlym.alen */
4963 if (ST.count == 1) {
4964 if (PL_reg_match_utf8) {
4966 while (s < PL_reginput) {
4972 ST.alen = PL_reginput - locinput;
4975 ST.count = ST.minmod ? ARG1(ST.me) : ARG2(ST.me);
4978 PerlIO_printf(Perl_debug_log,
4979 "%*s CURLYM now matched %"IVdf" times, len=%"IVdf"...\n",
4980 (int)(REPORT_CODE_OFF+(depth*2)), "",
4981 (IV) ST.count, (IV)ST.alen)
4984 locinput = PL_reginput;
4986 if (cur_eval && cur_eval->u.eval.close_paren &&
4987 cur_eval->u.eval.close_paren == (U32)ST.me->flags)
4991 I32 max = (ST.minmod ? ARG1(ST.me) : ARG2(ST.me));
4992 if ( max == REG_INFTY || ST.count < max )
4993 goto curlym_do_A; /* try to match another A */
4995 goto curlym_do_B; /* try to match B */
4997 case CURLYM_A_fail: /* just failed to match an A */
4998 REGCP_UNWIND(ST.cp);
5000 if (ST.minmod || ST.count < ARG1(ST.me) /* min*/
5001 || (cur_eval && cur_eval->u.eval.close_paren &&
5002 cur_eval->u.eval.close_paren == (U32)ST.me->flags))
5005 curlym_do_B: /* execute the B in /A{m,n}B/ */
5006 PL_reginput = locinput;
5007 if (ST.c1 == CHRTEST_UNINIT) {
5008 /* calculate c1 and c2 for possible match of 1st char
5009 * following curly */
5010 ST.c1 = ST.c2 = CHRTEST_VOID;
5011 if (HAS_TEXT(ST.B) || JUMPABLE(ST.B)) {
5012 regnode *text_node = ST.B;
5013 if (! HAS_TEXT(text_node))
5014 FIND_NEXT_IMPT(text_node);
5017 (HAS_TEXT(text_node) && PL_regkind[OP(text_node)] == EXACT)
5019 But the former is redundant in light of the latter.
5021 if this changes back then the macro for
5022 IS_TEXT and friends need to change.
5024 if (PL_regkind[OP(text_node)] == EXACT)
5027 ST.c1 = (U8)*STRING(text_node);
5028 switch (OP(text_node)) {
5029 case EXACTF: ST.c2 = PL_fold[ST.c1]; break;
5031 case EXACTFU: ST.c2 = PL_fold_latin1[ST.c1]; break;
5032 case EXACTFL: ST.c2 = PL_fold_locale[ST.c1]; break;
5033 default: ST.c2 = ST.c1;
5040 PerlIO_printf(Perl_debug_log,
5041 "%*s CURLYM trying tail with matches=%"IVdf"...\n",
5042 (int)(REPORT_CODE_OFF+(depth*2)),
5045 if (ST.c1 != CHRTEST_VOID
5046 && UCHARAT(PL_reginput) != ST.c1
5047 && UCHARAT(PL_reginput) != ST.c2)
5049 /* simulate B failing */
5051 PerlIO_printf(Perl_debug_log,
5052 "%*s CURLYM Fast bail c1=%"IVdf" c2=%"IVdf"\n",
5053 (int)(REPORT_CODE_OFF+(depth*2)),"",
5056 state_num = CURLYM_B_fail;
5057 goto reenter_switch;
5061 /* mark current A as captured */
5062 I32 paren = ST.me->flags;
5064 PL_regoffs[paren].start
5065 = HOPc(PL_reginput, -ST.alen) - PL_bostr;
5066 PL_regoffs[paren].end = PL_reginput - PL_bostr;
5067 /*dmq: *PL_reglastcloseparen = paren; */
5070 PL_regoffs[paren].end = -1;
5071 if (cur_eval && cur_eval->u.eval.close_paren &&
5072 cur_eval->u.eval.close_paren == (U32)ST.me->flags)
5081 PUSH_STATE_GOTO(CURLYM_B, ST.B); /* match B */
5084 case CURLYM_B_fail: /* just failed to match a B */
5085 REGCP_UNWIND(ST.cp);
5087 I32 max = ARG2(ST.me);
5088 if (max != REG_INFTY && ST.count == max)
5090 goto curlym_do_A; /* try to match a further A */
5092 /* backtrack one A */
5093 if (ST.count == ARG1(ST.me) /* min */)
5096 locinput = HOPc(locinput, -ST.alen);
5097 goto curlym_do_B; /* try to match B */
5100 #define ST st->u.curly
5102 #define CURLY_SETPAREN(paren, success) \
5105 PL_regoffs[paren].start = HOPc(locinput, -1) - PL_bostr; \
5106 PL_regoffs[paren].end = locinput - PL_bostr; \
5107 *PL_reglastcloseparen = paren; \
5110 PL_regoffs[paren].end = -1; \
5113 case STAR: /* /A*B/ where A is width 1 */
5117 scan = NEXTOPER(scan);
5119 case PLUS: /* /A+B/ where A is width 1 */
5123 scan = NEXTOPER(scan);
5125 case CURLYN: /* /(A){m,n}B/ where A is width 1 */
5126 ST.paren = scan->flags; /* Which paren to set */
5127 if (ST.paren > PL_regsize)
5128 PL_regsize = ST.paren;
5129 if (ST.paren > *PL_reglastparen)
5130 *PL_reglastparen = ST.paren;
5131 ST.min = ARG1(scan); /* min to match */
5132 ST.max = ARG2(scan); /* max to match */
5133 if (cur_eval && cur_eval->u.eval.close_paren &&
5134 cur_eval->u.eval.close_paren == (U32)ST.paren) {
5138 scan = regnext(NEXTOPER(scan) + NODE_STEP_REGNODE);
5140 case CURLY: /* /A{m,n}B/ where A is width 1 */
5142 ST.min = ARG1(scan); /* min to match */
5143 ST.max = ARG2(scan); /* max to match */
5144 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
5147 * Lookahead to avoid useless match attempts
5148 * when we know what character comes next.
5150 * Used to only do .*x and .*?x, but now it allows
5151 * for )'s, ('s and (?{ ... })'s to be in the way
5152 * of the quantifier and the EXACT-like node. -- japhy
5155 if (ST.min > ST.max) /* XXX make this a compile-time check? */
5157 if (HAS_TEXT(next) || JUMPABLE(next)) {
5159 regnode *text_node = next;
5161 if (! HAS_TEXT(text_node))
5162 FIND_NEXT_IMPT(text_node);
5164 if (! HAS_TEXT(text_node))
5165 ST.c1 = ST.c2 = CHRTEST_VOID;
5167 if ( PL_regkind[OP(text_node)] != EXACT ) {
5168 ST.c1 = ST.c2 = CHRTEST_VOID;
5169 goto assume_ok_easy;
5172 s = (U8*)STRING(text_node);
5174 /* Currently we only get here when
5176 PL_rekind[OP(text_node)] == EXACT
5178 if this changes back then the macro for IS_TEXT and
5179 friends need to change. */
5182 switch (OP(text_node)) {
5183 case EXACTF: ST.c2 = PL_fold[ST.c1]; break;
5185 case EXACTFU: ST.c2 = PL_fold_latin1[ST.c1]; break;
5186 case EXACTFL: ST.c2 = PL_fold_locale[ST.c1]; break;
5187 default: ST.c2 = ST.c1; break;
5190 else { /* UTF_PATTERN */
5191 if (IS_TEXTFU(text_node) || IS_TEXTF(text_node)) {
5192 STRLEN ulen1, ulen2;
5193 U8 tmpbuf1[UTF8_MAXBYTES_CASE+1];
5194 U8 tmpbuf2[UTF8_MAXBYTES_CASE+1];
5196 to_utf8_lower((U8*)s, tmpbuf1, &ulen1);
5197 to_utf8_upper((U8*)s, tmpbuf2, &ulen2);
5199 ST.c1 = utf8n_to_uvchr(tmpbuf1, UTF8_MAXLEN, 0,
5201 0 : UTF8_ALLOW_ANY);
5202 ST.c2 = utf8n_to_uvchr(tmpbuf2, UTF8_MAXLEN, 0,
5204 0 : UTF8_ALLOW_ANY);
5206 ST.c1 = utf8n_to_uvuni(tmpbuf1, UTF8_MAXBYTES, 0,
5208 ST.c2 = utf8n_to_uvuni(tmpbuf2, UTF8_MAXBYTES, 0,
5213 ST.c2 = ST.c1 = utf8n_to_uvchr(s, UTF8_MAXBYTES, 0,
5220 ST.c1 = ST.c2 = CHRTEST_VOID;
5225 PL_reginput = locinput;
5228 if (ST.min && regrepeat(rex, ST.A, ST.min, depth) < ST.min)
5231 locinput = PL_reginput;
5233 if (ST.c1 == CHRTEST_VOID)
5234 goto curly_try_B_min;
5236 ST.oldloc = locinput;
5238 /* set ST.maxpos to the furthest point along the
5239 * string that could possibly match */
5240 if (ST.max == REG_INFTY) {
5241 ST.maxpos = PL_regeol - 1;
5243 while (UTF8_IS_CONTINUATION(*(U8*)ST.maxpos))
5246 else if (utf8_target) {
5247 int m = ST.max - ST.min;
5248 for (ST.maxpos = locinput;
5249 m >0 && ST.maxpos + UTF8SKIP(ST.maxpos) <= PL_regeol; m--)
5250 ST.maxpos += UTF8SKIP(ST.maxpos);
5253 ST.maxpos = locinput + ST.max - ST.min;
5254 if (ST.maxpos >= PL_regeol)
5255 ST.maxpos = PL_regeol - 1;
5257 goto curly_try_B_min_known;
5261 ST.count = regrepeat(rex, ST.A, ST.max, depth);
5262 locinput = PL_reginput;
5263 if (ST.count < ST.min)
5265 if ((ST.count > ST.min)
5266 && (PL_regkind[OP(ST.B)] == EOL) && (OP(ST.B) != MEOL))
5268 /* A{m,n} must come at the end of the string, there's
5269 * no point in backing off ... */
5271 /* ...except that $ and \Z can match before *and* after
5272 newline at the end. Consider "\n\n" =~ /\n+\Z\n/.
5273 We may back off by one in this case. */
5274 if (UCHARAT(PL_reginput - 1) == '\n' && OP(ST.B) != EOS)
5278 goto curly_try_B_max;
5283 case CURLY_B_min_known_fail:
5284 /* failed to find B in a non-greedy match where c1,c2 valid */
5285 if (ST.paren && ST.count)
5286 PL_regoffs[ST.paren].end = -1;
5288 PL_reginput = locinput; /* Could be reset... */
5289 REGCP_UNWIND(ST.cp);
5290 /* Couldn't or didn't -- move forward. */
5291 ST.oldloc = locinput;
5293 locinput += UTF8SKIP(locinput);
5297 curly_try_B_min_known:
5298 /* find the next place where 'B' could work, then call B */
5302 n = (ST.oldloc == locinput) ? 0 : 1;
5303 if (ST.c1 == ST.c2) {
5305 /* set n to utf8_distance(oldloc, locinput) */
5306 while (locinput <= ST.maxpos &&
5307 utf8n_to_uvchr((U8*)locinput,
5308 UTF8_MAXBYTES, &len,
5309 uniflags) != (UV)ST.c1) {
5315 /* set n to utf8_distance(oldloc, locinput) */
5316 while (locinput <= ST.maxpos) {
5318 const UV c = utf8n_to_uvchr((U8*)locinput,
5319 UTF8_MAXBYTES, &len,
5321 if (c == (UV)ST.c1 || c == (UV)ST.c2)
5329 if (ST.c1 == ST.c2) {
5330 while (locinput <= ST.maxpos &&
5331 UCHARAT(locinput) != ST.c1)
5335 while (locinput <= ST.maxpos
5336 && UCHARAT(locinput) != ST.c1
5337 && UCHARAT(locinput) != ST.c2)
5340 n = locinput - ST.oldloc;
5342 if (locinput > ST.maxpos)
5344 /* PL_reginput == oldloc now */
5347 if (regrepeat(rex, ST.A, n, depth) < n)
5350 PL_reginput = locinput;
5351 CURLY_SETPAREN(ST.paren, ST.count);
5352 if (cur_eval && cur_eval->u.eval.close_paren &&
5353 cur_eval->u.eval.close_paren == (U32)ST.paren) {
5356 PUSH_STATE_GOTO(CURLY_B_min_known, ST.B);
5361 case CURLY_B_min_fail:
5362 /* failed to find B in a non-greedy match where c1,c2 invalid */
5363 if (ST.paren && ST.count)
5364 PL_regoffs[ST.paren].end = -1;
5366 REGCP_UNWIND(ST.cp);
5367 /* failed -- move forward one */
5368 PL_reginput = locinput;
5369 if (regrepeat(rex, ST.A, 1, depth)) {
5371 locinput = PL_reginput;
5372 if (ST.count <= ST.max || (ST.max == REG_INFTY &&
5373 ST.count > 0)) /* count overflow ? */
5376 CURLY_SETPAREN(ST.paren, ST.count);
5377 if (cur_eval && cur_eval->u.eval.close_paren &&
5378 cur_eval->u.eval.close_paren == (U32)ST.paren) {
5381 PUSH_STATE_GOTO(CURLY_B_min, ST.B);
5389 /* a successful greedy match: now try to match B */
5390 if (cur_eval && cur_eval->u.eval.close_paren &&
5391 cur_eval->u.eval.close_paren == (U32)ST.paren) {
5396 if (ST.c1 != CHRTEST_VOID)
5397 c = utf8_target ? utf8n_to_uvchr((U8*)PL_reginput,
5398 UTF8_MAXBYTES, 0, uniflags)
5399 : (UV) UCHARAT(PL_reginput);
5400 /* If it could work, try it. */
5401 if (ST.c1 == CHRTEST_VOID || c == (UV)ST.c1 || c == (UV)ST.c2) {
5402 CURLY_SETPAREN(ST.paren, ST.count);
5403 PUSH_STATE_GOTO(CURLY_B_max, ST.B);
5408 case CURLY_B_max_fail:
5409 /* failed to find B in a greedy match */
5410 if (ST.paren && ST.count)
5411 PL_regoffs[ST.paren].end = -1;
5413 REGCP_UNWIND(ST.cp);
5415 if (--ST.count < ST.min)
5417 PL_reginput = locinput = HOPc(locinput, -1);
5418 goto curly_try_B_max;
5425 /* we've just finished A in /(??{A})B/; now continue with B */
5427 st->u.eval.toggle_reg_flags
5428 = cur_eval->u.eval.toggle_reg_flags;
5429 PL_reg_flags ^= st->u.eval.toggle_reg_flags;
5431 st->u.eval.prev_rex = rex_sv; /* inner */
5432 SETREX(rex_sv,cur_eval->u.eval.prev_rex);
5433 rex = (struct regexp *)SvANY(rex_sv);
5434 rexi = RXi_GET(rex);
5435 cur_curlyx = cur_eval->u.eval.prev_curlyx;
5436 (void)ReREFCNT_inc(rex_sv);
5437 st->u.eval.cp = regcppush(0); /* Save *all* the positions. */
5439 /* rex was changed so update the pointer in PL_reglastparen and PL_reglastcloseparen */
5440 PL_reglastparen = &rex->lastparen;
5441 PL_reglastcloseparen = &rex->lastcloseparen;
5443 REGCP_SET(st->u.eval.lastcp);
5444 PL_reginput = locinput;
5446 /* Restore parens of the outer rex without popping the
5448 tmpix = PL_savestack_ix;
5449 PL_savestack_ix = cur_eval->u.eval.lastcp;
5451 PL_savestack_ix = tmpix;
5453 st->u.eval.prev_eval = cur_eval;
5454 cur_eval = cur_eval->u.eval.prev_eval;
5456 PerlIO_printf(Perl_debug_log, "%*s EVAL trying tail ... %"UVxf"\n",
5457 REPORT_CODE_OFF+depth*2, "",PTR2UV(cur_eval)););
5458 if ( nochange_depth )
5461 PUSH_YES_STATE_GOTO(EVAL_AB,
5462 st->u.eval.prev_eval->u.eval.B); /* match B */
5465 if (locinput < reginfo->till) {
5466 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
5467 "%sMatch possible, but length=%ld is smaller than requested=%ld, failing!%s\n",
5469 (long)(locinput - PL_reg_starttry),
5470 (long)(reginfo->till - PL_reg_starttry),
5473 sayNO_SILENT; /* Cannot match: too short. */
5475 PL_reginput = locinput; /* put where regtry can find it */
5476 sayYES; /* Success! */
5478 case SUCCEED: /* successful SUSPEND/UNLESSM/IFMATCH/CURLYM */
5480 PerlIO_printf(Perl_debug_log,
5481 "%*s %ssubpattern success...%s\n",
5482 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5]));
5483 PL_reginput = locinput; /* put where regtry can find it */
5484 sayYES; /* Success! */
5487 #define ST st->u.ifmatch
5489 case SUSPEND: /* (?>A) */
5491 PL_reginput = locinput;
5494 case UNLESSM: /* -ve lookaround: (?!A), or with flags, (?<!A) */
5496 goto ifmatch_trivial_fail_test;
5498 case IFMATCH: /* +ve lookaround: (?=A), or with flags, (?<=A) */
5500 ifmatch_trivial_fail_test:
5502 char * const s = HOPBACKc(locinput, scan->flags);
5507 sw = 1 - cBOOL(ST.wanted);
5511 next = scan + ARG(scan);
5519 PL_reginput = locinput;
5523 ST.logical = logical;
5524 logical = 0; /* XXX: reset state of logical once it has been saved into ST */
5526 /* execute body of (?...A) */
5527 PUSH_YES_STATE_GOTO(IFMATCH_A, NEXTOPER(NEXTOPER(scan)));
5530 case IFMATCH_A_fail: /* body of (?...A) failed */
5531 ST.wanted = !ST.wanted;
5534 case IFMATCH_A: /* body of (?...A) succeeded */
5536 sw = cBOOL(ST.wanted);
5538 else if (!ST.wanted)
5541 if (OP(ST.me) == SUSPEND)
5542 locinput = PL_reginput;
5544 locinput = PL_reginput = st->locinput;
5545 nextchr = UCHARAT(locinput);
5547 scan = ST.me + ARG(ST.me);
5550 continue; /* execute B */
5555 next = scan + ARG(scan);
5560 reginfo->cutpoint = PL_regeol;
5563 PL_reginput = locinput;
5565 sv_yes_mark = sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
5566 PUSH_STATE_GOTO(COMMIT_next,next);
5568 case COMMIT_next_fail:
5575 #define ST st->u.mark
5577 ST.prev_mark = mark_state;
5578 ST.mark_name = sv_commit = sv_yes_mark
5579 = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
5581 ST.mark_loc = PL_reginput = locinput;
5582 PUSH_YES_STATE_GOTO(MARKPOINT_next,next);
5584 case MARKPOINT_next:
5585 mark_state = ST.prev_mark;
5588 case MARKPOINT_next_fail:
5589 if (popmark && sv_eq(ST.mark_name,popmark))
5591 if (ST.mark_loc > startpoint)
5592 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
5593 popmark = NULL; /* we found our mark */
5594 sv_commit = ST.mark_name;
5597 PerlIO_printf(Perl_debug_log,
5598 "%*s %ssetting cutpoint to mark:%"SVf"...%s\n",
5599 REPORT_CODE_OFF+depth*2, "",
5600 PL_colors[4], SVfARG(sv_commit), PL_colors[5]);
5603 mark_state = ST.prev_mark;
5604 sv_yes_mark = mark_state ?
5605 mark_state->u.mark.mark_name : NULL;
5609 PL_reginput = locinput;
5611 /* (*SKIP) : if we fail we cut here*/
5612 ST.mark_name = NULL;
5613 ST.mark_loc = locinput;
5614 PUSH_STATE_GOTO(SKIP_next,next);
5616 /* (*SKIP:NAME) : if there is a (*MARK:NAME) fail where it was,
5617 otherwise do nothing. Meaning we need to scan
5619 regmatch_state *cur = mark_state;
5620 SV *find = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
5623 if ( sv_eq( cur->u.mark.mark_name,
5626 ST.mark_name = find;
5627 PUSH_STATE_GOTO( SKIP_next, next );
5629 cur = cur->u.mark.prev_mark;
5632 /* Didn't find our (*MARK:NAME) so ignore this (*SKIP:NAME) */
5634 case SKIP_next_fail:
5636 /* (*CUT:NAME) - Set up to search for the name as we
5637 collapse the stack*/
5638 popmark = ST.mark_name;
5640 /* (*CUT) - No name, we cut here.*/
5641 if (ST.mark_loc > startpoint)
5642 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
5643 /* but we set sv_commit to latest mark_name if there
5644 is one so they can test to see how things lead to this
5647 sv_commit=mark_state->u.mark.mark_name;
5655 if ( n == (U32)what_len_TRICKYFOLD(locinput,utf8_target,ln) ) {
5657 } else if ( LATIN_SMALL_LETTER_SHARP_S == n && !utf8_target && !UTF_PATTERN ) {
5660 U8 folded[UTF8_MAXBYTES_CASE+1];
5662 const char * const l = locinput;
5663 char *e = PL_regeol;
5664 to_uni_fold(n, folded, &foldlen);
5666 if (! foldEQ_utf8((const char*) folded, 0, foldlen, 1,
5667 l, &e, 0, utf8_target)) {
5672 nextchr = UCHARAT(locinput);
5675 if ((n=is_LNBREAK(locinput,utf8_target))) {
5677 nextchr = UCHARAT(locinput);
5682 #define CASE_CLASS(nAmE) \
5684 if ((n=is_##nAmE(locinput,utf8_target))) { \
5686 nextchr = UCHARAT(locinput); \
5691 if ((n=is_##nAmE(locinput,utf8_target))) { \
5694 locinput += UTF8SKIP(locinput); \
5695 nextchr = UCHARAT(locinput); \
5700 CASE_CLASS(HORIZWS);
5704 PerlIO_printf(Perl_error_log, "%"UVxf" %d\n",
5705 PTR2UV(scan), OP(scan));
5706 Perl_croak(aTHX_ "regexp memory corruption");
5710 /* switch break jumps here */
5711 scan = next; /* prepare to execute the next op and ... */
5712 continue; /* ... jump back to the top, reusing st */
5716 /* push a state that backtracks on success */
5717 st->u.yes.prev_yes_state = yes_state;
5721 /* push a new regex state, then continue at scan */
5723 regmatch_state *newst;
5726 regmatch_state *cur = st;
5727 regmatch_state *curyes = yes_state;
5729 regmatch_slab *slab = PL_regmatch_slab;
5730 for (;curd > -1;cur--,curd--) {
5731 if (cur < SLAB_FIRST(slab)) {
5733 cur = SLAB_LAST(slab);
5735 PerlIO_printf(Perl_error_log, "%*s#%-3d %-10s %s\n",
5736 REPORT_CODE_OFF + 2 + depth * 2,"",
5737 curd, PL_reg_name[cur->resume_state],
5738 (curyes == cur) ? "yes" : ""
5741 curyes = cur->u.yes.prev_yes_state;
5744 DEBUG_STATE_pp("push")
5747 st->locinput = locinput;
5749 if (newst > SLAB_LAST(PL_regmatch_slab))
5750 newst = S_push_slab(aTHX);
5751 PL_regmatch_state = newst;
5753 locinput = PL_reginput;
5754 nextchr = UCHARAT(locinput);
5762 * We get here only if there's trouble -- normally "case END" is
5763 * the terminating point.
5765 Perl_croak(aTHX_ "corrupted regexp pointers");
5771 /* we have successfully completed a subexpression, but we must now
5772 * pop to the state marked by yes_state and continue from there */
5773 assert(st != yes_state);
5775 while (st != yes_state) {
5777 if (st < SLAB_FIRST(PL_regmatch_slab)) {
5778 PL_regmatch_slab = PL_regmatch_slab->prev;
5779 st = SLAB_LAST(PL_regmatch_slab);
5783 DEBUG_STATE_pp("pop (no final)");
5785 DEBUG_STATE_pp("pop (yes)");
5791 while (yes_state < SLAB_FIRST(PL_regmatch_slab)
5792 || yes_state > SLAB_LAST(PL_regmatch_slab))
5794 /* not in this slab, pop slab */
5795 depth -= (st - SLAB_FIRST(PL_regmatch_slab) + 1);
5796 PL_regmatch_slab = PL_regmatch_slab->prev;
5797 st = SLAB_LAST(PL_regmatch_slab);
5799 depth -= (st - yes_state);
5802 yes_state = st->u.yes.prev_yes_state;
5803 PL_regmatch_state = st;
5806 locinput= st->locinput;
5807 nextchr = UCHARAT(locinput);
5809 state_num = st->resume_state + no_final;
5810 goto reenter_switch;
5813 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch successful!%s\n",
5814 PL_colors[4], PL_colors[5]));
5816 if (PL_reg_eval_set) {
5817 /* each successfully executed (?{...}) block does the equivalent of
5818 * local $^R = do {...}
5819 * When popping the save stack, all these locals would be undone;
5820 * bypass this by setting the outermost saved $^R to the latest
5822 if (oreplsv != GvSV(PL_replgv))
5823 sv_setsv(oreplsv, GvSV(PL_replgv));
5830 PerlIO_printf(Perl_debug_log,
5831 "%*s %sfailed...%s\n",
5832 REPORT_CODE_OFF+depth*2, "",
5833 PL_colors[4], PL_colors[5])
5845 /* there's a previous state to backtrack to */
5847 if (st < SLAB_FIRST(PL_regmatch_slab)) {
5848 PL_regmatch_slab = PL_regmatch_slab->prev;
5849 st = SLAB_LAST(PL_regmatch_slab);
5851 PL_regmatch_state = st;
5852 locinput= st->locinput;
5853 nextchr = UCHARAT(locinput);
5855 DEBUG_STATE_pp("pop");
5857 if (yes_state == st)
5858 yes_state = st->u.yes.prev_yes_state;
5860 state_num = st->resume_state + 1; /* failure = success + 1 */
5861 goto reenter_switch;
5866 if (rex->intflags & PREGf_VERBARG_SEEN) {
5867 SV *sv_err = get_sv("REGERROR", 1);
5868 SV *sv_mrk = get_sv("REGMARK", 1);
5870 sv_commit = &PL_sv_no;
5872 sv_yes_mark = &PL_sv_yes;
5875 sv_commit = &PL_sv_yes;
5876 sv_yes_mark = &PL_sv_no;
5878 sv_setsv(sv_err, sv_commit);
5879 sv_setsv(sv_mrk, sv_yes_mark);
5882 /* clean up; in particular, free all slabs above current one */
5883 LEAVE_SCOPE(oldsave);
5889 - regrepeat - repeatedly match something simple, report how many
5892 * [This routine now assumes that it will only match on things of length 1.
5893 * That was true before, but now we assume scan - reginput is the count,
5894 * rather than incrementing count on every character. [Er, except utf8.]]
5897 S_regrepeat(pTHX_ const regexp *prog, const regnode *p, I32 max, int depth)
5900 register char *scan;
5902 register char *loceol = PL_regeol;
5903 register I32 hardcount = 0;
5904 register bool utf8_target = PL_reg_match_utf8;
5907 PERL_UNUSED_ARG(depth);
5910 PERL_ARGS_ASSERT_REGREPEAT;
5913 if (max == REG_INFTY)
5915 else if (max < loceol - scan)
5916 loceol = scan + max;
5921 while (scan < loceol && hardcount < max && *scan != '\n') {
5922 scan += UTF8SKIP(scan);
5926 while (scan < loceol && *scan != '\n')
5933 while (scan < loceol && hardcount < max) {
5934 scan += UTF8SKIP(scan);
5945 /* To get here, EXACTish nodes must have *byte* length == 1. That
5946 * means they match only characters in the string that can be expressed
5947 * as a single byte. For non-utf8 strings, that means a simple match.
5948 * For utf8 strings, the character matched must be an invariant, or
5949 * downgradable to a single byte. The pattern's utf8ness is
5950 * irrelevant, as since it's a single byte, it either isn't utf8, or if
5951 * it is, it's an invariant */
5954 assert(! UTF_PATTERN || UNI_IS_INVARIANT(c));
5956 if (! utf8_target || UNI_IS_INVARIANT(c)) {
5957 while (scan < loceol && UCHARAT(scan) == c) {
5963 /* Here, the string is utf8, and the pattern char is different
5964 * in utf8 than not, so can't compare them directly. Outside the
5965 * loop, find find the two utf8 bytes that represent c, and then
5966 * look for those in sequence in the utf8 string */
5967 U8 high = UTF8_TWO_BYTE_HI(c);
5968 U8 low = UTF8_TWO_BYTE_LO(c);
5971 while (hardcount < max
5972 && scan + 1 < loceol
5973 && UCHARAT(scan) == high
5974 && UCHARAT(scan + 1) == low)
5982 utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
5986 PL_reg_flags |= RF_tainted;
5987 utf8_flags = FOLDEQ_UTF8_LOCALE;
5994 /* The comments for the EXACT case above apply as well to these fold
5999 assert(! UTF_PATTERN || UNI_IS_INVARIANT(c));
6001 if (utf8_target) { /* Use full Unicode fold matching */
6002 char *tmpeol = loceol;
6003 while (hardcount < max
6004 && foldEQ_utf8_flags(scan, &tmpeol, 0, utf8_target,
6005 STRING(p), NULL, 1, cBOOL(UTF_PATTERN), utf8_flags))
6012 /* XXX Note that the above handles properly the German sharp s in
6013 * the pattern matching ss in the string. But it doesn't handle
6014 * properly cases where the string contains say 'LIGATURE ff' and
6015 * the pattern is 'f+'. This would require, say, a new function or
6016 * revised interface to foldEQ_utf8(), in which the maximum number
6017 * of characters to match could be passed and it would return how
6018 * many actually did. This is just one of many cases where
6019 * multi-char folds don't work properly, and so the fix is being
6025 /* Here, the string isn't utf8 and c is a single byte; and either
6026 * the pattern isn't utf8 or c is an invariant, so its utf8ness
6027 * doesn't affect c. Can just do simple comparisons for exact or
6030 case EXACTF: folded = PL_fold[c]; break;
6032 case EXACTFU: folded = PL_fold_latin1[c]; break;
6033 case EXACTFL: folded = PL_fold_locale[c]; break;
6034 default: Perl_croak(aTHX_ "panic: Unexpected op %u", OP(p));
6036 while (scan < loceol &&
6037 (UCHARAT(scan) == c || UCHARAT(scan) == folded))
6045 if (utf8_target || OP(p) == ANYOFV) {
6048 inclasslen = loceol - scan;
6049 while (hardcount < max
6050 && ((inclasslen = loceol - scan) > 0)
6051 && reginclass(prog, p, (U8*)scan, &inclasslen, utf8_target))
6057 while (scan < loceol && REGINCLASS(prog, p, (U8*)scan))
6065 LOAD_UTF8_CHARCLASS_ALNUM();
6066 while (hardcount < max && scan < loceol &&
6067 swash_fetch(PL_utf8_alnum, (U8*)scan, utf8_target))
6069 scan += UTF8SKIP(scan);
6073 while (scan < loceol && isWORDCHAR_L1((U8) *scan)) {
6081 while (scan < loceol && isALNUM((U8) *scan)) {
6086 while (scan < loceol && isWORDCHAR_A((U8) *scan)) {
6091 PL_reg_flags |= RF_tainted;
6094 while (hardcount < max && scan < loceol &&
6095 isALNUM_LC_utf8((U8*)scan)) {
6096 scan += UTF8SKIP(scan);
6100 while (scan < loceol && isALNUM_LC(*scan))
6110 LOAD_UTF8_CHARCLASS_ALNUM();
6111 while (hardcount < max && scan < loceol &&
6112 ! swash_fetch(PL_utf8_alnum, (U8*)scan, utf8_target))
6114 scan += UTF8SKIP(scan);
6118 while (scan < loceol && ! isWORDCHAR_L1((U8) *scan)) {
6125 goto utf8_Nwordchar;
6126 while (scan < loceol && ! isALNUM((U8) *scan)) {
6132 while (scan < loceol && ! isWORDCHAR_A((U8) *scan)) {
6133 scan += UTF8SKIP(scan);
6137 while (scan < loceol && ! isWORDCHAR_A((U8) *scan)) {
6143 PL_reg_flags |= RF_tainted;
6146 while (hardcount < max && scan < loceol &&
6147 !isALNUM_LC_utf8((U8*)scan)) {
6148 scan += UTF8SKIP(scan);
6152 while (scan < loceol && !isALNUM_LC(*scan))
6162 LOAD_UTF8_CHARCLASS_SPACE();
6163 while (hardcount < max && scan < loceol &&
6165 swash_fetch(PL_utf8_space,(U8*)scan, utf8_target)))
6167 scan += UTF8SKIP(scan);
6173 while (scan < loceol && isSPACE_L1((U8) *scan)) {
6182 while (scan < loceol && isSPACE((U8) *scan)) {
6187 while (scan < loceol && isSPACE_A((U8) *scan)) {
6192 PL_reg_flags |= RF_tainted;
6195 while (hardcount < max && scan < loceol &&
6196 isSPACE_LC_utf8((U8*)scan)) {
6197 scan += UTF8SKIP(scan);
6201 while (scan < loceol && isSPACE_LC(*scan))
6211 LOAD_UTF8_CHARCLASS_SPACE();
6212 while (hardcount < max && scan < loceol &&
6214 swash_fetch(PL_utf8_space,(U8*)scan, utf8_target)))
6216 scan += UTF8SKIP(scan);
6222 while (scan < loceol && ! isSPACE_L1((U8) *scan)) {
6231 while (scan < loceol && ! isSPACE((U8) *scan)) {
6237 while (scan < loceol && ! isSPACE_A((U8) *scan)) {
6238 scan += UTF8SKIP(scan);
6242 while (scan < loceol && ! isSPACE_A((U8) *scan)) {
6248 PL_reg_flags |= RF_tainted;
6251 while (hardcount < max && scan < loceol &&
6252 !isSPACE_LC_utf8((U8*)scan)) {
6253 scan += UTF8SKIP(scan);
6257 while (scan < loceol && !isSPACE_LC(*scan))
6264 LOAD_UTF8_CHARCLASS_DIGIT();
6265 while (hardcount < max && scan < loceol &&
6266 swash_fetch(PL_utf8_digit, (U8*)scan, utf8_target)) {
6267 scan += UTF8SKIP(scan);
6271 while (scan < loceol && isDIGIT(*scan))
6276 while (scan < loceol && isDIGIT_A((U8) *scan)) {
6281 PL_reg_flags |= RF_tainted;
6284 while (hardcount < max && scan < loceol &&
6285 isDIGIT_LC_utf8((U8*)scan)) {
6286 scan += UTF8SKIP(scan);
6290 while (scan < loceol && isDIGIT_LC(*scan))
6297 LOAD_UTF8_CHARCLASS_DIGIT();
6298 while (hardcount < max && scan < loceol &&
6299 !swash_fetch(PL_utf8_digit, (U8*)scan, utf8_target)) {
6300 scan += UTF8SKIP(scan);
6304 while (scan < loceol && !isDIGIT(*scan))
6310 while (scan < loceol && ! isDIGIT_A((U8) *scan)) {
6311 scan += UTF8SKIP(scan);
6315 while (scan < loceol && ! isDIGIT_A((U8) *scan)) {
6321 PL_reg_flags |= RF_tainted;
6324 while (hardcount < max && scan < loceol &&
6325 !isDIGIT_LC_utf8((U8*)scan)) {
6326 scan += UTF8SKIP(scan);
6330 while (scan < loceol && !isDIGIT_LC(*scan))
6337 while (hardcount < max && scan < loceol && (c=is_LNBREAK_utf8(scan))) {
6343 LNBREAK can match two latin chars, which is ok,
6344 because we have a null terminated string, but we
6345 have to use hardcount in this situation
6347 while (scan < loceol && (c=is_LNBREAK_latin1(scan))) {
6356 while (hardcount < max && scan < loceol && (c=is_HORIZWS_utf8(scan))) {
6361 while (scan < loceol && is_HORIZWS_latin1(scan))
6368 while (hardcount < max && scan < loceol && !is_HORIZWS_utf8(scan)) {
6369 scan += UTF8SKIP(scan);
6373 while (scan < loceol && !is_HORIZWS_latin1(scan))
6381 while (hardcount < max && scan < loceol && (c=is_VERTWS_utf8(scan))) {
6386 while (scan < loceol && is_VERTWS_latin1(scan))
6394 while (hardcount < max && scan < loceol && !is_VERTWS_utf8(scan)) {
6395 scan += UTF8SKIP(scan);
6399 while (scan < loceol && !is_VERTWS_latin1(scan))
6405 default: /* Called on something of 0 width. */
6406 break; /* So match right here or not at all. */
6412 c = scan - PL_reginput;
6416 GET_RE_DEBUG_FLAGS_DECL;
6418 SV * const prop = sv_newmortal();
6419 regprop(prog, prop, p);
6420 PerlIO_printf(Perl_debug_log,
6421 "%*s %s can match %"IVdf" times out of %"IVdf"...\n",
6422 REPORT_CODE_OFF + depth*2, "", SvPVX_const(prop),(IV)c,(IV)max);
6430 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
6432 - regclass_swash - prepare the utf8 swash
6436 Perl_regclass_swash(pTHX_ const regexp *prog, register const regnode* node, bool doinit, SV** listsvp, SV **altsvp)
6442 RXi_GET_DECL(prog,progi);
6443 const struct reg_data * const data = prog ? progi->data : NULL;
6445 PERL_ARGS_ASSERT_REGCLASS_SWASH;
6447 assert(ANYOF_NONBITMAP(node));
6449 if (data && data->count) {
6450 const U32 n = ARG(node);
6452 if (data->what[n] == 's') {
6453 SV * const rv = MUTABLE_SV(data->data[n]);
6454 AV * const av = MUTABLE_AV(SvRV(rv));
6455 SV **const ary = AvARRAY(av);
6458 /* See the end of regcomp.c:S_regclass() for
6459 * documentation of these array elements. */
6462 a = SvROK(ary[1]) ? &ary[1] : NULL;
6463 b = SvTYPE(ary[2]) == SVt_PVAV ? &ary[2] : NULL;
6467 else if (si && doinit) {
6468 sw = swash_init("utf8", "", si, 1, 0);
6469 (void)av_store(av, 1, sw);
6486 - reginclass - determine if a character falls into a character class
6488 n is the ANYOF regnode
6489 p is the target string
6490 lenp is pointer to the maximum number of bytes of how far to go in p
6491 (This is assumed wthout checking to always be at least the current
6493 utf8_target tells whether p is in UTF-8.
6495 Returns true if matched; false otherwise. If lenp is not NULL, on return
6496 from a successful match, the value it points to will be updated to how many
6497 bytes in p were matched. If there was no match, the value is undefined,
6498 possibly changed from the input.
6500 Note that this can be a synthetic start class, a combination of various
6501 nodes, so things you think might be mutually exclusive, such as locale,
6502 aren't. It can match both locale and non-locale
6507 S_reginclass(pTHX_ const regexp * const prog, register const regnode * const n, register const U8* const p, STRLEN* lenp, register const bool utf8_target)
6510 const char flags = ANYOF_FLAGS(n);
6516 PERL_ARGS_ASSERT_REGINCLASS;
6518 /* If c is not already the code point, get it */
6519 if (utf8_target && !UTF8_IS_INVARIANT(c)) {
6520 c = utf8n_to_uvchr(p, UTF8_MAXBYTES, &c_len,
6521 (UTF8_ALLOW_DEFAULT & UTF8_ALLOW_ANYUV)
6522 | UTF8_ALLOW_FFFF | UTF8_CHECK_ONLY);
6523 /* see [perl #37836] for UTF8_ALLOW_ANYUV; [perl #38293] for
6524 * UTF8_ALLOW_FFFF */
6525 if (c_len == (STRLEN)-1)
6526 Perl_croak(aTHX_ "Malformed UTF-8 character (fatal)");
6532 /* Use passed in max length, or one character if none passed in or less
6533 * than one character. And assume will match just one character. This is
6534 * overwritten later if matched more. */
6536 maxlen = (*lenp > c_len) ? *lenp : c_len;
6544 /* If this character is potentially in the bitmap, check it */
6546 if (ANYOF_BITMAP_TEST(n, c))
6548 else if (flags & ANYOF_NON_UTF8_LATIN1_ALL
6555 else if (flags & ANYOF_LOCALE) {
6556 PL_reg_flags |= RF_tainted;
6558 if ((flags & ANYOF_LOC_NONBITMAP_FOLD)
6559 && ANYOF_BITMAP_TEST(n, PL_fold_locale[c]))
6563 else if (ANYOF_CLASS_TEST_ANY_SET(n) &&
6564 ((ANYOF_CLASS_TEST(n, ANYOF_ALNUM) && isALNUM_LC(c)) ||
6565 (ANYOF_CLASS_TEST(n, ANYOF_NALNUM) && !isALNUM_LC(c)) ||
6566 (ANYOF_CLASS_TEST(n, ANYOF_SPACE) && isSPACE_LC(c)) ||
6567 (ANYOF_CLASS_TEST(n, ANYOF_NSPACE) && !isSPACE_LC(c)) ||
6568 (ANYOF_CLASS_TEST(n, ANYOF_DIGIT) && isDIGIT_LC(c)) ||
6569 (ANYOF_CLASS_TEST(n, ANYOF_NDIGIT) && !isDIGIT_LC(c)) ||
6570 (ANYOF_CLASS_TEST(n, ANYOF_ALNUMC) && isALNUMC_LC(c)) ||
6571 (ANYOF_CLASS_TEST(n, ANYOF_NALNUMC) && !isALNUMC_LC(c)) ||
6572 (ANYOF_CLASS_TEST(n, ANYOF_ALPHA) && isALPHA_LC(c)) ||
6573 (ANYOF_CLASS_TEST(n, ANYOF_NALPHA) && !isALPHA_LC(c)) ||
6574 (ANYOF_CLASS_TEST(n, ANYOF_ASCII) && isASCII(c)) ||
6575 (ANYOF_CLASS_TEST(n, ANYOF_NASCII) && !isASCII(c)) ||
6576 (ANYOF_CLASS_TEST(n, ANYOF_CNTRL) && isCNTRL_LC(c)) ||
6577 (ANYOF_CLASS_TEST(n, ANYOF_NCNTRL) && !isCNTRL_LC(c)) ||
6578 (ANYOF_CLASS_TEST(n, ANYOF_GRAPH) && isGRAPH_LC(c)) ||
6579 (ANYOF_CLASS_TEST(n, ANYOF_NGRAPH) && !isGRAPH_LC(c)) ||
6580 (ANYOF_CLASS_TEST(n, ANYOF_LOWER) && isLOWER_LC(c)) ||
6581 (ANYOF_CLASS_TEST(n, ANYOF_NLOWER) && !isLOWER_LC(c)) ||
6582 (ANYOF_CLASS_TEST(n, ANYOF_PRINT) && isPRINT_LC(c)) ||
6583 (ANYOF_CLASS_TEST(n, ANYOF_NPRINT) && !isPRINT_LC(c)) ||
6584 (ANYOF_CLASS_TEST(n, ANYOF_PUNCT) && isPUNCT_LC(c)) ||
6585 (ANYOF_CLASS_TEST(n, ANYOF_NPUNCT) && !isPUNCT_LC(c)) ||
6586 (ANYOF_CLASS_TEST(n, ANYOF_UPPER) && isUPPER_LC(c)) ||
6587 (ANYOF_CLASS_TEST(n, ANYOF_NUPPER) && !isUPPER_LC(c)) ||
6588 (ANYOF_CLASS_TEST(n, ANYOF_XDIGIT) && isXDIGIT(c)) ||
6589 (ANYOF_CLASS_TEST(n, ANYOF_NXDIGIT) && !isXDIGIT(c)) ||
6590 (ANYOF_CLASS_TEST(n, ANYOF_PSXSPC) && isPSXSPC(c)) ||
6591 (ANYOF_CLASS_TEST(n, ANYOF_NPSXSPC) && !isPSXSPC(c)) ||
6592 (ANYOF_CLASS_TEST(n, ANYOF_BLANK) && isBLANK(c)) ||
6593 (ANYOF_CLASS_TEST(n, ANYOF_NBLANK) && !isBLANK(c))
6594 ) /* How's that for a conditional? */
6601 /* If the bitmap didn't (or couldn't) match, and something outside the
6602 * bitmap could match, try that. Locale nodes specifiy completely the
6603 * behavior of code points in the bit map (otherwise, a utf8 target would
6604 * cause them to be treated as Unicode and not locale), except in
6605 * the very unlikely event when this node is a synthetic start class, which
6606 * could be a combination of locale and non-locale nodes. So allow locale
6607 * to match for the synthetic start class, which will give a false
6608 * positive that will be resolved when the match is done again as not part
6609 * of the synthetic start class */
6611 if (utf8_target && (flags & ANYOF_UNICODE_ALL) && c >= 256) {
6612 match = TRUE; /* Everything above 255 matches */
6614 else if (ANYOF_NONBITMAP(n)
6615 && ((flags & ANYOF_NONBITMAP_NON_UTF8)
6618 || (! (flags & ANYOF_LOCALE))
6619 || (flags & ANYOF_IS_SYNTHETIC)))))
6622 SV * const sw = regclass_swash(prog, n, TRUE, 0, (SV**)&av);
6630 /* Not utf8. Convert as much of the string as available up
6631 * to the limit of how far the (single) character in the
6632 * pattern can possibly match (no need to go further). If
6633 * the node is a straight ANYOF or not folding, it can't
6634 * match more than one. Otherwise, It can match up to how
6635 * far a single char can fold to. Since not utf8, each
6636 * character is a single byte, so the max it can be in
6637 * bytes is the same as the max it can be in characters */
6638 STRLEN len = (OP(n) == ANYOF
6639 || ! (flags & ANYOF_LOC_NONBITMAP_FOLD))
6641 : (maxlen < UTF8_MAX_FOLD_CHAR_EXPAND)
6643 : UTF8_MAX_FOLD_CHAR_EXPAND;
6644 utf8_p = bytes_to_utf8(p, &len);
6647 if (swash_fetch(sw, utf8_p, TRUE))
6649 else if (flags & ANYOF_LOC_NONBITMAP_FOLD) {
6651 /* Here, we need to test if the fold of the target string
6652 * matches. The non-multi char folds have all been moved to
6653 * the compilation phase, and the multi-char folds have
6654 * been stored by regcomp into 'av'; we linearly check to
6655 * see if any match the target string (folded). We know
6656 * that the originals were each one character, but we don't
6657 * currently know how many characters/bytes each folded to,
6658 * except we do know that there are small limits imposed by
6659 * Unicode. XXX A performance enhancement would be to have
6660 * regcomp.c store the max number of chars/bytes that are
6661 * in an av entry, as, say the 0th element. Even better
6662 * would be to have a hash of the few characters that can
6663 * start a multi-char fold to the max number of chars of
6666 * If there is a match, we will need to advance (if lenp is
6667 * specified) the match pointer in the target string. But
6668 * what we are comparing here isn't that string directly,
6669 * but its fold, whose length may differ from the original.
6670 * As we go along in constructing the fold, therefore, we
6671 * create a map so that we know how many bytes in the
6672 * source to advance given that we have matched a certain
6673 * number of bytes in the fold. This map is stored in
6674 * 'map_fold_len_back'. Let n mean the number of bytes in
6675 * the fold of the first character that we are folding.
6676 * Then map_fold_len_back[n] is set to the number of bytes
6677 * in that first character. Similarly let m be the
6678 * corresponding number for the second character to be
6679 * folded. Then map_fold_len_back[n+m] is set to the
6680 * number of bytes occupied by the first two source
6681 * characters. ... */
6682 U8 map_fold_len_back[UTF8_MAXBYTES_CASE+1] = { 0 };
6683 U8 folded[UTF8_MAXBYTES_CASE+1];
6684 STRLEN foldlen = 0; /* num bytes in fold of 1st char */
6685 STRLEN total_foldlen = 0; /* num bytes in fold of all
6688 if (OP(n) == ANYOF || maxlen == 1 || ! lenp || ! av) {
6690 /* Here, only need to fold the first char of the target
6691 * string. It the source wasn't utf8, is 1 byte long */
6692 to_utf8_fold(utf8_p, folded, &foldlen);
6693 total_foldlen = foldlen;
6694 map_fold_len_back[foldlen] = (utf8_target)
6700 /* Here, need to fold more than the first char. Do so
6701 * up to the limits */
6702 U8* source_ptr = utf8_p; /* The source for the fold
6705 U8* folded_ptr = folded;
6706 U8* e = utf8_p + maxlen; /* Can't go beyond last
6707 available byte in the
6711 i < UTF8_MAX_FOLD_CHAR_EXPAND && source_ptr < e;
6715 /* Fold the next character */
6716 U8 this_char_folded[UTF8_MAXBYTES_CASE+1];
6717 STRLEN this_char_foldlen;
6718 to_utf8_fold(source_ptr,
6720 &this_char_foldlen);
6722 /* Bail if it would exceed the byte limit for
6723 * folding a single char. */
6724 if (this_char_foldlen + folded_ptr - folded >
6730 /* Add the fold of this character */
6731 Copy(this_char_folded,
6735 source_ptr += UTF8SKIP(source_ptr);
6736 folded_ptr += this_char_foldlen;
6737 total_foldlen = folded_ptr - folded;
6739 /* Create map from the number of bytes in the fold
6740 * back to the number of bytes in the source. If
6741 * the source isn't utf8, the byte count is just
6742 * the number of characters so far */
6743 map_fold_len_back[total_foldlen]
6745 ? source_ptr - utf8_p
6752 /* Do the linear search to see if the fold is in the list
6753 * of multi-char folds. */
6756 for (i = 0; i <= av_len(av); i++) {
6757 SV* const sv = *av_fetch(av, i, FALSE);
6759 const char * const s = SvPV_const(sv, len);
6761 if (len <= total_foldlen
6762 && memEQ(s, (char*)folded, len)
6764 /* If 0, means matched a partial char. See
6766 && map_fold_len_back[len])
6769 /* Advance the target string ptr to account for
6770 * this fold, but have to translate from the
6771 * folded length to the corresponding source
6774 *lenp = map_fold_len_back[len];
6783 /* If we allocated a string above, free it */
6784 if (! utf8_target) Safefree(utf8_p);
6789 return (flags & ANYOF_INVERT) ? !match : match;
6793 S_reghop3(U8 *s, I32 off, const U8* lim)
6797 PERL_ARGS_ASSERT_REGHOP3;
6800 while (off-- && s < lim) {
6801 /* XXX could check well-formedness here */
6806 while (off++ && s > lim) {
6808 if (UTF8_IS_CONTINUED(*s)) {
6809 while (s > lim && UTF8_IS_CONTINUATION(*s))
6812 /* XXX could check well-formedness here */
6819 /* there are a bunch of places where we use two reghop3's that should
6820 be replaced with this routine. but since thats not done yet
6821 we ifdef it out - dmq
6824 S_reghop4(U8 *s, I32 off, const U8* llim, const U8* rlim)
6828 PERL_ARGS_ASSERT_REGHOP4;
6831 while (off-- && s < rlim) {
6832 /* XXX could check well-formedness here */
6837 while (off++ && s > llim) {
6839 if (UTF8_IS_CONTINUED(*s)) {
6840 while (s > llim && UTF8_IS_CONTINUATION(*s))
6843 /* XXX could check well-formedness here */
6851 S_reghopmaybe3(U8* s, I32 off, const U8* lim)
6855 PERL_ARGS_ASSERT_REGHOPMAYBE3;
6858 while (off-- && s < lim) {
6859 /* XXX could check well-formedness here */
6866 while (off++ && s > lim) {
6868 if (UTF8_IS_CONTINUED(*s)) {
6869 while (s > lim && UTF8_IS_CONTINUATION(*s))
6872 /* XXX could check well-formedness here */
6881 restore_pos(pTHX_ void *arg)
6884 regexp * const rex = (regexp *)arg;
6885 if (PL_reg_eval_set) {
6886 if (PL_reg_oldsaved) {
6887 rex->subbeg = PL_reg_oldsaved;
6888 rex->sublen = PL_reg_oldsavedlen;
6889 #ifdef PERL_OLD_COPY_ON_WRITE
6890 rex->saved_copy = PL_nrs;
6892 RXp_MATCH_COPIED_on(rex);
6894 PL_reg_magic->mg_len = PL_reg_oldpos;
6895 PL_reg_eval_set = 0;
6896 PL_curpm = PL_reg_oldcurpm;
6901 S_to_utf8_substr(pTHX_ register regexp *prog)
6905 PERL_ARGS_ASSERT_TO_UTF8_SUBSTR;
6908 if (prog->substrs->data[i].substr
6909 && !prog->substrs->data[i].utf8_substr) {
6910 SV* const sv = newSVsv(prog->substrs->data[i].substr);
6911 prog->substrs->data[i].utf8_substr = sv;
6912 sv_utf8_upgrade(sv);
6913 if (SvVALID(prog->substrs->data[i].substr)) {
6914 if (SvTAIL(prog->substrs->data[i].substr)) {
6915 /* Trim the trailing \n that fbm_compile added last
6917 SvCUR_set(sv, SvCUR(sv) - 1);
6918 /* Whilst this makes the SV technically "invalid" (as its
6919 buffer is no longer followed by "\0") when fbm_compile()
6920 adds the "\n" back, a "\0" is restored. */
6921 fbm_compile(sv, FBMcf_TAIL);
6925 if (prog->substrs->data[i].substr == prog->check_substr)
6926 prog->check_utf8 = sv;
6932 S_to_byte_substr(pTHX_ register regexp *prog)
6937 PERL_ARGS_ASSERT_TO_BYTE_SUBSTR;
6940 if (prog->substrs->data[i].utf8_substr
6941 && !prog->substrs->data[i].substr) {
6942 SV* sv = newSVsv(prog->substrs->data[i].utf8_substr);
6943 if (sv_utf8_downgrade(sv, TRUE)) {
6944 if (SvVALID(prog->substrs->data[i].utf8_substr)) {
6945 if (SvTAIL(prog->substrs->data[i].utf8_substr)) {
6946 /* Trim the trailing \n that fbm_compile added last
6948 SvCUR_set(sv, SvCUR(sv) - 1);
6949 fbm_compile(sv, FBMcf_TAIL);
6957 prog->substrs->data[i].substr = sv;
6958 if (prog->substrs->data[i].utf8_substr == prog->check_utf8)
6959 prog->check_substr = sv;
6966 * c-indentation-style: bsd
6968 * indent-tabs-mode: t
6971 * ex: set ts=8 sts=4 sw=4 noet: