5 * One Ring to rule them all, One Ring to find them
7 * [p.v of _The Lord of the Rings_, opening poem]
8 * [p.50 of _The Lord of the Rings_, I/iii: "The Shadow of the Past"]
9 * [p.254 of _The Lord of the Rings_, II/ii: "The Council of Elrond"]
12 /* This file contains functions for executing a regular expression. See
13 * also regcomp.c which funnily enough, contains functions for compiling
14 * a regular expression.
16 * This file is also copied at build time to ext/re/re_exec.c, where
17 * it's built with -DPERL_EXT_RE_BUILD -DPERL_EXT_RE_DEBUG -DPERL_EXT.
18 * This causes the main functions to be compiled under new names and with
19 * debugging support added, which makes "use re 'debug'" work.
22 /* NOTE: this is derived from Henry Spencer's regexp code, and should not
23 * confused with the original package (see point 3 below). Thanks, Henry!
26 /* Additional note: this code is very heavily munged from Henry's version
27 * in places. In some spots I've traded clarity for efficiency, so don't
28 * blame Henry for some of the lack of readability.
31 /* The names of the functions have been changed from regcomp and
32 * regexec to pregcomp and pregexec in order to avoid conflicts
33 * with the POSIX routines of the same names.
36 #ifdef PERL_EXT_RE_BUILD
41 * pregcomp and pregexec -- regsub and regerror are not used in perl
43 * Copyright (c) 1986 by University of Toronto.
44 * Written by Henry Spencer. Not derived from licensed software.
46 * Permission is granted to anyone to use this software for any
47 * purpose on any computer system, and to redistribute it freely,
48 * subject to the following restrictions:
50 * 1. The author is not responsible for the consequences of use of
51 * this software, no matter how awful, even if they arise
54 * 2. The origin of this software must not be misrepresented, either
55 * by explicit claim or by omission.
57 * 3. Altered versions must be plainly marked as such, and must not
58 * be misrepresented as being the original software.
60 **** Alterations to Henry's code are...
62 **** Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
63 **** 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
64 **** by Larry Wall and others
66 **** You may distribute under the terms of either the GNU General Public
67 **** License or the Artistic License, as specified in the README file.
69 * Beware that some of this code is subtly aware of the way operator
70 * precedence is structured in regular expressions. Serious changes in
71 * regular-expression syntax might require a total rethink.
74 #define PERL_IN_REGEXEC_C
77 #ifdef PERL_IN_XSUB_RE
83 #include "invlist_inline.h"
84 #include "unicode_constants.h"
86 #define B_ON_NON_UTF8_LOCALE_IS_WRONG \
87 "Use of \\b{} or \\B{} for non-UTF-8 locale is wrong. Assuming a UTF-8 locale"
89 static const char utf8_locale_required[] =
90 "Use of (?[ ]) for non-UTF-8 locale is wrong. Assuming a UTF-8 locale";
93 /* At least one required character in the target string is expressible only in
95 static const char* const non_utf8_target_but_utf8_required
96 = "Can't match, because target string needs to be in UTF-8\n";
99 #define NON_UTF8_TARGET_BUT_UTF8_REQUIRED(target) STMT_START { \
100 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%s", non_utf8_target_but_utf8_required));\
104 #define HAS_NONLATIN1_FOLD_CLOSURE(i) _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
107 #define STATIC static
110 /* Valid only if 'c', the character being looke-up, is an invariant under
111 * UTF-8: it avoids the reginclass call if there are no complications: i.e., if
112 * everything matchable is straight forward in the bitmap */
113 #define REGINCLASS(prog,p,c,u) (ANYOF_FLAGS(p) \
114 ? reginclass(prog,p,c,c+1,u) \
115 : ANYOF_BITMAP_TEST(p,*(c)))
121 #define CHR_SVLEN(sv) (utf8_target ? sv_len_utf8(sv) : SvCUR(sv))
122 #define CHR_DIST(a,b) (reginfo->is_utf8_target ? utf8_distance(a,b) : a - b)
124 #define HOPc(pos,off) \
125 (char *)(reginfo->is_utf8_target \
126 ? reghop3((U8*)pos, off, \
127 (U8*)(off >= 0 ? reginfo->strend : reginfo->strbeg)) \
130 #define HOPBACKc(pos, off) \
131 (char*)(reginfo->is_utf8_target \
132 ? reghopmaybe3((U8*)pos, (SSize_t)0-off, (U8*)(reginfo->strbeg)) \
133 : (pos - off >= reginfo->strbeg) \
137 #define HOP3(pos,off,lim) (reginfo->is_utf8_target ? reghop3((U8*)(pos), off, (U8*)(lim)) : (U8*)(pos + off))
138 #define HOP3c(pos,off,lim) ((char*)HOP3(pos,off,lim))
140 /* lim must be +ve. Returns NULL on overshoot */
141 #define HOPMAYBE3(pos,off,lim) \
142 (reginfo->is_utf8_target \
143 ? reghopmaybe3((U8*)pos, off, (U8*)(lim)) \
144 : ((U8*)pos + off <= lim) \
148 /* like HOP3, but limits the result to <= lim even for the non-utf8 case.
149 * off must be >=0; args should be vars rather than expressions */
150 #define HOP3lim(pos,off,lim) (reginfo->is_utf8_target \
151 ? reghop3((U8*)(pos), off, (U8*)(lim)) \
152 : (U8*)((pos + off) > lim ? lim : (pos + off)))
154 #define HOP4(pos,off,llim, rlim) (reginfo->is_utf8_target \
155 ? reghop4((U8*)(pos), off, (U8*)(llim), (U8*)(rlim)) \
157 #define HOP4c(pos,off,llim, rlim) ((char*)HOP4(pos,off,llim, rlim))
159 #define NEXTCHR_EOS -10 /* nextchr has fallen off the end */
160 #define NEXTCHR_IS_EOS (nextchr < 0)
162 #define SET_nextchr \
163 nextchr = ((locinput < reginfo->strend) ? UCHARAT(locinput) : NEXTCHR_EOS)
165 #define SET_locinput(p) \
170 #define LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist) STMT_START { \
172 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST; \
173 swash_ptr = _core_swash_init("utf8", property_name, &PL_sv_undef, \
174 1, 0, invlist, &flags); \
179 /* If in debug mode, we test that a known character properly matches */
181 # define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
184 utf8_char_in_property) \
185 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist); \
186 assert(swash_fetch(swash_ptr, (U8 *) utf8_char_in_property, TRUE));
188 # define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
191 utf8_char_in_property) \
192 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist)
195 #define LOAD_UTF8_CHARCLASS_ALNUM() LOAD_UTF8_CHARCLASS_DEBUG_TEST( \
196 PL_utf8_swash_ptrs[_CC_WORDCHAR], \
198 PL_XPosix_ptrs[_CC_WORDCHAR], \
199 LATIN_SMALL_LIGATURE_LONG_S_T_UTF8);
201 #define PLACEHOLDER /* Something for the preprocessor to grab onto */
202 /* TODO: Combine JUMPABLE and HAS_TEXT to cache OP(rn) */
204 /* for use after a quantifier and before an EXACT-like node -- japhy */
205 /* it would be nice to rework regcomp.sym to generate this stuff. sigh
207 * NOTE that *nothing* that affects backtracking should be in here, specifically
208 * VERBS must NOT be included. JUMPABLE is used to determine if we can ignore a
209 * node that is in between two EXACT like nodes when ascertaining what the required
210 * "follow" character is. This should probably be moved to regex compile time
211 * although it may be done at run time beause of the REF possibility - more
212 * investigation required. -- demerphq
214 #define JUMPABLE(rn) ( \
216 (OP(rn) == CLOSE && \
217 !EVAL_CLOSE_PAREN_IS(cur_eval,ARG(rn)) ) || \
219 OP(rn) == SUSPEND || OP(rn) == IFMATCH || \
220 OP(rn) == PLUS || OP(rn) == MINMOD || \
222 (PL_regkind[OP(rn)] == CURLY && ARG1(rn) > 0) \
224 #define IS_EXACT(rn) (PL_regkind[OP(rn)] == EXACT)
226 #define HAS_TEXT(rn) ( IS_EXACT(rn) || PL_regkind[OP(rn)] == REF )
229 /* Currently these are only used when PL_regkind[OP(rn)] == EXACT so
230 we don't need this definition. XXX These are now out-of-sync*/
231 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==REF || OP(rn)==NREF )
232 #define IS_TEXTF(rn) ( OP(rn)==EXACTFU || OP(rn)==EXACTFU_SS || OP(rn)==EXACTFA || OP(rn)==EXACTFA_NO_TRIE || OP(rn)==EXACTF || OP(rn)==REFF || OP(rn)==NREFF )
233 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL || OP(rn)==REFFL || OP(rn)==NREFFL )
236 /* ... so we use this as its faster. */
237 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==EXACTL )
238 #define IS_TEXTFU(rn) ( OP(rn)==EXACTFU || OP(rn)==EXACTFLU8 || OP(rn)==EXACTFU_SS || OP(rn) == EXACTFA || OP(rn) == EXACTFA_NO_TRIE)
239 #define IS_TEXTF(rn) ( OP(rn)==EXACTF )
240 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL )
245 Search for mandatory following text node; for lookahead, the text must
246 follow but for lookbehind (rn->flags != 0) we skip to the next step.
248 #define FIND_NEXT_IMPT(rn) STMT_START { \
249 while (JUMPABLE(rn)) { \
250 const OPCODE type = OP(rn); \
251 if (type == SUSPEND || PL_regkind[type] == CURLY) \
252 rn = NEXTOPER(NEXTOPER(rn)); \
253 else if (type == PLUS) \
255 else if (type == IFMATCH) \
256 rn = (rn->flags == 0) ? NEXTOPER(NEXTOPER(rn)) : rn + ARG(rn); \
257 else rn += NEXT_OFF(rn); \
261 #define SLAB_FIRST(s) (&(s)->states[0])
262 #define SLAB_LAST(s) (&(s)->states[PERL_REGMATCH_SLAB_SLOTS-1])
264 static void S_setup_eval_state(pTHX_ regmatch_info *const reginfo);
265 static void S_cleanup_regmatch_info_aux(pTHX_ void *arg);
266 static regmatch_state * S_push_slab(pTHX);
268 #define REGCP_PAREN_ELEMS 3
269 #define REGCP_OTHER_ELEMS 3
270 #define REGCP_FRAME_ELEMS 1
271 /* REGCP_FRAME_ELEMS are not part of the REGCP_OTHER_ELEMS and
272 * are needed for the regexp context stack bookkeeping. */
275 S_regcppush(pTHX_ const regexp *rex, I32 parenfloor, U32 maxopenparen _pDEPTH)
277 const int retval = PL_savestack_ix;
278 const int paren_elems_to_push =
279 (maxopenparen - parenfloor) * REGCP_PAREN_ELEMS;
280 const UV total_elems = paren_elems_to_push + REGCP_OTHER_ELEMS;
281 const UV elems_shifted = total_elems << SAVE_TIGHT_SHIFT;
283 GET_RE_DEBUG_FLAGS_DECL;
285 PERL_ARGS_ASSERT_REGCPPUSH;
287 if (paren_elems_to_push < 0)
288 Perl_croak(aTHX_ "panic: paren_elems_to_push, %i < 0, maxopenparen: %i parenfloor: %i REGCP_PAREN_ELEMS: %u",
289 (int)paren_elems_to_push, (int)maxopenparen,
290 (int)parenfloor, (unsigned)REGCP_PAREN_ELEMS);
292 if ((elems_shifted >> SAVE_TIGHT_SHIFT) != total_elems)
293 Perl_croak(aTHX_ "panic: paren_elems_to_push offset %" UVuf
294 " out of range (%lu-%ld)",
296 (unsigned long)maxopenparen,
299 SSGROW(total_elems + REGCP_FRAME_ELEMS);
302 if ((int)maxopenparen > (int)parenfloor)
303 Perl_re_exec_indentf( aTHX_
304 "rex=0x%" UVxf " offs=0x%" UVxf ": saving capture indices:\n",
310 for (p = parenfloor+1; p <= (I32)maxopenparen; p++) {
311 /* REGCP_PARENS_ELEMS are pushed per pairs of parentheses. */
312 SSPUSHIV(rex->offs[p].end);
313 SSPUSHIV(rex->offs[p].start);
314 SSPUSHINT(rex->offs[p].start_tmp);
315 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_
316 " \\%" UVuf ": %" IVdf "(%" IVdf ")..%" IVdf "\n",
319 (IV)rex->offs[p].start,
320 (IV)rex->offs[p].start_tmp,
324 /* REGCP_OTHER_ELEMS are pushed in any case, parentheses or no. */
325 SSPUSHINT(maxopenparen);
326 SSPUSHINT(rex->lastparen);
327 SSPUSHINT(rex->lastcloseparen);
328 SSPUSHUV(SAVEt_REGCONTEXT | elems_shifted); /* Magic cookie. */
333 /* These are needed since we do not localize EVAL nodes: */
334 #define REGCP_SET(cp) \
336 Perl_re_exec_indentf( aTHX_ \
337 "Setting an EVAL scope, savestack=%" IVdf ",\n", \
338 depth, (IV)PL_savestack_ix \
343 #define REGCP_UNWIND(cp) \
345 if (cp != PL_savestack_ix) \
346 Perl_re_exec_indentf( aTHX_ \
347 "Clearing an EVAL scope, savestack=%" \
348 IVdf "..%" IVdf "\n", \
349 depth, (IV)(cp), (IV)PL_savestack_ix \
354 #define UNWIND_PAREN(lp, lcp) \
355 for (n = rex->lastparen; n > lp; n--) \
356 rex->offs[n].end = -1; \
357 rex->lastparen = n; \
358 rex->lastcloseparen = lcp;
362 S_regcppop(pTHX_ regexp *rex, U32 *maxopenparen_p _pDEPTH)
366 GET_RE_DEBUG_FLAGS_DECL;
368 PERL_ARGS_ASSERT_REGCPPOP;
370 /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
372 assert((i & SAVE_MASK) == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
373 i >>= SAVE_TIGHT_SHIFT; /* Parentheses elements to pop. */
374 rex->lastcloseparen = SSPOPINT;
375 rex->lastparen = SSPOPINT;
376 *maxopenparen_p = SSPOPINT;
378 i -= REGCP_OTHER_ELEMS;
379 /* Now restore the parentheses context. */
381 if (i || rex->lastparen + 1 <= rex->nparens)
382 Perl_re_exec_indentf( aTHX_
383 "rex=0x%" UVxf " offs=0x%" UVxf ": restoring capture indices to:\n",
389 paren = *maxopenparen_p;
390 for ( ; i > 0; i -= REGCP_PAREN_ELEMS) {
392 rex->offs[paren].start_tmp = SSPOPINT;
393 rex->offs[paren].start = SSPOPIV;
395 if (paren <= rex->lastparen)
396 rex->offs[paren].end = tmps;
397 DEBUG_BUFFERS_r( Perl_re_exec_indentf( aTHX_
398 " \\%" UVuf ": %" IVdf "(%" IVdf ")..%" IVdf "%s\n",
401 (IV)rex->offs[paren].start,
402 (IV)rex->offs[paren].start_tmp,
403 (IV)rex->offs[paren].end,
404 (paren > rex->lastparen ? "(skipped)" : ""));
409 /* It would seem that the similar code in regtry()
410 * already takes care of this, and in fact it is in
411 * a better location to since this code can #if 0-ed out
412 * but the code in regtry() is needed or otherwise tests
413 * requiring null fields (pat.t#187 and split.t#{13,14}
414 * (as of patchlevel 7877) will fail. Then again,
415 * this code seems to be necessary or otherwise
416 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
417 * --jhi updated by dapm */
418 for (i = rex->lastparen + 1; i <= rex->nparens; i++) {
419 if (i > *maxopenparen_p)
420 rex->offs[i].start = -1;
421 rex->offs[i].end = -1;
422 DEBUG_BUFFERS_r( Perl_re_exec_indentf( aTHX_
423 " \\%" UVuf ": %s ..-1 undeffing\n",
426 (i > *maxopenparen_p) ? "-1" : " "
432 /* restore the parens and associated vars at savestack position ix,
433 * but without popping the stack */
436 S_regcp_restore(pTHX_ regexp *rex, I32 ix, U32 *maxopenparen_p _pDEPTH)
438 I32 tmpix = PL_savestack_ix;
439 PERL_ARGS_ASSERT_REGCP_RESTORE;
441 PL_savestack_ix = ix;
442 regcppop(rex, maxopenparen_p);
443 PL_savestack_ix = tmpix;
446 #define regcpblow(cp) LEAVE_SCOPE(cp) /* Ignores regcppush()ed data. */
449 S_isFOO_lc(pTHX_ const U8 classnum, const U8 character)
451 /* Returns a boolean as to whether or not 'character' is a member of the
452 * Posix character class given by 'classnum' that should be equivalent to a
453 * value in the typedef '_char_class_number'.
455 * Ideally this could be replaced by a just an array of function pointers
456 * to the C library functions that implement the macros this calls.
457 * However, to compile, the precise function signatures are required, and
458 * these may vary from platform to to platform. To avoid having to figure
459 * out what those all are on each platform, I (khw) am using this method,
460 * which adds an extra layer of function call overhead (unless the C
461 * optimizer strips it away). But we don't particularly care about
462 * performance with locales anyway. */
464 switch ((_char_class_number) classnum) {
465 case _CC_ENUM_ALPHANUMERIC: return isALPHANUMERIC_LC(character);
466 case _CC_ENUM_ALPHA: return isALPHA_LC(character);
467 case _CC_ENUM_ASCII: return isASCII_LC(character);
468 case _CC_ENUM_BLANK: return isBLANK_LC(character);
469 case _CC_ENUM_CASED: return isLOWER_LC(character)
470 || isUPPER_LC(character);
471 case _CC_ENUM_CNTRL: return isCNTRL_LC(character);
472 case _CC_ENUM_DIGIT: return isDIGIT_LC(character);
473 case _CC_ENUM_GRAPH: return isGRAPH_LC(character);
474 case _CC_ENUM_LOWER: return isLOWER_LC(character);
475 case _CC_ENUM_PRINT: return isPRINT_LC(character);
476 case _CC_ENUM_PUNCT: return isPUNCT_LC(character);
477 case _CC_ENUM_SPACE: return isSPACE_LC(character);
478 case _CC_ENUM_UPPER: return isUPPER_LC(character);
479 case _CC_ENUM_WORDCHAR: return isWORDCHAR_LC(character);
480 case _CC_ENUM_XDIGIT: return isXDIGIT_LC(character);
481 default: /* VERTSPACE should never occur in locales */
482 Perl_croak(aTHX_ "panic: isFOO_lc() has an unexpected character class '%d'", classnum);
485 NOT_REACHED; /* NOTREACHED */
490 S_isFOO_utf8_lc(pTHX_ const U8 classnum, const U8* character)
492 /* Returns a boolean as to whether or not the (well-formed) UTF-8-encoded
493 * 'character' is a member of the Posix character class given by 'classnum'
494 * that should be equivalent to a value in the typedef
495 * '_char_class_number'.
497 * This just calls isFOO_lc on the code point for the character if it is in
498 * the range 0-255. Outside that range, all characters use Unicode
499 * rules, ignoring any locale. So use the Unicode function if this class
500 * requires a swash, and use the Unicode macro otherwise. */
502 PERL_ARGS_ASSERT_ISFOO_UTF8_LC;
504 if (UTF8_IS_INVARIANT(*character)) {
505 return isFOO_lc(classnum, *character);
507 else if (UTF8_IS_DOWNGRADEABLE_START(*character)) {
508 return isFOO_lc(classnum,
509 EIGHT_BIT_UTF8_TO_NATIVE(*character, *(character + 1)));
512 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(character, character + UTF8SKIP(character));
514 if (classnum < _FIRST_NON_SWASH_CC) {
516 /* Initialize the swash unless done already */
517 if (! PL_utf8_swash_ptrs[classnum]) {
518 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
519 PL_utf8_swash_ptrs[classnum] =
520 _core_swash_init("utf8",
523 PL_XPosix_ptrs[classnum], &flags);
526 return cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum], (U8 *)
528 TRUE /* is UTF */ ));
531 switch ((_char_class_number) classnum) {
532 case _CC_ENUM_SPACE: return is_XPERLSPACE_high(character);
533 case _CC_ENUM_BLANK: return is_HORIZWS_high(character);
534 case _CC_ENUM_XDIGIT: return is_XDIGIT_high(character);
535 case _CC_ENUM_VERTSPACE: return is_VERTWS_high(character);
539 return FALSE; /* Things like CNTRL are always below 256 */
543 * pregexec and friends
546 #ifndef PERL_IN_XSUB_RE
548 - pregexec - match a regexp against a string
551 Perl_pregexec(pTHX_ REGEXP * const prog, char* stringarg, char *strend,
552 char *strbeg, SSize_t minend, SV *screamer, U32 nosave)
553 /* stringarg: the point in the string at which to begin matching */
554 /* strend: pointer to null at end of string */
555 /* strbeg: real beginning of string */
556 /* minend: end of match must be >= minend bytes after stringarg. */
557 /* screamer: SV being matched: only used for utf8 flag, pos() etc; string
558 * itself is accessed via the pointers above */
559 /* nosave: For optimizations. */
561 PERL_ARGS_ASSERT_PREGEXEC;
564 regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
565 nosave ? 0 : REXEC_COPY_STR);
571 /* re_intuit_start():
573 * Based on some optimiser hints, try to find the earliest position in the
574 * string where the regex could match.
576 * rx: the regex to match against
577 * sv: the SV being matched: only used for utf8 flag; the string
578 * itself is accessed via the pointers below. Note that on
579 * something like an overloaded SV, SvPOK(sv) may be false
580 * and the string pointers may point to something unrelated to
582 * strbeg: real beginning of string
583 * strpos: the point in the string at which to begin matching
584 * strend: pointer to the byte following the last char of the string
585 * flags currently unused; set to 0
586 * data: currently unused; set to NULL
588 * The basic idea of re_intuit_start() is to use some known information
589 * about the pattern, namely:
591 * a) the longest known anchored substring (i.e. one that's at a
592 * constant offset from the beginning of the pattern; but not
593 * necessarily at a fixed offset from the beginning of the
595 * b) the longest floating substring (i.e. one that's not at a constant
596 * offset from the beginning of the pattern);
597 * c) Whether the pattern is anchored to the string; either
598 * an absolute anchor: /^../, or anchored to \n: /^.../m,
599 * or anchored to pos(): /\G/;
600 * d) A start class: a real or synthetic character class which
601 * represents which characters are legal at the start of the pattern;
603 * to either quickly reject the match, or to find the earliest position
604 * within the string at which the pattern might match, thus avoiding
605 * running the full NFA engine at those earlier locations, only to
606 * eventually fail and retry further along.
608 * Returns NULL if the pattern can't match, or returns the address within
609 * the string which is the earliest place the match could occur.
611 * The longest of the anchored and floating substrings is called 'check'
612 * and is checked first. The other is called 'other' and is checked
613 * second. The 'other' substring may not be present. For example,
615 * /(abc|xyz)ABC\d{0,3}DEFG/
619 * check substr (float) = "DEFG", offset 6..9 chars
620 * other substr (anchored) = "ABC", offset 3..3 chars
623 * Be aware that during the course of this function, sometimes 'anchored'
624 * refers to a substring being anchored relative to the start of the
625 * pattern, and sometimes to the pattern itself being anchored relative to
626 * the string. For example:
628 * /\dabc/: "abc" is anchored to the pattern;
629 * /^\dabc/: "abc" is anchored to the pattern and the string;
630 * /\d+abc/: "abc" is anchored to neither the pattern nor the string;
631 * /^\d+abc/: "abc" is anchored to neither the pattern nor the string,
632 * but the pattern is anchored to the string.
636 Perl_re_intuit_start(pTHX_
639 const char * const strbeg,
643 re_scream_pos_data *data)
645 struct regexp *const prog = ReANY(rx);
646 SSize_t start_shift = prog->check_offset_min;
647 /* Should be nonnegative! */
648 SSize_t end_shift = 0;
649 /* current lowest pos in string where the regex can start matching */
650 char *rx_origin = strpos;
652 const bool utf8_target = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
653 U8 other_ix = 1 - prog->substrs->check_ix;
655 char *other_last = strpos;/* latest pos 'other' substr already checked to */
656 char *check_at = NULL; /* check substr found at this pos */
657 const I32 multiline = prog->extflags & RXf_PMf_MULTILINE;
658 RXi_GET_DECL(prog,progi);
659 regmatch_info reginfo_buf; /* create some info to pass to find_byclass */
660 regmatch_info *const reginfo = ®info_buf;
661 GET_RE_DEBUG_FLAGS_DECL;
663 PERL_ARGS_ASSERT_RE_INTUIT_START;
664 PERL_UNUSED_ARG(flags);
665 PERL_UNUSED_ARG(data);
667 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
668 "Intuit: trying to determine minimum start position...\n"));
670 /* for now, assume that all substr offsets are positive. If at some point
671 * in the future someone wants to do clever things with lookbehind and
672 * -ve offsets, they'll need to fix up any code in this function
673 * which uses these offsets. See the thread beginning
674 * <20140113145929.GF27210@iabyn.com>
676 assert(prog->substrs->data[0].min_offset >= 0);
677 assert(prog->substrs->data[0].max_offset >= 0);
678 assert(prog->substrs->data[1].min_offset >= 0);
679 assert(prog->substrs->data[1].max_offset >= 0);
680 assert(prog->substrs->data[2].min_offset >= 0);
681 assert(prog->substrs->data[2].max_offset >= 0);
683 /* for now, assume that if both present, that the floating substring
684 * doesn't start before the anchored substring.
685 * If you break this assumption (e.g. doing better optimisations
686 * with lookahead/behind), then you'll need to audit the code in this
687 * function carefully first
690 ! ( (prog->anchored_utf8 || prog->anchored_substr)
691 && (prog->float_utf8 || prog->float_substr))
692 || (prog->float_min_offset >= prog->anchored_offset));
694 /* byte rather than char calculation for efficiency. It fails
695 * to quickly reject some cases that can't match, but will reject
696 * them later after doing full char arithmetic */
697 if (prog->minlen > strend - strpos) {
698 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
699 " String too short...\n"));
703 RX_MATCH_UTF8_set(rx,utf8_target);
704 reginfo->is_utf8_target = cBOOL(utf8_target);
705 reginfo->info_aux = NULL;
706 reginfo->strbeg = strbeg;
707 reginfo->strend = strend;
708 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
710 /* not actually used within intuit, but zero for safety anyway */
711 reginfo->poscache_maxiter = 0;
714 if ((!prog->anchored_utf8 && prog->anchored_substr)
715 || (!prog->float_utf8 && prog->float_substr))
716 to_utf8_substr(prog);
717 check = prog->check_utf8;
719 if (!prog->check_substr && prog->check_utf8) {
720 if (! to_byte_substr(prog)) {
721 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(fail);
724 check = prog->check_substr;
727 /* dump the various substring data */
728 DEBUG_OPTIMISE_MORE_r({
730 for (i=0; i<=2; i++) {
731 SV *sv = (utf8_target ? prog->substrs->data[i].utf8_substr
732 : prog->substrs->data[i].substr);
736 Perl_re_printf( aTHX_
737 " substrs[%d]: min=%" IVdf " max=%" IVdf " end shift=%" IVdf
738 " useful=%" IVdf " utf8=%d [%s]\n",
740 (IV)prog->substrs->data[i].min_offset,
741 (IV)prog->substrs->data[i].max_offset,
742 (IV)prog->substrs->data[i].end_shift,
749 if (prog->intflags & PREGf_ANCH) { /* Match at \G, beg-of-str or after \n */
751 /* ml_anch: check after \n?
753 * A note about PREGf_IMPLICIT: on an un-anchored pattern beginning
754 * with /.*.../, these flags will have been added by the
756 * /.*abc/, /.*abc/m: PREGf_IMPLICIT | PREGf_ANCH_MBOL
757 * /.*abc/s: PREGf_IMPLICIT | PREGf_ANCH_SBOL
759 ml_anch = (prog->intflags & PREGf_ANCH_MBOL)
760 && !(prog->intflags & PREGf_IMPLICIT);
762 if (!ml_anch && !(prog->intflags & PREGf_IMPLICIT)) {
763 /* we are only allowed to match at BOS or \G */
765 /* trivially reject if there's a BOS anchor and we're not at BOS.
767 * Note that we don't try to do a similar quick reject for
768 * \G, since generally the caller will have calculated strpos
769 * based on pos() and gofs, so the string is already correctly
770 * anchored by definition; and handling the exceptions would
771 * be too fiddly (e.g. REXEC_IGNOREPOS).
773 if ( strpos != strbeg
774 && (prog->intflags & PREGf_ANCH_SBOL))
776 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
777 " Not at start...\n"));
781 /* in the presence of an anchor, the anchored (relative to the
782 * start of the regex) substr must also be anchored relative
783 * to strpos. So quickly reject if substr isn't found there.
784 * This works for \G too, because the caller will already have
785 * subtracted gofs from pos, and gofs is the offset from the
786 * \G to the start of the regex. For example, in /.abc\Gdef/,
787 * where substr="abcdef", pos()=3, gofs=4, offset_min=1:
788 * caller will have set strpos=pos()-4; we look for the substr
789 * at position pos()-4+1, which lines up with the "a" */
791 if (prog->check_offset_min == prog->check_offset_max) {
792 /* Substring at constant offset from beg-of-str... */
793 SSize_t slen = SvCUR(check);
794 char *s = HOP3c(strpos, prog->check_offset_min, strend);
796 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
797 " Looking for check substr at fixed offset %" IVdf "...\n",
798 (IV)prog->check_offset_min));
801 /* In this case, the regex is anchored at the end too.
802 * Unless it's a multiline match, the lengths must match
803 * exactly, give or take a \n. NB: slen >= 1 since
804 * the last char of check is \n */
806 && ( strend - s > slen
807 || strend - s < slen - 1
808 || (strend - s == slen && strend[-1] != '\n')))
810 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
811 " String too long...\n"));
814 /* Now should match s[0..slen-2] */
817 if (slen && (strend - s < slen
818 || *SvPVX_const(check) != *s
819 || (slen > 1 && (memNE(SvPVX_const(check), s, slen)))))
821 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
822 " String not equal...\n"));
827 goto success_at_start;
832 end_shift = prog->check_end_shift;
834 #ifdef DEBUGGING /* 7/99: reports of failure (with the older version) */
836 Perl_croak(aTHX_ "panic: end_shift: %" IVdf " pattern:\n%s\n ",
837 (IV)end_shift, RX_PRECOMP(prog));
842 /* This is the (re)entry point of the main loop in this function.
843 * The goal of this loop is to:
844 * 1) find the "check" substring in the region rx_origin..strend
845 * (adjusted by start_shift / end_shift). If not found, reject
847 * 2) If it exists, look for the "other" substr too if defined; for
848 * example, if the check substr maps to the anchored substr, then
849 * check the floating substr, and vice-versa. If not found, go
850 * back to (1) with rx_origin suitably incremented.
851 * 3) If we find an rx_origin position that doesn't contradict
852 * either of the substrings, then check the possible additional
853 * constraints on rx_origin of /^.../m or a known start class.
854 * If these fail, then depending on which constraints fail, jump
855 * back to here, or to various other re-entry points further along
856 * that skip some of the first steps.
857 * 4) If we pass all those tests, update the BmUSEFUL() count on the
858 * substring. If the start position was determined to be at the
859 * beginning of the string - so, not rejected, but not optimised,
860 * since we have to run regmatch from position 0 - decrement the
861 * BmUSEFUL() count. Otherwise increment it.
865 /* first, look for the 'check' substring */
871 DEBUG_OPTIMISE_MORE_r({
872 Perl_re_printf( aTHX_
873 " At restart: rx_origin=%" IVdf " Check offset min: %" IVdf
874 " Start shift: %" IVdf " End shift %" IVdf
875 " Real end Shift: %" IVdf "\n",
876 (IV)(rx_origin - strbeg),
877 (IV)prog->check_offset_min,
880 (IV)prog->check_end_shift);
883 end_point = HOP3(strend, -end_shift, strbeg);
884 start_point = HOPMAYBE3(rx_origin, start_shift, end_point);
889 /* If the regex is absolutely anchored to either the start of the
890 * string (SBOL) or to pos() (ANCH_GPOS), then
891 * check_offset_max represents an upper bound on the string where
892 * the substr could start. For the ANCH_GPOS case, we assume that
893 * the caller of intuit will have already set strpos to
894 * pos()-gofs, so in this case strpos + offset_max will still be
895 * an upper bound on the substr.
898 && prog->intflags & PREGf_ANCH
899 && prog->check_offset_max != SSize_t_MAX)
901 SSize_t len = SvCUR(check) - !!SvTAIL(check);
902 const char * const anchor =
903 (prog->intflags & PREGf_ANCH_GPOS ? strpos : strbeg);
905 /* do a bytes rather than chars comparison. It's conservative;
906 * so it skips doing the HOP if the result can't possibly end
907 * up earlier than the old value of end_point.
909 if ((char*)end_point - anchor > prog->check_offset_max) {
910 end_point = HOP3lim((U8*)anchor,
911 prog->check_offset_max,
917 check_at = fbm_instr( start_point, end_point,
918 check, multiline ? FBMrf_MULTILINE : 0);
920 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
921 " doing 'check' fbm scan, [%" IVdf "..%" IVdf "] gave %" IVdf "\n",
922 (IV)((char*)start_point - strbeg),
923 (IV)((char*)end_point - strbeg),
924 (IV)(check_at ? check_at - strbeg : -1)
927 /* Update the count-of-usability, remove useless subpatterns,
931 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
932 SvPVX_const(check), RE_SV_DUMPLEN(check), 30);
933 Perl_re_printf( aTHX_ " %s %s substr %s%s%s",
934 (check_at ? "Found" : "Did not find"),
935 (check == (utf8_target ? prog->anchored_utf8 : prog->anchored_substr)
936 ? "anchored" : "floating"),
939 (check_at ? " at offset " : "...\n") );
944 /* set rx_origin to the minimum position where the regex could start
945 * matching, given the constraint of the just-matched check substring.
946 * But don't set it lower than previously.
949 if (check_at - rx_origin > prog->check_offset_max)
950 rx_origin = HOP3c(check_at, -prog->check_offset_max, rx_origin);
951 /* Finish the diagnostic message */
952 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
953 "%ld (rx_origin now %" IVdf ")...\n",
954 (long)(check_at - strbeg),
955 (IV)(rx_origin - strbeg)
960 /* now look for the 'other' substring if defined */
962 if (utf8_target ? prog->substrs->data[other_ix].utf8_substr
963 : prog->substrs->data[other_ix].substr)
965 /* Take into account the "other" substring. */
969 struct reg_substr_datum *other;
972 other = &prog->substrs->data[other_ix];
974 /* if "other" is anchored:
975 * we've previously found a floating substr starting at check_at.
976 * This means that the regex origin must lie somewhere
977 * between min (rx_origin): HOP3(check_at, -check_offset_max)
978 * and max: HOP3(check_at, -check_offset_min)
979 * (except that min will be >= strpos)
980 * So the fixed substr must lie somewhere between
981 * HOP3(min, anchored_offset)
982 * HOP3(max, anchored_offset) + SvCUR(substr)
985 /* if "other" is floating
986 * Calculate last1, the absolute latest point where the
987 * floating substr could start in the string, ignoring any
988 * constraints from the earlier fixed match. It is calculated
991 * strend - prog->minlen (in chars) is the absolute latest
992 * position within the string where the origin of the regex
993 * could appear. The latest start point for the floating
994 * substr is float_min_offset(*) on from the start of the
995 * regex. last1 simply combines thee two offsets.
997 * (*) You might think the latest start point should be
998 * float_max_offset from the regex origin, and technically
999 * you'd be correct. However, consider
1001 * Here, float min, max are 3,5 and minlen is 7.
1002 * This can match either
1006 * In the first case, the regex matches minlen chars; in the
1007 * second, minlen+1, in the third, minlen+2.
1008 * In the first case, the floating offset is 3 (which equals
1009 * float_min), in the second, 4, and in the third, 5 (which
1010 * equals float_max). In all cases, the floating string bcd
1011 * can never start more than 4 chars from the end of the
1012 * string, which equals minlen - float_min. As the substring
1013 * starts to match more than float_min from the start of the
1014 * regex, it makes the regex match more than minlen chars,
1015 * and the two cancel each other out. So we can always use
1016 * float_min - minlen, rather than float_max - minlen for the
1017 * latest position in the string.
1019 * Note that -minlen + float_min_offset is equivalent (AFAIKT)
1020 * to CHR_SVLEN(must) - !!SvTAIL(must) + prog->float_end_shift
1023 assert(prog->minlen >= other->min_offset);
1024 last1 = HOP3c(strend,
1025 other->min_offset - prog->minlen, strbeg);
1027 if (other_ix) {/* i.e. if (other-is-float) */
1028 /* last is the latest point where the floating substr could
1029 * start, *given* any constraints from the earlier fixed
1030 * match. This constraint is that the floating string starts
1031 * <= float_max_offset chars from the regex origin (rx_origin).
1032 * If this value is less than last1, use it instead.
1034 assert(rx_origin <= last1);
1036 /* this condition handles the offset==infinity case, and
1037 * is a short-cut otherwise. Although it's comparing a
1038 * byte offset to a char length, it does so in a safe way,
1039 * since 1 char always occupies 1 or more bytes,
1040 * so if a string range is (last1 - rx_origin) bytes,
1041 * it will be less than or equal to (last1 - rx_origin)
1042 * chars; meaning it errs towards doing the accurate HOP3
1043 * rather than just using last1 as a short-cut */
1044 (last1 - rx_origin) < other->max_offset
1046 : (char*)HOP3lim(rx_origin, other->max_offset, last1);
1049 assert(strpos + start_shift <= check_at);
1050 last = HOP4c(check_at, other->min_offset - start_shift,
1054 s = HOP3c(rx_origin, other->min_offset, strend);
1055 if (s < other_last) /* These positions already checked */
1058 must = utf8_target ? other->utf8_substr : other->substr;
1059 assert(SvPOK(must));
1062 char *to = last + SvCUR(must) - (SvTAIL(must)!=0);
1068 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1069 " skipping 'other' fbm scan: %" IVdf " > %" IVdf "\n",
1070 (IV)(from - strbeg),
1076 (unsigned char*)from,
1079 multiline ? FBMrf_MULTILINE : 0
1081 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1082 " doing 'other' fbm scan, [%" IVdf "..%" IVdf "] gave %" IVdf "\n",
1083 (IV)(from - strbeg),
1085 (IV)(s ? s - strbeg : -1)
1091 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
1092 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
1093 Perl_re_printf( aTHX_ " %s %s substr %s%s",
1094 s ? "Found" : "Contradicts",
1095 other_ix ? "floating" : "anchored",
1096 quoted, RE_SV_TAIL(must));
1101 /* last1 is latest possible substr location. If we didn't
1102 * find it before there, we never will */
1103 if (last >= last1) {
1104 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1105 "; giving up...\n"));
1109 /* try to find the check substr again at a later
1110 * position. Maybe next time we'll find the "other" substr
1112 other_last = HOP3c(last, 1, strend) /* highest failure */;
1114 other_ix /* i.e. if other-is-float */
1115 ? HOP3c(rx_origin, 1, strend)
1116 : HOP4c(last, 1 - other->min_offset, strbeg, strend);
1117 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1118 "; about to retry %s at offset %ld (rx_origin now %" IVdf ")...\n",
1119 (other_ix ? "floating" : "anchored"),
1120 (long)(HOP3c(check_at, 1, strend) - strbeg),
1121 (IV)(rx_origin - strbeg)
1126 if (other_ix) { /* if (other-is-float) */
1127 /* other_last is set to s, not s+1, since its possible for
1128 * a floating substr to fail first time, then succeed
1129 * second time at the same floating position; e.g.:
1130 * "-AB--AABZ" =~ /\wAB\d*Z/
1131 * The first time round, anchored and float match at
1132 * "-(AB)--AAB(Z)" then fail on the initial \w character
1133 * class. Second time round, they match at "-AB--A(AB)(Z)".
1138 rx_origin = HOP3c(s, -other->min_offset, strbeg);
1139 other_last = HOP3c(s, 1, strend);
1141 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1142 " at offset %ld (rx_origin now %" IVdf ")...\n",
1144 (IV)(rx_origin - strbeg)
1150 DEBUG_OPTIMISE_MORE_r(
1151 Perl_re_printf( aTHX_
1152 " Check-only match: offset min:%" IVdf " max:%" IVdf
1153 " check_at:%" IVdf " rx_origin:%" IVdf " rx_origin-check_at:%" IVdf
1154 " strend:%" IVdf "\n",
1155 (IV)prog->check_offset_min,
1156 (IV)prog->check_offset_max,
1157 (IV)(check_at-strbeg),
1158 (IV)(rx_origin-strbeg),
1159 (IV)(rx_origin-check_at),
1165 postprocess_substr_matches:
1167 /* handle the extra constraint of /^.../m if present */
1169 if (ml_anch && rx_origin != strbeg && rx_origin[-1] != '\n') {
1172 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1173 " looking for /^/m anchor"));
1175 /* we have failed the constraint of a \n before rx_origin.
1176 * Find the next \n, if any, even if it's beyond the current
1177 * anchored and/or floating substrings. Whether we should be
1178 * scanning ahead for the next \n or the next substr is debatable.
1179 * On the one hand you'd expect rare substrings to appear less
1180 * often than \n's. On the other hand, searching for \n means
1181 * we're effectively flipping between check_substr and "\n" on each
1182 * iteration as the current "rarest" string candidate, which
1183 * means for example that we'll quickly reject the whole string if
1184 * hasn't got a \n, rather than trying every substr position
1188 s = HOP3c(strend, - prog->minlen, strpos);
1189 if (s <= rx_origin ||
1190 ! ( rx_origin = (char *)memchr(rx_origin, '\n', s - rx_origin)))
1192 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1193 " Did not find /%s^%s/m...\n",
1194 PL_colors[0], PL_colors[1]));
1198 /* earliest possible origin is 1 char after the \n.
1199 * (since *rx_origin == '\n', it's safe to ++ here rather than
1200 * HOP(rx_origin, 1)) */
1203 if (prog->substrs->check_ix == 0 /* check is anchored */
1204 || rx_origin >= HOP3c(check_at, - prog->check_offset_min, strpos))
1206 /* Position contradicts check-string; either because
1207 * check was anchored (and thus has no wiggle room),
1208 * or check was float and rx_origin is above the float range */
1209 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1210 " Found /%s^%s/m, about to restart lookup for check-string with rx_origin %ld...\n",
1211 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1215 /* if we get here, the check substr must have been float,
1216 * is in range, and we may or may not have had an anchored
1217 * "other" substr which still contradicts */
1218 assert(prog->substrs->check_ix); /* check is float */
1220 if (utf8_target ? prog->anchored_utf8 : prog->anchored_substr) {
1221 /* whoops, the anchored "other" substr exists, so we still
1222 * contradict. On the other hand, the float "check" substr
1223 * didn't contradict, so just retry the anchored "other"
1225 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1226 " Found /%s^%s/m, rescanning for anchored from offset %" IVdf " (rx_origin now %" IVdf ")...\n",
1227 PL_colors[0], PL_colors[1],
1228 (IV)(rx_origin - strbeg + prog->anchored_offset),
1229 (IV)(rx_origin - strbeg)
1231 goto do_other_substr;
1234 /* success: we don't contradict the found floating substring
1235 * (and there's no anchored substr). */
1236 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1237 " Found /%s^%s/m with rx_origin %ld...\n",
1238 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1241 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1242 " (multiline anchor test skipped)\n"));
1248 /* if we have a starting character class, then test that extra constraint.
1249 * (trie stclasses are too expensive to use here, we are better off to
1250 * leave it to regmatch itself) */
1252 if (progi->regstclass && PL_regkind[OP(progi->regstclass)]!=TRIE) {
1253 const U8* const str = (U8*)STRING(progi->regstclass);
1255 /* XXX this value could be pre-computed */
1256 const int cl_l = (PL_regkind[OP(progi->regstclass)] == EXACT
1257 ? (reginfo->is_utf8_pat
1258 ? utf8_distance(str + STR_LEN(progi->regstclass), str)
1259 : STR_LEN(progi->regstclass))
1263 /* latest pos that a matching float substr constrains rx start to */
1264 char *rx_max_float = NULL;
1266 /* if the current rx_origin is anchored, either by satisfying an
1267 * anchored substring constraint, or a /^.../m constraint, then we
1268 * can reject the current origin if the start class isn't found
1269 * at the current position. If we have a float-only match, then
1270 * rx_origin is constrained to a range; so look for the start class
1271 * in that range. if neither, then look for the start class in the
1272 * whole rest of the string */
1274 /* XXX DAPM it's not clear what the minlen test is for, and why
1275 * it's not used in the floating case. Nothing in the test suite
1276 * causes minlen == 0 here. See <20140313134639.GS12844@iabyn.com>.
1277 * Here are some old comments, which may or may not be correct:
1279 * minlen == 0 is possible if regstclass is \b or \B,
1280 * and the fixed substr is ''$.
1281 * Since minlen is already taken into account, rx_origin+1 is
1282 * before strend; accidentally, minlen >= 1 guaranties no false
1283 * positives at rx_origin + 1 even for \b or \B. But (minlen? 1 :
1284 * 0) below assumes that regstclass does not come from lookahead...
1285 * If regstclass takes bytelength more than 1: If charlength==1, OK.
1286 * This leaves EXACTF-ish only, which are dealt with in
1290 if (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
1291 endpos= HOP3c(rx_origin, (prog->minlen ? cl_l : 0), strend);
1292 else if (prog->float_substr || prog->float_utf8) {
1293 rx_max_float = HOP3c(check_at, -start_shift, strbeg);
1294 endpos= HOP3c(rx_max_float, cl_l, strend);
1299 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1300 " looking for class: start_shift: %" IVdf " check_at: %" IVdf
1301 " rx_origin: %" IVdf " endpos: %" IVdf "\n",
1302 (IV)start_shift, (IV)(check_at - strbeg),
1303 (IV)(rx_origin - strbeg), (IV)(endpos - strbeg)));
1305 s = find_byclass(prog, progi->regstclass, rx_origin, endpos,
1308 if (endpos == strend) {
1309 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1310 " Could not match STCLASS...\n") );
1313 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1314 " This position contradicts STCLASS...\n") );
1315 if ((prog->intflags & PREGf_ANCH) && !ml_anch
1316 && !(prog->intflags & PREGf_IMPLICIT))
1319 /* Contradict one of substrings */
1320 if (prog->anchored_substr || prog->anchored_utf8) {
1321 if (prog->substrs->check_ix == 1) { /* check is float */
1322 /* Have both, check_string is floating */
1323 assert(rx_origin + start_shift <= check_at);
1324 if (rx_origin + start_shift != check_at) {
1325 /* not at latest position float substr could match:
1326 * Recheck anchored substring, but not floating.
1327 * The condition above is in bytes rather than
1328 * chars for efficiency. It's conservative, in
1329 * that it errs on the side of doing 'goto
1330 * do_other_substr'. In this case, at worst,
1331 * an extra anchored search may get done, but in
1332 * practice the extra fbm_instr() is likely to
1333 * get skipped anyway. */
1334 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1335 " about to retry anchored at offset %ld (rx_origin now %" IVdf ")...\n",
1336 (long)(other_last - strbeg),
1337 (IV)(rx_origin - strbeg)
1339 goto do_other_substr;
1347 /* In the presence of ml_anch, we might be able to
1348 * find another \n without breaking the current float
1351 /* strictly speaking this should be HOP3c(..., 1, ...),
1352 * but since we goto a block of code that's going to
1353 * search for the next \n if any, its safe here */
1355 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1356 " about to look for /%s^%s/m starting at rx_origin %ld...\n",
1357 PL_colors[0], PL_colors[1],
1358 (long)(rx_origin - strbeg)) );
1359 goto postprocess_substr_matches;
1362 /* strictly speaking this can never be true; but might
1363 * be if we ever allow intuit without substrings */
1364 if (!(utf8_target ? prog->float_utf8 : prog->float_substr))
1367 rx_origin = rx_max_float;
1370 /* at this point, any matching substrings have been
1371 * contradicted. Start again... */
1373 rx_origin = HOP3c(rx_origin, 1, strend);
1375 /* uses bytes rather than char calculations for efficiency.
1376 * It's conservative: it errs on the side of doing 'goto restart',
1377 * where there is code that does a proper char-based test */
1378 if (rx_origin + start_shift + end_shift > strend) {
1379 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1380 " Could not match STCLASS...\n") );
1383 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1384 " about to look for %s substr starting at offset %ld (rx_origin now %" IVdf ")...\n",
1385 (prog->substrs->check_ix ? "floating" : "anchored"),
1386 (long)(rx_origin + start_shift - strbeg),
1387 (IV)(rx_origin - strbeg)
1394 if (rx_origin != s) {
1395 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1396 " By STCLASS: moving %ld --> %ld\n",
1397 (long)(rx_origin - strbeg), (long)(s - strbeg))
1401 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1402 " Does not contradict STCLASS...\n");
1407 /* Decide whether using the substrings helped */
1409 if (rx_origin != strpos) {
1410 /* Fixed substring is found far enough so that the match
1411 cannot start at strpos. */
1413 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ " try at offset...\n"));
1414 ++BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr); /* hooray/5 */
1417 /* The found rx_origin position does not prohibit matching at
1418 * strpos, so calling intuit didn't gain us anything. Decrement
1419 * the BmUSEFUL() count on the check substring, and if we reach
1421 if (!(prog->intflags & PREGf_NAUGHTY)
1423 prog->check_utf8 /* Could be deleted already */
1424 && --BmUSEFUL(prog->check_utf8) < 0
1425 && (prog->check_utf8 == prog->float_utf8)
1427 prog->check_substr /* Could be deleted already */
1428 && --BmUSEFUL(prog->check_substr) < 0
1429 && (prog->check_substr == prog->float_substr)
1432 /* If flags & SOMETHING - do not do it many times on the same match */
1433 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ " ... Disabling check substring...\n"));
1434 /* XXX Does the destruction order has to change with utf8_target? */
1435 SvREFCNT_dec(utf8_target ? prog->check_utf8 : prog->check_substr);
1436 SvREFCNT_dec(utf8_target ? prog->check_substr : prog->check_utf8);
1437 prog->check_substr = prog->check_utf8 = NULL; /* disable */
1438 prog->float_substr = prog->float_utf8 = NULL; /* clear */
1439 check = NULL; /* abort */
1440 /* XXXX This is a remnant of the old implementation. It
1441 looks wasteful, since now INTUIT can use many
1442 other heuristics. */
1443 prog->extflags &= ~RXf_USE_INTUIT;
1447 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1448 "Intuit: %sSuccessfully guessed:%s match at offset %ld\n",
1449 PL_colors[4], PL_colors[5], (long)(rx_origin - strbeg)) );
1453 fail_finish: /* Substring not found */
1454 if (prog->check_substr || prog->check_utf8) /* could be removed already */
1455 BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
1457 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%sMatch rejected by optimizer%s\n",
1458 PL_colors[4], PL_colors[5]));
1463 #define DECL_TRIE_TYPE(scan) \
1464 const enum { trie_plain, trie_utf8, trie_utf8_fold, trie_latin_utf8_fold, \
1465 trie_utf8_exactfa_fold, trie_latin_utf8_exactfa_fold, \
1466 trie_utf8l, trie_flu8 } \
1467 trie_type = ((scan->flags == EXACT) \
1468 ? (utf8_target ? trie_utf8 : trie_plain) \
1469 : (scan->flags == EXACTL) \
1470 ? (utf8_target ? trie_utf8l : trie_plain) \
1471 : (scan->flags == EXACTFA) \
1473 ? trie_utf8_exactfa_fold \
1474 : trie_latin_utf8_exactfa_fold) \
1475 : (scan->flags == EXACTFLU8 \
1479 : trie_latin_utf8_fold)))
1481 #define REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc, uscan, len, uvc, charid, foldlen, foldbuf, uniflags) \
1484 U8 flags = FOLD_FLAGS_FULL; \
1485 switch (trie_type) { \
1487 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1488 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1489 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1491 goto do_trie_utf8_fold; \
1492 case trie_utf8_exactfa_fold: \
1493 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1495 case trie_utf8_fold: \
1496 do_trie_utf8_fold: \
1497 if ( foldlen>0 ) { \
1498 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1503 uvc = _to_utf8_fold_flags( (const U8*) uc, foldbuf, &foldlen, flags); \
1504 len = UTF8SKIP(uc); \
1505 skiplen = UVCHR_SKIP( uvc ); \
1506 foldlen -= skiplen; \
1507 uscan = foldbuf + skiplen; \
1510 case trie_latin_utf8_exactfa_fold: \
1511 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1513 case trie_latin_utf8_fold: \
1514 if ( foldlen>0 ) { \
1515 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1521 uvc = _to_fold_latin1( (U8) *uc, foldbuf, &foldlen, flags); \
1522 skiplen = UVCHR_SKIP( uvc ); \
1523 foldlen -= skiplen; \
1524 uscan = foldbuf + skiplen; \
1528 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1529 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1530 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1534 uvc = utf8n_to_uvchr( (const U8*) uc, UTF8_MAXLEN, &len, uniflags ); \
1541 charid = trie->charmap[ uvc ]; \
1545 if (widecharmap) { \
1546 SV** const svpp = hv_fetch(widecharmap, \
1547 (char*)&uvc, sizeof(UV), 0); \
1549 charid = (U16)SvIV(*svpp); \
1554 #define DUMP_EXEC_POS(li,s,doutf8,depth) \
1555 dump_exec_pos(li,s,(reginfo->strend),(reginfo->strbeg), \
1556 startpos, doutf8, depth)
1558 #define REXEC_FBC_EXACTISH_SCAN(COND) \
1562 && (ln == 1 || folder(s, pat_string, ln)) \
1563 && (reginfo->intuit || regtry(reginfo, &s)) )\
1569 #define REXEC_FBC_UTF8_SCAN(CODE) \
1571 while (s < strend) { \
1577 #define REXEC_FBC_SCAN(CODE) \
1579 while (s < strend) { \
1585 #define REXEC_FBC_UTF8_CLASS_SCAN(COND) \
1586 REXEC_FBC_UTF8_SCAN( /* Loops while (s < strend) */ \
1588 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1597 #define REXEC_FBC_CLASS_SCAN(COND) \
1598 REXEC_FBC_SCAN( /* Loops while (s < strend) */ \
1600 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1609 #define REXEC_FBC_CSCAN(CONDUTF8,COND) \
1610 if (utf8_target) { \
1611 REXEC_FBC_UTF8_CLASS_SCAN(CONDUTF8); \
1614 REXEC_FBC_CLASS_SCAN(COND); \
1617 /* The three macros below are slightly different versions of the same logic.
1619 * The first is for /a and /aa when the target string is UTF-8. This can only
1620 * match ascii, but it must advance based on UTF-8. The other two handle the
1621 * non-UTF-8 and the more generic UTF-8 cases. In all three, we are looking
1622 * for the boundary (or non-boundary) between a word and non-word character.
1623 * The utf8 and non-utf8 cases have the same logic, but the details must be
1624 * different. Find the "wordness" of the character just prior to this one, and
1625 * compare it with the wordness of this one. If they differ, we have a
1626 * boundary. At the beginning of the string, pretend that the previous
1627 * character was a new-line.
1629 * All these macros uncleanly have side-effects with each other and outside
1630 * variables. So far it's been too much trouble to clean-up
1632 * TEST_NON_UTF8 is the macro or function to call to test if its byte input is
1633 * a word character or not.
1634 * IF_SUCCESS is code to do if it finds that we are at a boundary between
1636 * IF_FAIL is code to do if we aren't at a boundary between word/non-word
1638 * Exactly one of the two IF_FOO parameters is a no-op, depending on whether we
1639 * are looking for a boundary or for a non-boundary. If we are looking for a
1640 * boundary, we want IF_FAIL to be the no-op, and for IF_SUCCESS to go out and
1641 * see if this tentative match actually works, and if so, to quit the loop
1642 * here. And vice-versa if we are looking for a non-boundary.
1644 * 'tmp' below in the next three macros in the REXEC_FBC_SCAN and
1645 * REXEC_FBC_UTF8_SCAN loops is a loop invariant, a bool giving the return of
1646 * TEST_NON_UTF8(s-1). To see this, note that that's what it is defined to be
1647 * at entry to the loop, and to get to the IF_FAIL branch, tmp must equal
1648 * TEST_NON_UTF8(s), and in the opposite branch, IF_SUCCESS, tmp is that
1649 * complement. But in that branch we complement tmp, meaning that at the
1650 * bottom of the loop tmp is always going to be equal to TEST_NON_UTF8(s),
1651 * which means at the top of the loop in the next iteration, it is
1652 * TEST_NON_UTF8(s-1) */
1653 #define FBC_UTF8_A(TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1654 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1655 tmp = TEST_NON_UTF8(tmp); \
1656 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1657 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1659 IF_SUCCESS; /* Is a boundary if values for s-1 and s differ */ \
1666 /* Like FBC_UTF8_A, but TEST_UV is a macro which takes a UV as its input, and
1667 * TEST_UTF8 is a macro that for the same input code points returns identically
1668 * to TEST_UV, but takes a pointer to a UTF-8 encoded string instead */
1669 #define FBC_UTF8(TEST_UV, TEST_UTF8, IF_SUCCESS, IF_FAIL) \
1670 if (s == reginfo->strbeg) { \
1673 else { /* Back-up to the start of the previous character */ \
1674 U8 * const r = reghop3((U8*)s, -1, (U8*)reginfo->strbeg); \
1675 tmp = utf8n_to_uvchr(r, (U8*) reginfo->strend - r, \
1676 0, UTF8_ALLOW_DEFAULT); \
1678 tmp = TEST_UV(tmp); \
1679 LOAD_UTF8_CHARCLASS_ALNUM(); \
1680 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1681 if (tmp == ! (TEST_UTF8((U8 *) s, (U8 *) reginfo->strend))) { \
1690 /* Like the above two macros. UTF8_CODE is the complete code for handling
1691 * UTF-8. Common to the BOUND and NBOUND cases, set-up by the FBC_BOUND, etc
1693 #define FBC_BOUND_COMMON(UTF8_CODE, TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1694 if (utf8_target) { \
1697 else { /* Not utf8 */ \
1698 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1699 tmp = TEST_NON_UTF8(tmp); \
1700 REXEC_FBC_SCAN( /* advances s while s < strend */ \
1701 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1710 /* Here, things have been set up by the previous code so that tmp is the \
1711 * return of TEST_NON_UTF(s-1) or TEST_UTF8(s-1) (depending on the \
1712 * utf8ness of the target). We also have to check if this matches against \
1713 * the EOS, which we treat as a \n (which is the same value in both UTF-8 \
1714 * or non-UTF8, so can use the non-utf8 test condition even for a UTF-8 \
1716 if (tmp == ! TEST_NON_UTF8('\n')) { \
1723 /* This is the macro to use when we want to see if something that looks like it
1724 * could match, actually does, and if so exits the loop */
1725 #define REXEC_FBC_TRYIT \
1726 if ((reginfo->intuit || regtry(reginfo, &s))) \
1729 /* The only difference between the BOUND and NBOUND cases is that
1730 * REXEC_FBC_TRYIT is called when matched in BOUND, and when non-matched in
1731 * NBOUND. This is accomplished by passing it as either the if or else clause,
1732 * with the other one being empty (PLACEHOLDER is defined as empty).
1734 * The TEST_FOO parameters are for operating on different forms of input, but
1735 * all should be ones that return identically for the same underlying code
1737 #define FBC_BOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1739 FBC_UTF8(TEST_UV, TEST_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1740 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1742 #define FBC_BOUND_A(TEST_NON_UTF8) \
1744 FBC_UTF8_A(TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1745 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1747 #define FBC_NBOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1749 FBC_UTF8(TEST_UV, TEST_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1750 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1752 #define FBC_NBOUND_A(TEST_NON_UTF8) \
1754 FBC_UTF8_A(TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1755 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1759 S_get_break_val_cp_checked(SV* const invlist, const UV cp_in) {
1760 IV cp_out = Perl__invlist_search(invlist, cp_in);
1761 assert(cp_out >= 0);
1764 # define _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp) \
1765 invmap[S_get_break_val_cp_checked(invlist, cp)]
1767 # define _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp) \
1768 invmap[_invlist_search(invlist, cp)]
1771 /* Takes a pointer to an inversion list, a pointer to its corresponding
1772 * inversion map, and a code point, and returns the code point's value
1773 * according to the two arrays. It assumes that all code points have a value.
1774 * This is used as the base macro for macros for particular properties */
1775 #define _generic_GET_BREAK_VAL_CP(invlist, invmap, cp) \
1776 _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp)
1778 /* Same as above, but takes begin, end ptrs to a UTF-8 encoded string instead
1779 * of a code point, returning the value for the first code point in the string.
1780 * And it takes the particular macro name that finds the desired value given a
1781 * code point. Merely convert the UTF-8 to code point and call the cp macro */
1782 #define _generic_GET_BREAK_VAL_UTF8(cp_macro, pos, strend) \
1783 (__ASSERT_(pos < strend) \
1784 /* Note assumes is valid UTF-8 */ \
1785 (cp_macro(utf8_to_uvchr_buf((pos), (strend), NULL))))
1787 /* Returns the GCB value for the input code point */
1788 #define getGCB_VAL_CP(cp) \
1789 _generic_GET_BREAK_VAL_CP( \
1794 /* Returns the GCB value for the first code point in the UTF-8 encoded string
1795 * bounded by pos and strend */
1796 #define getGCB_VAL_UTF8(pos, strend) \
1797 _generic_GET_BREAK_VAL_UTF8(getGCB_VAL_CP, pos, strend)
1799 /* Returns the LB value for the input code point */
1800 #define getLB_VAL_CP(cp) \
1801 _generic_GET_BREAK_VAL_CP( \
1806 /* Returns the LB value for the first code point in the UTF-8 encoded string
1807 * bounded by pos and strend */
1808 #define getLB_VAL_UTF8(pos, strend) \
1809 _generic_GET_BREAK_VAL_UTF8(getLB_VAL_CP, pos, strend)
1812 /* Returns the SB value for the input code point */
1813 #define getSB_VAL_CP(cp) \
1814 _generic_GET_BREAK_VAL_CP( \
1819 /* Returns the SB value for the first code point in the UTF-8 encoded string
1820 * bounded by pos and strend */
1821 #define getSB_VAL_UTF8(pos, strend) \
1822 _generic_GET_BREAK_VAL_UTF8(getSB_VAL_CP, pos, strend)
1824 /* Returns the WB value for the input code point */
1825 #define getWB_VAL_CP(cp) \
1826 _generic_GET_BREAK_VAL_CP( \
1831 /* Returns the WB value for the first code point in the UTF-8 encoded string
1832 * bounded by pos and strend */
1833 #define getWB_VAL_UTF8(pos, strend) \
1834 _generic_GET_BREAK_VAL_UTF8(getWB_VAL_CP, pos, strend)
1836 /* We know what class REx starts with. Try to find this position... */
1837 /* if reginfo->intuit, its a dryrun */
1838 /* annoyingly all the vars in this routine have different names from their counterparts
1839 in regmatch. /grrr */
1841 S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
1842 const char *strend, regmatch_info *reginfo)
1845 const I32 doevery = (prog->intflags & PREGf_SKIP) == 0;
1846 char *pat_string; /* The pattern's exactish string */
1847 char *pat_end; /* ptr to end char of pat_string */
1848 re_fold_t folder; /* Function for computing non-utf8 folds */
1849 const U8 *fold_array; /* array for folding ords < 256 */
1855 I32 tmp = 1; /* Scratch variable? */
1856 const bool utf8_target = reginfo->is_utf8_target;
1857 UV utf8_fold_flags = 0;
1858 const bool is_utf8_pat = reginfo->is_utf8_pat;
1859 bool to_complement = FALSE; /* Invert the result? Taking the xor of this
1860 with a result inverts that result, as 0^1 =
1862 _char_class_number classnum;
1864 RXi_GET_DECL(prog,progi);
1866 PERL_ARGS_ASSERT_FIND_BYCLASS;
1868 /* We know what class it must start with. */
1871 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1873 if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(c)) && ! IN_UTF8_CTYPE_LOCALE) {
1874 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
1881 REXEC_FBC_UTF8_CLASS_SCAN(
1882 reginclass(prog, c, (U8*)s, (U8*) strend, utf8_target));
1884 else if (ANYOF_FLAGS(c)) {
1885 REXEC_FBC_CLASS_SCAN(reginclass(prog,c, (U8*)s, (U8*)s+1, 0));
1888 REXEC_FBC_CLASS_SCAN(ANYOF_BITMAP_TEST(c, *((U8*)s)));
1892 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
1893 assert(! is_utf8_pat);
1896 if (is_utf8_pat || utf8_target) {
1897 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
1898 goto do_exactf_utf8;
1900 fold_array = PL_fold_latin1; /* Latin1 folds are not affected by */
1901 folder = foldEQ_latin1; /* /a, except the sharp s one which */
1902 goto do_exactf_non_utf8; /* isn't dealt with by these */
1904 case EXACTF: /* This node only generated for non-utf8 patterns */
1905 assert(! is_utf8_pat);
1907 utf8_fold_flags = 0;
1908 goto do_exactf_utf8;
1910 fold_array = PL_fold;
1912 goto do_exactf_non_utf8;
1915 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1916 if (is_utf8_pat || utf8_target || IN_UTF8_CTYPE_LOCALE) {
1917 utf8_fold_flags = FOLDEQ_LOCALE;
1918 goto do_exactf_utf8;
1920 fold_array = PL_fold_locale;
1921 folder = foldEQ_locale;
1922 goto do_exactf_non_utf8;
1926 utf8_fold_flags = FOLDEQ_S2_ALREADY_FOLDED;
1928 goto do_exactf_utf8;
1931 if (! utf8_target) { /* All code points in this node require
1932 UTF-8 to express. */
1935 utf8_fold_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
1936 | FOLDEQ_S2_FOLDS_SANE;
1937 goto do_exactf_utf8;
1940 if (is_utf8_pat || utf8_target) {
1941 utf8_fold_flags = is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
1942 goto do_exactf_utf8;
1945 /* Any 'ss' in the pattern should have been replaced by regcomp,
1946 * so we don't have to worry here about this single special case
1947 * in the Latin1 range */
1948 fold_array = PL_fold_latin1;
1949 folder = foldEQ_latin1;
1953 do_exactf_non_utf8: /* Neither pattern nor string are UTF8, and there
1954 are no glitches with fold-length differences
1955 between the target string and pattern */
1957 /* The idea in the non-utf8 EXACTF* cases is to first find the
1958 * first character of the EXACTF* node and then, if necessary,
1959 * case-insensitively compare the full text of the node. c1 is the
1960 * first character. c2 is its fold. This logic will not work for
1961 * Unicode semantics and the german sharp ss, which hence should
1962 * not be compiled into a node that gets here. */
1963 pat_string = STRING(c);
1964 ln = STR_LEN(c); /* length to match in octets/bytes */
1966 /* We know that we have to match at least 'ln' bytes (which is the
1967 * same as characters, since not utf8). If we have to match 3
1968 * characters, and there are only 2 availabe, we know without
1969 * trying that it will fail; so don't start a match past the
1970 * required minimum number from the far end */
1971 e = HOP3c(strend, -((SSize_t)ln), s);
1973 if (reginfo->intuit && e < s) {
1974 e = s; /* Due to minlen logic of intuit() */
1978 c2 = fold_array[c1];
1979 if (c1 == c2) { /* If char and fold are the same */
1980 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1);
1983 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1 || *(U8*)s == c2);
1991 /* If one of the operands is in utf8, we can't use the simpler folding
1992 * above, due to the fact that many different characters can have the
1993 * same fold, or portion of a fold, or different- length fold */
1994 pat_string = STRING(c);
1995 ln = STR_LEN(c); /* length to match in octets/bytes */
1996 pat_end = pat_string + ln;
1997 lnc = is_utf8_pat /* length to match in characters */
1998 ? utf8_length((U8 *) pat_string, (U8 *) pat_end)
2001 /* We have 'lnc' characters to match in the pattern, but because of
2002 * multi-character folding, each character in the target can match
2003 * up to 3 characters (Unicode guarantees it will never exceed
2004 * this) if it is utf8-encoded; and up to 2 if not (based on the
2005 * fact that the Latin 1 folds are already determined, and the
2006 * only multi-char fold in that range is the sharp-s folding to
2007 * 'ss'. Thus, a pattern character can match as little as 1/3 of a
2008 * string character. Adjust lnc accordingly, rounding up, so that
2009 * if we need to match at least 4+1/3 chars, that really is 5. */
2010 expansion = (utf8_target) ? UTF8_MAX_FOLD_CHAR_EXPAND : 2;
2011 lnc = (lnc + expansion - 1) / expansion;
2013 /* As in the non-UTF8 case, if we have to match 3 characters, and
2014 * only 2 are left, it's guaranteed to fail, so don't start a
2015 * match that would require us to go beyond the end of the string
2017 e = HOP3c(strend, -((SSize_t)lnc), s);
2019 if (reginfo->intuit && e < s) {
2020 e = s; /* Due to minlen logic of intuit() */
2023 /* XXX Note that we could recalculate e to stop the loop earlier,
2024 * as the worst case expansion above will rarely be met, and as we
2025 * go along we would usually find that e moves further to the left.
2026 * This would happen only after we reached the point in the loop
2027 * where if there were no expansion we should fail. Unclear if
2028 * worth the expense */
2031 char *my_strend= (char *)strend;
2032 if (foldEQ_utf8_flags(s, &my_strend, 0, utf8_target,
2033 pat_string, NULL, ln, is_utf8_pat, utf8_fold_flags)
2034 && (reginfo->intuit || regtry(reginfo, &s)) )
2038 s += (utf8_target) ? UTF8SKIP(s) : 1;
2044 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2045 if (FLAGS(c) != TRADITIONAL_BOUND) {
2046 if (! IN_UTF8_CTYPE_LOCALE) {
2047 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2048 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2053 FBC_BOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8_safe);
2057 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2058 if (FLAGS(c) != TRADITIONAL_BOUND) {
2059 if (! IN_UTF8_CTYPE_LOCALE) {
2060 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2061 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2066 FBC_NBOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8_safe);
2069 case BOUND: /* regcomp.c makes sure that this only has the traditional \b
2071 assert(FLAGS(c) == TRADITIONAL_BOUND);
2073 FBC_BOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8_safe);
2076 case BOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2078 assert(FLAGS(c) == TRADITIONAL_BOUND);
2080 FBC_BOUND_A(isWORDCHAR_A);
2083 case NBOUND: /* regcomp.c makes sure that this only has the traditional \b
2085 assert(FLAGS(c) == TRADITIONAL_BOUND);
2087 FBC_NBOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8_safe);
2090 case NBOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2092 assert(FLAGS(c) == TRADITIONAL_BOUND);
2094 FBC_NBOUND_A(isWORDCHAR_A);
2098 if ((bound_type) FLAGS(c) == TRADITIONAL_BOUND) {
2099 FBC_NBOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8_safe);
2110 switch((bound_type) FLAGS(c)) {
2111 case TRADITIONAL_BOUND:
2112 FBC_BOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8_safe);
2115 if (s == reginfo->strbeg) {
2116 if (reginfo->intuit || regtry(reginfo, &s))
2121 /* Didn't match. Try at the next position (if there is one) */
2122 s += (utf8_target) ? UTF8SKIP(s) : 1;
2123 if (UNLIKELY(s >= reginfo->strend)) {
2129 GCB_enum before = getGCB_VAL_UTF8(
2131 (U8*)(reginfo->strbeg)),
2132 (U8*) reginfo->strend);
2133 while (s < strend) {
2134 GCB_enum after = getGCB_VAL_UTF8((U8*) s,
2135 (U8*) reginfo->strend);
2136 if ( (to_complement ^ isGCB(before,
2138 (U8*) reginfo->strbeg,
2141 && (reginfo->intuit || regtry(reginfo, &s)))
2149 else { /* Not utf8. Everything is a GCB except between CR and
2151 while (s < strend) {
2152 if ((to_complement ^ ( UCHARAT(s - 1) != '\r'
2153 || UCHARAT(s) != '\n'))
2154 && (reginfo->intuit || regtry(reginfo, &s)))
2162 /* And, since this is a bound, it can match after the final
2163 * character in the string */
2164 if ((reginfo->intuit || regtry(reginfo, &s))) {
2170 if (s == reginfo->strbeg) {
2171 if (reginfo->intuit || regtry(reginfo, &s)) {
2174 s += (utf8_target) ? UTF8SKIP(s) : 1;
2175 if (UNLIKELY(s >= reginfo->strend)) {
2181 LB_enum before = getLB_VAL_UTF8(reghop3((U8*)s,
2183 (U8*)(reginfo->strbeg)),
2184 (U8*) reginfo->strend);
2185 while (s < strend) {
2186 LB_enum after = getLB_VAL_UTF8((U8*) s, (U8*) reginfo->strend);
2187 if (to_complement ^ isLB(before,
2189 (U8*) reginfo->strbeg,
2191 (U8*) reginfo->strend,
2193 && (reginfo->intuit || regtry(reginfo, &s)))
2201 else { /* Not utf8. */
2202 LB_enum before = getLB_VAL_CP((U8) *(s -1));
2203 while (s < strend) {
2204 LB_enum after = getLB_VAL_CP((U8) *s);
2205 if (to_complement ^ isLB(before,
2207 (U8*) reginfo->strbeg,
2209 (U8*) reginfo->strend,
2211 && (reginfo->intuit || regtry(reginfo, &s)))
2220 if (reginfo->intuit || regtry(reginfo, &s)) {
2227 if (s == reginfo->strbeg) {
2228 if (reginfo->intuit || regtry(reginfo, &s)) {
2231 s += (utf8_target) ? UTF8SKIP(s) : 1;
2232 if (UNLIKELY(s >= reginfo->strend)) {
2238 SB_enum before = getSB_VAL_UTF8(reghop3((U8*)s,
2240 (U8*)(reginfo->strbeg)),
2241 (U8*) reginfo->strend);
2242 while (s < strend) {
2243 SB_enum after = getSB_VAL_UTF8((U8*) s,
2244 (U8*) reginfo->strend);
2245 if ((to_complement ^ isSB(before,
2247 (U8*) reginfo->strbeg,
2249 (U8*) reginfo->strend,
2251 && (reginfo->intuit || regtry(reginfo, &s)))
2259 else { /* Not utf8. */
2260 SB_enum before = getSB_VAL_CP((U8) *(s -1));
2261 while (s < strend) {
2262 SB_enum after = getSB_VAL_CP((U8) *s);
2263 if ((to_complement ^ isSB(before,
2265 (U8*) reginfo->strbeg,
2267 (U8*) reginfo->strend,
2269 && (reginfo->intuit || regtry(reginfo, &s)))
2278 /* Here are at the final position in the target string. The SB
2279 * value is always true here, so matches, depending on other
2281 if (reginfo->intuit || regtry(reginfo, &s)) {
2288 if (s == reginfo->strbeg) {
2289 if (reginfo->intuit || regtry(reginfo, &s)) {
2292 s += (utf8_target) ? UTF8SKIP(s) : 1;
2293 if (UNLIKELY(s >= reginfo->strend)) {
2299 /* We are at a boundary between char_sub_0 and char_sub_1.
2300 * We also keep track of the value for char_sub_-1 as we
2301 * loop through the line. Context may be needed to make a
2302 * determination, and if so, this can save having to
2304 WB_enum previous = WB_UNKNOWN;
2305 WB_enum before = getWB_VAL_UTF8(
2308 (U8*)(reginfo->strbeg)),
2309 (U8*) reginfo->strend);
2310 while (s < strend) {
2311 WB_enum after = getWB_VAL_UTF8((U8*) s,
2312 (U8*) reginfo->strend);
2313 if ((to_complement ^ isWB(previous,
2316 (U8*) reginfo->strbeg,
2318 (U8*) reginfo->strend,
2320 && (reginfo->intuit || regtry(reginfo, &s)))
2329 else { /* Not utf8. */
2330 WB_enum previous = WB_UNKNOWN;
2331 WB_enum before = getWB_VAL_CP((U8) *(s -1));
2332 while (s < strend) {
2333 WB_enum after = getWB_VAL_CP((U8) *s);
2334 if ((to_complement ^ isWB(previous,
2337 (U8*) reginfo->strbeg,
2339 (U8*) reginfo->strend,
2341 && (reginfo->intuit || regtry(reginfo, &s)))
2351 if (reginfo->intuit || regtry(reginfo, &s)) {
2358 REXEC_FBC_CSCAN(is_LNBREAK_utf8_safe(s, strend),
2359 is_LNBREAK_latin1_safe(s, strend)
2363 /* The argument to all the POSIX node types is the class number to pass to
2364 * _generic_isCC() to build a mask for searching in PL_charclass[] */
2371 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2372 REXEC_FBC_CSCAN(to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(c), (U8 *) s)),
2373 to_complement ^ cBOOL(isFOO_lc(FLAGS(c), *s)));
2388 /* The complement of something that matches only ASCII matches all
2389 * non-ASCII, plus everything in ASCII that isn't in the class. */
2390 REXEC_FBC_UTF8_CLASS_SCAN( ! isASCII_utf8_safe(s, strend)
2391 || ! _generic_isCC_A(*s, FLAGS(c)));
2400 /* Don't need to worry about utf8, as it can match only a single
2401 * byte invariant character. */
2402 REXEC_FBC_CLASS_SCAN(
2403 to_complement ^ cBOOL(_generic_isCC_A(*s, FLAGS(c))));
2411 if (! utf8_target) {
2412 REXEC_FBC_CLASS_SCAN(to_complement ^ cBOOL(_generic_isCC(*s,
2418 classnum = (_char_class_number) FLAGS(c);
2419 if (classnum < _FIRST_NON_SWASH_CC) {
2420 while (s < strend) {
2422 /* We avoid loading in the swash as long as possible, but
2423 * should we have to, we jump to a separate loop. This
2424 * extra 'if' statement is what keeps this code from being
2425 * just a call to REXEC_FBC_UTF8_CLASS_SCAN() */
2426 if (UTF8_IS_ABOVE_LATIN1(*s)) {
2427 goto found_above_latin1;
2429 if ((UTF8_IS_INVARIANT(*s)
2430 && to_complement ^ cBOOL(_generic_isCC((U8) *s,
2432 || (UTF8_IS_DOWNGRADEABLE_START(*s)
2433 && to_complement ^ cBOOL(
2434 _generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(*s,
2438 if (tmp && (reginfo->intuit || regtry(reginfo, &s)))
2450 else switch (classnum) { /* These classes are implemented as
2452 case _CC_ENUM_SPACE:
2453 REXEC_FBC_UTF8_CLASS_SCAN(
2454 to_complement ^ cBOOL(isSPACE_utf8_safe(s, strend)));
2457 case _CC_ENUM_BLANK:
2458 REXEC_FBC_UTF8_CLASS_SCAN(
2459 to_complement ^ cBOOL(isBLANK_utf8_safe(s, strend)));
2462 case _CC_ENUM_XDIGIT:
2463 REXEC_FBC_UTF8_CLASS_SCAN(
2464 to_complement ^ cBOOL(isXDIGIT_utf8_safe(s, strend)));
2467 case _CC_ENUM_VERTSPACE:
2468 REXEC_FBC_UTF8_CLASS_SCAN(
2469 to_complement ^ cBOOL(isVERTWS_utf8_safe(s, strend)));
2472 case _CC_ENUM_CNTRL:
2473 REXEC_FBC_UTF8_CLASS_SCAN(
2474 to_complement ^ cBOOL(isCNTRL_utf8_safe(s, strend)));
2478 Perl_croak(aTHX_ "panic: find_byclass() node %d='%s' has an unexpected character class '%d'", OP(c), PL_reg_name[OP(c)], classnum);
2479 NOT_REACHED; /* NOTREACHED */
2484 found_above_latin1: /* Here we have to load a swash to get the result
2485 for the current code point */
2486 if (! PL_utf8_swash_ptrs[classnum]) {
2487 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
2488 PL_utf8_swash_ptrs[classnum] =
2489 _core_swash_init("utf8",
2492 PL_XPosix_ptrs[classnum], &flags);
2495 /* This is a copy of the loop above for swash classes, though using the
2496 * FBC macro instead of being expanded out. Since we've loaded the
2497 * swash, we don't have to check for that each time through the loop */
2498 REXEC_FBC_UTF8_CLASS_SCAN(
2499 to_complement ^ cBOOL(_generic_utf8_safe(
2503 swash_fetch(PL_utf8_swash_ptrs[classnum],
2511 /* what trie are we using right now */
2512 reg_ac_data *aho = (reg_ac_data*)progi->data->data[ ARG( c ) ];
2513 reg_trie_data *trie = (reg_trie_data*)progi->data->data[ aho->trie ];
2514 HV *widecharmap = MUTABLE_HV(progi->data->data[ aho->trie + 1 ]);
2516 const char *last_start = strend - trie->minlen;
2518 const char *real_start = s;
2520 STRLEN maxlen = trie->maxlen;
2522 U8 **points; /* map of where we were in the input string
2523 when reading a given char. For ASCII this
2524 is unnecessary overhead as the relationship
2525 is always 1:1, but for Unicode, especially
2526 case folded Unicode this is not true. */
2527 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
2531 GET_RE_DEBUG_FLAGS_DECL;
2533 /* We can't just allocate points here. We need to wrap it in
2534 * an SV so it gets freed properly if there is a croak while
2535 * running the match */
2538 sv_points=newSV(maxlen * sizeof(U8 *));
2539 SvCUR_set(sv_points,
2540 maxlen * sizeof(U8 *));
2541 SvPOK_on(sv_points);
2542 sv_2mortal(sv_points);
2543 points=(U8**)SvPV_nolen(sv_points );
2544 if ( trie_type != trie_utf8_fold
2545 && (trie->bitmap || OP(c)==AHOCORASICKC) )
2548 bitmap=(U8*)trie->bitmap;
2550 bitmap=(U8*)ANYOF_BITMAP(c);
2552 /* this is the Aho-Corasick algorithm modified a touch
2553 to include special handling for long "unknown char" sequences.
2554 The basic idea being that we use AC as long as we are dealing
2555 with a possible matching char, when we encounter an unknown char
2556 (and we have not encountered an accepting state) we scan forward
2557 until we find a legal starting char.
2558 AC matching is basically that of trie matching, except that when
2559 we encounter a failing transition, we fall back to the current
2560 states "fail state", and try the current char again, a process
2561 we repeat until we reach the root state, state 1, or a legal
2562 transition. If we fail on the root state then we can either
2563 terminate if we have reached an accepting state previously, or
2564 restart the entire process from the beginning if we have not.
2567 while (s <= last_start) {
2568 const U32 uniflags = UTF8_ALLOW_DEFAULT;
2576 U8 *uscan = (U8*)NULL;
2577 U8 *leftmost = NULL;
2579 U32 accepted_word= 0;
2583 while ( state && uc <= (U8*)strend ) {
2585 U32 word = aho->states[ state ].wordnum;
2589 DEBUG_TRIE_EXECUTE_r(
2590 if ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2591 dump_exec_pos( (char *)uc, c, strend, real_start,
2592 (char *)uc, utf8_target, 0 );
2593 Perl_re_printf( aTHX_
2594 " Scanning for legal start char...\n");
2598 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2602 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2608 if (uc >(U8*)last_start) break;
2612 U8 *lpos= points[ (pointpos - trie->wordinfo[word].len) % maxlen ];
2613 if (!leftmost || lpos < leftmost) {
2614 DEBUG_r(accepted_word=word);
2620 points[pointpos++ % maxlen]= uc;
2621 if (foldlen || uc < (U8*)strend) {
2622 REXEC_TRIE_READ_CHAR(trie_type, trie,
2624 uscan, len, uvc, charid, foldlen,
2626 DEBUG_TRIE_EXECUTE_r({
2627 dump_exec_pos( (char *)uc, c, strend,
2628 real_start, s, utf8_target, 0);
2629 Perl_re_printf( aTHX_
2630 " Charid:%3u CP:%4" UVxf " ",
2642 word = aho->states[ state ].wordnum;
2644 base = aho->states[ state ].trans.base;
2646 DEBUG_TRIE_EXECUTE_r({
2648 dump_exec_pos( (char *)uc, c, strend, real_start,
2649 s, utf8_target, 0 );
2650 Perl_re_printf( aTHX_
2651 "%sState: %4" UVxf ", word=%" UVxf,
2652 failed ? " Fail transition to " : "",
2653 (UV)state, (UV)word);
2659 ( ((offset = base + charid
2660 - 1 - trie->uniquecharcount)) >= 0)
2661 && ((U32)offset < trie->lasttrans)
2662 && trie->trans[offset].check == state
2663 && (tmp=trie->trans[offset].next))
2665 DEBUG_TRIE_EXECUTE_r(
2666 Perl_re_printf( aTHX_ " - legal\n"));
2671 DEBUG_TRIE_EXECUTE_r(
2672 Perl_re_printf( aTHX_ " - fail\n"));
2674 state = aho->fail[state];
2678 /* we must be accepting here */
2679 DEBUG_TRIE_EXECUTE_r(
2680 Perl_re_printf( aTHX_ " - accepting\n"));
2689 if (!state) state = 1;
2692 if ( aho->states[ state ].wordnum ) {
2693 U8 *lpos = points[ (pointpos - trie->wordinfo[aho->states[ state ].wordnum].len) % maxlen ];
2694 if (!leftmost || lpos < leftmost) {
2695 DEBUG_r(accepted_word=aho->states[ state ].wordnum);
2700 s = (char*)leftmost;
2701 DEBUG_TRIE_EXECUTE_r({
2702 Perl_re_printf( aTHX_ "Matches word #%" UVxf " at position %" IVdf ". Trying full pattern...\n",
2703 (UV)accepted_word, (IV)(s - real_start)
2706 if (reginfo->intuit || regtry(reginfo, &s)) {
2712 DEBUG_TRIE_EXECUTE_r({
2713 Perl_re_printf( aTHX_ "Pattern failed. Looking for new start point...\n");
2716 DEBUG_TRIE_EXECUTE_r(
2717 Perl_re_printf( aTHX_ "No match.\n"));
2726 Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
2733 /* set RX_SAVED_COPY, RX_SUBBEG etc.
2734 * flags have same meanings as with regexec_flags() */
2737 S_reg_set_capture_string(pTHX_ REGEXP * const rx,
2744 struct regexp *const prog = ReANY(rx);
2746 if (flags & REXEC_COPY_STR) {
2749 DEBUG_C(Perl_re_printf( aTHX_
2750 "Copy on write: regexp capture, type %d\n",
2752 /* Create a new COW SV to share the match string and store
2753 * in saved_copy, unless the current COW SV in saved_copy
2754 * is valid and suitable for our purpose */
2755 if (( prog->saved_copy
2756 && SvIsCOW(prog->saved_copy)
2757 && SvPOKp(prog->saved_copy)
2760 && SvPVX(sv) == SvPVX(prog->saved_copy)))
2762 /* just reuse saved_copy SV */
2763 if (RXp_MATCH_COPIED(prog)) {
2764 Safefree(prog->subbeg);
2765 RXp_MATCH_COPIED_off(prog);
2769 /* create new COW SV to share string */
2770 RX_MATCH_COPY_FREE(rx);
2771 prog->saved_copy = sv_setsv_cow(prog->saved_copy, sv);
2773 prog->subbeg = (char *)SvPVX_const(prog->saved_copy);
2774 assert (SvPOKp(prog->saved_copy));
2775 prog->sublen = strend - strbeg;
2776 prog->suboffset = 0;
2777 prog->subcoffset = 0;
2782 SSize_t max = strend - strbeg;
2785 if ( (flags & REXEC_COPY_SKIP_POST)
2786 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2787 && !(PL_sawampersand & SAWAMPERSAND_RIGHT)
2788 ) { /* don't copy $' part of string */
2791 /* calculate the right-most part of the string covered
2792 * by a capture. Due to lookahead, this may be to
2793 * the right of $&, so we have to scan all captures */
2794 while (n <= prog->lastparen) {
2795 if (prog->offs[n].end > max)
2796 max = prog->offs[n].end;
2800 max = (PL_sawampersand & SAWAMPERSAND_LEFT)
2801 ? prog->offs[0].start
2803 assert(max >= 0 && max <= strend - strbeg);
2806 if ( (flags & REXEC_COPY_SKIP_PRE)
2807 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2808 && !(PL_sawampersand & SAWAMPERSAND_LEFT)
2809 ) { /* don't copy $` part of string */
2812 /* calculate the left-most part of the string covered
2813 * by a capture. Due to lookbehind, this may be to
2814 * the left of $&, so we have to scan all captures */
2815 while (min && n <= prog->lastparen) {
2816 if ( prog->offs[n].start != -1
2817 && prog->offs[n].start < min)
2819 min = prog->offs[n].start;
2823 if ((PL_sawampersand & SAWAMPERSAND_RIGHT)
2824 && min > prog->offs[0].end
2826 min = prog->offs[0].end;
2830 assert(min >= 0 && min <= max && min <= strend - strbeg);
2833 if (RX_MATCH_COPIED(rx)) {
2834 if (sublen > prog->sublen)
2836 (char*)saferealloc(prog->subbeg, sublen+1);
2839 prog->subbeg = (char*)safemalloc(sublen+1);
2840 Copy(strbeg + min, prog->subbeg, sublen, char);
2841 prog->subbeg[sublen] = '\0';
2842 prog->suboffset = min;
2843 prog->sublen = sublen;
2844 RX_MATCH_COPIED_on(rx);
2846 prog->subcoffset = prog->suboffset;
2847 if (prog->suboffset && utf8_target) {
2848 /* Convert byte offset to chars.
2849 * XXX ideally should only compute this if @-/@+
2850 * has been seen, a la PL_sawampersand ??? */
2852 /* If there's a direct correspondence between the
2853 * string which we're matching and the original SV,
2854 * then we can use the utf8 len cache associated with
2855 * the SV. In particular, it means that under //g,
2856 * sv_pos_b2u() will use the previously cached
2857 * position to speed up working out the new length of
2858 * subcoffset, rather than counting from the start of
2859 * the string each time. This stops
2860 * $x = "\x{100}" x 1E6; 1 while $x =~ /(.)/g;
2861 * from going quadratic */
2862 if (SvPOKp(sv) && SvPVX(sv) == strbeg)
2863 prog->subcoffset = sv_pos_b2u_flags(sv, prog->subcoffset,
2864 SV_GMAGIC|SV_CONST_RETURN);
2866 prog->subcoffset = utf8_length((U8*)strbeg,
2867 (U8*)(strbeg+prog->suboffset));
2871 RX_MATCH_COPY_FREE(rx);
2872 prog->subbeg = strbeg;
2873 prog->suboffset = 0;
2874 prog->subcoffset = 0;
2875 prog->sublen = strend - strbeg;
2883 - regexec_flags - match a regexp against a string
2886 Perl_regexec_flags(pTHX_ REGEXP * const rx, char *stringarg, char *strend,
2887 char *strbeg, SSize_t minend, SV *sv, void *data, U32 flags)
2888 /* stringarg: the point in the string at which to begin matching */
2889 /* strend: pointer to null at end of string */
2890 /* strbeg: real beginning of string */
2891 /* minend: end of match must be >= minend bytes after stringarg. */
2892 /* sv: SV being matched: only used for utf8 flag, pos() etc; string
2893 * itself is accessed via the pointers above */
2894 /* data: May be used for some additional optimizations.
2895 Currently unused. */
2896 /* flags: For optimizations. See REXEC_* in regexp.h */
2899 struct regexp *const prog = ReANY(rx);
2903 SSize_t minlen; /* must match at least this many chars */
2904 SSize_t dontbother = 0; /* how many characters not to try at end */
2905 const bool utf8_target = cBOOL(DO_UTF8(sv));
2907 RXi_GET_DECL(prog,progi);
2908 regmatch_info reginfo_buf; /* create some info to pass to regtry etc */
2909 regmatch_info *const reginfo = ®info_buf;
2910 regexp_paren_pair *swap = NULL;
2912 GET_RE_DEBUG_FLAGS_DECL;
2914 PERL_ARGS_ASSERT_REGEXEC_FLAGS;
2915 PERL_UNUSED_ARG(data);
2917 /* Be paranoid... */
2919 Perl_croak(aTHX_ "NULL regexp parameter");
2923 debug_start_match(rx, utf8_target, stringarg, strend,
2927 startpos = stringarg;
2929 /* set these early as they may be used by the HOP macros below */
2930 reginfo->strbeg = strbeg;
2931 reginfo->strend = strend;
2932 reginfo->is_utf8_target = cBOOL(utf8_target);
2934 if (prog->intflags & PREGf_GPOS_SEEN) {
2937 /* set reginfo->ganch, the position where \G can match */
2940 (flags & REXEC_IGNOREPOS)
2941 ? stringarg /* use start pos rather than pos() */
2942 : ((mg = mg_find_mglob(sv)) && mg->mg_len >= 0)
2943 /* Defined pos(): */
2944 ? strbeg + MgBYTEPOS(mg, sv, strbeg, strend-strbeg)
2945 : strbeg; /* pos() not defined; use start of string */
2947 DEBUG_GPOS_r(Perl_re_printf( aTHX_
2948 "GPOS ganch set to strbeg[%" IVdf "]\n", (IV)(reginfo->ganch - strbeg)));
2950 /* in the presence of \G, we may need to start looking earlier in
2951 * the string than the suggested start point of stringarg:
2952 * if prog->gofs is set, then that's a known, fixed minimum
2955 * /ab|c\G/: gofs = 1
2956 * or if the minimum offset isn't known, then we have to go back
2957 * to the start of the string, e.g. /w+\G/
2960 if (prog->intflags & PREGf_ANCH_GPOS) {
2962 startpos = HOPBACKc(reginfo->ganch, prog->gofs);
2964 ((flags & REXEC_FAIL_ON_UNDERFLOW) && startpos < stringarg))
2966 DEBUG_r(Perl_re_printf( aTHX_
2967 "fail: ganch-gofs before earliest possible start\n"));
2972 startpos = reginfo->ganch;
2974 else if (prog->gofs) {
2975 startpos = HOPBACKc(startpos, prog->gofs);
2979 else if (prog->intflags & PREGf_GPOS_FLOAT)
2983 minlen = prog->minlen;
2984 if ((startpos + minlen) > strend || startpos < strbeg) {
2985 DEBUG_r(Perl_re_printf( aTHX_
2986 "Regex match can't succeed, so not even tried\n"));
2990 /* at the end of this function, we'll do a LEAVE_SCOPE(oldsave),
2991 * which will call destuctors to reset PL_regmatch_state, free higher
2992 * PL_regmatch_slabs, and clean up regmatch_info_aux and
2993 * regmatch_info_aux_eval */
2995 oldsave = PL_savestack_ix;
2999 if ((prog->extflags & RXf_USE_INTUIT)
3000 && !(flags & REXEC_CHECKED))
3002 s = re_intuit_start(rx, sv, strbeg, startpos, strend,
3007 if (prog->extflags & RXf_CHECK_ALL) {
3008 /* we can match based purely on the result of INTUIT.
3009 * Set up captures etc just for $& and $-[0]
3010 * (an intuit-only match wont have $1,$2,..) */
3011 assert(!prog->nparens);
3013 /* s/// doesn't like it if $& is earlier than where we asked it to
3014 * start searching (which can happen on something like /.\G/) */
3015 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
3018 /* this should only be possible under \G */
3019 assert(prog->intflags & PREGf_GPOS_SEEN);
3020 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
3021 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3025 /* match via INTUIT shouldn't have any captures.
3026 * Let @-, @+, $^N know */
3027 prog->lastparen = prog->lastcloseparen = 0;
3028 RX_MATCH_UTF8_set(rx, utf8_target);
3029 prog->offs[0].start = s - strbeg;
3030 prog->offs[0].end = utf8_target
3031 ? (char*)utf8_hop((U8*)s, prog->minlenret) - strbeg
3032 : s - strbeg + prog->minlenret;
3033 if ( !(flags & REXEC_NOT_FIRST) )
3034 S_reg_set_capture_string(aTHX_ rx,
3036 sv, flags, utf8_target);
3042 multiline = prog->extflags & RXf_PMf_MULTILINE;
3044 if (strend - s < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
3045 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
3046 "String too short [regexec_flags]...\n"));
3050 /* Check validity of program. */
3051 if (UCHARAT(progi->program) != REG_MAGIC) {
3052 Perl_croak(aTHX_ "corrupted regexp program");
3055 RX_MATCH_TAINTED_off(rx);
3056 RX_MATCH_UTF8_set(rx, utf8_target);
3058 reginfo->prog = rx; /* Yes, sorry that this is confusing. */
3059 reginfo->intuit = 0;
3060 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
3061 reginfo->warned = FALSE;
3063 reginfo->poscache_maxiter = 0; /* not yet started a countdown */
3064 /* see how far we have to get to not match where we matched before */
3065 reginfo->till = stringarg + minend;
3067 if (prog->extflags & RXf_EVAL_SEEN && SvPADTMP(sv)) {
3068 /* SAVEFREESV, not sv_mortalcopy, as this SV must last until after
3069 S_cleanup_regmatch_info_aux has executed (registered by
3070 SAVEDESTRUCTOR_X below). S_cleanup_regmatch_info_aux modifies
3071 magic belonging to this SV.
3072 Not newSVsv, either, as it does not COW.
3074 reginfo->sv = newSV(0);
3075 SvSetSV_nosteal(reginfo->sv, sv);
3076 SAVEFREESV(reginfo->sv);
3079 /* reserve next 2 or 3 slots in PL_regmatch_state:
3080 * slot N+0: may currently be in use: skip it
3081 * slot N+1: use for regmatch_info_aux struct
3082 * slot N+2: use for regmatch_info_aux_eval struct if we have (?{})'s
3083 * slot N+3: ready for use by regmatch()
3087 regmatch_state *old_regmatch_state;
3088 regmatch_slab *old_regmatch_slab;
3089 int i, max = (prog->extflags & RXf_EVAL_SEEN) ? 2 : 1;
3091 /* on first ever match, allocate first slab */
3092 if (!PL_regmatch_slab) {
3093 Newx(PL_regmatch_slab, 1, regmatch_slab);
3094 PL_regmatch_slab->prev = NULL;
3095 PL_regmatch_slab->next = NULL;
3096 PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
3099 old_regmatch_state = PL_regmatch_state;
3100 old_regmatch_slab = PL_regmatch_slab;
3102 for (i=0; i <= max; i++) {
3104 reginfo->info_aux = &(PL_regmatch_state->u.info_aux);
3106 reginfo->info_aux_eval =
3107 reginfo->info_aux->info_aux_eval =
3108 &(PL_regmatch_state->u.info_aux_eval);
3110 if (++PL_regmatch_state > SLAB_LAST(PL_regmatch_slab))
3111 PL_regmatch_state = S_push_slab(aTHX);
3114 /* note initial PL_regmatch_state position; at end of match we'll
3115 * pop back to there and free any higher slabs */
3117 reginfo->info_aux->old_regmatch_state = old_regmatch_state;
3118 reginfo->info_aux->old_regmatch_slab = old_regmatch_slab;
3119 reginfo->info_aux->poscache = NULL;
3121 SAVEDESTRUCTOR_X(S_cleanup_regmatch_info_aux, reginfo->info_aux);
3123 if ((prog->extflags & RXf_EVAL_SEEN))
3124 S_setup_eval_state(aTHX_ reginfo);
3126 reginfo->info_aux_eval = reginfo->info_aux->info_aux_eval = NULL;
3129 /* If there is a "must appear" string, look for it. */
3131 if (PL_curpm && (PM_GETRE(PL_curpm) == rx)) {
3132 /* We have to be careful. If the previous successful match
3133 was from this regex we don't want a subsequent partially
3134 successful match to clobber the old results.
3135 So when we detect this possibility we add a swap buffer
3136 to the re, and switch the buffer each match. If we fail,
3137 we switch it back; otherwise we leave it swapped.
3140 /* do we need a save destructor here for eval dies? */
3141 Newxz(prog->offs, (prog->nparens + 1), regexp_paren_pair);
3142 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_
3143 "rex=0x%" UVxf " saving offs: orig=0x%" UVxf " new=0x%" UVxf "\n",
3151 if (prog->recurse_locinput)
3152 Zero(prog->recurse_locinput,prog->nparens + 1, char *);
3154 /* Simplest case: anchored match need be tried only once, or with
3155 * MBOL, only at the beginning of each line.
3157 * Note that /.*.../ sets PREGf_IMPLICIT|MBOL, while /.*.../s sets
3158 * PREGf_IMPLICIT|SBOL. The idea is that with /.*.../s, if it doesn't
3159 * match at the start of the string then it won't match anywhere else
3160 * either; while with /.*.../, if it doesn't match at the beginning,
3161 * the earliest it could match is at the start of the next line */
3163 if (prog->intflags & (PREGf_ANCH & ~PREGf_ANCH_GPOS)) {
3166 if (regtry(reginfo, &s))
3169 if (!(prog->intflags & PREGf_ANCH_MBOL))
3172 /* didn't match at start, try at other newline positions */
3175 dontbother = minlen - 1;
3176 end = HOP3c(strend, -dontbother, strbeg) - 1;
3178 /* skip to next newline */
3180 while (s <= end) { /* note it could be possible to match at the end of the string */
3181 /* NB: newlines are the same in unicode as they are in latin */
3184 if (prog->check_substr || prog->check_utf8) {
3185 /* note that with PREGf_IMPLICIT, intuit can only fail
3186 * or return the start position, so it's of limited utility.
3187 * Nevertheless, I made the decision that the potential for
3188 * quick fail was still worth it - DAPM */
3189 s = re_intuit_start(rx, sv, strbeg, s, strend, flags, NULL);
3193 if (regtry(reginfo, &s))
3197 } /* end anchored search */
3199 if (prog->intflags & PREGf_ANCH_GPOS)
3201 /* PREGf_ANCH_GPOS should never be true if PREGf_GPOS_SEEN is not true */
3202 assert(prog->intflags & PREGf_GPOS_SEEN);
3203 /* For anchored \G, the only position it can match from is
3204 * (ganch-gofs); we already set startpos to this above; if intuit
3205 * moved us on from there, we can't possibly succeed */
3206 assert(startpos == HOPBACKc(reginfo->ganch, prog->gofs));
3207 if (s == startpos && regtry(reginfo, &s))
3212 /* Messy cases: unanchored match. */
3213 if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
3214 /* we have /x+whatever/ */
3215 /* it must be a one character string (XXXX Except is_utf8_pat?) */
3221 if (! prog->anchored_utf8) {
3222 to_utf8_substr(prog);
3224 ch = SvPVX_const(prog->anchored_utf8)[0];
3227 DEBUG_EXECUTE_r( did_match = 1 );
3228 if (regtry(reginfo, &s)) goto got_it;
3230 while (s < strend && *s == ch)
3237 if (! prog->anchored_substr) {
3238 if (! to_byte_substr(prog)) {
3239 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3242 ch = SvPVX_const(prog->anchored_substr)[0];
3245 DEBUG_EXECUTE_r( did_match = 1 );
3246 if (regtry(reginfo, &s)) goto got_it;
3248 while (s < strend && *s == ch)
3253 DEBUG_EXECUTE_r(if (!did_match)
3254 Perl_re_printf( aTHX_
3255 "Did not find anchored character...\n")
3258 else if (prog->anchored_substr != NULL
3259 || prog->anchored_utf8 != NULL
3260 || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
3261 && prog->float_max_offset < strend - s)) {
3266 char *last1; /* Last position checked before */
3270 if (prog->anchored_substr || prog->anchored_utf8) {
3272 if (! prog->anchored_utf8) {
3273 to_utf8_substr(prog);
3275 must = prog->anchored_utf8;
3278 if (! prog->anchored_substr) {
3279 if (! to_byte_substr(prog)) {
3280 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3283 must = prog->anchored_substr;
3285 back_max = back_min = prog->anchored_offset;
3288 if (! prog->float_utf8) {
3289 to_utf8_substr(prog);
3291 must = prog->float_utf8;
3294 if (! prog->float_substr) {
3295 if (! to_byte_substr(prog)) {
3296 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3299 must = prog->float_substr;
3301 back_max = prog->float_max_offset;
3302 back_min = prog->float_min_offset;
3308 last = HOP3c(strend, /* Cannot start after this */
3309 -(SSize_t)(CHR_SVLEN(must)
3310 - (SvTAIL(must) != 0) + back_min), strbeg);
3312 if (s > reginfo->strbeg)
3313 last1 = HOPc(s, -1);
3315 last1 = s - 1; /* bogus */
3317 /* XXXX check_substr already used to find "s", can optimize if
3318 check_substr==must. */
3320 strend = HOPc(strend, -dontbother);
3321 while ( (s <= last) &&
3322 (s = fbm_instr((unsigned char*)HOP4c(s, back_min, strbeg, strend),
3323 (unsigned char*)strend, must,
3324 multiline ? FBMrf_MULTILINE : 0)) ) {
3325 DEBUG_EXECUTE_r( did_match = 1 );
3326 if (HOPc(s, -back_max) > last1) {
3327 last1 = HOPc(s, -back_min);
3328 s = HOPc(s, -back_max);
3331 char * const t = (last1 >= reginfo->strbeg)
3332 ? HOPc(last1, 1) : last1 + 1;
3334 last1 = HOPc(s, -back_min);
3338 while (s <= last1) {
3339 if (regtry(reginfo, &s))
3342 s++; /* to break out of outer loop */
3349 while (s <= last1) {
3350 if (regtry(reginfo, &s))
3356 DEBUG_EXECUTE_r(if (!did_match) {
3357 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
3358 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
3359 Perl_re_printf( aTHX_ "Did not find %s substr %s%s...\n",
3360 ((must == prog->anchored_substr || must == prog->anchored_utf8)
3361 ? "anchored" : "floating"),
3362 quoted, RE_SV_TAIL(must));
3366 else if ( (c = progi->regstclass) ) {
3368 const OPCODE op = OP(progi->regstclass);
3369 /* don't bother with what can't match */
3370 if (PL_regkind[op] != EXACT && PL_regkind[op] != TRIE)
3371 strend = HOPc(strend, -(minlen - 1));
3374 SV * const prop = sv_newmortal();
3375 regprop(prog, prop, c, reginfo, NULL);
3377 RE_PV_QUOTED_DECL(quoted,utf8_target,PERL_DEBUG_PAD_ZERO(1),
3379 Perl_re_printf( aTHX_
3380 "Matching stclass %.*s against %s (%d bytes)\n",
3381 (int)SvCUR(prop), SvPVX_const(prop),
3382 quoted, (int)(strend - s));
3385 if (find_byclass(prog, c, s, strend, reginfo))
3387 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "Contradicts stclass... [regexec_flags]\n"));
3391 if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
3399 if (! prog->float_utf8) {
3400 to_utf8_substr(prog);
3402 float_real = prog->float_utf8;
3405 if (! prog->float_substr) {
3406 if (! to_byte_substr(prog)) {
3407 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3410 float_real = prog->float_substr;
3413 little = SvPV_const(float_real, len);
3414 if (SvTAIL(float_real)) {
3415 /* This means that float_real contains an artificial \n on
3416 * the end due to the presence of something like this:
3417 * /foo$/ where we can match both "foo" and "foo\n" at the
3418 * end of the string. So we have to compare the end of the
3419 * string first against the float_real without the \n and
3420 * then against the full float_real with the string. We
3421 * have to watch out for cases where the string might be
3422 * smaller than the float_real or the float_real without
3424 char *checkpos= strend - len;
3426 Perl_re_printf( aTHX_
3427 "%sChecking for float_real.%s\n",
3428 PL_colors[4], PL_colors[5]));
3429 if (checkpos + 1 < strbeg) {
3430 /* can't match, even if we remove the trailing \n
3431 * string is too short to match */
3433 Perl_re_printf( aTHX_
3434 "%sString shorter than required trailing substring, cannot match.%s\n",
3435 PL_colors[4], PL_colors[5]));
3437 } else if (memEQ(checkpos + 1, little, len - 1)) {
3438 /* can match, the end of the string matches without the
3440 last = checkpos + 1;
3441 } else if (checkpos < strbeg) {
3442 /* cant match, string is too short when the "\n" is
3445 Perl_re_printf( aTHX_
3446 "%sString does not contain required trailing substring, cannot match.%s\n",
3447 PL_colors[4], PL_colors[5]));
3449 } else if (!multiline) {
3450 /* non multiline match, so compare with the "\n" at the
3451 * end of the string */
3452 if (memEQ(checkpos, little, len)) {
3456 Perl_re_printf( aTHX_
3457 "%sString does not contain required trailing substring, cannot match.%s\n",
3458 PL_colors[4], PL_colors[5]));
3462 /* multiline match, so we have to search for a place
3463 * where the full string is located */
3469 last = rninstr(s, strend, little, little + len);
3471 last = strend; /* matching "$" */
3474 /* at one point this block contained a comment which was
3475 * probably incorrect, which said that this was a "should not
3476 * happen" case. Even if it was true when it was written I am
3477 * pretty sure it is not anymore, so I have removed the comment
3478 * and replaced it with this one. Yves */
3480 Perl_re_printf( aTHX_
3481 "%sString does not contain required substring, cannot match.%s\n",
3482 PL_colors[4], PL_colors[5]
3486 dontbother = strend - last + prog->float_min_offset;
3488 if (minlen && (dontbother < minlen))
3489 dontbother = minlen - 1;
3490 strend -= dontbother; /* this one's always in bytes! */
3491 /* We don't know much -- general case. */
3494 if (regtry(reginfo, &s))
3503 if (regtry(reginfo, &s))
3505 } while (s++ < strend);
3513 /* s/// doesn't like it if $& is earlier than where we asked it to
3514 * start searching (which can happen on something like /.\G/) */
3515 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
3516 && (prog->offs[0].start < stringarg - strbeg))
3518 /* this should only be possible under \G */
3519 assert(prog->intflags & PREGf_GPOS_SEEN);
3520 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
3521 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3527 Perl_re_exec_indentf( aTHX_
3528 "rex=0x%" UVxf " freeing offs: 0x%" UVxf "\n",
3536 /* clean up; this will trigger destructors that will free all slabs
3537 * above the current one, and cleanup the regmatch_info_aux
3538 * and regmatch_info_aux_eval sructs */
3540 LEAVE_SCOPE(oldsave);
3542 if (RXp_PAREN_NAMES(prog))
3543 (void)hv_iterinit(RXp_PAREN_NAMES(prog));
3545 /* make sure $`, $&, $', and $digit will work later */
3546 if ( !(flags & REXEC_NOT_FIRST) )
3547 S_reg_set_capture_string(aTHX_ rx,
3548 strbeg, reginfo->strend,
3549 sv, flags, utf8_target);
3554 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%sMatch failed%s\n",
3555 PL_colors[4], PL_colors[5]));
3557 /* clean up; this will trigger destructors that will free all slabs
3558 * above the current one, and cleanup the regmatch_info_aux
3559 * and regmatch_info_aux_eval sructs */
3561 LEAVE_SCOPE(oldsave);
3564 /* we failed :-( roll it back */
3565 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_
3566 "rex=0x%" UVxf " rolling back offs: freeing=0x%" UVxf " restoring=0x%" UVxf "\n",
3572 Safefree(prog->offs);
3579 /* Set which rex is pointed to by PL_reg_curpm, handling ref counting.
3580 * Do inc before dec, in case old and new rex are the same */
3581 #define SET_reg_curpm(Re2) \
3582 if (reginfo->info_aux_eval) { \
3583 (void)ReREFCNT_inc(Re2); \
3584 ReREFCNT_dec(PM_GETRE(PL_reg_curpm)); \
3585 PM_SETRE((PL_reg_curpm), (Re2)); \
3590 - regtry - try match at specific point
3592 STATIC bool /* 0 failure, 1 success */
3593 S_regtry(pTHX_ regmatch_info *reginfo, char **startposp)
3596 REGEXP *const rx = reginfo->prog;
3597 regexp *const prog = ReANY(rx);
3600 U32 depth = 0; /* used by REGCP_SET */
3602 RXi_GET_DECL(prog,progi);
3603 GET_RE_DEBUG_FLAGS_DECL;
3605 PERL_ARGS_ASSERT_REGTRY;
3607 reginfo->cutpoint=NULL;
3609 prog->offs[0].start = *startposp - reginfo->strbeg;
3610 prog->lastparen = 0;
3611 prog->lastcloseparen = 0;
3613 /* XXXX What this code is doing here?!!! There should be no need
3614 to do this again and again, prog->lastparen should take care of
3617 /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
3618 * Actually, the code in regcppop() (which Ilya may be meaning by
3619 * prog->lastparen), is not needed at all by the test suite
3620 * (op/regexp, op/pat, op/split), but that code is needed otherwise
3621 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
3622 * Meanwhile, this code *is* needed for the
3623 * above-mentioned test suite tests to succeed. The common theme
3624 * on those tests seems to be returning null fields from matches.
3625 * --jhi updated by dapm */
3627 /* After encountering a variant of the issue mentioned above I think
3628 * the point Ilya was making is that if we properly unwind whenever
3629 * we set lastparen to a smaller value then we should not need to do
3630 * this every time, only when needed. So if we have tests that fail if
3631 * we remove this, then it suggests somewhere else we are improperly
3632 * unwinding the lastparen/paren buffers. See UNWIND_PARENS() and
3633 * places it is called, and related regcp() routines. - Yves */
3635 if (prog->nparens) {
3636 regexp_paren_pair *pp = prog->offs;
3638 for (i = prog->nparens; i > (I32)prog->lastparen; i--) {
3646 result = regmatch(reginfo, *startposp, progi->program + 1);
3648 prog->offs[0].end = result;
3651 if (reginfo->cutpoint)
3652 *startposp= reginfo->cutpoint;
3653 REGCP_UNWIND(lastcp);
3658 #define sayYES goto yes
3659 #define sayNO goto no
3660 #define sayNO_SILENT goto no_silent
3662 /* we dont use STMT_START/END here because it leads to
3663 "unreachable code" warnings, which are bogus, but distracting. */
3664 #define CACHEsayNO \
3665 if (ST.cache_mask) \
3666 reginfo->info_aux->poscache[ST.cache_offset] |= ST.cache_mask; \
3669 /* this is used to determine how far from the left messages like
3670 'failed...' are printed in regexec.c. It should be set such that
3671 messages are inline with the regop output that created them.
3673 #define REPORT_CODE_OFF 29
3674 #define INDENT_CHARS(depth) ((int)(depth) % 20)
3677 Perl_re_exec_indentf(pTHX_ const char *fmt, U32 depth, ...)
3681 PerlIO *f= Perl_debug_log;
3682 PERL_ARGS_ASSERT_RE_EXEC_INDENTF;
3683 va_start(ap, depth);
3684 PerlIO_printf(f, "%*s|%4" UVuf "| %*s", REPORT_CODE_OFF, "", (UV)depth, INDENT_CHARS(depth), "" );
3685 result = PerlIO_vprintf(f, fmt, ap);
3689 #endif /* DEBUGGING */
3692 #define CHRTEST_UNINIT -1001 /* c1/c2 haven't been calculated yet */
3693 #define CHRTEST_VOID -1000 /* the c1/c2 "next char" test should be skipped */
3694 #define CHRTEST_NOT_A_CP_1 -999
3695 #define CHRTEST_NOT_A_CP_2 -998
3697 /* grab a new slab and return the first slot in it */
3699 STATIC regmatch_state *
3702 regmatch_slab *s = PL_regmatch_slab->next;
3704 Newx(s, 1, regmatch_slab);
3705 s->prev = PL_regmatch_slab;
3707 PL_regmatch_slab->next = s;
3709 PL_regmatch_slab = s;
3710 return SLAB_FIRST(s);
3714 /* push a new state then goto it */
3716 #define PUSH_STATE_GOTO(state, node, input) \
3717 pushinput = input; \
3719 st->resume_state = state; \
3722 /* push a new state with success backtracking, then goto it */
3724 #define PUSH_YES_STATE_GOTO(state, node, input) \
3725 pushinput = input; \
3727 st->resume_state = state; \
3728 goto push_yes_state;
3735 regmatch() - main matching routine
3737 This is basically one big switch statement in a loop. We execute an op,
3738 set 'next' to point the next op, and continue. If we come to a point which
3739 we may need to backtrack to on failure such as (A|B|C), we push a
3740 backtrack state onto the backtrack stack. On failure, we pop the top
3741 state, and re-enter the loop at the state indicated. If there are no more
3742 states to pop, we return failure.
3744 Sometimes we also need to backtrack on success; for example /A+/, where
3745 after successfully matching one A, we need to go back and try to
3746 match another one; similarly for lookahead assertions: if the assertion
3747 completes successfully, we backtrack to the state just before the assertion
3748 and then carry on. In these cases, the pushed state is marked as
3749 'backtrack on success too'. This marking is in fact done by a chain of
3750 pointers, each pointing to the previous 'yes' state. On success, we pop to
3751 the nearest yes state, discarding any intermediate failure-only states.
3752 Sometimes a yes state is pushed just to force some cleanup code to be
3753 called at the end of a successful match or submatch; e.g. (??{$re}) uses
3754 it to free the inner regex.
3756 Note that failure backtracking rewinds the cursor position, while
3757 success backtracking leaves it alone.
3759 A pattern is complete when the END op is executed, while a subpattern
3760 such as (?=foo) is complete when the SUCCESS op is executed. Both of these
3761 ops trigger the "pop to last yes state if any, otherwise return true"
3764 A common convention in this function is to use A and B to refer to the two
3765 subpatterns (or to the first nodes thereof) in patterns like /A*B/: so A is
3766 the subpattern to be matched possibly multiple times, while B is the entire
3767 rest of the pattern. Variable and state names reflect this convention.
3769 The states in the main switch are the union of ops and failure/success of
3770 substates associated with with that op. For example, IFMATCH is the op
3771 that does lookahead assertions /(?=A)B/ and so the IFMATCH state means
3772 'execute IFMATCH'; while IFMATCH_A is a state saying that we have just
3773 successfully matched A and IFMATCH_A_fail is a state saying that we have
3774 just failed to match A. Resume states always come in pairs. The backtrack
3775 state we push is marked as 'IFMATCH_A', but when that is popped, we resume
3776 at IFMATCH_A or IFMATCH_A_fail, depending on whether we are backtracking
3777 on success or failure.
3779 The struct that holds a backtracking state is actually a big union, with
3780 one variant for each major type of op. The variable st points to the
3781 top-most backtrack struct. To make the code clearer, within each
3782 block of code we #define ST to alias the relevant union.
3784 Here's a concrete example of a (vastly oversimplified) IFMATCH
3790 #define ST st->u.ifmatch
3792 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3793 ST.foo = ...; // some state we wish to save
3795 // push a yes backtrack state with a resume value of
3796 // IFMATCH_A/IFMATCH_A_fail, then continue execution at the
3798 PUSH_YES_STATE_GOTO(IFMATCH_A, A, newinput);
3801 case IFMATCH_A: // we have successfully executed A; now continue with B
3803 bar = ST.foo; // do something with the preserved value
3806 case IFMATCH_A_fail: // A failed, so the assertion failed
3807 ...; // do some housekeeping, then ...
3808 sayNO; // propagate the failure
3815 For any old-timers reading this who are familiar with the old recursive
3816 approach, the code above is equivalent to:
3818 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3827 ...; // do some housekeeping, then ...
3828 sayNO; // propagate the failure
3831 The topmost backtrack state, pointed to by st, is usually free. If you
3832 want to claim it, populate any ST.foo fields in it with values you wish to
3833 save, then do one of