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(PerlIO_printf(Perl_debug_log, "%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, -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)
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 PerlIO_printf(Perl_debug_log,
304 "rex=0x%"UVxf" offs=0x%"UVxf": saving capture indices:\n",
309 for (p = parenfloor+1; p <= (I32)maxopenparen; p++) {
310 /* REGCP_PARENS_ELEMS are pushed per pairs of parentheses. */
311 SSPUSHIV(rex->offs[p].end);
312 SSPUSHIV(rex->offs[p].start);
313 SSPUSHINT(rex->offs[p].start_tmp);
314 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
315 " \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"\n",
317 (IV)rex->offs[p].start,
318 (IV)rex->offs[p].start_tmp,
322 /* REGCP_OTHER_ELEMS are pushed in any case, parentheses or no. */
323 SSPUSHINT(maxopenparen);
324 SSPUSHINT(rex->lastparen);
325 SSPUSHINT(rex->lastcloseparen);
326 SSPUSHUV(SAVEt_REGCONTEXT | elems_shifted); /* Magic cookie. */
331 /* These are needed since we do not localize EVAL nodes: */
332 #define REGCP_SET(cp) \
334 PerlIO_printf(Perl_debug_log, \
335 " Setting an EVAL scope, savestack=%"IVdf"\n", \
336 (IV)PL_savestack_ix)); \
339 #define REGCP_UNWIND(cp) \
341 if (cp != PL_savestack_ix) \
342 PerlIO_printf(Perl_debug_log, \
343 " Clearing an EVAL scope, savestack=%"IVdf"..%"IVdf"\n", \
344 (IV)(cp), (IV)PL_savestack_ix)); \
347 #define UNWIND_PAREN(lp, lcp) \
348 for (n = rex->lastparen; n > lp; n--) \
349 rex->offs[n].end = -1; \
350 rex->lastparen = n; \
351 rex->lastcloseparen = lcp;
355 S_regcppop(pTHX_ regexp *rex, U32 *maxopenparen_p)
359 GET_RE_DEBUG_FLAGS_DECL;
361 PERL_ARGS_ASSERT_REGCPPOP;
363 /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
365 assert((i & SAVE_MASK) == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
366 i >>= SAVE_TIGHT_SHIFT; /* Parentheses elements to pop. */
367 rex->lastcloseparen = SSPOPINT;
368 rex->lastparen = SSPOPINT;
369 *maxopenparen_p = SSPOPINT;
371 i -= REGCP_OTHER_ELEMS;
372 /* Now restore the parentheses context. */
374 if (i || rex->lastparen + 1 <= rex->nparens)
375 PerlIO_printf(Perl_debug_log,
376 "rex=0x%"UVxf" offs=0x%"UVxf": restoring capture indices to:\n",
381 paren = *maxopenparen_p;
382 for ( ; i > 0; i -= REGCP_PAREN_ELEMS) {
384 rex->offs[paren].start_tmp = SSPOPINT;
385 rex->offs[paren].start = SSPOPIV;
387 if (paren <= rex->lastparen)
388 rex->offs[paren].end = tmps;
389 DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
390 " \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"%s\n",
392 (IV)rex->offs[paren].start,
393 (IV)rex->offs[paren].start_tmp,
394 (IV)rex->offs[paren].end,
395 (paren > rex->lastparen ? "(skipped)" : ""));
400 /* It would seem that the similar code in regtry()
401 * already takes care of this, and in fact it is in
402 * a better location to since this code can #if 0-ed out
403 * but the code in regtry() is needed or otherwise tests
404 * requiring null fields (pat.t#187 and split.t#{13,14}
405 * (as of patchlevel 7877) will fail. Then again,
406 * this code seems to be necessary or otherwise
407 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
408 * --jhi updated by dapm */
409 for (i = rex->lastparen + 1; i <= rex->nparens; i++) {
410 if (i > *maxopenparen_p)
411 rex->offs[i].start = -1;
412 rex->offs[i].end = -1;
413 DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
414 " \\%"UVuf": %s ..-1 undeffing\n",
416 (i > *maxopenparen_p) ? "-1" : " "
422 /* restore the parens and associated vars at savestack position ix,
423 * but without popping the stack */
426 S_regcp_restore(pTHX_ regexp *rex, I32 ix, U32 *maxopenparen_p)
428 I32 tmpix = PL_savestack_ix;
429 PL_savestack_ix = ix;
430 regcppop(rex, maxopenparen_p);
431 PL_savestack_ix = tmpix;
434 #define regcpblow(cp) LEAVE_SCOPE(cp) /* Ignores regcppush()ed data. */
437 S_isFOO_lc(pTHX_ const U8 classnum, const U8 character)
439 /* Returns a boolean as to whether or not 'character' is a member of the
440 * Posix character class given by 'classnum' that should be equivalent to a
441 * value in the typedef '_char_class_number'.
443 * Ideally this could be replaced by a just an array of function pointers
444 * to the C library functions that implement the macros this calls.
445 * However, to compile, the precise function signatures are required, and
446 * these may vary from platform to to platform. To avoid having to figure
447 * out what those all are on each platform, I (khw) am using this method,
448 * which adds an extra layer of function call overhead (unless the C
449 * optimizer strips it away). But we don't particularly care about
450 * performance with locales anyway. */
452 switch ((_char_class_number) classnum) {
453 case _CC_ENUM_ALPHANUMERIC: return isALPHANUMERIC_LC(character);
454 case _CC_ENUM_ALPHA: return isALPHA_LC(character);
455 case _CC_ENUM_ASCII: return isASCII_LC(character);
456 case _CC_ENUM_BLANK: return isBLANK_LC(character);
457 case _CC_ENUM_CASED: return isLOWER_LC(character)
458 || isUPPER_LC(character);
459 case _CC_ENUM_CNTRL: return isCNTRL_LC(character);
460 case _CC_ENUM_DIGIT: return isDIGIT_LC(character);
461 case _CC_ENUM_GRAPH: return isGRAPH_LC(character);
462 case _CC_ENUM_LOWER: return isLOWER_LC(character);
463 case _CC_ENUM_PRINT: return isPRINT_LC(character);
464 case _CC_ENUM_PUNCT: return isPUNCT_LC(character);
465 case _CC_ENUM_SPACE: return isSPACE_LC(character);
466 case _CC_ENUM_UPPER: return isUPPER_LC(character);
467 case _CC_ENUM_WORDCHAR: return isWORDCHAR_LC(character);
468 case _CC_ENUM_XDIGIT: return isXDIGIT_LC(character);
469 default: /* VERTSPACE should never occur in locales */
470 Perl_croak(aTHX_ "panic: isFOO_lc() has an unexpected character class '%d'", classnum);
473 NOT_REACHED; /* NOTREACHED */
478 S_isFOO_utf8_lc(pTHX_ const U8 classnum, const U8* character)
480 /* Returns a boolean as to whether or not the (well-formed) UTF-8-encoded
481 * 'character' is a member of the Posix character class given by 'classnum'
482 * that should be equivalent to a value in the typedef
483 * '_char_class_number'.
485 * This just calls isFOO_lc on the code point for the character if it is in
486 * the range 0-255. Outside that range, all characters use Unicode
487 * rules, ignoring any locale. So use the Unicode function if this class
488 * requires a swash, and use the Unicode macro otherwise. */
490 PERL_ARGS_ASSERT_ISFOO_UTF8_LC;
492 if (UTF8_IS_INVARIANT(*character)) {
493 return isFOO_lc(classnum, *character);
495 else if (UTF8_IS_DOWNGRADEABLE_START(*character)) {
496 return isFOO_lc(classnum,
497 EIGHT_BIT_UTF8_TO_NATIVE(*character, *(character + 1)));
500 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(character, character + UTF8SKIP(character));
502 if (classnum < _FIRST_NON_SWASH_CC) {
504 /* Initialize the swash unless done already */
505 if (! PL_utf8_swash_ptrs[classnum]) {
506 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
507 PL_utf8_swash_ptrs[classnum] =
508 _core_swash_init("utf8",
511 PL_XPosix_ptrs[classnum], &flags);
514 return cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum], (U8 *)
516 TRUE /* is UTF */ ));
519 switch ((_char_class_number) classnum) {
520 case _CC_ENUM_SPACE: return is_XPERLSPACE_high(character);
521 case _CC_ENUM_BLANK: return is_HORIZWS_high(character);
522 case _CC_ENUM_XDIGIT: return is_XDIGIT_high(character);
523 case _CC_ENUM_VERTSPACE: return is_VERTWS_high(character);
527 return FALSE; /* Things like CNTRL are always below 256 */
531 * pregexec and friends
534 #ifndef PERL_IN_XSUB_RE
536 - pregexec - match a regexp against a string
539 Perl_pregexec(pTHX_ REGEXP * const prog, char* stringarg, char *strend,
540 char *strbeg, SSize_t minend, SV *screamer, U32 nosave)
541 /* stringarg: the point in the string at which to begin matching */
542 /* strend: pointer to null at end of string */
543 /* strbeg: real beginning of string */
544 /* minend: end of match must be >= minend bytes after stringarg. */
545 /* screamer: SV being matched: only used for utf8 flag, pos() etc; string
546 * itself is accessed via the pointers above */
547 /* nosave: For optimizations. */
549 PERL_ARGS_ASSERT_PREGEXEC;
552 regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
553 nosave ? 0 : REXEC_COPY_STR);
559 /* re_intuit_start():
561 * Based on some optimiser hints, try to find the earliest position in the
562 * string where the regex could match.
564 * rx: the regex to match against
565 * sv: the SV being matched: only used for utf8 flag; the string
566 * itself is accessed via the pointers below. Note that on
567 * something like an overloaded SV, SvPOK(sv) may be false
568 * and the string pointers may point to something unrelated to
570 * strbeg: real beginning of string
571 * strpos: the point in the string at which to begin matching
572 * strend: pointer to the byte following the last char of the string
573 * flags currently unused; set to 0
574 * data: currently unused; set to NULL
576 * The basic idea of re_intuit_start() is to use some known information
577 * about the pattern, namely:
579 * a) the longest known anchored substring (i.e. one that's at a
580 * constant offset from the beginning of the pattern; but not
581 * necessarily at a fixed offset from the beginning of the
583 * b) the longest floating substring (i.e. one that's not at a constant
584 * offset from the beginning of the pattern);
585 * c) Whether the pattern is anchored to the string; either
586 * an absolute anchor: /^../, or anchored to \n: /^.../m,
587 * or anchored to pos(): /\G/;
588 * d) A start class: a real or synthetic character class which
589 * represents which characters are legal at the start of the pattern;
591 * to either quickly reject the match, or to find the earliest position
592 * within the string at which the pattern might match, thus avoiding
593 * running the full NFA engine at those earlier locations, only to
594 * eventually fail and retry further along.
596 * Returns NULL if the pattern can't match, or returns the address within
597 * the string which is the earliest place the match could occur.
599 * The longest of the anchored and floating substrings is called 'check'
600 * and is checked first. The other is called 'other' and is checked
601 * second. The 'other' substring may not be present. For example,
603 * /(abc|xyz)ABC\d{0,3}DEFG/
607 * check substr (float) = "DEFG", offset 6..9 chars
608 * other substr (anchored) = "ABC", offset 3..3 chars
611 * Be aware that during the course of this function, sometimes 'anchored'
612 * refers to a substring being anchored relative to the start of the
613 * pattern, and sometimes to the pattern itself being anchored relative to
614 * the string. For example:
616 * /\dabc/: "abc" is anchored to the pattern;
617 * /^\dabc/: "abc" is anchored to the pattern and the string;
618 * /\d+abc/: "abc" is anchored to neither the pattern nor the string;
619 * /^\d+abc/: "abc" is anchored to neither the pattern nor the string,
620 * but the pattern is anchored to the string.
624 Perl_re_intuit_start(pTHX_
627 const char * const strbeg,
631 re_scream_pos_data *data)
633 struct regexp *const prog = ReANY(rx);
634 SSize_t start_shift = prog->check_offset_min;
635 /* Should be nonnegative! */
636 SSize_t end_shift = 0;
637 /* current lowest pos in string where the regex can start matching */
638 char *rx_origin = strpos;
640 const bool utf8_target = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
641 U8 other_ix = 1 - prog->substrs->check_ix;
643 char *other_last = strpos;/* latest pos 'other' substr already checked to */
644 char *check_at = NULL; /* check substr found at this pos */
645 const I32 multiline = prog->extflags & RXf_PMf_MULTILINE;
646 RXi_GET_DECL(prog,progi);
647 regmatch_info reginfo_buf; /* create some info to pass to find_byclass */
648 regmatch_info *const reginfo = ®info_buf;
649 GET_RE_DEBUG_FLAGS_DECL;
651 PERL_ARGS_ASSERT_RE_INTUIT_START;
652 PERL_UNUSED_ARG(flags);
653 PERL_UNUSED_ARG(data);
655 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
656 "Intuit: trying to determine minimum start position...\n"));
658 /* for now, assume that all substr offsets are positive. If at some point
659 * in the future someone wants to do clever things with lookbehind and
660 * -ve offsets, they'll need to fix up any code in this function
661 * which uses these offsets. See the thread beginning
662 * <20140113145929.GF27210@iabyn.com>
664 assert(prog->substrs->data[0].min_offset >= 0);
665 assert(prog->substrs->data[0].max_offset >= 0);
666 assert(prog->substrs->data[1].min_offset >= 0);
667 assert(prog->substrs->data[1].max_offset >= 0);
668 assert(prog->substrs->data[2].min_offset >= 0);
669 assert(prog->substrs->data[2].max_offset >= 0);
671 /* for now, assume that if both present, that the floating substring
672 * doesn't start before the anchored substring.
673 * If you break this assumption (e.g. doing better optimisations
674 * with lookahead/behind), then you'll need to audit the code in this
675 * function carefully first
678 ! ( (prog->anchored_utf8 || prog->anchored_substr)
679 && (prog->float_utf8 || prog->float_substr))
680 || (prog->float_min_offset >= prog->anchored_offset));
682 /* byte rather than char calculation for efficiency. It fails
683 * to quickly reject some cases that can't match, but will reject
684 * them later after doing full char arithmetic */
685 if (prog->minlen > strend - strpos) {
686 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
687 " String too short...\n"));
691 RX_MATCH_UTF8_set(rx,utf8_target);
692 reginfo->is_utf8_target = cBOOL(utf8_target);
693 reginfo->info_aux = NULL;
694 reginfo->strbeg = strbeg;
695 reginfo->strend = strend;
696 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
698 /* not actually used within intuit, but zero for safety anyway */
699 reginfo->poscache_maxiter = 0;
702 if (!prog->check_utf8 && prog->check_substr)
703 to_utf8_substr(prog);
704 check = prog->check_utf8;
706 if (!prog->check_substr && prog->check_utf8) {
707 if (! to_byte_substr(prog)) {
708 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(fail);
711 check = prog->check_substr;
714 /* dump the various substring data */
715 DEBUG_OPTIMISE_MORE_r({
717 for (i=0; i<=2; i++) {
718 SV *sv = (utf8_target ? prog->substrs->data[i].utf8_substr
719 : prog->substrs->data[i].substr);
723 PerlIO_printf(Perl_debug_log,
724 " substrs[%d]: min=%"IVdf" max=%"IVdf" end shift=%"IVdf
725 " useful=%"IVdf" utf8=%d [%s]\n",
727 (IV)prog->substrs->data[i].min_offset,
728 (IV)prog->substrs->data[i].max_offset,
729 (IV)prog->substrs->data[i].end_shift,
736 if (prog->intflags & PREGf_ANCH) { /* Match at \G, beg-of-str or after \n */
738 /* ml_anch: check after \n?
740 * A note about PREGf_IMPLICIT: on an un-anchored pattern beginning
741 * with /.*.../, these flags will have been added by the
743 * /.*abc/, /.*abc/m: PREGf_IMPLICIT | PREGf_ANCH_MBOL
744 * /.*abc/s: PREGf_IMPLICIT | PREGf_ANCH_SBOL
746 ml_anch = (prog->intflags & PREGf_ANCH_MBOL)
747 && !(prog->intflags & PREGf_IMPLICIT);
749 if (!ml_anch && !(prog->intflags & PREGf_IMPLICIT)) {
750 /* we are only allowed to match at BOS or \G */
752 /* trivially reject if there's a BOS anchor and we're not at BOS.
754 * Note that we don't try to do a similar quick reject for
755 * \G, since generally the caller will have calculated strpos
756 * based on pos() and gofs, so the string is already correctly
757 * anchored by definition; and handling the exceptions would
758 * be too fiddly (e.g. REXEC_IGNOREPOS).
760 if ( strpos != strbeg
761 && (prog->intflags & PREGf_ANCH_SBOL))
763 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
764 " Not at start...\n"));
768 /* in the presence of an anchor, the anchored (relative to the
769 * start of the regex) substr must also be anchored relative
770 * to strpos. So quickly reject if substr isn't found there.
771 * This works for \G too, because the caller will already have
772 * subtracted gofs from pos, and gofs is the offset from the
773 * \G to the start of the regex. For example, in /.abc\Gdef/,
774 * where substr="abcdef", pos()=3, gofs=4, offset_min=1:
775 * caller will have set strpos=pos()-4; we look for the substr
776 * at position pos()-4+1, which lines up with the "a" */
778 if (prog->check_offset_min == prog->check_offset_max) {
779 /* Substring at constant offset from beg-of-str... */
780 SSize_t slen = SvCUR(check);
781 char *s = HOP3c(strpos, prog->check_offset_min, strend);
783 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
784 " Looking for check substr at fixed offset %"IVdf"...\n",
785 (IV)prog->check_offset_min));
788 /* In this case, the regex is anchored at the end too.
789 * Unless it's a multiline match, the lengths must match
790 * exactly, give or take a \n. NB: slen >= 1 since
791 * the last char of check is \n */
793 && ( strend - s > slen
794 || strend - s < slen - 1
795 || (strend - s == slen && strend[-1] != '\n')))
797 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
798 " String too long...\n"));
801 /* Now should match s[0..slen-2] */
804 if (slen && (*SvPVX_const(check) != *s
805 || (slen > 1 && memNE(SvPVX_const(check), s, slen))))
807 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
808 " String not equal...\n"));
813 goto success_at_start;
818 end_shift = prog->check_end_shift;
820 #ifdef DEBUGGING /* 7/99: reports of failure (with the older version) */
822 Perl_croak(aTHX_ "panic: end_shift: %"IVdf" pattern:\n%s\n ",
823 (IV)end_shift, RX_PRECOMP(prog));
828 /* This is the (re)entry point of the main loop in this function.
829 * The goal of this loop is to:
830 * 1) find the "check" substring in the region rx_origin..strend
831 * (adjusted by start_shift / end_shift). If not found, reject
833 * 2) If it exists, look for the "other" substr too if defined; for
834 * example, if the check substr maps to the anchored substr, then
835 * check the floating substr, and vice-versa. If not found, go
836 * back to (1) with rx_origin suitably incremented.
837 * 3) If we find an rx_origin position that doesn't contradict
838 * either of the substrings, then check the possible additional
839 * constraints on rx_origin of /^.../m or a known start class.
840 * If these fail, then depending on which constraints fail, jump
841 * back to here, or to various other re-entry points further along
842 * that skip some of the first steps.
843 * 4) If we pass all those tests, update the BmUSEFUL() count on the
844 * substring. If the start position was determined to be at the
845 * beginning of the string - so, not rejected, but not optimised,
846 * since we have to run regmatch from position 0 - decrement the
847 * BmUSEFUL() count. Otherwise increment it.
851 /* first, look for the 'check' substring */
857 DEBUG_OPTIMISE_MORE_r({
858 PerlIO_printf(Perl_debug_log,
859 " At restart: rx_origin=%"IVdf" Check offset min: %"IVdf
860 " Start shift: %"IVdf" End shift %"IVdf
861 " Real end Shift: %"IVdf"\n",
862 (IV)(rx_origin - strbeg),
863 (IV)prog->check_offset_min,
866 (IV)prog->check_end_shift);
869 end_point = HOP3(strend, -end_shift, strbeg);
870 start_point = HOPMAYBE3(rx_origin, start_shift, end_point);
875 /* If the regex is absolutely anchored to either the start of the
876 * string (SBOL) or to pos() (ANCH_GPOS), then
877 * check_offset_max represents an upper bound on the string where
878 * the substr could start. For the ANCH_GPOS case, we assume that
879 * the caller of intuit will have already set strpos to
880 * pos()-gofs, so in this case strpos + offset_max will still be
881 * an upper bound on the substr.
884 && prog->intflags & PREGf_ANCH
885 && prog->check_offset_max != SSize_t_MAX)
887 SSize_t len = SvCUR(check) - !!SvTAIL(check);
888 const char * const anchor =
889 (prog->intflags & PREGf_ANCH_GPOS ? strpos : strbeg);
891 /* do a bytes rather than chars comparison. It's conservative;
892 * so it skips doing the HOP if the result can't possibly end
893 * up earlier than the old value of end_point.
895 if ((char*)end_point - anchor > prog->check_offset_max) {
896 end_point = HOP3lim((U8*)anchor,
897 prog->check_offset_max,
903 check_at = fbm_instr( start_point, end_point,
904 check, multiline ? FBMrf_MULTILINE : 0);
906 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
907 " doing 'check' fbm scan, [%"IVdf"..%"IVdf"] gave %"IVdf"\n",
908 (IV)((char*)start_point - strbeg),
909 (IV)((char*)end_point - strbeg),
910 (IV)(check_at ? check_at - strbeg : -1)
913 /* Update the count-of-usability, remove useless subpatterns,
917 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
918 SvPVX_const(check), RE_SV_DUMPLEN(check), 30);
919 PerlIO_printf(Perl_debug_log, " %s %s substr %s%s%s",
920 (check_at ? "Found" : "Did not find"),
921 (check == (utf8_target ? prog->anchored_utf8 : prog->anchored_substr)
922 ? "anchored" : "floating"),
925 (check_at ? " at offset " : "...\n") );
930 /* set rx_origin to the minimum position where the regex could start
931 * matching, given the constraint of the just-matched check substring.
932 * But don't set it lower than previously.
935 if (check_at - rx_origin > prog->check_offset_max)
936 rx_origin = HOP3c(check_at, -prog->check_offset_max, rx_origin);
937 /* Finish the diagnostic message */
938 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
939 "%ld (rx_origin now %"IVdf")...\n",
940 (long)(check_at - strbeg),
941 (IV)(rx_origin - strbeg)
946 /* now look for the 'other' substring if defined */
948 if (utf8_target ? prog->substrs->data[other_ix].utf8_substr
949 : prog->substrs->data[other_ix].substr)
951 /* Take into account the "other" substring. */
955 struct reg_substr_datum *other;
958 other = &prog->substrs->data[other_ix];
960 /* if "other" is anchored:
961 * we've previously found a floating substr starting at check_at.
962 * This means that the regex origin must lie somewhere
963 * between min (rx_origin): HOP3(check_at, -check_offset_max)
964 * and max: HOP3(check_at, -check_offset_min)
965 * (except that min will be >= strpos)
966 * So the fixed substr must lie somewhere between
967 * HOP3(min, anchored_offset)
968 * HOP3(max, anchored_offset) + SvCUR(substr)
971 /* if "other" is floating
972 * Calculate last1, the absolute latest point where the
973 * floating substr could start in the string, ignoring any
974 * constraints from the earlier fixed match. It is calculated
977 * strend - prog->minlen (in chars) is the absolute latest
978 * position within the string where the origin of the regex
979 * could appear. The latest start point for the floating
980 * substr is float_min_offset(*) on from the start of the
981 * regex. last1 simply combines thee two offsets.
983 * (*) You might think the latest start point should be
984 * float_max_offset from the regex origin, and technically
985 * you'd be correct. However, consider
987 * Here, float min, max are 3,5 and minlen is 7.
988 * This can match either
992 * In the first case, the regex matches minlen chars; in the
993 * second, minlen+1, in the third, minlen+2.
994 * In the first case, the floating offset is 3 (which equals
995 * float_min), in the second, 4, and in the third, 5 (which
996 * equals float_max). In all cases, the floating string bcd
997 * can never start more than 4 chars from the end of the
998 * string, which equals minlen - float_min. As the substring
999 * starts to match more than float_min from the start of the
1000 * regex, it makes the regex match more than minlen chars,
1001 * and the two cancel each other out. So we can always use
1002 * float_min - minlen, rather than float_max - minlen for the
1003 * latest position in the string.
1005 * Note that -minlen + float_min_offset is equivalent (AFAIKT)
1006 * to CHR_SVLEN(must) - !!SvTAIL(must) + prog->float_end_shift
1009 assert(prog->minlen >= other->min_offset);
1010 last1 = HOP3c(strend,
1011 other->min_offset - prog->minlen, strbeg);
1013 if (other_ix) {/* i.e. if (other-is-float) */
1014 /* last is the latest point where the floating substr could
1015 * start, *given* any constraints from the earlier fixed
1016 * match. This constraint is that the floating string starts
1017 * <= float_max_offset chars from the regex origin (rx_origin).
1018 * If this value is less than last1, use it instead.
1020 assert(rx_origin <= last1);
1022 /* this condition handles the offset==infinity case, and
1023 * is a short-cut otherwise. Although it's comparing a
1024 * byte offset to a char length, it does so in a safe way,
1025 * since 1 char always occupies 1 or more bytes,
1026 * so if a string range is (last1 - rx_origin) bytes,
1027 * it will be less than or equal to (last1 - rx_origin)
1028 * chars; meaning it errs towards doing the accurate HOP3
1029 * rather than just using last1 as a short-cut */
1030 (last1 - rx_origin) < other->max_offset
1032 : (char*)HOP3lim(rx_origin, other->max_offset, last1);
1035 assert(strpos + start_shift <= check_at);
1036 last = HOP4c(check_at, other->min_offset - start_shift,
1040 s = HOP3c(rx_origin, other->min_offset, strend);
1041 if (s < other_last) /* These positions already checked */
1044 must = utf8_target ? other->utf8_substr : other->substr;
1045 assert(SvPOK(must));
1048 char *to = last + SvCUR(must) - (SvTAIL(must)!=0);
1052 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1053 " skipping 'other' fbm scan: %"IVdf" > %"IVdf"\n",
1054 (IV)(from - strbeg),
1060 (unsigned char*)from,
1063 multiline ? FBMrf_MULTILINE : 0
1065 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1066 " doing 'other' fbm scan, [%"IVdf"..%"IVdf"] gave %"IVdf"\n",
1067 (IV)(from - strbeg),
1069 (IV)(s ? s - strbeg : -1)
1075 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
1076 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
1077 PerlIO_printf(Perl_debug_log, " %s %s substr %s%s",
1078 s ? "Found" : "Contradicts",
1079 other_ix ? "floating" : "anchored",
1080 quoted, RE_SV_TAIL(must));
1085 /* last1 is latest possible substr location. If we didn't
1086 * find it before there, we never will */
1087 if (last >= last1) {
1088 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1089 "; giving up...\n"));
1093 /* try to find the check substr again at a later
1094 * position. Maybe next time we'll find the "other" substr
1096 other_last = HOP3c(last, 1, strend) /* highest failure */;
1098 other_ix /* i.e. if other-is-float */
1099 ? HOP3c(rx_origin, 1, strend)
1100 : HOP4c(last, 1 - other->min_offset, strbeg, strend);
1101 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1102 "; about to retry %s at offset %ld (rx_origin now %"IVdf")...\n",
1103 (other_ix ? "floating" : "anchored"),
1104 (long)(HOP3c(check_at, 1, strend) - strbeg),
1105 (IV)(rx_origin - strbeg)
1110 if (other_ix) { /* if (other-is-float) */
1111 /* other_last is set to s, not s+1, since its possible for
1112 * a floating substr to fail first time, then succeed
1113 * second time at the same floating position; e.g.:
1114 * "-AB--AABZ" =~ /\wAB\d*Z/
1115 * The first time round, anchored and float match at
1116 * "-(AB)--AAB(Z)" then fail on the initial \w character
1117 * class. Second time round, they match at "-AB--A(AB)(Z)".
1122 rx_origin = HOP3c(s, -other->min_offset, strbeg);
1123 other_last = HOP3c(s, 1, strend);
1125 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1126 " at offset %ld (rx_origin now %"IVdf")...\n",
1128 (IV)(rx_origin - strbeg)
1134 DEBUG_OPTIMISE_MORE_r(
1135 PerlIO_printf(Perl_debug_log,
1136 " Check-only match: offset min:%"IVdf" max:%"IVdf
1137 " check_at:%"IVdf" rx_origin:%"IVdf" rx_origin-check_at:%"IVdf
1138 " strend:%"IVdf"\n",
1139 (IV)prog->check_offset_min,
1140 (IV)prog->check_offset_max,
1141 (IV)(check_at-strbeg),
1142 (IV)(rx_origin-strbeg),
1143 (IV)(rx_origin-check_at),
1149 postprocess_substr_matches:
1151 /* handle the extra constraint of /^.../m if present */
1153 if (ml_anch && rx_origin != strbeg && rx_origin[-1] != '\n') {
1156 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1157 " looking for /^/m anchor"));
1159 /* we have failed the constraint of a \n before rx_origin.
1160 * Find the next \n, if any, even if it's beyond the current
1161 * anchored and/or floating substrings. Whether we should be
1162 * scanning ahead for the next \n or the next substr is debatable.
1163 * On the one hand you'd expect rare substrings to appear less
1164 * often than \n's. On the other hand, searching for \n means
1165 * we're effectively flipping between check_substr and "\n" on each
1166 * iteration as the current "rarest" string candidate, which
1167 * means for example that we'll quickly reject the whole string if
1168 * hasn't got a \n, rather than trying every substr position
1172 s = HOP3c(strend, - prog->minlen, strpos);
1173 if (s <= rx_origin ||
1174 ! ( rx_origin = (char *)memchr(rx_origin, '\n', s - rx_origin)))
1176 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1177 " Did not find /%s^%s/m...\n",
1178 PL_colors[0], PL_colors[1]));
1182 /* earliest possible origin is 1 char after the \n.
1183 * (since *rx_origin == '\n', it's safe to ++ here rather than
1184 * HOP(rx_origin, 1)) */
1187 if (prog->substrs->check_ix == 0 /* check is anchored */
1188 || rx_origin >= HOP3c(check_at, - prog->check_offset_min, strpos))
1190 /* Position contradicts check-string; either because
1191 * check was anchored (and thus has no wiggle room),
1192 * or check was float and rx_origin is above the float range */
1193 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1194 " Found /%s^%s/m, about to restart lookup for check-string with rx_origin %ld...\n",
1195 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1199 /* if we get here, the check substr must have been float,
1200 * is in range, and we may or may not have had an anchored
1201 * "other" substr which still contradicts */
1202 assert(prog->substrs->check_ix); /* check is float */
1204 if (utf8_target ? prog->anchored_utf8 : prog->anchored_substr) {
1205 /* whoops, the anchored "other" substr exists, so we still
1206 * contradict. On the other hand, the float "check" substr
1207 * didn't contradict, so just retry the anchored "other"
1209 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1210 " Found /%s^%s/m, rescanning for anchored from offset %"IVdf" (rx_origin now %"IVdf")...\n",
1211 PL_colors[0], PL_colors[1],
1212 (IV)(rx_origin - strbeg + prog->anchored_offset),
1213 (IV)(rx_origin - strbeg)
1215 goto do_other_substr;
1218 /* success: we don't contradict the found floating substring
1219 * (and there's no anchored substr). */
1220 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1221 " Found /%s^%s/m with rx_origin %ld...\n",
1222 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1225 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1226 " (multiline anchor test skipped)\n"));
1232 /* if we have a starting character class, then test that extra constraint.
1233 * (trie stclasses are too expensive to use here, we are better off to
1234 * leave it to regmatch itself) */
1236 if (progi->regstclass && PL_regkind[OP(progi->regstclass)]!=TRIE) {
1237 const U8* const str = (U8*)STRING(progi->regstclass);
1239 /* XXX this value could be pre-computed */
1240 const int cl_l = (PL_regkind[OP(progi->regstclass)] == EXACT
1241 ? (reginfo->is_utf8_pat
1242 ? utf8_distance(str + STR_LEN(progi->regstclass), str)
1243 : STR_LEN(progi->regstclass))
1247 /* latest pos that a matching float substr constrains rx start to */
1248 char *rx_max_float = NULL;
1250 /* if the current rx_origin is anchored, either by satisfying an
1251 * anchored substring constraint, or a /^.../m constraint, then we
1252 * can reject the current origin if the start class isn't found
1253 * at the current position. If we have a float-only match, then
1254 * rx_origin is constrained to a range; so look for the start class
1255 * in that range. if neither, then look for the start class in the
1256 * whole rest of the string */
1258 /* XXX DAPM it's not clear what the minlen test is for, and why
1259 * it's not used in the floating case. Nothing in the test suite
1260 * causes minlen == 0 here. See <20140313134639.GS12844@iabyn.com>.
1261 * Here are some old comments, which may or may not be correct:
1263 * minlen == 0 is possible if regstclass is \b or \B,
1264 * and the fixed substr is ''$.
1265 * Since minlen is already taken into account, rx_origin+1 is
1266 * before strend; accidentally, minlen >= 1 guaranties no false
1267 * positives at rx_origin + 1 even for \b or \B. But (minlen? 1 :
1268 * 0) below assumes that regstclass does not come from lookahead...
1269 * If regstclass takes bytelength more than 1: If charlength==1, OK.
1270 * This leaves EXACTF-ish only, which are dealt with in
1274 if (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
1275 endpos= HOP3c(rx_origin, (prog->minlen ? cl_l : 0), strend);
1276 else if (prog->float_substr || prog->float_utf8) {
1277 rx_max_float = HOP3c(check_at, -start_shift, strbeg);
1278 endpos= HOP3c(rx_max_float, cl_l, strend);
1283 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1284 " looking for class: start_shift: %"IVdf" check_at: %"IVdf
1285 " rx_origin: %"IVdf" endpos: %"IVdf"\n",
1286 (IV)start_shift, (IV)(check_at - strbeg),
1287 (IV)(rx_origin - strbeg), (IV)(endpos - strbeg)));
1289 s = find_byclass(prog, progi->regstclass, rx_origin, endpos,
1292 if (endpos == strend) {
1293 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1294 " Could not match STCLASS...\n") );
1297 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1298 " This position contradicts STCLASS...\n") );
1299 if ((prog->intflags & PREGf_ANCH) && !ml_anch
1300 && !(prog->intflags & PREGf_IMPLICIT))
1303 /* Contradict one of substrings */
1304 if (prog->anchored_substr || prog->anchored_utf8) {
1305 if (prog->substrs->check_ix == 1) { /* check is float */
1306 /* Have both, check_string is floating */
1307 assert(rx_origin + start_shift <= check_at);
1308 if (rx_origin + start_shift != check_at) {
1309 /* not at latest position float substr could match:
1310 * Recheck anchored substring, but not floating.
1311 * The condition above is in bytes rather than
1312 * chars for efficiency. It's conservative, in
1313 * that it errs on the side of doing 'goto
1314 * do_other_substr'. In this case, at worst,
1315 * an extra anchored search may get done, but in
1316 * practice the extra fbm_instr() is likely to
1317 * get skipped anyway. */
1318 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1319 " about to retry anchored at offset %ld (rx_origin now %"IVdf")...\n",
1320 (long)(other_last - strbeg),
1321 (IV)(rx_origin - strbeg)
1323 goto do_other_substr;
1331 /* In the presence of ml_anch, we might be able to
1332 * find another \n without breaking the current float
1335 /* strictly speaking this should be HOP3c(..., 1, ...),
1336 * but since we goto a block of code that's going to
1337 * search for the next \n if any, its safe here */
1339 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1340 " about to look for /%s^%s/m starting at rx_origin %ld...\n",
1341 PL_colors[0], PL_colors[1],
1342 (long)(rx_origin - strbeg)) );
1343 goto postprocess_substr_matches;
1346 /* strictly speaking this can never be true; but might
1347 * be if we ever allow intuit without substrings */
1348 if (!(utf8_target ? prog->float_utf8 : prog->float_substr))
1351 rx_origin = rx_max_float;
1354 /* at this point, any matching substrings have been
1355 * contradicted. Start again... */
1357 rx_origin = HOP3c(rx_origin, 1, strend);
1359 /* uses bytes rather than char calculations for efficiency.
1360 * It's conservative: it errs on the side of doing 'goto restart',
1361 * where there is code that does a proper char-based test */
1362 if (rx_origin + start_shift + end_shift > strend) {
1363 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1364 " Could not match STCLASS...\n") );
1367 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1368 " about to look for %s substr starting at offset %ld (rx_origin now %"IVdf")...\n",
1369 (prog->substrs->check_ix ? "floating" : "anchored"),
1370 (long)(rx_origin + start_shift - strbeg),
1371 (IV)(rx_origin - strbeg)
1378 if (rx_origin != s) {
1379 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1380 " By STCLASS: moving %ld --> %ld\n",
1381 (long)(rx_origin - strbeg), (long)(s - strbeg))
1385 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1386 " Does not contradict STCLASS...\n");
1391 /* Decide whether using the substrings helped */
1393 if (rx_origin != strpos) {
1394 /* Fixed substring is found far enough so that the match
1395 cannot start at strpos. */
1397 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " try at offset...\n"));
1398 ++BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr); /* hooray/5 */
1401 /* The found rx_origin position does not prohibit matching at
1402 * strpos, so calling intuit didn't gain us anything. Decrement
1403 * the BmUSEFUL() count on the check substring, and if we reach
1405 if (!(prog->intflags & PREGf_NAUGHTY)
1407 prog->check_utf8 /* Could be deleted already */
1408 && --BmUSEFUL(prog->check_utf8) < 0
1409 && (prog->check_utf8 == prog->float_utf8)
1411 prog->check_substr /* Could be deleted already */
1412 && --BmUSEFUL(prog->check_substr) < 0
1413 && (prog->check_substr == prog->float_substr)
1416 /* If flags & SOMETHING - do not do it many times on the same match */
1417 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " ... Disabling check substring...\n"));
1418 /* XXX Does the destruction order has to change with utf8_target? */
1419 SvREFCNT_dec(utf8_target ? prog->check_utf8 : prog->check_substr);
1420 SvREFCNT_dec(utf8_target ? prog->check_substr : prog->check_utf8);
1421 prog->check_substr = prog->check_utf8 = NULL; /* disable */
1422 prog->float_substr = prog->float_utf8 = NULL; /* clear */
1423 check = NULL; /* abort */
1424 /* XXXX This is a remnant of the old implementation. It
1425 looks wasteful, since now INTUIT can use many
1426 other heuristics. */
1427 prog->extflags &= ~RXf_USE_INTUIT;
1431 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1432 "Intuit: %sSuccessfully guessed:%s match at offset %ld\n",
1433 PL_colors[4], PL_colors[5], (long)(rx_origin - strbeg)) );
1437 fail_finish: /* Substring not found */
1438 if (prog->check_substr || prog->check_utf8) /* could be removed already */
1439 BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
1441 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch rejected by optimizer%s\n",
1442 PL_colors[4], PL_colors[5]));
1447 #define DECL_TRIE_TYPE(scan) \
1448 const enum { trie_plain, trie_utf8, trie_utf8_fold, trie_latin_utf8_fold, \
1449 trie_utf8_exactfa_fold, trie_latin_utf8_exactfa_fold, \
1450 trie_utf8l, trie_flu8 } \
1451 trie_type = ((scan->flags == EXACT) \
1452 ? (utf8_target ? trie_utf8 : trie_plain) \
1453 : (scan->flags == EXACTL) \
1454 ? (utf8_target ? trie_utf8l : trie_plain) \
1455 : (scan->flags == EXACTFA) \
1457 ? trie_utf8_exactfa_fold \
1458 : trie_latin_utf8_exactfa_fold) \
1459 : (scan->flags == EXACTFLU8 \
1463 : trie_latin_utf8_fold)))
1465 #define REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc, uscan, len, uvc, charid, foldlen, foldbuf, uniflags) \
1468 U8 flags = FOLD_FLAGS_FULL; \
1469 switch (trie_type) { \
1471 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1472 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1473 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1475 goto do_trie_utf8_fold; \
1476 case trie_utf8_exactfa_fold: \
1477 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1479 case trie_utf8_fold: \
1480 do_trie_utf8_fold: \
1481 if ( foldlen>0 ) { \
1482 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1487 uvc = _to_utf8_fold_flags( (const U8*) uc, foldbuf, &foldlen, flags); \
1488 len = UTF8SKIP(uc); \
1489 skiplen = UVCHR_SKIP( uvc ); \
1490 foldlen -= skiplen; \
1491 uscan = foldbuf + skiplen; \
1494 case trie_latin_utf8_exactfa_fold: \
1495 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1497 case trie_latin_utf8_fold: \
1498 if ( foldlen>0 ) { \
1499 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1505 uvc = _to_fold_latin1( (U8) *uc, foldbuf, &foldlen, flags); \
1506 skiplen = UVCHR_SKIP( uvc ); \
1507 foldlen -= skiplen; \
1508 uscan = foldbuf + skiplen; \
1512 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1513 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1514 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1518 uvc = utf8n_to_uvchr( (const U8*) uc, UTF8_MAXLEN, &len, uniflags ); \
1525 charid = trie->charmap[ uvc ]; \
1529 if (widecharmap) { \
1530 SV** const svpp = hv_fetch(widecharmap, \
1531 (char*)&uvc, sizeof(UV), 0); \
1533 charid = (U16)SvIV(*svpp); \
1538 #define DUMP_EXEC_POS(li,s,doutf8) \
1539 dump_exec_pos(li,s,(reginfo->strend),(reginfo->strbeg), \
1542 #define REXEC_FBC_EXACTISH_SCAN(COND) \
1546 && (ln == 1 || folder(s, pat_string, ln)) \
1547 && (reginfo->intuit || regtry(reginfo, &s)) )\
1553 #define REXEC_FBC_UTF8_SCAN(CODE) \
1555 while (s < strend) { \
1561 #define REXEC_FBC_SCAN(CODE) \
1563 while (s < strend) { \
1569 #define REXEC_FBC_UTF8_CLASS_SCAN(COND) \
1570 REXEC_FBC_UTF8_SCAN( /* Loops while (s < strend) */ \
1572 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1581 #define REXEC_FBC_CLASS_SCAN(COND) \
1582 REXEC_FBC_SCAN( /* Loops while (s < strend) */ \
1584 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1593 #define REXEC_FBC_CSCAN(CONDUTF8,COND) \
1594 if (utf8_target) { \
1595 REXEC_FBC_UTF8_CLASS_SCAN(CONDUTF8); \
1598 REXEC_FBC_CLASS_SCAN(COND); \
1601 /* The three macros below are slightly different versions of the same logic.
1603 * The first is for /a and /aa when the target string is UTF-8. This can only
1604 * match ascii, but it must advance based on UTF-8. The other two handle the
1605 * non-UTF-8 and the more generic UTF-8 cases. In all three, we are looking
1606 * for the boundary (or non-boundary) between a word and non-word character.
1607 * The utf8 and non-utf8 cases have the same logic, but the details must be
1608 * different. Find the "wordness" of the character just prior to this one, and
1609 * compare it with the wordness of this one. If they differ, we have a
1610 * boundary. At the beginning of the string, pretend that the previous
1611 * character was a new-line.
1613 * All these macros uncleanly have side-effects with each other and outside
1614 * variables. So far it's been too much trouble to clean-up
1616 * TEST_NON_UTF8 is the macro or function to call to test if its byte input is
1617 * a word character or not.
1618 * IF_SUCCESS is code to do if it finds that we are at a boundary between
1620 * IF_FAIL is code to do if we aren't at a boundary between word/non-word
1622 * Exactly one of the two IF_FOO parameters is a no-op, depending on whether we
1623 * are looking for a boundary or for a non-boundary. If we are looking for a
1624 * boundary, we want IF_FAIL to be the no-op, and for IF_SUCCESS to go out and
1625 * see if this tentative match actually works, and if so, to quit the loop
1626 * here. And vice-versa if we are looking for a non-boundary.
1628 * 'tmp' below in the next three macros in the REXEC_FBC_SCAN and
1629 * REXEC_FBC_UTF8_SCAN loops is a loop invariant, a bool giving the return of
1630 * TEST_NON_UTF8(s-1). To see this, note that that's what it is defined to be
1631 * at entry to the loop, and to get to the IF_FAIL branch, tmp must equal
1632 * TEST_NON_UTF8(s), and in the opposite branch, IF_SUCCESS, tmp is that
1633 * complement. But in that branch we complement tmp, meaning that at the
1634 * bottom of the loop tmp is always going to be equal to TEST_NON_UTF8(s),
1635 * which means at the top of the loop in the next iteration, it is
1636 * TEST_NON_UTF8(s-1) */
1637 #define FBC_UTF8_A(TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1638 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1639 tmp = TEST_NON_UTF8(tmp); \
1640 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1641 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1643 IF_SUCCESS; /* Is a boundary if values for s-1 and s differ */ \
1650 /* Like FBC_UTF8_A, but TEST_UV is a macro which takes a UV as its input, and
1651 * TEST_UTF8 is a macro that for the same input code points returns identically
1652 * to TEST_UV, but takes a pointer to a UTF-8 encoded string instead */
1653 #define FBC_UTF8(TEST_UV, TEST_UTF8, IF_SUCCESS, IF_FAIL) \
1654 if (s == reginfo->strbeg) { \
1657 else { /* Back-up to the start of the previous character */ \
1658 U8 * const r = reghop3((U8*)s, -1, (U8*)reginfo->strbeg); \
1659 tmp = utf8n_to_uvchr(r, (U8*) reginfo->strend - r, \
1660 0, UTF8_ALLOW_DEFAULT); \
1662 tmp = TEST_UV(tmp); \
1663 LOAD_UTF8_CHARCLASS_ALNUM(); \
1664 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1665 if (tmp == ! (TEST_UTF8((U8 *) s))) { \
1674 /* Like the above two macros. UTF8_CODE is the complete code for handling
1675 * UTF-8. Common to the BOUND and NBOUND cases, set-up by the FBC_BOUND, etc
1677 #define FBC_BOUND_COMMON(UTF8_CODE, TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1678 if (utf8_target) { \
1681 else { /* Not utf8 */ \
1682 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1683 tmp = TEST_NON_UTF8(tmp); \
1684 REXEC_FBC_SCAN( /* advances s while s < strend */ \
1685 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1694 /* Here, things have been set up by the previous code so that tmp is the \
1695 * return of TEST_NON_UTF(s-1) or TEST_UTF8(s-1) (depending on the \
1696 * utf8ness of the target). We also have to check if this matches against \
1697 * the EOS, which we treat as a \n (which is the same value in both UTF-8 \
1698 * or non-UTF8, so can use the non-utf8 test condition even for a UTF-8 \
1700 if (tmp == ! TEST_NON_UTF8('\n')) { \
1707 /* This is the macro to use when we want to see if something that looks like it
1708 * could match, actually does, and if so exits the loop */
1709 #define REXEC_FBC_TRYIT \
1710 if ((reginfo->intuit || regtry(reginfo, &s))) \
1713 /* The only difference between the BOUND and NBOUND cases is that
1714 * REXEC_FBC_TRYIT is called when matched in BOUND, and when non-matched in
1715 * NBOUND. This is accomplished by passing it as either the if or else clause,
1716 * with the other one being empty (PLACEHOLDER is defined as empty).
1718 * The TEST_FOO parameters are for operating on different forms of input, but
1719 * all should be ones that return identically for the same underlying code
1721 #define FBC_BOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1723 FBC_UTF8(TEST_UV, TEST_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1724 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1726 #define FBC_BOUND_A(TEST_NON_UTF8) \
1728 FBC_UTF8_A(TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1729 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1731 #define FBC_NBOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1733 FBC_UTF8(TEST_UV, TEST_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1734 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1736 #define FBC_NBOUND_A(TEST_NON_UTF8) \
1738 FBC_UTF8_A(TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1739 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1743 S_get_break_val_cp_checked(SV* const invlist, const UV cp_in) {
1744 IV cp_out = Perl__invlist_search(invlist, cp_in);
1745 assert(cp_out >= 0);
1748 # define _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp) \
1749 invmap[S_get_break_val_cp_checked(invlist, cp)]
1751 # define _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp) \
1752 invmap[_invlist_search(invlist, cp)]
1755 /* Takes a pointer to an inversion list, a pointer to its corresponding
1756 * inversion map, and a code point, and returns the code point's value
1757 * according to the two arrays. It assumes that all code points have a value.
1758 * This is used as the base macro for macros for particular properties */
1759 #define _generic_GET_BREAK_VAL_CP(invlist, invmap, cp) \
1760 _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp)
1762 /* Same as above, but takes begin, end ptrs to a UTF-8 encoded string instead
1763 * of a code point, returning the value for the first code point in the string.
1764 * And it takes the particular macro name that finds the desired value given a
1765 * code point. Merely convert the UTF-8 to code point and call the cp macro */
1766 #define _generic_GET_BREAK_VAL_UTF8(cp_macro, pos, strend) \
1767 (__ASSERT_(pos < strend) \
1768 /* Note assumes is valid UTF-8 */ \
1769 (cp_macro(utf8_to_uvchr_buf((pos), (strend), NULL))))
1771 /* Returns the GCB value for the input code point */
1772 #define getGCB_VAL_CP(cp) \
1773 _generic_GET_BREAK_VAL_CP( \
1778 /* Returns the GCB value for the first code point in the UTF-8 encoded string
1779 * bounded by pos and strend */
1780 #define getGCB_VAL_UTF8(pos, strend) \
1781 _generic_GET_BREAK_VAL_UTF8(getGCB_VAL_CP, pos, strend)
1783 /* Returns the LB value for the input code point */
1784 #define getLB_VAL_CP(cp) \
1785 _generic_GET_BREAK_VAL_CP( \
1790 /* Returns the LB value for the first code point in the UTF-8 encoded string
1791 * bounded by pos and strend */
1792 #define getLB_VAL_UTF8(pos, strend) \
1793 _generic_GET_BREAK_VAL_UTF8(getLB_VAL_CP, pos, strend)
1796 /* Returns the SB value for the input code point */
1797 #define getSB_VAL_CP(cp) \
1798 _generic_GET_BREAK_VAL_CP( \
1803 /* Returns the SB value for the first code point in the UTF-8 encoded string
1804 * bounded by pos and strend */
1805 #define getSB_VAL_UTF8(pos, strend) \
1806 _generic_GET_BREAK_VAL_UTF8(getSB_VAL_CP, pos, strend)
1808 /* Returns the WB value for the input code point */
1809 #define getWB_VAL_CP(cp) \
1810 _generic_GET_BREAK_VAL_CP( \
1815 /* Returns the WB value for the first code point in the UTF-8 encoded string
1816 * bounded by pos and strend */
1817 #define getWB_VAL_UTF8(pos, strend) \
1818 _generic_GET_BREAK_VAL_UTF8(getWB_VAL_CP, pos, strend)
1820 /* We know what class REx starts with. Try to find this position... */
1821 /* if reginfo->intuit, its a dryrun */
1822 /* annoyingly all the vars in this routine have different names from their counterparts
1823 in regmatch. /grrr */
1825 S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
1826 const char *strend, regmatch_info *reginfo)
1829 const I32 doevery = (prog->intflags & PREGf_SKIP) == 0;
1830 char *pat_string; /* The pattern's exactish string */
1831 char *pat_end; /* ptr to end char of pat_string */
1832 re_fold_t folder; /* Function for computing non-utf8 folds */
1833 const U8 *fold_array; /* array for folding ords < 256 */
1839 I32 tmp = 1; /* Scratch variable? */
1840 const bool utf8_target = reginfo->is_utf8_target;
1841 UV utf8_fold_flags = 0;
1842 const bool is_utf8_pat = reginfo->is_utf8_pat;
1843 bool to_complement = FALSE; /* Invert the result? Taking the xor of this
1844 with a result inverts that result, as 0^1 =
1846 _char_class_number classnum;
1848 RXi_GET_DECL(prog,progi);
1850 PERL_ARGS_ASSERT_FIND_BYCLASS;
1852 /* We know what class it must start with. */
1855 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1857 if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(c)) && ! IN_UTF8_CTYPE_LOCALE) {
1858 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
1865 REXEC_FBC_UTF8_CLASS_SCAN(
1866 reginclass(prog, c, (U8*)s, (U8*) strend, utf8_target));
1869 REXEC_FBC_CLASS_SCAN(REGINCLASS(prog, c, (U8*)s, 0));
1873 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
1874 assert(! is_utf8_pat);
1877 if (is_utf8_pat || utf8_target) {
1878 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
1879 goto do_exactf_utf8;
1881 fold_array = PL_fold_latin1; /* Latin1 folds are not affected by */
1882 folder = foldEQ_latin1; /* /a, except the sharp s one which */
1883 goto do_exactf_non_utf8; /* isn't dealt with by these */
1885 case EXACTF: /* This node only generated for non-utf8 patterns */
1886 assert(! is_utf8_pat);
1888 utf8_fold_flags = 0;
1889 goto do_exactf_utf8;
1891 fold_array = PL_fold;
1893 goto do_exactf_non_utf8;
1896 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1897 if (is_utf8_pat || utf8_target || IN_UTF8_CTYPE_LOCALE) {
1898 utf8_fold_flags = FOLDEQ_LOCALE;
1899 goto do_exactf_utf8;
1901 fold_array = PL_fold_locale;
1902 folder = foldEQ_locale;
1903 goto do_exactf_non_utf8;
1907 utf8_fold_flags = FOLDEQ_S2_ALREADY_FOLDED;
1909 goto do_exactf_utf8;
1912 if (! utf8_target) { /* All code points in this node require
1913 UTF-8 to express. */
1916 utf8_fold_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
1917 | FOLDEQ_S2_FOLDS_SANE;
1918 goto do_exactf_utf8;
1921 if (is_utf8_pat || utf8_target) {
1922 utf8_fold_flags = is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
1923 goto do_exactf_utf8;
1926 /* Any 'ss' in the pattern should have been replaced by regcomp,
1927 * so we don't have to worry here about this single special case
1928 * in the Latin1 range */
1929 fold_array = PL_fold_latin1;
1930 folder = foldEQ_latin1;
1934 do_exactf_non_utf8: /* Neither pattern nor string are UTF8, and there
1935 are no glitches with fold-length differences
1936 between the target string and pattern */
1938 /* The idea in the non-utf8 EXACTF* cases is to first find the
1939 * first character of the EXACTF* node and then, if necessary,
1940 * case-insensitively compare the full text of the node. c1 is the
1941 * first character. c2 is its fold. This logic will not work for
1942 * Unicode semantics and the german sharp ss, which hence should
1943 * not be compiled into a node that gets here. */
1944 pat_string = STRING(c);
1945 ln = STR_LEN(c); /* length to match in octets/bytes */
1947 /* We know that we have to match at least 'ln' bytes (which is the
1948 * same as characters, since not utf8). If we have to match 3
1949 * characters, and there are only 2 availabe, we know without
1950 * trying that it will fail; so don't start a match past the
1951 * required minimum number from the far end */
1952 e = HOP3c(strend, -((SSize_t)ln), s);
1954 if (reginfo->intuit && e < s) {
1955 e = s; /* Due to minlen logic of intuit() */
1959 c2 = fold_array[c1];
1960 if (c1 == c2) { /* If char and fold are the same */
1961 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1);
1964 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1 || *(U8*)s == c2);
1972 /* If one of the operands is in utf8, we can't use the simpler folding
1973 * above, due to the fact that many different characters can have the
1974 * same fold, or portion of a fold, or different- length fold */
1975 pat_string = STRING(c);
1976 ln = STR_LEN(c); /* length to match in octets/bytes */
1977 pat_end = pat_string + ln;
1978 lnc = is_utf8_pat /* length to match in characters */
1979 ? utf8_length((U8 *) pat_string, (U8 *) pat_end)
1982 /* We have 'lnc' characters to match in the pattern, but because of
1983 * multi-character folding, each character in the target can match
1984 * up to 3 characters (Unicode guarantees it will never exceed
1985 * this) if it is utf8-encoded; and up to 2 if not (based on the
1986 * fact that the Latin 1 folds are already determined, and the
1987 * only multi-char fold in that range is the sharp-s folding to
1988 * 'ss'. Thus, a pattern character can match as little as 1/3 of a
1989 * string character. Adjust lnc accordingly, rounding up, so that
1990 * if we need to match at least 4+1/3 chars, that really is 5. */
1991 expansion = (utf8_target) ? UTF8_MAX_FOLD_CHAR_EXPAND : 2;
1992 lnc = (lnc + expansion - 1) / expansion;
1994 /* As in the non-UTF8 case, if we have to match 3 characters, and
1995 * only 2 are left, it's guaranteed to fail, so don't start a
1996 * match that would require us to go beyond the end of the string
1998 e = HOP3c(strend, -((SSize_t)lnc), s);
2000 if (reginfo->intuit && e < s) {
2001 e = s; /* Due to minlen logic of intuit() */
2004 /* XXX Note that we could recalculate e to stop the loop earlier,
2005 * as the worst case expansion above will rarely be met, and as we
2006 * go along we would usually find that e moves further to the left.
2007 * This would happen only after we reached the point in the loop
2008 * where if there were no expansion we should fail. Unclear if
2009 * worth the expense */
2012 char *my_strend= (char *)strend;
2013 if (foldEQ_utf8_flags(s, &my_strend, 0, utf8_target,
2014 pat_string, NULL, ln, is_utf8_pat, utf8_fold_flags)
2015 && (reginfo->intuit || regtry(reginfo, &s)) )
2019 s += (utf8_target) ? UTF8SKIP(s) : 1;
2025 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2026 if (FLAGS(c) != TRADITIONAL_BOUND) {
2027 if (! IN_UTF8_CTYPE_LOCALE) {
2028 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2029 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2034 FBC_BOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8);
2038 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2039 if (FLAGS(c) != TRADITIONAL_BOUND) {
2040 if (! IN_UTF8_CTYPE_LOCALE) {
2041 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2042 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2047 FBC_NBOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8);
2050 case BOUND: /* regcomp.c makes sure that this only has the traditional \b
2052 assert(FLAGS(c) == TRADITIONAL_BOUND);
2054 FBC_BOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8);
2057 case BOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2059 assert(FLAGS(c) == TRADITIONAL_BOUND);
2061 FBC_BOUND_A(isWORDCHAR_A);
2064 case NBOUND: /* regcomp.c makes sure that this only has the traditional \b
2066 assert(FLAGS(c) == TRADITIONAL_BOUND);
2068 FBC_NBOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8);
2071 case NBOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2073 assert(FLAGS(c) == TRADITIONAL_BOUND);
2075 FBC_NBOUND_A(isWORDCHAR_A);
2079 if ((bound_type) FLAGS(c) == TRADITIONAL_BOUND) {
2080 FBC_NBOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8);
2091 switch((bound_type) FLAGS(c)) {
2092 case TRADITIONAL_BOUND:
2093 FBC_BOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8);
2096 if (s == reginfo->strbeg) {
2097 if (reginfo->intuit || regtry(reginfo, &s))
2102 /* Didn't match. Try at the next position (if there is one) */
2103 s += (utf8_target) ? UTF8SKIP(s) : 1;
2104 if (UNLIKELY(s >= reginfo->strend)) {
2110 GCB_enum before = getGCB_VAL_UTF8(
2112 (U8*)(reginfo->strbeg)),
2113 (U8*) reginfo->strend);
2114 while (s < strend) {
2115 GCB_enum after = getGCB_VAL_UTF8((U8*) s,
2116 (U8*) reginfo->strend);
2117 if ( (to_complement ^ isGCB(before, after))
2118 && (reginfo->intuit || regtry(reginfo, &s)))
2126 else { /* Not utf8. Everything is a GCB except between CR and
2128 while (s < strend) {
2129 if ((to_complement ^ ( UCHARAT(s - 1) != '\r'
2130 || UCHARAT(s) != '\n'))
2131 && (reginfo->intuit || regtry(reginfo, &s)))
2139 /* And, since this is a bound, it can match after the final
2140 * character in the string */
2141 if ((reginfo->intuit || regtry(reginfo, &s))) {
2147 if (s == reginfo->strbeg) {
2148 if (reginfo->intuit || regtry(reginfo, &s)) {
2151 s += (utf8_target) ? UTF8SKIP(s) : 1;
2152 if (UNLIKELY(s >= reginfo->strend)) {
2158 LB_enum before = getLB_VAL_UTF8(reghop3((U8*)s,
2160 (U8*)(reginfo->strbeg)),
2161 (U8*) reginfo->strend);
2162 while (s < strend) {
2163 LB_enum after = getLB_VAL_UTF8((U8*) s, (U8*) reginfo->strend);
2164 if (to_complement ^ isLB(before,
2166 (U8*) reginfo->strbeg,
2168 (U8*) reginfo->strend,
2170 && (reginfo->intuit || regtry(reginfo, &s)))
2178 else { /* Not utf8. */
2179 LB_enum before = getLB_VAL_CP((U8) *(s -1));
2180 while (s < strend) {
2181 LB_enum after = getLB_VAL_CP((U8) *s);
2182 if (to_complement ^ isLB(before,
2184 (U8*) reginfo->strbeg,
2186 (U8*) reginfo->strend,
2188 && (reginfo->intuit || regtry(reginfo, &s)))
2197 if (reginfo->intuit || regtry(reginfo, &s)) {
2204 if (s == reginfo->strbeg) {
2205 if (reginfo->intuit || regtry(reginfo, &s)) {
2208 s += (utf8_target) ? UTF8SKIP(s) : 1;
2209 if (UNLIKELY(s >= reginfo->strend)) {
2215 SB_enum before = getSB_VAL_UTF8(reghop3((U8*)s,
2217 (U8*)(reginfo->strbeg)),
2218 (U8*) reginfo->strend);
2219 while (s < strend) {
2220 SB_enum after = getSB_VAL_UTF8((U8*) s,
2221 (U8*) reginfo->strend);
2222 if ((to_complement ^ isSB(before,
2224 (U8*) reginfo->strbeg,
2226 (U8*) reginfo->strend,
2228 && (reginfo->intuit || regtry(reginfo, &s)))
2236 else { /* Not utf8. */
2237 SB_enum before = getSB_VAL_CP((U8) *(s -1));
2238 while (s < strend) {
2239 SB_enum after = getSB_VAL_CP((U8) *s);
2240 if ((to_complement ^ isSB(before,
2242 (U8*) reginfo->strbeg,
2244 (U8*) reginfo->strend,
2246 && (reginfo->intuit || regtry(reginfo, &s)))
2255 /* Here are at the final position in the target string. The SB
2256 * value is always true here, so matches, depending on other
2258 if (reginfo->intuit || regtry(reginfo, &s)) {
2265 if (s == reginfo->strbeg) {
2266 if (reginfo->intuit || regtry(reginfo, &s)) {
2269 s += (utf8_target) ? UTF8SKIP(s) : 1;
2270 if (UNLIKELY(s >= reginfo->strend)) {
2276 /* We are at a boundary between char_sub_0 and char_sub_1.
2277 * We also keep track of the value for char_sub_-1 as we
2278 * loop through the line. Context may be needed to make a
2279 * determination, and if so, this can save having to
2281 WB_enum previous = WB_UNKNOWN;
2282 WB_enum before = getWB_VAL_UTF8(
2285 (U8*)(reginfo->strbeg)),
2286 (U8*) reginfo->strend);
2287 while (s < strend) {
2288 WB_enum after = getWB_VAL_UTF8((U8*) s,
2289 (U8*) reginfo->strend);
2290 if ((to_complement ^ isWB(previous,
2293 (U8*) reginfo->strbeg,
2295 (U8*) reginfo->strend,
2297 && (reginfo->intuit || regtry(reginfo, &s)))
2306 else { /* Not utf8. */
2307 WB_enum previous = WB_UNKNOWN;
2308 WB_enum before = getWB_VAL_CP((U8) *(s -1));
2309 while (s < strend) {
2310 WB_enum after = getWB_VAL_CP((U8) *s);
2311 if ((to_complement ^ isWB(previous,
2314 (U8*) reginfo->strbeg,
2316 (U8*) reginfo->strend,
2318 && (reginfo->intuit || regtry(reginfo, &s)))
2328 if (reginfo->intuit || regtry(reginfo, &s)) {
2335 REXEC_FBC_CSCAN(is_LNBREAK_utf8_safe(s, strend),
2336 is_LNBREAK_latin1_safe(s, strend)
2340 /* The argument to all the POSIX node types is the class number to pass to
2341 * _generic_isCC() to build a mask for searching in PL_charclass[] */
2348 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2349 REXEC_FBC_CSCAN(to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(c), (U8 *) s)),
2350 to_complement ^ cBOOL(isFOO_lc(FLAGS(c), *s)));
2365 /* The complement of something that matches only ASCII matches all
2366 * non-ASCII, plus everything in ASCII that isn't in the class. */
2367 REXEC_FBC_UTF8_CLASS_SCAN(! isASCII_utf8(s)
2368 || ! _generic_isCC_A(*s, FLAGS(c)));
2377 /* Don't need to worry about utf8, as it can match only a single
2378 * byte invariant character. */
2379 REXEC_FBC_CLASS_SCAN(
2380 to_complement ^ cBOOL(_generic_isCC_A(*s, FLAGS(c))));
2388 if (! utf8_target) {
2389 REXEC_FBC_CLASS_SCAN(to_complement ^ cBOOL(_generic_isCC(*s,
2395 classnum = (_char_class_number) FLAGS(c);
2396 if (classnum < _FIRST_NON_SWASH_CC) {
2397 while (s < strend) {
2399 /* We avoid loading in the swash as long as possible, but
2400 * should we have to, we jump to a separate loop. This
2401 * extra 'if' statement is what keeps this code from being
2402 * just a call to REXEC_FBC_UTF8_CLASS_SCAN() */
2403 if (UTF8_IS_ABOVE_LATIN1(*s)) {
2404 goto found_above_latin1;
2406 if ((UTF8_IS_INVARIANT(*s)
2407 && to_complement ^ cBOOL(_generic_isCC((U8) *s,
2409 || (UTF8_IS_DOWNGRADEABLE_START(*s)
2410 && to_complement ^ cBOOL(
2411 _generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(*s,
2415 if (tmp && (reginfo->intuit || regtry(reginfo, &s)))
2427 else switch (classnum) { /* These classes are implemented as
2429 case _CC_ENUM_SPACE:
2430 REXEC_FBC_UTF8_CLASS_SCAN(
2431 to_complement ^ cBOOL(isSPACE_utf8(s)));
2434 case _CC_ENUM_BLANK:
2435 REXEC_FBC_UTF8_CLASS_SCAN(
2436 to_complement ^ cBOOL(isBLANK_utf8(s)));
2439 case _CC_ENUM_XDIGIT:
2440 REXEC_FBC_UTF8_CLASS_SCAN(
2441 to_complement ^ cBOOL(isXDIGIT_utf8(s)));
2444 case _CC_ENUM_VERTSPACE:
2445 REXEC_FBC_UTF8_CLASS_SCAN(
2446 to_complement ^ cBOOL(isVERTWS_utf8(s)));
2449 case _CC_ENUM_CNTRL:
2450 REXEC_FBC_UTF8_CLASS_SCAN(
2451 to_complement ^ cBOOL(isCNTRL_utf8(s)));
2455 Perl_croak(aTHX_ "panic: find_byclass() node %d='%s' has an unexpected character class '%d'", OP(c), PL_reg_name[OP(c)], classnum);
2456 NOT_REACHED; /* NOTREACHED */
2461 found_above_latin1: /* Here we have to load a swash to get the result
2462 for the current code point */
2463 if (! PL_utf8_swash_ptrs[classnum]) {
2464 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
2465 PL_utf8_swash_ptrs[classnum] =
2466 _core_swash_init("utf8",
2469 PL_XPosix_ptrs[classnum], &flags);
2472 /* This is a copy of the loop above for swash classes, though using the
2473 * FBC macro instead of being expanded out. Since we've loaded the
2474 * swash, we don't have to check for that each time through the loop */
2475 REXEC_FBC_UTF8_CLASS_SCAN(
2476 to_complement ^ cBOOL(_generic_utf8(
2479 swash_fetch(PL_utf8_swash_ptrs[classnum],
2487 /* what trie are we using right now */
2488 reg_ac_data *aho = (reg_ac_data*)progi->data->data[ ARG( c ) ];
2489 reg_trie_data *trie = (reg_trie_data*)progi->data->data[ aho->trie ];
2490 HV *widecharmap = MUTABLE_HV(progi->data->data[ aho->trie + 1 ]);
2492 const char *last_start = strend - trie->minlen;
2494 const char *real_start = s;
2496 STRLEN maxlen = trie->maxlen;
2498 U8 **points; /* map of where we were in the input string
2499 when reading a given char. For ASCII this
2500 is unnecessary overhead as the relationship
2501 is always 1:1, but for Unicode, especially
2502 case folded Unicode this is not true. */
2503 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
2507 GET_RE_DEBUG_FLAGS_DECL;
2509 /* We can't just allocate points here. We need to wrap it in
2510 * an SV so it gets freed properly if there is a croak while
2511 * running the match */
2514 sv_points=newSV(maxlen * sizeof(U8 *));
2515 SvCUR_set(sv_points,
2516 maxlen * sizeof(U8 *));
2517 SvPOK_on(sv_points);
2518 sv_2mortal(sv_points);
2519 points=(U8**)SvPV_nolen(sv_points );
2520 if ( trie_type != trie_utf8_fold
2521 && (trie->bitmap || OP(c)==AHOCORASICKC) )
2524 bitmap=(U8*)trie->bitmap;
2526 bitmap=(U8*)ANYOF_BITMAP(c);
2528 /* this is the Aho-Corasick algorithm modified a touch
2529 to include special handling for long "unknown char" sequences.
2530 The basic idea being that we use AC as long as we are dealing
2531 with a possible matching char, when we encounter an unknown char
2532 (and we have not encountered an accepting state) we scan forward
2533 until we find a legal starting char.
2534 AC matching is basically that of trie matching, except that when
2535 we encounter a failing transition, we fall back to the current
2536 states "fail state", and try the current char again, a process
2537 we repeat until we reach the root state, state 1, or a legal
2538 transition. If we fail on the root state then we can either
2539 terminate if we have reached an accepting state previously, or
2540 restart the entire process from the beginning if we have not.
2543 while (s <= last_start) {
2544 const U32 uniflags = UTF8_ALLOW_DEFAULT;
2552 U8 *uscan = (U8*)NULL;
2553 U8 *leftmost = NULL;
2555 U32 accepted_word= 0;
2559 while ( state && uc <= (U8*)strend ) {
2561 U32 word = aho->states[ state ].wordnum;
2565 DEBUG_TRIE_EXECUTE_r(
2566 if ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2567 dump_exec_pos( (char *)uc, c, strend, real_start,
2568 (char *)uc, utf8_target );
2569 PerlIO_printf( Perl_debug_log,
2570 " Scanning for legal start char...\n");
2574 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2578 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2584 if (uc >(U8*)last_start) break;
2588 U8 *lpos= points[ (pointpos - trie->wordinfo[word].len) % maxlen ];
2589 if (!leftmost || lpos < leftmost) {
2590 DEBUG_r(accepted_word=word);
2596 points[pointpos++ % maxlen]= uc;
2597 if (foldlen || uc < (U8*)strend) {
2598 REXEC_TRIE_READ_CHAR(trie_type, trie,
2600 uscan, len, uvc, charid, foldlen,
2602 DEBUG_TRIE_EXECUTE_r({
2603 dump_exec_pos( (char *)uc, c, strend,
2604 real_start, s, utf8_target);
2605 PerlIO_printf(Perl_debug_log,
2606 " Charid:%3u CP:%4"UVxf" ",
2618 word = aho->states[ state ].wordnum;
2620 base = aho->states[ state ].trans.base;
2622 DEBUG_TRIE_EXECUTE_r({
2624 dump_exec_pos( (char *)uc, c, strend, real_start,
2626 PerlIO_printf( Perl_debug_log,
2627 "%sState: %4"UVxf", word=%"UVxf,
2628 failed ? " Fail transition to " : "",
2629 (UV)state, (UV)word);
2635 ( ((offset = base + charid
2636 - 1 - trie->uniquecharcount)) >= 0)
2637 && ((U32)offset < trie->lasttrans)
2638 && trie->trans[offset].check == state
2639 && (tmp=trie->trans[offset].next))
2641 DEBUG_TRIE_EXECUTE_r(
2642 PerlIO_printf( Perl_debug_log," - legal\n"));
2647 DEBUG_TRIE_EXECUTE_r(
2648 PerlIO_printf( Perl_debug_log," - fail\n"));
2650 state = aho->fail[state];
2654 /* we must be accepting here */
2655 DEBUG_TRIE_EXECUTE_r(
2656 PerlIO_printf( Perl_debug_log," - accepting\n"));
2665 if (!state) state = 1;
2668 if ( aho->states[ state ].wordnum ) {
2669 U8 *lpos = points[ (pointpos - trie->wordinfo[aho->states[ state ].wordnum].len) % maxlen ];
2670 if (!leftmost || lpos < leftmost) {
2671 DEBUG_r(accepted_word=aho->states[ state ].wordnum);
2676 s = (char*)leftmost;
2677 DEBUG_TRIE_EXECUTE_r({
2679 Perl_debug_log,"Matches word #%"UVxf" at position %"IVdf". Trying full pattern...\n",
2680 (UV)accepted_word, (IV)(s - real_start)
2683 if (reginfo->intuit || regtry(reginfo, &s)) {
2689 DEBUG_TRIE_EXECUTE_r({
2690 PerlIO_printf( Perl_debug_log,"Pattern failed. Looking for new start point...\n");
2693 DEBUG_TRIE_EXECUTE_r(
2694 PerlIO_printf( Perl_debug_log,"No match.\n"));
2703 Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
2710 /* set RX_SAVED_COPY, RX_SUBBEG etc.
2711 * flags have same meanings as with regexec_flags() */
2714 S_reg_set_capture_string(pTHX_ REGEXP * const rx,
2721 struct regexp *const prog = ReANY(rx);
2723 if (flags & REXEC_COPY_STR) {
2727 PerlIO_printf(Perl_debug_log,
2728 "Copy on write: regexp capture, type %d\n",
2731 /* Create a new COW SV to share the match string and store
2732 * in saved_copy, unless the current COW SV in saved_copy
2733 * is valid and suitable for our purpose */
2734 if (( prog->saved_copy
2735 && SvIsCOW(prog->saved_copy)
2736 && SvPOKp(prog->saved_copy)
2739 && SvPVX(sv) == SvPVX(prog->saved_copy)))
2741 /* just reuse saved_copy SV */
2742 if (RXp_MATCH_COPIED(prog)) {
2743 Safefree(prog->subbeg);
2744 RXp_MATCH_COPIED_off(prog);
2748 /* create new COW SV to share string */
2749 RX_MATCH_COPY_FREE(rx);
2750 prog->saved_copy = sv_setsv_cow(prog->saved_copy, sv);
2752 prog->subbeg = (char *)SvPVX_const(prog->saved_copy);
2753 assert (SvPOKp(prog->saved_copy));
2754 prog->sublen = strend - strbeg;
2755 prog->suboffset = 0;
2756 prog->subcoffset = 0;
2761 SSize_t max = strend - strbeg;
2764 if ( (flags & REXEC_COPY_SKIP_POST)
2765 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2766 && !(PL_sawampersand & SAWAMPERSAND_RIGHT)
2767 ) { /* don't copy $' part of string */
2770 /* calculate the right-most part of the string covered
2771 * by a capture. Due to lookahead, this may be to
2772 * the right of $&, so we have to scan all captures */
2773 while (n <= prog->lastparen) {
2774 if (prog->offs[n].end > max)
2775 max = prog->offs[n].end;
2779 max = (PL_sawampersand & SAWAMPERSAND_LEFT)
2780 ? prog->offs[0].start
2782 assert(max >= 0 && max <= strend - strbeg);
2785 if ( (flags & REXEC_COPY_SKIP_PRE)
2786 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2787 && !(PL_sawampersand & SAWAMPERSAND_LEFT)
2788 ) { /* don't copy $` part of string */
2791 /* calculate the left-most part of the string covered
2792 * by a capture. Due to lookbehind, this may be to
2793 * the left of $&, so we have to scan all captures */
2794 while (min && n <= prog->lastparen) {
2795 if ( prog->offs[n].start != -1
2796 && prog->offs[n].start < min)
2798 min = prog->offs[n].start;
2802 if ((PL_sawampersand & SAWAMPERSAND_RIGHT)
2803 && min > prog->offs[0].end
2805 min = prog->offs[0].end;
2809 assert(min >= 0 && min <= max && min <= strend - strbeg);
2812 if (RX_MATCH_COPIED(rx)) {
2813 if (sublen > prog->sublen)
2815 (char*)saferealloc(prog->subbeg, sublen+1);
2818 prog->subbeg = (char*)safemalloc(sublen+1);
2819 Copy(strbeg + min, prog->subbeg, sublen, char);
2820 prog->subbeg[sublen] = '\0';
2821 prog->suboffset = min;
2822 prog->sublen = sublen;
2823 RX_MATCH_COPIED_on(rx);
2825 prog->subcoffset = prog->suboffset;
2826 if (prog->suboffset && utf8_target) {
2827 /* Convert byte offset to chars.
2828 * XXX ideally should only compute this if @-/@+
2829 * has been seen, a la PL_sawampersand ??? */
2831 /* If there's a direct correspondence between the
2832 * string which we're matching and the original SV,
2833 * then we can use the utf8 len cache associated with
2834 * the SV. In particular, it means that under //g,
2835 * sv_pos_b2u() will use the previously cached
2836 * position to speed up working out the new length of
2837 * subcoffset, rather than counting from the start of
2838 * the string each time. This stops
2839 * $x = "\x{100}" x 1E6; 1 while $x =~ /(.)/g;
2840 * from going quadratic */
2841 if (SvPOKp(sv) && SvPVX(sv) == strbeg)
2842 prog->subcoffset = sv_pos_b2u_flags(sv, prog->subcoffset,
2843 SV_GMAGIC|SV_CONST_RETURN);
2845 prog->subcoffset = utf8_length((U8*)strbeg,
2846 (U8*)(strbeg+prog->suboffset));
2850 RX_MATCH_COPY_FREE(rx);
2851 prog->subbeg = strbeg;
2852 prog->suboffset = 0;
2853 prog->subcoffset = 0;
2854 prog->sublen = strend - strbeg;
2862 - regexec_flags - match a regexp against a string
2865 Perl_regexec_flags(pTHX_ REGEXP * const rx, char *stringarg, char *strend,
2866 char *strbeg, SSize_t minend, SV *sv, void *data, U32 flags)
2867 /* stringarg: the point in the string at which to begin matching */
2868 /* strend: pointer to null at end of string */
2869 /* strbeg: real beginning of string */
2870 /* minend: end of match must be >= minend bytes after stringarg. */
2871 /* sv: SV being matched: only used for utf8 flag, pos() etc; string
2872 * itself is accessed via the pointers above */
2873 /* data: May be used for some additional optimizations.
2874 Currently unused. */
2875 /* flags: For optimizations. See REXEC_* in regexp.h */
2878 struct regexp *const prog = ReANY(rx);
2882 SSize_t minlen; /* must match at least this many chars */
2883 SSize_t dontbother = 0; /* how many characters not to try at end */
2884 const bool utf8_target = cBOOL(DO_UTF8(sv));
2886 RXi_GET_DECL(prog,progi);
2887 regmatch_info reginfo_buf; /* create some info to pass to regtry etc */
2888 regmatch_info *const reginfo = ®info_buf;
2889 regexp_paren_pair *swap = NULL;
2891 GET_RE_DEBUG_FLAGS_DECL;
2893 PERL_ARGS_ASSERT_REGEXEC_FLAGS;
2894 PERL_UNUSED_ARG(data);
2896 /* Be paranoid... */
2898 Perl_croak(aTHX_ "NULL regexp parameter");
2902 debug_start_match(rx, utf8_target, stringarg, strend,
2906 startpos = stringarg;
2908 /* set these early as they may be used by the HOP macros below */
2909 reginfo->strbeg = strbeg;
2910 reginfo->strend = strend;
2911 reginfo->is_utf8_target = cBOOL(utf8_target);
2913 if (prog->intflags & PREGf_GPOS_SEEN) {
2916 /* set reginfo->ganch, the position where \G can match */
2919 (flags & REXEC_IGNOREPOS)
2920 ? stringarg /* use start pos rather than pos() */
2921 : ((mg = mg_find_mglob(sv)) && mg->mg_len >= 0)
2922 /* Defined pos(): */
2923 ? strbeg + MgBYTEPOS(mg, sv, strbeg, strend-strbeg)
2924 : strbeg; /* pos() not defined; use start of string */
2926 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
2927 "GPOS ganch set to strbeg[%"IVdf"]\n", (IV)(reginfo->ganch - strbeg)));
2929 /* in the presence of \G, we may need to start looking earlier in
2930 * the string than the suggested start point of stringarg:
2931 * if prog->gofs is set, then that's a known, fixed minimum
2934 * /ab|c\G/: gofs = 1
2935 * or if the minimum offset isn't known, then we have to go back
2936 * to the start of the string, e.g. /w+\G/
2939 if (prog->intflags & PREGf_ANCH_GPOS) {
2941 startpos = HOPBACKc(reginfo->ganch, prog->gofs);
2943 ((flags & REXEC_FAIL_ON_UNDERFLOW) && startpos < stringarg))
2945 DEBUG_r(PerlIO_printf(Perl_debug_log,
2946 "fail: ganch-gofs before earliest possible start\n"));
2951 startpos = reginfo->ganch;
2953 else if (prog->gofs) {
2954 startpos = HOPBACKc(startpos, prog->gofs);
2958 else if (prog->intflags & PREGf_GPOS_FLOAT)
2962 minlen = prog->minlen;
2963 if ((startpos + minlen) > strend || startpos < strbeg) {
2964 DEBUG_r(PerlIO_printf(Perl_debug_log,
2965 "Regex match can't succeed, so not even tried\n"));
2969 /* at the end of this function, we'll do a LEAVE_SCOPE(oldsave),
2970 * which will call destuctors to reset PL_regmatch_state, free higher
2971 * PL_regmatch_slabs, and clean up regmatch_info_aux and
2972 * regmatch_info_aux_eval */
2974 oldsave = PL_savestack_ix;
2978 if ((prog->extflags & RXf_USE_INTUIT)
2979 && !(flags & REXEC_CHECKED))
2981 s = re_intuit_start(rx, sv, strbeg, startpos, strend,
2986 if (prog->extflags & RXf_CHECK_ALL) {
2987 /* we can match based purely on the result of INTUIT.
2988 * Set up captures etc just for $& and $-[0]
2989 * (an intuit-only match wont have $1,$2,..) */
2990 assert(!prog->nparens);
2992 /* s/// doesn't like it if $& is earlier than where we asked it to
2993 * start searching (which can happen on something like /.\G/) */
2994 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
2997 /* this should only be possible under \G */
2998 assert(prog->intflags & PREGf_GPOS_SEEN);
2999 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
3000 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3004 /* match via INTUIT shouldn't have any captures.
3005 * Let @-, @+, $^N know */
3006 prog->lastparen = prog->lastcloseparen = 0;
3007 RX_MATCH_UTF8_set(rx, utf8_target);
3008 prog->offs[0].start = s - strbeg;
3009 prog->offs[0].end = utf8_target
3010 ? (char*)utf8_hop((U8*)s, prog->minlenret) - strbeg
3011 : s - strbeg + prog->minlenret;
3012 if ( !(flags & REXEC_NOT_FIRST) )
3013 S_reg_set_capture_string(aTHX_ rx,
3015 sv, flags, utf8_target);
3021 multiline = prog->extflags & RXf_PMf_MULTILINE;
3023 if (strend - s < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
3024 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
3025 "String too short [regexec_flags]...\n"));
3029 /* Check validity of program. */
3030 if (UCHARAT(progi->program) != REG_MAGIC) {
3031 Perl_croak(aTHX_ "corrupted regexp program");
3034 RX_MATCH_TAINTED_off(rx);
3035 RX_MATCH_UTF8_set(rx, utf8_target);
3037 reginfo->prog = rx; /* Yes, sorry that this is confusing. */
3038 reginfo->intuit = 0;
3039 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
3040 reginfo->warned = FALSE;
3042 reginfo->poscache_maxiter = 0; /* not yet started a countdown */
3043 /* see how far we have to get to not match where we matched before */
3044 reginfo->till = stringarg + minend;
3046 if (prog->extflags & RXf_EVAL_SEEN && SvPADTMP(sv)) {
3047 /* SAVEFREESV, not sv_mortalcopy, as this SV must last until after
3048 S_cleanup_regmatch_info_aux has executed (registered by
3049 SAVEDESTRUCTOR_X below). S_cleanup_regmatch_info_aux modifies
3050 magic belonging to this SV.
3051 Not newSVsv, either, as it does not COW.
3053 reginfo->sv = newSV(0);
3054 SvSetSV_nosteal(reginfo->sv, sv);
3055 SAVEFREESV(reginfo->sv);
3058 /* reserve next 2 or 3 slots in PL_regmatch_state:
3059 * slot N+0: may currently be in use: skip it
3060 * slot N+1: use for regmatch_info_aux struct
3061 * slot N+2: use for regmatch_info_aux_eval struct if we have (?{})'s
3062 * slot N+3: ready for use by regmatch()
3066 regmatch_state *old_regmatch_state;
3067 regmatch_slab *old_regmatch_slab;
3068 int i, max = (prog->extflags & RXf_EVAL_SEEN) ? 2 : 1;
3070 /* on first ever match, allocate first slab */
3071 if (!PL_regmatch_slab) {
3072 Newx(PL_regmatch_slab, 1, regmatch_slab);
3073 PL_regmatch_slab->prev = NULL;
3074 PL_regmatch_slab->next = NULL;
3075 PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
3078 old_regmatch_state = PL_regmatch_state;
3079 old_regmatch_slab = PL_regmatch_slab;
3081 for (i=0; i <= max; i++) {
3083 reginfo->info_aux = &(PL_regmatch_state->u.info_aux);
3085 reginfo->info_aux_eval =
3086 reginfo->info_aux->info_aux_eval =
3087 &(PL_regmatch_state->u.info_aux_eval);
3089 if (++PL_regmatch_state > SLAB_LAST(PL_regmatch_slab))
3090 PL_regmatch_state = S_push_slab(aTHX);
3093 /* note initial PL_regmatch_state position; at end of match we'll
3094 * pop back to there and free any higher slabs */
3096 reginfo->info_aux->old_regmatch_state = old_regmatch_state;
3097 reginfo->info_aux->old_regmatch_slab = old_regmatch_slab;
3098 reginfo->info_aux->poscache = NULL;
3100 SAVEDESTRUCTOR_X(S_cleanup_regmatch_info_aux, reginfo->info_aux);
3102 if ((prog->extflags & RXf_EVAL_SEEN))
3103 S_setup_eval_state(aTHX_ reginfo);
3105 reginfo->info_aux_eval = reginfo->info_aux->info_aux_eval = NULL;
3108 /* If there is a "must appear" string, look for it. */
3110 if (PL_curpm && (PM_GETRE(PL_curpm) == rx)) {
3111 /* We have to be careful. If the previous successful match
3112 was from this regex we don't want a subsequent partially
3113 successful match to clobber the old results.
3114 So when we detect this possibility we add a swap buffer
3115 to the re, and switch the buffer each match. If we fail,
3116 we switch it back; otherwise we leave it swapped.
3119 /* do we need a save destructor here for eval dies? */
3120 Newxz(prog->offs, (prog->nparens + 1), regexp_paren_pair);
3121 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
3122 "rex=0x%"UVxf" saving offs: orig=0x%"UVxf" new=0x%"UVxf"\n",
3129 if (prog->recurse_locinput)
3130 Zero(prog->recurse_locinput,prog->nparens + 1, char *);
3132 /* Simplest case: anchored match need be tried only once, or with
3133 * MBOL, only at the beginning of each line.
3135 * Note that /.*.../ sets PREGf_IMPLICIT|MBOL, while /.*.../s sets
3136 * PREGf_IMPLICIT|SBOL. The idea is that with /.*.../s, if it doesn't
3137 * match at the start of the string then it won't match anywhere else
3138 * either; while with /.*.../, if it doesn't match at the beginning,
3139 * the earliest it could match is at the start of the next line */
3141 if (prog->intflags & (PREGf_ANCH & ~PREGf_ANCH_GPOS)) {
3144 if (regtry(reginfo, &s))
3147 if (!(prog->intflags & PREGf_ANCH_MBOL))
3150 /* didn't match at start, try at other newline positions */
3153 dontbother = minlen - 1;
3154 end = HOP3c(strend, -dontbother, strbeg) - 1;
3156 /* skip to next newline */
3158 while (s <= end) { /* note it could be possible to match at the end of the string */
3159 /* NB: newlines are the same in unicode as they are in latin */
3162 if (prog->check_substr || prog->check_utf8) {
3163 /* note that with PREGf_IMPLICIT, intuit can only fail
3164 * or return the start position, so it's of limited utility.
3165 * Nevertheless, I made the decision that the potential for
3166 * quick fail was still worth it - DAPM */
3167 s = re_intuit_start(rx, sv, strbeg, s, strend, flags, NULL);
3171 if (regtry(reginfo, &s))
3175 } /* end anchored search */
3177 if (prog->intflags & PREGf_ANCH_GPOS)
3179 /* PREGf_ANCH_GPOS should never be true if PREGf_GPOS_SEEN is not true */
3180 assert(prog->intflags & PREGf_GPOS_SEEN);
3181 /* For anchored \G, the only position it can match from is
3182 * (ganch-gofs); we already set startpos to this above; if intuit
3183 * moved us on from there, we can't possibly succeed */
3184 assert(startpos == HOPBACKc(reginfo->ganch, prog->gofs));
3185 if (s == startpos && regtry(reginfo, &s))
3190 /* Messy cases: unanchored match. */
3191 if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
3192 /* we have /x+whatever/ */
3193 /* it must be a one character string (XXXX Except is_utf8_pat?) */
3199 if (! prog->anchored_utf8) {
3200 to_utf8_substr(prog);
3202 ch = SvPVX_const(prog->anchored_utf8)[0];
3205 DEBUG_EXECUTE_r( did_match = 1 );
3206 if (regtry(reginfo, &s)) goto got_it;
3208 while (s < strend && *s == ch)
3215 if (! prog->anchored_substr) {
3216 if (! to_byte_substr(prog)) {
3217 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3220 ch = SvPVX_const(prog->anchored_substr)[0];
3223 DEBUG_EXECUTE_r( did_match = 1 );
3224 if (regtry(reginfo, &s)) goto got_it;
3226 while (s < strend && *s == ch)
3231 DEBUG_EXECUTE_r(if (!did_match)
3232 PerlIO_printf(Perl_debug_log,
3233 "Did not find anchored character...\n")
3236 else if (prog->anchored_substr != NULL
3237 || prog->anchored_utf8 != NULL
3238 || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
3239 && prog->float_max_offset < strend - s)) {
3244 char *last1; /* Last position checked before */
3248 if (prog->anchored_substr || prog->anchored_utf8) {
3250 if (! prog->anchored_utf8) {
3251 to_utf8_substr(prog);
3253 must = prog->anchored_utf8;
3256 if (! prog->anchored_substr) {
3257 if (! to_byte_substr(prog)) {
3258 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3261 must = prog->anchored_substr;
3263 back_max = back_min = prog->anchored_offset;
3266 if (! prog->float_utf8) {
3267 to_utf8_substr(prog);
3269 must = prog->float_utf8;
3272 if (! prog->float_substr) {
3273 if (! to_byte_substr(prog)) {
3274 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3277 must = prog->float_substr;
3279 back_max = prog->float_max_offset;
3280 back_min = prog->float_min_offset;
3286 last = HOP3c(strend, /* Cannot start after this */
3287 -(SSize_t)(CHR_SVLEN(must)
3288 - (SvTAIL(must) != 0) + back_min), strbeg);
3290 if (s > reginfo->strbeg)
3291 last1 = HOPc(s, -1);
3293 last1 = s - 1; /* bogus */
3295 /* XXXX check_substr already used to find "s", can optimize if
3296 check_substr==must. */
3298 strend = HOPc(strend, -dontbother);
3299 while ( (s <= last) &&
3300 (s = fbm_instr((unsigned char*)HOP4c(s, back_min, strbeg, strend),
3301 (unsigned char*)strend, must,
3302 multiline ? FBMrf_MULTILINE : 0)) ) {
3303 DEBUG_EXECUTE_r( did_match = 1 );
3304 if (HOPc(s, -back_max) > last1) {
3305 last1 = HOPc(s, -back_min);
3306 s = HOPc(s, -back_max);
3309 char * const t = (last1 >= reginfo->strbeg)
3310 ? HOPc(last1, 1) : last1 + 1;
3312 last1 = HOPc(s, -back_min);
3316 while (s <= last1) {
3317 if (regtry(reginfo, &s))
3320 s++; /* to break out of outer loop */
3327 while (s <= last1) {
3328 if (regtry(reginfo, &s))
3334 DEBUG_EXECUTE_r(if (!did_match) {
3335 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
3336 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
3337 PerlIO_printf(Perl_debug_log, "Did not find %s substr %s%s...\n",
3338 ((must == prog->anchored_substr || must == prog->anchored_utf8)
3339 ? "anchored" : "floating"),
3340 quoted, RE_SV_TAIL(must));
3344 else if ( (c = progi->regstclass) ) {
3346 const OPCODE op = OP(progi->regstclass);
3347 /* don't bother with what can't match */
3348 if (PL_regkind[op] != EXACT && PL_regkind[op] != TRIE)
3349 strend = HOPc(strend, -(minlen - 1));
3352 SV * const prop = sv_newmortal();
3353 regprop(prog, prop, c, reginfo, NULL);
3355 RE_PV_QUOTED_DECL(quoted,utf8_target,PERL_DEBUG_PAD_ZERO(1),
3357 PerlIO_printf(Perl_debug_log,
3358 "Matching stclass %.*s against %s (%d bytes)\n",
3359 (int)SvCUR(prop), SvPVX_const(prop),
3360 quoted, (int)(strend - s));
3363 if (find_byclass(prog, c, s, strend, reginfo))
3365 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Contradicts stclass... [regexec_flags]\n"));
3369 if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
3377 if (! prog->float_utf8) {
3378 to_utf8_substr(prog);
3380 float_real = prog->float_utf8;
3383 if (! prog->float_substr) {
3384 if (! to_byte_substr(prog)) {
3385 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3388 float_real = prog->float_substr;
3391 little = SvPV_const(float_real, len);
3392 if (SvTAIL(float_real)) {
3393 /* This means that float_real contains an artificial \n on
3394 * the end due to the presence of something like this:
3395 * /foo$/ where we can match both "foo" and "foo\n" at the
3396 * end of the string. So we have to compare the end of the
3397 * string first against the float_real without the \n and
3398 * then against the full float_real with the string. We
3399 * have to watch out for cases where the string might be
3400 * smaller than the float_real or the float_real without
3402 char *checkpos= strend - len;
3404 PerlIO_printf(Perl_debug_log,
3405 "%sChecking for float_real.%s\n",
3406 PL_colors[4], PL_colors[5]));
3407 if (checkpos + 1 < strbeg) {
3408 /* can't match, even if we remove the trailing \n
3409 * string is too short to match */
3411 PerlIO_printf(Perl_debug_log,
3412 "%sString shorter than required trailing substring, cannot match.%s\n",
3413 PL_colors[4], PL_colors[5]));
3415 } else if (memEQ(checkpos + 1, little, len - 1)) {
3416 /* can match, the end of the string matches without the
3418 last = checkpos + 1;
3419 } else if (checkpos < strbeg) {
3420 /* cant match, string is too short when the "\n" is
3423 PerlIO_printf(Perl_debug_log,
3424 "%sString does not contain required trailing substring, cannot match.%s\n",
3425 PL_colors[4], PL_colors[5]));
3427 } else if (!multiline) {
3428 /* non multiline match, so compare with the "\n" at the
3429 * end of the string */
3430 if (memEQ(checkpos, little, len)) {
3434 PerlIO_printf(Perl_debug_log,
3435 "%sString does not contain required trailing substring, cannot match.%s\n",
3436 PL_colors[4], PL_colors[5]));
3440 /* multiline match, so we have to search for a place
3441 * where the full string is located */
3447 last = rninstr(s, strend, little, little + len);
3449 last = strend; /* matching "$" */
3452 /* at one point this block contained a comment which was
3453 * probably incorrect, which said that this was a "should not
3454 * happen" case. Even if it was true when it was written I am
3455 * pretty sure it is not anymore, so I have removed the comment
3456 * and replaced it with this one. Yves */
3458 PerlIO_printf(Perl_debug_log,
3459 "%sString does not contain required substring, cannot match.%s\n",
3460 PL_colors[4], PL_colors[5]
3464 dontbother = strend - last + prog->float_min_offset;
3466 if (minlen && (dontbother < minlen))
3467 dontbother = minlen - 1;
3468 strend -= dontbother; /* this one's always in bytes! */
3469 /* We don't know much -- general case. */
3472 if (regtry(reginfo, &s))
3481 if (regtry(reginfo, &s))
3483 } while (s++ < strend);
3491 /* s/// doesn't like it if $& is earlier than where we asked it to
3492 * start searching (which can happen on something like /.\G/) */
3493 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
3494 && (prog->offs[0].start < stringarg - strbeg))
3496 /* this should only be possible under \G */
3497 assert(prog->intflags & PREGf_GPOS_SEEN);
3498 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
3499 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3505 PerlIO_printf(Perl_debug_log,
3506 "rex=0x%"UVxf" freeing offs: 0x%"UVxf"\n",
3513 /* clean up; this will trigger destructors that will free all slabs
3514 * above the current one, and cleanup the regmatch_info_aux
3515 * and regmatch_info_aux_eval sructs */
3517 LEAVE_SCOPE(oldsave);
3519 if (RXp_PAREN_NAMES(prog))
3520 (void)hv_iterinit(RXp_PAREN_NAMES(prog));
3522 /* make sure $`, $&, $', and $digit will work later */
3523 if ( !(flags & REXEC_NOT_FIRST) )
3524 S_reg_set_capture_string(aTHX_ rx,
3525 strbeg, reginfo->strend,
3526 sv, flags, utf8_target);
3531 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch failed%s\n",
3532 PL_colors[4], PL_colors[5]));
3534 /* clean up; this will trigger destructors that will free all slabs
3535 * above the current one, and cleanup the regmatch_info_aux
3536 * and regmatch_info_aux_eval sructs */
3538 LEAVE_SCOPE(oldsave);
3541 /* we failed :-( roll it back */
3542 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
3543 "rex=0x%"UVxf" rolling back offs: freeing=0x%"UVxf" restoring=0x%"UVxf"\n",
3548 Safefree(prog->offs);
3555 /* Set which rex is pointed to by PL_reg_curpm, handling ref counting.
3556 * Do inc before dec, in case old and new rex are the same */
3557 #define SET_reg_curpm(Re2) \
3558 if (reginfo->info_aux_eval) { \
3559 (void)ReREFCNT_inc(Re2); \
3560 ReREFCNT_dec(PM_GETRE(PL_reg_curpm)); \
3561 PM_SETRE((PL_reg_curpm), (Re2)); \
3566 - regtry - try match at specific point
3568 STATIC bool /* 0 failure, 1 success */
3569 S_regtry(pTHX_ regmatch_info *reginfo, char **startposp)
3572 REGEXP *const rx = reginfo->prog;
3573 regexp *const prog = ReANY(rx);
3575 RXi_GET_DECL(prog,progi);
3576 GET_RE_DEBUG_FLAGS_DECL;
3578 PERL_ARGS_ASSERT_REGTRY;
3580 reginfo->cutpoint=NULL;
3582 prog->offs[0].start = *startposp - reginfo->strbeg;
3583 prog->lastparen = 0;
3584 prog->lastcloseparen = 0;
3586 /* XXXX What this code is doing here?!!! There should be no need
3587 to do this again and again, prog->lastparen should take care of
3590 /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
3591 * Actually, the code in regcppop() (which Ilya may be meaning by
3592 * prog->lastparen), is not needed at all by the test suite
3593 * (op/regexp, op/pat, op/split), but that code is needed otherwise
3594 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
3595 * Meanwhile, this code *is* needed for the
3596 * above-mentioned test suite tests to succeed. The common theme
3597 * on those tests seems to be returning null fields from matches.
3598 * --jhi updated by dapm */
3600 if (prog->nparens) {
3601 regexp_paren_pair *pp = prog->offs;
3603 for (i = prog->nparens; i > (I32)prog->lastparen; i--) {
3611 result = regmatch(reginfo, *startposp, progi->program + 1);
3613 prog->offs[0].end = result;
3616 if (reginfo->cutpoint)
3617 *startposp= reginfo->cutpoint;
3618 REGCP_UNWIND(lastcp);
3623 #define sayYES goto yes
3624 #define sayNO goto no
3625 #define sayNO_SILENT goto no_silent
3627 /* we dont use STMT_START/END here because it leads to
3628 "unreachable code" warnings, which are bogus, but distracting. */
3629 #define CACHEsayNO \
3630 if (ST.cache_mask) \
3631 reginfo->info_aux->poscache[ST.cache_offset] |= ST.cache_mask; \
3634 /* this is used to determine how far from the left messages like
3635 'failed...' are printed. It should be set such that messages
3636 are inline with the regop output that created them.
3638 #define REPORT_CODE_OFF 32
3641 #define CHRTEST_UNINIT -1001 /* c1/c2 haven't been calculated yet */
3642 #define CHRTEST_VOID -1000 /* the c1/c2 "next char" test should be skipped */
3643 #define CHRTEST_NOT_A_CP_1 -999
3644 #define CHRTEST_NOT_A_CP_2 -998
3646 /* grab a new slab and return the first slot in it */
3648 STATIC regmatch_state *
3651 #if PERL_VERSION < 9 && !defined(PERL_CORE)
3654 regmatch_slab *s = PL_regmatch_slab->next;
3656 Newx(s, 1, regmatch_slab);
3657 s->prev = PL_regmatch_slab;
3659 PL_regmatch_slab->next = s;
3661 PL_regmatch_slab = s;
3662 return SLAB_FIRST(s);
3666 /* push a new state then goto it */
3668 #define PUSH_STATE_GOTO(state, node, input) \
3669 pushinput = input; \
3671 st->resume_state = state; \
3674 /* push a new state with success backtracking, then goto it */
3676 #define PUSH_YES_STATE_GOTO(state, node, input) \
3677 pushinput = input; \
3679 st->resume_state = state; \
3680 goto push_yes_state;
3687 regmatch() - main matching routine
3689 This is basically one big switch statement in a loop. We execute an op,
3690 set 'next' to point the next op, and continue. If we come to a point which
3691 we may need to backtrack to on failure such as (A|B|C), we push a
3692 backtrack state onto the backtrack stack. On failure, we pop the top
3693 state, and re-enter the loop at the state indicated. If there are no more
3694 states to pop, we return failure.
3696 Sometimes we also need to backtrack on success; for example /A+/, where
3697 after successfully matching one A, we need to go back and try to
3698 match another one; similarly for lookahead assertions: if the assertion
3699 completes successfully, we backtrack to the state just before the assertion
3700 and then carry on. In these cases, the pushed state is marked as
3701 'backtrack on success too'. This marking is in fact done by a chain of
3702 pointers, each pointing to the previous 'yes' state. On success, we pop to
3703 the nearest yes state, discarding any intermediate failure-only states.
3704 Sometimes a yes state is pushed just to force some cleanup code to be
3705 called at the end of a successful match or submatch; e.g. (??{$re}) uses
3706 it to free the inner regex.
3708 Note that failure backtracking rewinds the cursor position, while
3709 success backtracking leaves it alone.
3711 A pattern is complete when the END op is executed, while a subpattern
3712 such as (?=foo) is complete when the SUCCESS op is executed. Both of these
3713 ops trigger the "pop to last yes state if any, otherwise return true"
3716 A common convention in this function is to use A and B to refer to the two
3717 subpatterns (or to the first nodes thereof) in patterns like /A*B/: so A is
3718 the subpattern to be matched possibly multiple times, while B is the entire
3719 rest of the pattern. Variable and state names reflect this convention.
3721 The states in the main switch are the union of ops and failure/success of
3722 substates associated with with that op. For example, IFMATCH is the op
3723 that does lookahead assertions /(?=A)B/ and so the IFMATCH state means
3724 'execute IFMATCH'; while IFMATCH_A is a state saying that we have just
3725 successfully matched A and IFMATCH_A_fail is a state saying that we have
3726 just failed to match A. Resume states always come in pairs. The backtrack
3727 state we push is marked as 'IFMATCH_A', but when that is popped, we resume
3728 at IFMATCH_A or IFMATCH_A_fail, depending on whether we are backtracking
3729 on success or failure.
3731 The struct that holds a backtracking state is actually a big union, with
3732 one variant for each major type of op. The variable st points to the
3733 top-most backtrack struct. To make the code clearer, within each
3734 block of code we #define ST to alias the relevant union.
3736 Here's a concrete example of a (vastly oversimplified) IFMATCH
3742 #define ST st->u.ifmatch
3744 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3745 ST.foo = ...; // some state we wish to save
3747 // push a yes backtrack state with a resume value of
3748 // IFMATCH_A/IFMATCH_A_fail, then continue execution at the
3750 PUSH_YES_STATE_GOTO(IFMATCH_A, A, newinput);
3753 case IFMATCH_A: // we have successfully executed A; now continue with B
3755 bar = ST.foo; // do something with the preserved value
3758 case IFMATCH_A_fail: // A failed, so the assertion failed
3759 ...; // do some housekeeping, then ...
3760 sayNO; // propagate the failure
3767 For any old-timers reading this who are familiar with the old recursive
3768 approach, the code above is equivalent to:
3770 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3779 ...; // do some housekeeping, then ...
3780 sayNO; // propagate the failure
3783 The topmost backtrack state, pointed to by st, is usually free. If you
3784 want to claim it, populate any ST.foo fields in it with values you wish to
3785 save, then do one of
3787 PUSH_STATE_GOTO(resume_state, node, newinput);
3788 PUSH_YES_STATE_GOTO(resume_state, node, newinput);
3790 which sets that backtrack state's resume value to 'resume_state', pushes a
3791 new free entry to the top of the backtrack stack, then goes to 'node'.
3792 On backtracking, the free slot is popped, and the saved state becomes the
3793 new free state. An ST.foo field in this new top state can be temporarily
3794 accessed to retrieve values, but once the main loop is re-entered, it
3795 becomes available for reuse.
3797 Note that the depth of the backtrack stack constantly increases during the
3798 left-to-right execution of the pattern, rather than going up and down with
3799 the pattern nesting. For example the stack is at its maximum at Z at the
3800 end of the pattern, rather than at X in the following:
3802 /(((X)+)+)+....(Y)+....Z/
3804 The only exceptions to this are lookahead/behind assertions and the cut,
3805 (?>A), which pop all the backtrack states associated with A before
3808 Backtrack state structs are allocated in slabs of about 4K in size.
3809 PL_regmatch_state and st always point to the currently active state,
3810 and PL_regmatch_slab points to the slab currently containing
3811 PL_regmatch_state. The first time regmatch() is called, the first slab is
3812 allocated, and is never freed until interpreter destruction. When the slab
3813 is full, a new one is allocated and chained to the end. At exit from
3814 regmatch(), slabs allocated since entry are freed.
3819 #define DEBUG_STATE_pp(pp) \
3821 DUMP_EXEC_POS(locinput, scan, utf8_target); \
3822 PerlIO_printf(Perl_debug_log, \
3823 " %*s"pp" %s%s%s%s%s\n", \
3825 PL_reg_name[st->resume_state], \
3826 ((st==yes_state||st==mark_state) ? "[" : ""), \
3827 ((st==yes_state) ? "Y" : ""), \
3828 ((st==mark_state) ? "M" : ""), \
3829 ((st==yes_state||st==mark_state) ? "]" : "") \
3834 #define REG_NODE_NUM(x) ((x) ? (int)((x)-prog) : -1)
3839 S_debug_start_match(pTHX_ const REGEXP *prog, const bool utf8_target,
3840 const char *start, const char *end, const char *blurb)
3842 const bool utf8_pat = RX_UTF8(prog) ? 1 : 0;
3844 PERL_ARGS_ASSERT_DEBUG_START_MATCH;
3849 RE_PV_QUOTED_DECL(s0, utf8_pat, PERL_DEBUG_PAD_ZERO(0),
3850 RX_PRECOMP_const(prog), RX_PRELEN(prog), 60);
3852 RE_PV_QUOTED_DECL(s1, utf8_target, PERL_DEBUG_PAD_ZERO(1),
3853 start, end - start, 60);
3855 PerlIO_printf(Perl_debug_log,
3856 "%s%s REx%s %s against %s\n",