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
40 #define B_ON_NON_UTF8_LOCALE_IS_WRONG \
41 "Use of \\b{} for non-UTF-8 locale is wrong. Assuming a UTF-8 locale"
44 * pregcomp and pregexec -- regsub and regerror are not used in perl
46 * Copyright (c) 1986 by University of Toronto.
47 * Written by Henry Spencer. Not derived from licensed software.
49 * Permission is granted to anyone to use this software for any
50 * purpose on any computer system, and to redistribute it freely,
51 * subject to the following restrictions:
53 * 1. The author is not responsible for the consequences of use of
54 * this software, no matter how awful, even if they arise
57 * 2. The origin of this software must not be misrepresented, either
58 * by explicit claim or by omission.
60 * 3. Altered versions must be plainly marked as such, and must not
61 * be misrepresented as being the original software.
63 **** Alterations to Henry's code are...
65 **** Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
66 **** 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
67 **** by Larry Wall and others
69 **** You may distribute under the terms of either the GNU General Public
70 **** License or the Artistic License, as specified in the README file.
72 * Beware that some of this code is subtly aware of the way operator
73 * precedence is structured in regular expressions. Serious changes in
74 * regular-expression syntax might require a total rethink.
77 #define PERL_IN_REGEXEC_C
80 #ifdef PERL_IN_XSUB_RE
86 #include "inline_invlist.c"
87 #include "unicode_constants.h"
90 /* At least one required character in the target string is expressible only in
92 static const char* const non_utf8_target_but_utf8_required
93 = "Can't match, because target string needs to be in UTF-8\n";
96 #define NON_UTF8_TARGET_BUT_UTF8_REQUIRED(target) STMT_START { \
97 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%s", non_utf8_target_but_utf8_required));\
101 #define HAS_NONLATIN1_FOLD_CLOSURE(i) _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
104 #define STATIC static
107 /* Valid only for non-utf8 strings: avoids the reginclass
108 * call if there are no complications: i.e., if everything matchable is
109 * straight forward in the bitmap */
110 #define REGINCLASS(prog,p,c) (ANYOF_FLAGS(p) ? reginclass(prog,p,c,c+1,0) \
111 : ANYOF_BITMAP_TEST(p,*(c)))
117 #define CHR_SVLEN(sv) (utf8_target ? sv_len_utf8(sv) : SvCUR(sv))
118 #define CHR_DIST(a,b) (reginfo->is_utf8_target ? utf8_distance(a,b) : a - b)
120 #define HOPc(pos,off) \
121 (char *)(reginfo->is_utf8_target \
122 ? reghop3((U8*)pos, off, \
123 (U8*)(off >= 0 ? reginfo->strend : reginfo->strbeg)) \
126 #define HOPBACKc(pos, off) \
127 (char*)(reginfo->is_utf8_target \
128 ? reghopmaybe3((U8*)pos, -off, (U8*)(reginfo->strbeg)) \
129 : (pos - off >= reginfo->strbeg) \
133 #define HOP3(pos,off,lim) (reginfo->is_utf8_target ? reghop3((U8*)(pos), off, (U8*)(lim)) : (U8*)(pos + off))
134 #define HOP3c(pos,off,lim) ((char*)HOP3(pos,off,lim))
136 /* lim must be +ve. Returns NULL on overshoot */
137 #define HOPMAYBE3(pos,off,lim) \
138 (reginfo->is_utf8_target \
139 ? reghopmaybe3((U8*)pos, off, (U8*)(lim)) \
140 : ((U8*)pos + off <= lim) \
144 /* like HOP3, but limits the result to <= lim even for the non-utf8 case.
145 * off must be >=0; args should be vars rather than expressions */
146 #define HOP3lim(pos,off,lim) (reginfo->is_utf8_target \
147 ? reghop3((U8*)(pos), off, (U8*)(lim)) \
148 : (U8*)((pos + off) > lim ? lim : (pos + off)))
150 #define HOP4(pos,off,llim, rlim) (reginfo->is_utf8_target \
151 ? reghop4((U8*)(pos), off, (U8*)(llim), (U8*)(rlim)) \
153 #define HOP4c(pos,off,llim, rlim) ((char*)HOP4(pos,off,llim, rlim))
155 #define NEXTCHR_EOS -10 /* nextchr has fallen off the end */
156 #define NEXTCHR_IS_EOS (nextchr < 0)
158 #define SET_nextchr \
159 nextchr = ((locinput < reginfo->strend) ? UCHARAT(locinput) : NEXTCHR_EOS)
161 #define SET_locinput(p) \
166 #define LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist) STMT_START { \
168 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST; \
169 swash_ptr = _core_swash_init("utf8", property_name, &PL_sv_undef, \
170 1, 0, invlist, &flags); \
175 /* If in debug mode, we test that a known character properly matches */
177 # define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
180 utf8_char_in_property) \
181 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist); \
182 assert(swash_fetch(swash_ptr, (U8 *) utf8_char_in_property, TRUE));
184 # define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
187 utf8_char_in_property) \
188 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist)
191 #define LOAD_UTF8_CHARCLASS_ALNUM() LOAD_UTF8_CHARCLASS_DEBUG_TEST( \
192 PL_utf8_swash_ptrs[_CC_WORDCHAR], \
194 PL_XPosix_ptrs[_CC_WORDCHAR], \
195 LATIN_CAPITAL_LETTER_SHARP_S_UTF8);
197 #define PLACEHOLDER /* Something for the preprocessor to grab onto */
198 /* TODO: Combine JUMPABLE and HAS_TEXT to cache OP(rn) */
200 /* for use after a quantifier and before an EXACT-like node -- japhy */
201 /* it would be nice to rework regcomp.sym to generate this stuff. sigh
203 * NOTE that *nothing* that affects backtracking should be in here, specifically
204 * VERBS must NOT be included. JUMPABLE is used to determine if we can ignore a
205 * node that is in between two EXACT like nodes when ascertaining what the required
206 * "follow" character is. This should probably be moved to regex compile time
207 * although it may be done at run time beause of the REF possibility - more
208 * investigation required. -- demerphq
210 #define JUMPABLE(rn) ( \
212 (OP(rn) == CLOSE && (!cur_eval || cur_eval->u.eval.close_paren != ARG(rn))) || \
214 OP(rn) == SUSPEND || OP(rn) == IFMATCH || \
215 OP(rn) == PLUS || OP(rn) == MINMOD || \
217 (PL_regkind[OP(rn)] == CURLY && ARG1(rn) > 0) \
219 #define IS_EXACT(rn) (PL_regkind[OP(rn)] == EXACT)
221 #define HAS_TEXT(rn) ( IS_EXACT(rn) || PL_regkind[OP(rn)] == REF )
224 /* Currently these are only used when PL_regkind[OP(rn)] == EXACT so
225 we don't need this definition. XXX These are now out-of-sync*/
226 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==REF || OP(rn)==NREF )
227 #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 )
228 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL || OP(rn)==REFFL || OP(rn)==NREFFL )
231 /* ... so we use this as its faster. */
232 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==EXACTL )
233 #define IS_TEXTFU(rn) ( OP(rn)==EXACTFU || OP(rn)==EXACTFLU8 || OP(rn)==EXACTFU_SS || OP(rn) == EXACTFA || OP(rn) == EXACTFA_NO_TRIE)
234 #define IS_TEXTF(rn) ( OP(rn)==EXACTF )
235 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL )
240 Search for mandatory following text node; for lookahead, the text must
241 follow but for lookbehind (rn->flags != 0) we skip to the next step.
243 #define FIND_NEXT_IMPT(rn) STMT_START { \
244 while (JUMPABLE(rn)) { \
245 const OPCODE type = OP(rn); \
246 if (type == SUSPEND || PL_regkind[type] == CURLY) \
247 rn = NEXTOPER(NEXTOPER(rn)); \
248 else if (type == PLUS) \
250 else if (type == IFMATCH) \
251 rn = (rn->flags == 0) ? NEXTOPER(NEXTOPER(rn)) : rn + ARG(rn); \
252 else rn += NEXT_OFF(rn); \
256 #define SLAB_FIRST(s) (&(s)->states[0])
257 #define SLAB_LAST(s) (&(s)->states[PERL_REGMATCH_SLAB_SLOTS-1])
259 static void S_setup_eval_state(pTHX_ regmatch_info *const reginfo);
260 static void S_cleanup_regmatch_info_aux(pTHX_ void *arg);
261 static regmatch_state * S_push_slab(pTHX);
263 #define REGCP_PAREN_ELEMS 3
264 #define REGCP_OTHER_ELEMS 3
265 #define REGCP_FRAME_ELEMS 1
266 /* REGCP_FRAME_ELEMS are not part of the REGCP_OTHER_ELEMS and
267 * are needed for the regexp context stack bookkeeping. */
270 S_regcppush(pTHX_ const regexp *rex, I32 parenfloor, U32 maxopenparen)
272 const int retval = PL_savestack_ix;
273 const int paren_elems_to_push =
274 (maxopenparen - parenfloor) * REGCP_PAREN_ELEMS;
275 const UV total_elems = paren_elems_to_push + REGCP_OTHER_ELEMS;
276 const UV elems_shifted = total_elems << SAVE_TIGHT_SHIFT;
278 GET_RE_DEBUG_FLAGS_DECL;
280 PERL_ARGS_ASSERT_REGCPPUSH;
282 if (paren_elems_to_push < 0)
283 Perl_croak(aTHX_ "panic: paren_elems_to_push, %i < 0, maxopenparen: %i parenfloor: %i REGCP_PAREN_ELEMS: %u",
284 (int)paren_elems_to_push, (int)maxopenparen,
285 (int)parenfloor, (unsigned)REGCP_PAREN_ELEMS);
287 if ((elems_shifted >> SAVE_TIGHT_SHIFT) != total_elems)
288 Perl_croak(aTHX_ "panic: paren_elems_to_push offset %"UVuf
289 " out of range (%lu-%ld)",
291 (unsigned long)maxopenparen,
294 SSGROW(total_elems + REGCP_FRAME_ELEMS);
297 if ((int)maxopenparen > (int)parenfloor)
298 PerlIO_printf(Perl_debug_log,
299 "rex=0x%"UVxf" offs=0x%"UVxf": saving capture indices:\n",
304 for (p = parenfloor+1; p <= (I32)maxopenparen; p++) {
305 /* REGCP_PARENS_ELEMS are pushed per pairs of parentheses. */
306 SSPUSHIV(rex->offs[p].end);
307 SSPUSHIV(rex->offs[p].start);
308 SSPUSHINT(rex->offs[p].start_tmp);
309 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
310 " \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"\n",
312 (IV)rex->offs[p].start,
313 (IV)rex->offs[p].start_tmp,
317 /* REGCP_OTHER_ELEMS are pushed in any case, parentheses or no. */
318 SSPUSHINT(maxopenparen);
319 SSPUSHINT(rex->lastparen);
320 SSPUSHINT(rex->lastcloseparen);
321 SSPUSHUV(SAVEt_REGCONTEXT | elems_shifted); /* Magic cookie. */
326 /* These are needed since we do not localize EVAL nodes: */
327 #define REGCP_SET(cp) \
329 PerlIO_printf(Perl_debug_log, \
330 " Setting an EVAL scope, savestack=%"IVdf"\n", \
331 (IV)PL_savestack_ix)); \
334 #define REGCP_UNWIND(cp) \
336 if (cp != PL_savestack_ix) \
337 PerlIO_printf(Perl_debug_log, \
338 " Clearing an EVAL scope, savestack=%"IVdf"..%"IVdf"\n", \
339 (IV)(cp), (IV)PL_savestack_ix)); \
342 #define UNWIND_PAREN(lp, lcp) \
343 for (n = rex->lastparen; n > lp; n--) \
344 rex->offs[n].end = -1; \
345 rex->lastparen = n; \
346 rex->lastcloseparen = lcp;
350 S_regcppop(pTHX_ regexp *rex, U32 *maxopenparen_p)
354 GET_RE_DEBUG_FLAGS_DECL;
356 PERL_ARGS_ASSERT_REGCPPOP;
358 /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
360 assert((i & SAVE_MASK) == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
361 i >>= SAVE_TIGHT_SHIFT; /* Parentheses elements to pop. */
362 rex->lastcloseparen = SSPOPINT;
363 rex->lastparen = SSPOPINT;
364 *maxopenparen_p = SSPOPINT;
366 i -= REGCP_OTHER_ELEMS;
367 /* Now restore the parentheses context. */
369 if (i || rex->lastparen + 1 <= rex->nparens)
370 PerlIO_printf(Perl_debug_log,
371 "rex=0x%"UVxf" offs=0x%"UVxf": restoring capture indices to:\n",
376 paren = *maxopenparen_p;
377 for ( ; i > 0; i -= REGCP_PAREN_ELEMS) {
379 rex->offs[paren].start_tmp = SSPOPINT;
380 rex->offs[paren].start = SSPOPIV;
382 if (paren <= rex->lastparen)
383 rex->offs[paren].end = tmps;
384 DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
385 " \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"%s\n",
387 (IV)rex->offs[paren].start,
388 (IV)rex->offs[paren].start_tmp,
389 (IV)rex->offs[paren].end,
390 (paren > rex->lastparen ? "(skipped)" : ""));
395 /* It would seem that the similar code in regtry()
396 * already takes care of this, and in fact it is in
397 * a better location to since this code can #if 0-ed out
398 * but the code in regtry() is needed or otherwise tests
399 * requiring null fields (pat.t#187 and split.t#{13,14}
400 * (as of patchlevel 7877) will fail. Then again,
401 * this code seems to be necessary or otherwise
402 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
403 * --jhi updated by dapm */
404 for (i = rex->lastparen + 1; i <= rex->nparens; i++) {
405 if (i > *maxopenparen_p)
406 rex->offs[i].start = -1;
407 rex->offs[i].end = -1;
408 DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
409 " \\%"UVuf": %s ..-1 undeffing\n",
411 (i > *maxopenparen_p) ? "-1" : " "
417 /* restore the parens and associated vars at savestack position ix,
418 * but without popping the stack */
421 S_regcp_restore(pTHX_ regexp *rex, I32 ix, U32 *maxopenparen_p)
423 I32 tmpix = PL_savestack_ix;
424 PL_savestack_ix = ix;
425 regcppop(rex, maxopenparen_p);
426 PL_savestack_ix = tmpix;
429 #define regcpblow(cp) LEAVE_SCOPE(cp) /* Ignores regcppush()ed data. */
432 S_isFOO_lc(pTHX_ const U8 classnum, const U8 character)
434 /* Returns a boolean as to whether or not 'character' is a member of the
435 * Posix character class given by 'classnum' that should be equivalent to a
436 * value in the typedef '_char_class_number'.
438 * Ideally this could be replaced by a just an array of function pointers
439 * to the C library functions that implement the macros this calls.
440 * However, to compile, the precise function signatures are required, and
441 * these may vary from platform to to platform. To avoid having to figure
442 * out what those all are on each platform, I (khw) am using this method,
443 * which adds an extra layer of function call overhead (unless the C
444 * optimizer strips it away). But we don't particularly care about
445 * performance with locales anyway. */
447 switch ((_char_class_number) classnum) {
448 case _CC_ENUM_ALPHANUMERIC: return isALPHANUMERIC_LC(character);
449 case _CC_ENUM_ALPHA: return isALPHA_LC(character);
450 case _CC_ENUM_ASCII: return isASCII_LC(character);
451 case _CC_ENUM_BLANK: return isBLANK_LC(character);
452 case _CC_ENUM_CASED: return isLOWER_LC(character)
453 || isUPPER_LC(character);
454 case _CC_ENUM_CNTRL: return isCNTRL_LC(character);
455 case _CC_ENUM_DIGIT: return isDIGIT_LC(character);
456 case _CC_ENUM_GRAPH: return isGRAPH_LC(character);
457 case _CC_ENUM_LOWER: return isLOWER_LC(character);
458 case _CC_ENUM_PRINT: return isPRINT_LC(character);
459 case _CC_ENUM_PUNCT: return isPUNCT_LC(character);
460 case _CC_ENUM_SPACE: return isSPACE_LC(character);
461 case _CC_ENUM_UPPER: return isUPPER_LC(character);
462 case _CC_ENUM_WORDCHAR: return isWORDCHAR_LC(character);
463 case _CC_ENUM_XDIGIT: return isXDIGIT_LC(character);
464 default: /* VERTSPACE should never occur in locales */
465 Perl_croak(aTHX_ "panic: isFOO_lc() has an unexpected character class '%d'", classnum);
468 NOT_REACHED; /* NOTREACHED */
473 S_isFOO_utf8_lc(pTHX_ const U8 classnum, const U8* character)
475 /* Returns a boolean as to whether or not the (well-formed) UTF-8-encoded
476 * 'character' is a member of the Posix character class given by 'classnum'
477 * that should be equivalent to a value in the typedef
478 * '_char_class_number'.
480 * This just calls isFOO_lc on the code point for the character if it is in
481 * the range 0-255. Outside that range, all characters use Unicode
482 * rules, ignoring any locale. So use the Unicode function if this class
483 * requires a swash, and use the Unicode macro otherwise. */
485 PERL_ARGS_ASSERT_ISFOO_UTF8_LC;
487 if (UTF8_IS_INVARIANT(*character)) {
488 return isFOO_lc(classnum, *character);
490 else if (UTF8_IS_DOWNGRADEABLE_START(*character)) {
491 return isFOO_lc(classnum,
492 TWO_BYTE_UTF8_TO_NATIVE(*character, *(character + 1)));
495 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(character, character + UTF8SKIP(character));
497 if (classnum < _FIRST_NON_SWASH_CC) {
499 /* Initialize the swash unless done already */
500 if (! PL_utf8_swash_ptrs[classnum]) {
501 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
502 PL_utf8_swash_ptrs[classnum] =
503 _core_swash_init("utf8",
506 PL_XPosix_ptrs[classnum], &flags);
509 return cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum], (U8 *)
511 TRUE /* is UTF */ ));
514 switch ((_char_class_number) classnum) {
515 case _CC_ENUM_SPACE: return is_XPERLSPACE_high(character);
516 case _CC_ENUM_BLANK: return is_HORIZWS_high(character);
517 case _CC_ENUM_XDIGIT: return is_XDIGIT_high(character);
518 case _CC_ENUM_VERTSPACE: return is_VERTWS_high(character);
522 return FALSE; /* Things like CNTRL are always below 256 */
526 * pregexec and friends
529 #ifndef PERL_IN_XSUB_RE
531 - pregexec - match a regexp against a string
534 Perl_pregexec(pTHX_ REGEXP * const prog, char* stringarg, char *strend,
535 char *strbeg, SSize_t minend, SV *screamer, U32 nosave)
536 /* stringarg: the point in the string at which to begin matching */
537 /* strend: pointer to null at end of string */
538 /* strbeg: real beginning of string */
539 /* minend: end of match must be >= minend bytes after stringarg. */
540 /* screamer: SV being matched: only used for utf8 flag, pos() etc; string
541 * itself is accessed via the pointers above */
542 /* nosave: For optimizations. */
544 PERL_ARGS_ASSERT_PREGEXEC;
547 regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
548 nosave ? 0 : REXEC_COPY_STR);
554 /* re_intuit_start():
556 * Based on some optimiser hints, try to find the earliest position in the
557 * string where the regex could match.
559 * rx: the regex to match against
560 * sv: the SV being matched: only used for utf8 flag; the string
561 * itself is accessed via the pointers below. Note that on
562 * something like an overloaded SV, SvPOK(sv) may be false
563 * and the string pointers may point to something unrelated to
565 * strbeg: real beginning of string
566 * strpos: the point in the string at which to begin matching
567 * strend: pointer to the byte following the last char of the string
568 * flags currently unused; set to 0
569 * data: currently unused; set to NULL
571 * The basic idea of re_intuit_start() is to use some known information
572 * about the pattern, namely:
574 * a) the longest known anchored substring (i.e. one that's at a
575 * constant offset from the beginning of the pattern; but not
576 * necessarily at a fixed offset from the beginning of the
578 * b) the longest floating substring (i.e. one that's not at a constant
579 * offset from the beginning of the pattern);
580 * c) Whether the pattern is anchored to the string; either
581 * an absolute anchor: /^../, or anchored to \n: /^.../m,
582 * or anchored to pos(): /\G/;
583 * d) A start class: a real or synthetic character class which
584 * represents which characters are legal at the start of the pattern;
586 * to either quickly reject the match, or to find the earliest position
587 * within the string at which the pattern might match, thus avoiding
588 * running the full NFA engine at those earlier locations, only to
589 * eventually fail and retry further along.
591 * Returns NULL if the pattern can't match, or returns the address within
592 * the string which is the earliest place the match could occur.
594 * The longest of the anchored and floating substrings is called 'check'
595 * and is checked first. The other is called 'other' and is checked
596 * second. The 'other' substring may not be present. For example,
598 * /(abc|xyz)ABC\d{0,3}DEFG/
602 * check substr (float) = "DEFG", offset 6..9 chars
603 * other substr (anchored) = "ABC", offset 3..3 chars
606 * Be aware that during the course of this function, sometimes 'anchored'
607 * refers to a substring being anchored relative to the start of the
608 * pattern, and sometimes to the pattern itself being anchored relative to
609 * the string. For example:
611 * /\dabc/: "abc" is anchored to the pattern;
612 * /^\dabc/: "abc" is anchored to the pattern and the string;
613 * /\d+abc/: "abc" is anchored to neither the pattern nor the string;
614 * /^\d+abc/: "abc" is anchored to neither the pattern nor the string,
615 * but the pattern is anchored to the string.
619 Perl_re_intuit_start(pTHX_
622 const char * const strbeg,
626 re_scream_pos_data *data)
628 struct regexp *const prog = ReANY(rx);
629 SSize_t start_shift = prog->check_offset_min;
630 /* Should be nonnegative! */
631 SSize_t end_shift = 0;
632 /* current lowest pos in string where the regex can start matching */
633 char *rx_origin = strpos;
635 const bool utf8_target = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
636 U8 other_ix = 1 - prog->substrs->check_ix;
638 char *other_last = strpos;/* latest pos 'other' substr already checked to */
639 char *check_at = NULL; /* check substr found at this pos */
640 const I32 multiline = prog->extflags & RXf_PMf_MULTILINE;
641 RXi_GET_DECL(prog,progi);
642 regmatch_info reginfo_buf; /* create some info to pass to find_byclass */
643 regmatch_info *const reginfo = ®info_buf;
644 GET_RE_DEBUG_FLAGS_DECL;
646 PERL_ARGS_ASSERT_RE_INTUIT_START;
647 PERL_UNUSED_ARG(flags);
648 PERL_UNUSED_ARG(data);
650 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
651 "Intuit: trying to determine minimum start position...\n"));
653 /* for now, assume that all substr offsets are positive. If at some point
654 * in the future someone wants to do clever things with look-behind and
655 * -ve offsets, they'll need to fix up any code in this function
656 * which uses these offsets. See the thread beginning
657 * <20140113145929.GF27210@iabyn.com>
659 assert(prog->substrs->data[0].min_offset >= 0);
660 assert(prog->substrs->data[0].max_offset >= 0);
661 assert(prog->substrs->data[1].min_offset >= 0);
662 assert(prog->substrs->data[1].max_offset >= 0);
663 assert(prog->substrs->data[2].min_offset >= 0);
664 assert(prog->substrs->data[2].max_offset >= 0);
666 /* for now, assume that if both present, that the floating substring
667 * doesn't start before the anchored substring.
668 * If you break this assumption (e.g. doing better optimisations
669 * with lookahead/behind), then you'll need to audit the code in this
670 * function carefully first
673 ! ( (prog->anchored_utf8 || prog->anchored_substr)
674 && (prog->float_utf8 || prog->float_substr))
675 || (prog->float_min_offset >= prog->anchored_offset));
677 /* byte rather than char calculation for efficiency. It fails
678 * to quickly reject some cases that can't match, but will reject
679 * them later after doing full char arithmetic */
680 if (prog->minlen > strend - strpos) {
681 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
682 " String too short...\n"));
686 RX_MATCH_UTF8_set(rx,utf8_target);
687 reginfo->is_utf8_target = cBOOL(utf8_target);
688 reginfo->info_aux = NULL;
689 reginfo->strbeg = strbeg;
690 reginfo->strend = strend;
691 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
693 /* not actually used within intuit, but zero for safety anyway */
694 reginfo->poscache_maxiter = 0;
697 if (!prog->check_utf8 && prog->check_substr)
698 to_utf8_substr(prog);
699 check = prog->check_utf8;
701 if (!prog->check_substr && prog->check_utf8) {
702 if (! to_byte_substr(prog)) {
703 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(fail);
706 check = prog->check_substr;
709 /* dump the various substring data */
710 DEBUG_OPTIMISE_MORE_r({
712 for (i=0; i<=2; i++) {
713 SV *sv = (utf8_target ? prog->substrs->data[i].utf8_substr
714 : prog->substrs->data[i].substr);
718 PerlIO_printf(Perl_debug_log,
719 " substrs[%d]: min=%"IVdf" max=%"IVdf" end shift=%"IVdf
720 " useful=%"IVdf" utf8=%d [%s]\n",
722 (IV)prog->substrs->data[i].min_offset,
723 (IV)prog->substrs->data[i].max_offset,
724 (IV)prog->substrs->data[i].end_shift,
731 if (prog->intflags & PREGf_ANCH) { /* Match at \G, beg-of-str or after \n */
733 /* ml_anch: check after \n?
735 * A note about PREGf_IMPLICIT: on an un-anchored pattern beginning
736 * with /.*.../, these flags will have been added by the
738 * /.*abc/, /.*abc/m: PREGf_IMPLICIT | PREGf_ANCH_MBOL
739 * /.*abc/s: PREGf_IMPLICIT | PREGf_ANCH_SBOL
741 ml_anch = (prog->intflags & PREGf_ANCH_MBOL)
742 && !(prog->intflags & PREGf_IMPLICIT);
744 if (!ml_anch && !(prog->intflags & PREGf_IMPLICIT)) {
745 /* we are only allowed to match at BOS or \G */
747 /* trivially reject if there's a BOS anchor and we're not at BOS.
749 * Note that we don't try to do a similar quick reject for
750 * \G, since generally the caller will have calculated strpos
751 * based on pos() and gofs, so the string is already correctly
752 * anchored by definition; and handling the exceptions would
753 * be too fiddly (e.g. REXEC_IGNOREPOS).
755 if ( strpos != strbeg
756 && (prog->intflags & PREGf_ANCH_SBOL))
758 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
759 " Not at start...\n"));
763 /* in the presence of an anchor, the anchored (relative to the
764 * start of the regex) substr must also be anchored relative
765 * to strpos. So quickly reject if substr isn't found there.
766 * This works for \G too, because the caller will already have
767 * subtracted gofs from pos, and gofs is the offset from the
768 * \G to the start of the regex. For example, in /.abc\Gdef/,
769 * where substr="abcdef", pos()=3, gofs=4, offset_min=1:
770 * caller will have set strpos=pos()-4; we look for the substr
771 * at position pos()-4+1, which lines up with the "a" */
773 if (prog->check_offset_min == prog->check_offset_max
774 && !(prog->intflags & PREGf_CANY_SEEN))
776 /* Substring at constant offset from beg-of-str... */
777 SSize_t slen = SvCUR(check);
778 char *s = HOP3c(strpos, prog->check_offset_min, strend);
780 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
781 " Looking for check substr at fixed offset %"IVdf"...\n",
782 (IV)prog->check_offset_min));
785 /* In this case, the regex is anchored at the end too.
786 * Unless it's a multiline match, the lengths must match
787 * exactly, give or take a \n. NB: slen >= 1 since
788 * the last char of check is \n */
790 && ( strend - s > slen
791 || strend - s < slen - 1
792 || (strend - s == slen && strend[-1] != '\n')))
794 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
795 " String too long...\n"));
798 /* Now should match s[0..slen-2] */
801 if (slen && (*SvPVX_const(check) != *s
802 || (slen > 1 && memNE(SvPVX_const(check), s, slen))))
804 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
805 " String not equal...\n"));
810 goto success_at_start;
815 end_shift = prog->check_end_shift;
817 #ifdef DEBUGGING /* 7/99: reports of failure (with the older version) */
819 Perl_croak(aTHX_ "panic: end_shift: %"IVdf" pattern:\n%s\n ",
820 (IV)end_shift, RX_PRECOMP(prog));
825 /* This is the (re)entry point of the main loop in this function.
826 * The goal of this loop is to:
827 * 1) find the "check" substring in the region rx_origin..strend
828 * (adjusted by start_shift / end_shift). If not found, reject
830 * 2) If it exists, look for the "other" substr too if defined; for
831 * example, if the check substr maps to the anchored substr, then
832 * check the floating substr, and vice-versa. If not found, go
833 * back to (1) with rx_origin suitably incremented.
834 * 3) If we find an rx_origin position that doesn't contradict
835 * either of the substrings, then check the possible additional
836 * constraints on rx_origin of /^.../m or a known start class.
837 * If these fail, then depending on which constraints fail, jump
838 * back to here, or to various other re-entry points further along
839 * that skip some of the first steps.
840 * 4) If we pass all those tests, update the BmUSEFUL() count on the
841 * substring. If the start position was determined to be at the
842 * beginning of the string - so, not rejected, but not optimised,
843 * since we have to run regmatch from position 0 - decrement the
844 * BmUSEFUL() count. Otherwise increment it.
848 /* first, look for the 'check' substring */
854 DEBUG_OPTIMISE_MORE_r({
855 PerlIO_printf(Perl_debug_log,
856 " At restart: rx_origin=%"IVdf" Check offset min: %"IVdf
857 " Start shift: %"IVdf" End shift %"IVdf
858 " Real end Shift: %"IVdf"\n",
859 (IV)(rx_origin - strbeg),
860 (IV)prog->check_offset_min,
863 (IV)prog->check_end_shift);
866 if (prog->intflags & PREGf_CANY_SEEN) {
867 start_point= (U8*)(rx_origin + start_shift);
868 end_point= (U8*)(strend - end_shift);
869 if (start_point > end_point)
872 end_point = HOP3(strend, -end_shift, strbeg);
873 start_point = HOPMAYBE3(rx_origin, start_shift, end_point);
879 /* If the regex is absolutely anchored to either the start of the
880 * string (SBOL) or to pos() (ANCH_GPOS), then
881 * check_offset_max represents an upper bound on the string where
882 * the substr could start. For the ANCH_GPOS case, we assume that
883 * the caller of intuit will have already set strpos to
884 * pos()-gofs, so in this case strpos + offset_max will still be
885 * an upper bound on the substr.
888 && prog->intflags & PREGf_ANCH
889 && prog->check_offset_max != SSize_t_MAX)
891 SSize_t len = SvCUR(check) - !!SvTAIL(check);
892 const char * const anchor =
893 (prog->intflags & PREGf_ANCH_GPOS ? strpos : strbeg);
895 /* do a bytes rather than chars comparison. It's conservative;
896 * so it skips doing the HOP if the result can't possibly end
897 * up earlier than the old value of end_point.
899 if ((char*)end_point - anchor > prog->check_offset_max) {
900 end_point = HOP3lim((U8*)anchor,
901 prog->check_offset_max,
907 check_at = fbm_instr( start_point, end_point,
908 check, multiline ? FBMrf_MULTILINE : 0);
910 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
911 " doing 'check' fbm scan, [%"IVdf"..%"IVdf"] gave %"IVdf"\n",
912 (IV)((char*)start_point - strbeg),
913 (IV)((char*)end_point - strbeg),
914 (IV)(check_at ? check_at - strbeg : -1)
917 /* Update the count-of-usability, remove useless subpatterns,
921 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
922 SvPVX_const(check), RE_SV_DUMPLEN(check), 30);
923 PerlIO_printf(Perl_debug_log, " %s %s substr %s%s%s",
924 (check_at ? "Found" : "Did not find"),
925 (check == (utf8_target ? prog->anchored_utf8 : prog->anchored_substr)
926 ? "anchored" : "floating"),
929 (check_at ? " at offset " : "...\n") );
934 /* set rx_origin to the minimum position where the regex could start
935 * matching, given the constraint of the just-matched check substring.
936 * But don't set it lower than previously.
939 if (check_at - rx_origin > prog->check_offset_max)
940 rx_origin = HOP3c(check_at, -prog->check_offset_max, rx_origin);
941 /* Finish the diagnostic message */
942 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
943 "%ld (rx_origin now %"IVdf")...\n",
944 (long)(check_at - strbeg),
945 (IV)(rx_origin - strbeg)
950 /* now look for the 'other' substring if defined */
952 if (utf8_target ? prog->substrs->data[other_ix].utf8_substr
953 : prog->substrs->data[other_ix].substr)
955 /* Take into account the "other" substring. */
959 struct reg_substr_datum *other;
962 other = &prog->substrs->data[other_ix];
964 /* if "other" is anchored:
965 * we've previously found a floating substr starting at check_at.
966 * This means that the regex origin must lie somewhere
967 * between min (rx_origin): HOP3(check_at, -check_offset_max)
968 * and max: HOP3(check_at, -check_offset_min)
969 * (except that min will be >= strpos)
970 * So the fixed substr must lie somewhere between
971 * HOP3(min, anchored_offset)
972 * HOP3(max, anchored_offset) + SvCUR(substr)
975 /* if "other" is floating
976 * Calculate last1, the absolute latest point where the
977 * floating substr could start in the string, ignoring any
978 * constraints from the earlier fixed match. It is calculated
981 * strend - prog->minlen (in chars) is the absolute latest
982 * position within the string where the origin of the regex
983 * could appear. The latest start point for the floating
984 * substr is float_min_offset(*) on from the start of the
985 * regex. last1 simply combines thee two offsets.
987 * (*) You might think the latest start point should be
988 * float_max_offset from the regex origin, and technically
989 * you'd be correct. However, consider
991 * Here, float min, max are 3,5 and minlen is 7.
992 * This can match either
996 * In the first case, the regex matches minlen chars; in the
997 * second, minlen+1, in the third, minlen+2.
998 * In the first case, the floating offset is 3 (which equals
999 * float_min), in the second, 4, and in the third, 5 (which
1000 * equals float_max). In all cases, the floating string bcd
1001 * can never start more than 4 chars from the end of the
1002 * string, which equals minlen - float_min. As the substring
1003 * starts to match more than float_min from the start of the
1004 * regex, it makes the regex match more than minlen chars,
1005 * and the two cancel each other out. So we can always use
1006 * float_min - minlen, rather than float_max - minlen for the
1007 * latest position in the string.
1009 * Note that -minlen + float_min_offset is equivalent (AFAIKT)
1010 * to CHR_SVLEN(must) - !!SvTAIL(must) + prog->float_end_shift
1013 assert(prog->minlen >= other->min_offset);
1014 last1 = HOP3c(strend,
1015 other->min_offset - prog->minlen, strbeg);
1017 if (other_ix) {/* i.e. if (other-is-float) */
1018 /* last is the latest point where the floating substr could
1019 * start, *given* any constraints from the earlier fixed
1020 * match. This constraint is that the floating string starts
1021 * <= float_max_offset chars from the regex origin (rx_origin).
1022 * If this value is less than last1, use it instead.
1024 assert(rx_origin <= last1);
1026 /* this condition handles the offset==infinity case, and
1027 * is a short-cut otherwise. Although it's comparing a
1028 * byte offset to a char length, it does so in a safe way,
1029 * since 1 char always occupies 1 or more bytes,
1030 * so if a string range is (last1 - rx_origin) bytes,
1031 * it will be less than or equal to (last1 - rx_origin)
1032 * chars; meaning it errs towards doing the accurate HOP3
1033 * rather than just using last1 as a short-cut */
1034 (last1 - rx_origin) < other->max_offset
1036 : (char*)HOP3lim(rx_origin, other->max_offset, last1);
1039 assert(strpos + start_shift <= check_at);
1040 last = HOP4c(check_at, other->min_offset - start_shift,
1044 s = HOP3c(rx_origin, other->min_offset, strend);
1045 if (s < other_last) /* These positions already checked */
1048 must = utf8_target ? other->utf8_substr : other->substr;
1049 assert(SvPOK(must));
1052 char *to = last + SvCUR(must) - (SvTAIL(must)!=0);
1056 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1057 " skipping 'other' fbm scan: %"IVdf" > %"IVdf"\n",
1058 (IV)(from - strbeg),
1064 (unsigned char*)from,
1067 multiline ? FBMrf_MULTILINE : 0
1069 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1070 " doing 'other' fbm scan, [%"IVdf"..%"IVdf"] gave %"IVdf"\n",
1071 (IV)(from - strbeg),
1073 (IV)(s ? s - strbeg : -1)
1079 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
1080 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
1081 PerlIO_printf(Perl_debug_log, " %s %s substr %s%s",
1082 s ? "Found" : "Contradicts",
1083 other_ix ? "floating" : "anchored",
1084 quoted, RE_SV_TAIL(must));
1089 /* last1 is latest possible substr location. If we didn't
1090 * find it before there, we never will */
1091 if (last >= last1) {
1092 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1093 "; giving up...\n"));
1097 /* try to find the check substr again at a later
1098 * position. Maybe next time we'll find the "other" substr
1100 other_last = HOP3c(last, 1, strend) /* highest failure */;
1102 other_ix /* i.e. if other-is-float */
1103 ? HOP3c(rx_origin, 1, strend)
1104 : HOP4c(last, 1 - other->min_offset, strbeg, strend);
1105 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1106 "; about to retry %s at offset %ld (rx_origin now %"IVdf")...\n",
1107 (other_ix ? "floating" : "anchored"),
1108 (long)(HOP3c(check_at, 1, strend) - strbeg),
1109 (IV)(rx_origin - strbeg)
1114 if (other_ix) { /* if (other-is-float) */
1115 /* other_last is set to s, not s+1, since its possible for
1116 * a floating substr to fail first time, then succeed
1117 * second time at the same floating position; e.g.:
1118 * "-AB--AABZ" =~ /\wAB\d*Z/
1119 * The first time round, anchored and float match at
1120 * "-(AB)--AAB(Z)" then fail on the initial \w character
1121 * class. Second time round, they match at "-AB--A(AB)(Z)".
1126 rx_origin = HOP3c(s, -other->min_offset, strbeg);
1127 other_last = HOP3c(s, 1, strend);
1129 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1130 " at offset %ld (rx_origin now %"IVdf")...\n",
1132 (IV)(rx_origin - strbeg)
1138 DEBUG_OPTIMISE_MORE_r(
1139 PerlIO_printf(Perl_debug_log,
1140 " Check-only match: offset min:%"IVdf" max:%"IVdf
1141 " check_at:%"IVdf" rx_origin:%"IVdf" rx_origin-check_at:%"IVdf
1142 " strend:%"IVdf"\n",
1143 (IV)prog->check_offset_min,
1144 (IV)prog->check_offset_max,
1145 (IV)(check_at-strbeg),
1146 (IV)(rx_origin-strbeg),
1147 (IV)(rx_origin-check_at),
1153 postprocess_substr_matches:
1155 /* handle the extra constraint of /^.../m if present */
1157 if (ml_anch && rx_origin != strbeg && rx_origin[-1] != '\n') {
1160 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1161 " looking for /^/m anchor"));
1163 /* we have failed the constraint of a \n before rx_origin.
1164 * Find the next \n, if any, even if it's beyond the current
1165 * anchored and/or floating substrings. Whether we should be
1166 * scanning ahead for the next \n or the next substr is debatable.
1167 * On the one hand you'd expect rare substrings to appear less
1168 * often than \n's. On the other hand, searching for \n means
1169 * we're effectively flipping between check_substr and "\n" on each
1170 * iteration as the current "rarest" string candidate, which
1171 * means for example that we'll quickly reject the whole string if
1172 * hasn't got a \n, rather than trying every substr position
1176 s = HOP3c(strend, - prog->minlen, strpos);
1177 if (s <= rx_origin ||
1178 ! ( rx_origin = (char *)memchr(rx_origin, '\n', s - rx_origin)))
1180 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1181 " Did not find /%s^%s/m...\n",
1182 PL_colors[0], PL_colors[1]));
1186 /* earliest possible origin is 1 char after the \n.
1187 * (since *rx_origin == '\n', it's safe to ++ here rather than
1188 * HOP(rx_origin, 1)) */
1191 if (prog->substrs->check_ix == 0 /* check is anchored */
1192 || rx_origin >= HOP3c(check_at, - prog->check_offset_min, strpos))
1194 /* Position contradicts check-string; either because
1195 * check was anchored (and thus has no wiggle room),
1196 * or check was float and rx_origin is above the float range */
1197 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1198 " Found /%s^%s/m, about to restart lookup for check-string with rx_origin %ld...\n",
1199 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1203 /* if we get here, the check substr must have been float,
1204 * is in range, and we may or may not have had an anchored
1205 * "other" substr which still contradicts */
1206 assert(prog->substrs->check_ix); /* check is float */
1208 if (utf8_target ? prog->anchored_utf8 : prog->anchored_substr) {
1209 /* whoops, the anchored "other" substr exists, so we still
1210 * contradict. On the other hand, the float "check" substr
1211 * didn't contradict, so just retry the anchored "other"
1213 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1214 " Found /%s^%s/m, rescanning for anchored from offset %ld (rx_origin now %"IVdf")...\n",
1215 PL_colors[0], PL_colors[1],
1216 (long)(rx_origin - strbeg + prog->anchored_offset),
1217 (long)(rx_origin - strbeg)
1219 goto do_other_substr;
1222 /* success: we don't contradict the found floating substring
1223 * (and there's no anchored substr). */
1224 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1225 " Found /%s^%s/m with rx_origin %ld...\n",
1226 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1229 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1230 " (multiline anchor test skipped)\n"));
1236 /* if we have a starting character class, then test that extra constraint.
1237 * (trie stclasses are too expensive to use here, we are better off to
1238 * leave it to regmatch itself) */
1240 if (progi->regstclass && PL_regkind[OP(progi->regstclass)]!=TRIE) {
1241 const U8* const str = (U8*)STRING(progi->regstclass);
1243 /* XXX this value could be pre-computed */
1244 const int cl_l = (PL_regkind[OP(progi->regstclass)] == EXACT
1245 ? (reginfo->is_utf8_pat
1246 ? utf8_distance(str + STR_LEN(progi->regstclass), str)
1247 : STR_LEN(progi->regstclass))
1251 /* latest pos that a matching float substr constrains rx start to */
1252 char *rx_max_float = NULL;
1254 /* if the current rx_origin is anchored, either by satisfying an
1255 * anchored substring constraint, or a /^.../m constraint, then we
1256 * can reject the current origin if the start class isn't found
1257 * at the current position. If we have a float-only match, then
1258 * rx_origin is constrained to a range; so look for the start class
1259 * in that range. if neither, then look for the start class in the
1260 * whole rest of the string */
1262 /* XXX DAPM it's not clear what the minlen test is for, and why
1263 * it's not used in the floating case. Nothing in the test suite
1264 * causes minlen == 0 here. See <20140313134639.GS12844@iabyn.com>.
1265 * Here are some old comments, which may or may not be correct:
1267 * minlen == 0 is possible if regstclass is \b or \B,
1268 * and the fixed substr is ''$.
1269 * Since minlen is already taken into account, rx_origin+1 is
1270 * before strend; accidentally, minlen >= 1 guaranties no false
1271 * positives at rx_origin + 1 even for \b or \B. But (minlen? 1 :
1272 * 0) below assumes that regstclass does not come from lookahead...
1273 * If regstclass takes bytelength more than 1: If charlength==1, OK.
1274 * This leaves EXACTF-ish only, which are dealt with in
1278 if (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
1279 endpos= HOP3c(rx_origin, (prog->minlen ? cl_l : 0), strend);
1280 else if (prog->float_substr || prog->float_utf8) {
1281 rx_max_float = HOP3c(check_at, -start_shift, strbeg);
1282 endpos= HOP3c(rx_max_float, cl_l, strend);
1287 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1288 " looking for class: start_shift: %"IVdf" check_at: %"IVdf
1289 " rx_origin: %"IVdf" endpos: %"IVdf"\n",
1290 (IV)start_shift, (IV)(check_at - strbeg),
1291 (IV)(rx_origin - strbeg), (IV)(endpos - strbeg)));
1293 s = find_byclass(prog, progi->regstclass, rx_origin, endpos,
1296 if (endpos == strend) {
1297 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1298 " Could not match STCLASS...\n") );
1301 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1302 " This position contradicts STCLASS...\n") );
1303 if ((prog->intflags & PREGf_ANCH) && !ml_anch
1304 && !(prog->intflags & PREGf_IMPLICIT))
1307 /* Contradict one of substrings */
1308 if (prog->anchored_substr || prog->anchored_utf8) {
1309 if (prog->substrs->check_ix == 1) { /* check is float */
1310 /* Have both, check_string is floating */
1311 assert(rx_origin + start_shift <= check_at);
1312 if (rx_origin + start_shift != check_at) {
1313 /* not at latest position float substr could match:
1314 * Recheck anchored substring, but not floating.
1315 * The condition above is in bytes rather than
1316 * chars for efficiency. It's conservative, in
1317 * that it errs on the side of doing 'goto
1318 * do_other_substr'. In this case, at worst,
1319 * an extra anchored search may get done, but in
1320 * practice the extra fbm_instr() is likely to
1321 * get skipped anyway. */
1322 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1323 " about to retry anchored at offset %ld (rx_origin now %"IVdf")...\n",
1324 (long)(other_last - strbeg),
1325 (IV)(rx_origin - strbeg)
1327 goto do_other_substr;
1335 /* In the presence of ml_anch, we might be able to
1336 * find another \n without breaking the current float
1339 /* strictly speaking this should be HOP3c(..., 1, ...),
1340 * but since we goto a block of code that's going to
1341 * search for the next \n if any, its safe here */
1343 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1344 " about to look for /%s^%s/m starting at rx_origin %ld...\n",
1345 PL_colors[0], PL_colors[1],
1346 (long)(rx_origin - strbeg)) );
1347 goto postprocess_substr_matches;
1350 /* strictly speaking this can never be true; but might
1351 * be if we ever allow intuit without substrings */
1352 if (!(utf8_target ? prog->float_utf8 : prog->float_substr))
1355 rx_origin = rx_max_float;
1358 /* at this point, any matching substrings have been
1359 * contradicted. Start again... */
1361 rx_origin = HOP3c(rx_origin, 1, strend);
1363 /* uses bytes rather than char calculations for efficiency.
1364 * It's conservative: it errs on the side of doing 'goto restart',
1365 * where there is code that does a proper char-based test */
1366 if (rx_origin + start_shift + end_shift > strend) {
1367 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1368 " Could not match STCLASS...\n") );
1371 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1372 " about to look for %s substr starting at offset %ld (rx_origin now %"IVdf")...\n",
1373 (prog->substrs->check_ix ? "floating" : "anchored"),
1374 (long)(rx_origin + start_shift - strbeg),
1375 (IV)(rx_origin - strbeg)
1382 if (rx_origin != s) {
1383 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1384 " By STCLASS: moving %ld --> %ld\n",
1385 (long)(rx_origin - strbeg), (long)(s - strbeg))
1389 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1390 " Does not contradict STCLASS...\n");
1395 /* Decide whether using the substrings helped */
1397 if (rx_origin != strpos) {
1398 /* Fixed substring is found far enough so that the match
1399 cannot start at strpos. */
1401 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " try at offset...\n"));
1402 ++BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr); /* hooray/5 */
1405 /* The found rx_origin position does not prohibit matching at
1406 * strpos, so calling intuit didn't gain us anything. Decrement
1407 * the BmUSEFUL() count on the check substring, and if we reach
1409 if (!(prog->intflags & PREGf_NAUGHTY)
1411 prog->check_utf8 /* Could be deleted already */
1412 && --BmUSEFUL(prog->check_utf8) < 0
1413 && (prog->check_utf8 == prog->float_utf8)
1415 prog->check_substr /* Could be deleted already */
1416 && --BmUSEFUL(prog->check_substr) < 0
1417 && (prog->check_substr == prog->float_substr)
1420 /* If flags & SOMETHING - do not do it many times on the same match */
1421 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " ... Disabling check substring...\n"));
1422 /* XXX Does the destruction order has to change with utf8_target? */
1423 SvREFCNT_dec(utf8_target ? prog->check_utf8 : prog->check_substr);
1424 SvREFCNT_dec(utf8_target ? prog->check_substr : prog->check_utf8);
1425 prog->check_substr = prog->check_utf8 = NULL; /* disable */
1426 prog->float_substr = prog->float_utf8 = NULL; /* clear */
1427 check = NULL; /* abort */
1428 /* XXXX This is a remnant of the old implementation. It
1429 looks wasteful, since now INTUIT can use many
1430 other heuristics. */
1431 prog->extflags &= ~RXf_USE_INTUIT;
1435 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1436 "Intuit: %sSuccessfully guessed:%s match at offset %ld\n",
1437 PL_colors[4], PL_colors[5], (long)(rx_origin - strbeg)) );
1441 fail_finish: /* Substring not found */
1442 if (prog->check_substr || prog->check_utf8) /* could be removed already */
1443 BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
1445 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch rejected by optimizer%s\n",
1446 PL_colors[4], PL_colors[5]));
1451 #define DECL_TRIE_TYPE(scan) \
1452 const enum { trie_plain, trie_utf8, trie_utf8_fold, trie_latin_utf8_fold, \
1453 trie_utf8_exactfa_fold, trie_latin_utf8_exactfa_fold, \
1454 trie_utf8l, trie_flu8 } \
1455 trie_type = ((scan->flags == EXACT) \
1456 ? (utf8_target ? trie_utf8 : trie_plain) \
1457 : (scan->flags == EXACTL) \
1458 ? (utf8_target ? trie_utf8l : trie_plain) \
1459 : (scan->flags == EXACTFA) \
1461 ? trie_utf8_exactfa_fold \
1462 : trie_latin_utf8_exactfa_fold) \
1463 : (scan->flags == EXACTFLU8 \
1467 : trie_latin_utf8_fold)))
1469 #define REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc, uscan, len, uvc, charid, foldlen, foldbuf, uniflags) \
1472 U8 flags = FOLD_FLAGS_FULL; \
1473 switch (trie_type) { \
1475 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1476 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1477 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1479 goto do_trie_utf8_fold; \
1480 case trie_utf8_exactfa_fold: \
1481 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1483 case trie_utf8_fold: \
1484 do_trie_utf8_fold: \
1485 if ( foldlen>0 ) { \
1486 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1491 uvc = _to_utf8_fold_flags( (const U8*) uc, foldbuf, &foldlen, flags); \
1492 len = UTF8SKIP(uc); \
1493 skiplen = UNISKIP( uvc ); \
1494 foldlen -= skiplen; \
1495 uscan = foldbuf + skiplen; \
1498 case trie_latin_utf8_exactfa_fold: \
1499 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1501 case trie_latin_utf8_fold: \
1502 if ( foldlen>0 ) { \
1503 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1509 uvc = _to_fold_latin1( (U8) *uc, foldbuf, &foldlen, flags); \
1510 skiplen = UNISKIP( uvc ); \
1511 foldlen -= skiplen; \
1512 uscan = foldbuf + skiplen; \
1516 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1517 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1518 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1522 uvc = utf8n_to_uvchr( (const U8*) uc, UTF8_MAXLEN, &len, uniflags ); \
1529 charid = trie->charmap[ uvc ]; \
1533 if (widecharmap) { \
1534 SV** const svpp = hv_fetch(widecharmap, \
1535 (char*)&uvc, sizeof(UV), 0); \
1537 charid = (U16)SvIV(*svpp); \
1542 #define DUMP_EXEC_POS(li,s,doutf8) \
1543 dump_exec_pos(li,s,(reginfo->strend),(reginfo->strbeg), \
1546 #define REXEC_FBC_EXACTISH_SCAN(COND) \
1550 && (ln == 1 || folder(s, pat_string, ln)) \
1551 && (reginfo->intuit || regtry(reginfo, &s)) )\
1557 #define REXEC_FBC_UTF8_SCAN(CODE) \
1559 while (s < strend) { \
1565 #define REXEC_FBC_SCAN(CODE) \
1567 while (s < strend) { \
1573 #define REXEC_FBC_UTF8_CLASS_SCAN(COND) \
1574 REXEC_FBC_UTF8_SCAN( /* Loops while (s < strend) */ \
1576 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1585 #define REXEC_FBC_CLASS_SCAN(COND) \
1586 REXEC_FBC_SCAN( /* Loops while (s < strend) */ \
1588 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1597 #define REXEC_FBC_CSCAN(CONDUTF8,COND) \
1598 if (utf8_target) { \
1599 REXEC_FBC_UTF8_CLASS_SCAN(CONDUTF8); \
1602 REXEC_FBC_CLASS_SCAN(COND); \
1605 /* The three macros below are slightly different versions of the same logic.
1607 * The first is for /a and /aa when the target string is UTF-8. This can only
1608 * match ascii, but it must advance based on UTF-8. The other two handle the
1609 * non-UTF-8 and the more generic UTF-8 cases. In all three, we are looking
1610 * for the boundary (or non-boundary) between a word and non-word character.
1611 * The utf8 and non-utf8 cases have the same logic, but the details must be
1612 * different. Find the "wordness" of the character just prior to this one, and
1613 * compare it with the wordness of this one. If they differ, we have a
1614 * boundary. At the beginning of the string, pretend that the previous
1615 * character was a new-line.
1617 * All these macros uncleanly have side-effects with each other and outside
1618 * variables. So far it's been too much trouble to clean-up
1620 * TEST_NON_UTF8 is the macro or function to call to test if its byte input is
1621 * a word character or not.
1622 * IF_SUCCESS is code to do if it finds that we are at a boundary between
1624 * IF_FAIL is code to do if we aren't at a boundary between word/non-word
1626 * Exactly one of the two IF_FOO parameters is a no-op, depending on whether we
1627 * are looking for a boundary or for a non-boundary. If we are looking for a
1628 * boundary, we want IF_FAIL to be the no-op, and for IF_SUCCESS to go out and
1629 * see if this tentative match actually works, and if so, to quit the loop
1630 * here. And vice-versa if we are looking for a non-boundary.
1632 * 'tmp' below in the next three macros in the REXEC_FBC_SCAN and
1633 * REXEC_FBC_UTF8_SCAN loops is a loop invariant, a bool giving the return of
1634 * TEST_NON_UTF8(s-1). To see this, note that that's what it is defined to be
1635 * at entry to the loop, and to get to the IF_FAIL branch, tmp must equal
1636 * TEST_NON_UTF8(s), and in the opposite branch, IF_SUCCESS, tmp is that
1637 * complement. But in that branch we complement tmp, meaning that at the
1638 * bottom of the loop tmp is always going to be equal to TEST_NON_UTF8(s),
1639 * which means at the top of the loop in the next iteration, it is
1640 * TEST_NON_UTF8(s-1) */
1641 #define FBC_UTF8_A(TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1642 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1643 tmp = TEST_NON_UTF8(tmp); \
1644 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1645 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1647 IF_SUCCESS; /* Is a boundary if values for s-1 and s differ */ \
1654 /* Like FBC_UTF8_A, but TEST_UV is a macro which takes a UV as its input, and
1655 * TEST_UTF8 is a macro that for the same input code points returns identically
1656 * to TEST_UV, but takes a pointer to a UTF-8 encoded string instead */
1657 #define FBC_UTF8(TEST_UV, TEST_UTF8, IF_SUCCESS, IF_FAIL) \
1658 if (s == reginfo->strbeg) { \
1661 else { /* Back-up to the start of the previous character */ \
1662 U8 * const r = reghop3((U8*)s, -1, (U8*)reginfo->strbeg); \
1663 tmp = utf8n_to_uvchr(r, (U8*) reginfo->strend - r, \
1664 0, UTF8_ALLOW_DEFAULT); \
1666 tmp = TEST_UV(tmp); \
1667 LOAD_UTF8_CHARCLASS_ALNUM(); \
1668 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1669 if (tmp == ! (TEST_UTF8((U8 *) s))) { \
1678 /* Like the above two macros. UTF8_CODE is the complete code for handling
1679 * UTF-8. Common to the BOUND and NBOUND cases, set-up by the FBC_BOUND, etc
1681 #define FBC_BOUND_COMMON(UTF8_CODE, TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1682 if (utf8_target) { \
1685 else { /* Not utf8 */ \
1686 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1687 tmp = TEST_NON_UTF8(tmp); \
1688 REXEC_FBC_SCAN( /* advances s while s < strend */ \
1689 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1698 /* Here, things have been set up by the previous code so that tmp is the \
1699 * return of TEST_NON_UTF(s-1) or TEST_UTF8(s-1) (depending on the \
1700 * utf8ness of the target). We also have to check if this matches against \
1701 * the EOS, which we treat as a \n (which is the same value in both UTF-8 \
1702 * or non-UTF8, so can use the non-utf8 test condition even for a UTF-8 \
1704 if (tmp == ! TEST_NON_UTF8('\n')) { \
1711 /* This is the macro to use when we want to see if something that looks like it
1712 * could match, actually does, and if so exits the loop */
1713 #define REXEC_FBC_TRYIT \
1714 if ((reginfo->intuit || regtry(reginfo, &s))) \
1717 /* The only difference between the BOUND and NBOUND cases is that
1718 * REXEC_FBC_TRYIT is called when matched in BOUND, and when non-matched in
1719 * NBOUND. This is accomplished by passing it as either the if or else clause,
1720 * with the other one being empty (PLACEHOLDER is defined as empty).
1722 * The TEST_FOO parameters are for operating on different forms of input, but
1723 * all should be ones that return identically for the same underlying code
1725 #define FBC_BOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1727 FBC_UTF8(TEST_UV, TEST_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1728 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1730 #define FBC_BOUND_A(TEST_NON_UTF8) \
1732 FBC_UTF8_A(TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1733 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1735 #define FBC_NBOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1737 FBC_UTF8(TEST_UV, TEST_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1738 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1740 #define FBC_NBOUND_A(TEST_NON_UTF8) \
1742 FBC_UTF8_A(TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1743 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1745 /* Takes a pointer to an inversion list, a pointer to its corresponding
1746 * inversion map, and a code point, and returns the code point's value
1747 * according to the two arrays. It assumes that all code points have a value.
1748 * This is used as the base macro for macros for particular properties */
1749 #define _generic_GET_BREAK_VAL_CP(invlist, invmap, cp) \
1750 invmap[_invlist_search(invlist, cp)]
1752 /* Same as above, but takes begin, end ptrs to a UTF-8 encoded string instead
1753 * of a code point, returning the value for the first code point in the string.
1754 * And it takes the particular macro name that finds the desired value given a
1755 * code point. Merely convert the UTF-8 to code point and call the cp macro */
1756 #define _generic_GET_BREAK_VAL_UTF8(cp_macro, pos, strend) \
1757 (__ASSERT_(pos < strend) \
1758 /* Note assumes is valid UTF-8 */ \
1759 (cp_macro(utf8_to_uvchr_buf((pos), (strend), NULL))))
1761 /* Returns the GCB value for the input code point */
1762 #define getGCB_VAL_CP(cp) \
1763 _generic_GET_BREAK_VAL_CP( \
1765 Grapheme_Cluster_Break_invmap, \
1768 /* Returns the GCB value for the first code point in the UTF-8 encoded string
1769 * bounded by pos and strend */
1770 #define getGCB_VAL_UTF8(pos, strend) \
1771 _generic_GET_BREAK_VAL_UTF8(getGCB_VAL_CP, pos, strend)
1774 /* Returns the SB value for the input code point */
1775 #define getSB_VAL_CP(cp) \
1776 _generic_GET_BREAK_VAL_CP( \
1778 Sentence_Break_invmap, \
1781 /* Returns the SB value for the first code point in the UTF-8 encoded string
1782 * bounded by pos and strend */
1783 #define getSB_VAL_UTF8(pos, strend) \
1784 _generic_GET_BREAK_VAL_UTF8(getSB_VAL_CP, pos, strend)
1786 /* Returns the WB value for the input code point */
1787 #define getWB_VAL_CP(cp) \
1788 _generic_GET_BREAK_VAL_CP( \
1790 Word_Break_invmap, \
1793 /* Returns the WB value for the first code point in the UTF-8 encoded string
1794 * bounded by pos and strend */
1795 #define getWB_VAL_UTF8(pos, strend) \
1796 _generic_GET_BREAK_VAL_UTF8(getWB_VAL_CP, pos, strend)
1798 /* We know what class REx starts with. Try to find this position... */
1799 /* if reginfo->intuit, its a dryrun */
1800 /* annoyingly all the vars in this routine have different names from their counterparts
1801 in regmatch. /grrr */
1803 S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
1804 const char *strend, regmatch_info *reginfo)
1807 const I32 doevery = (prog->intflags & PREGf_SKIP) == 0;
1808 char *pat_string; /* The pattern's exactish string */
1809 char *pat_end; /* ptr to end char of pat_string */
1810 re_fold_t folder; /* Function for computing non-utf8 folds */
1811 const U8 *fold_array; /* array for folding ords < 256 */
1817 I32 tmp = 1; /* Scratch variable? */
1818 const bool utf8_target = reginfo->is_utf8_target;
1819 UV utf8_fold_flags = 0;
1820 const bool is_utf8_pat = reginfo->is_utf8_pat;
1821 bool to_complement = FALSE; /* Invert the result? Taking the xor of this
1822 with a result inverts that result, as 0^1 =
1824 _char_class_number classnum;
1826 RXi_GET_DECL(prog,progi);
1828 PERL_ARGS_ASSERT_FIND_BYCLASS;
1830 /* We know what class it must start with. */
1833 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1837 REXEC_FBC_UTF8_CLASS_SCAN(
1838 reginclass(prog, c, (U8*)s, (U8*) strend, utf8_target));
1841 REXEC_FBC_CLASS_SCAN(REGINCLASS(prog, c, (U8*)s));
1846 if (tmp && (reginfo->intuit || regtry(reginfo, &s)))
1853 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
1854 assert(! is_utf8_pat);
1857 if (is_utf8_pat || utf8_target) {
1858 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
1859 goto do_exactf_utf8;
1861 fold_array = PL_fold_latin1; /* Latin1 folds are not affected by */
1862 folder = foldEQ_latin1; /* /a, except the sharp s one which */
1863 goto do_exactf_non_utf8; /* isn't dealt with by these */
1865 case EXACTF: /* This node only generated for non-utf8 patterns */
1866 assert(! is_utf8_pat);
1868 utf8_fold_flags = 0;
1869 goto do_exactf_utf8;
1871 fold_array = PL_fold;
1873 goto do_exactf_non_utf8;
1876 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1877 if (is_utf8_pat || utf8_target || IN_UTF8_CTYPE_LOCALE) {
1878 utf8_fold_flags = FOLDEQ_LOCALE;
1879 goto do_exactf_utf8;
1881 fold_array = PL_fold_locale;
1882 folder = foldEQ_locale;
1883 goto do_exactf_non_utf8;
1887 utf8_fold_flags = FOLDEQ_S2_ALREADY_FOLDED;
1889 goto do_exactf_utf8;
1892 if (! utf8_target) { /* All code points in this node require
1893 UTF-8 to express. */
1896 utf8_fold_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
1897 | FOLDEQ_S2_FOLDS_SANE;
1898 goto do_exactf_utf8;
1901 if (is_utf8_pat || utf8_target) {
1902 utf8_fold_flags = is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
1903 goto do_exactf_utf8;
1906 /* Any 'ss' in the pattern should have been replaced by regcomp,
1907 * so we don't have to worry here about this single special case
1908 * in the Latin1 range */
1909 fold_array = PL_fold_latin1;
1910 folder = foldEQ_latin1;
1914 do_exactf_non_utf8: /* Neither pattern nor string are UTF8, and there
1915 are no glitches with fold-length differences
1916 between the target string and pattern */
1918 /* The idea in the non-utf8 EXACTF* cases is to first find the
1919 * first character of the EXACTF* node and then, if necessary,
1920 * case-insensitively compare the full text of the node. c1 is the
1921 * first character. c2 is its fold. This logic will not work for
1922 * Unicode semantics and the german sharp ss, which hence should
1923 * not be compiled into a node that gets here. */
1924 pat_string = STRING(c);
1925 ln = STR_LEN(c); /* length to match in octets/bytes */
1927 /* We know that we have to match at least 'ln' bytes (which is the
1928 * same as characters, since not utf8). If we have to match 3
1929 * characters, and there are only 2 availabe, we know without
1930 * trying that it will fail; so don't start a match past the
1931 * required minimum number from the far end */
1932 e = HOP3c(strend, -((SSize_t)ln), s);
1934 if (reginfo->intuit && e < s) {
1935 e = s; /* Due to minlen logic of intuit() */
1939 c2 = fold_array[c1];
1940 if (c1 == c2) { /* If char and fold are the same */
1941 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1);
1944 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1 || *(U8*)s == c2);
1952 /* If one of the operands is in utf8, we can't use the simpler folding
1953 * above, due to the fact that many different characters can have the
1954 * same fold, or portion of a fold, or different- length fold */
1955 pat_string = STRING(c);
1956 ln = STR_LEN(c); /* length to match in octets/bytes */
1957 pat_end = pat_string + ln;
1958 lnc = is_utf8_pat /* length to match in characters */
1959 ? utf8_length((U8 *) pat_string, (U8 *) pat_end)
1962 /* We have 'lnc' characters to match in the pattern, but because of
1963 * multi-character folding, each character in the target can match
1964 * up to 3 characters (Unicode guarantees it will never exceed
1965 * this) if it is utf8-encoded; and up to 2 if not (based on the
1966 * fact that the Latin 1 folds are already determined, and the
1967 * only multi-char fold in that range is the sharp-s folding to
1968 * 'ss'. Thus, a pattern character can match as little as 1/3 of a
1969 * string character. Adjust lnc accordingly, rounding up, so that
1970 * if we need to match at least 4+1/3 chars, that really is 5. */
1971 expansion = (utf8_target) ? UTF8_MAX_FOLD_CHAR_EXPAND : 2;
1972 lnc = (lnc + expansion - 1) / expansion;
1974 /* As in the non-UTF8 case, if we have to match 3 characters, and
1975 * only 2 are left, it's guaranteed to fail, so don't start a
1976 * match that would require us to go beyond the end of the string
1978 e = HOP3c(strend, -((SSize_t)lnc), s);
1980 if (reginfo->intuit && e < s) {
1981 e = s; /* Due to minlen logic of intuit() */
1984 /* XXX Note that we could recalculate e to stop the loop earlier,
1985 * as the worst case expansion above will rarely be met, and as we
1986 * go along we would usually find that e moves further to the left.
1987 * This would happen only after we reached the point in the loop
1988 * where if there were no expansion we should fail. Unclear if
1989 * worth the expense */
1992 char *my_strend= (char *)strend;
1993 if (foldEQ_utf8_flags(s, &my_strend, 0, utf8_target,
1994 pat_string, NULL, ln, is_utf8_pat, utf8_fold_flags)
1995 && (reginfo->intuit || regtry(reginfo, &s)) )
1999 s += (utf8_target) ? UTF8SKIP(s) : 1;
2005 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2006 if (FLAGS(c) != TRADITIONAL_BOUND) {
2007 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2008 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2012 FBC_BOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8);
2016 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2017 if (FLAGS(c) != TRADITIONAL_BOUND) {
2018 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2019 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2023 FBC_NBOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8);
2026 case BOUND: /* regcomp.c makes sure that this only has the traditional \b
2028 assert(FLAGS(c) == TRADITIONAL_BOUND);
2030 FBC_BOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8);
2033 case BOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2035 assert(FLAGS(c) == TRADITIONAL_BOUND);
2037 FBC_BOUND_A(isWORDCHAR_A);
2040 case NBOUND: /* regcomp.c makes sure that this only has the traditional \b
2042 assert(FLAGS(c) == TRADITIONAL_BOUND);
2044 FBC_NBOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8);
2047 case NBOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2049 assert(FLAGS(c) == TRADITIONAL_BOUND);
2051 FBC_NBOUND_A(isWORDCHAR_A);
2055 if ((bound_type) FLAGS(c) == TRADITIONAL_BOUND) {
2056 FBC_NBOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8);
2067 switch((bound_type) FLAGS(c)) {
2068 case TRADITIONAL_BOUND:
2069 FBC_BOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8);
2072 if (s == reginfo->strbeg) { /* GCB always matches at begin and
2074 if (to_complement ^ cBOOL(reginfo->intuit
2075 || regtry(reginfo, &s)))
2079 s += (utf8_target) ? UTF8SKIP(s) : 1;
2083 GCB_enum before = getGCB_VAL_UTF8(
2085 (U8*)(reginfo->strbeg)),
2086 (U8*) reginfo->strend);
2087 while (s < strend) {
2088 GCB_enum after = getGCB_VAL_UTF8((U8*) s,
2089 (U8*) reginfo->strend);
2090 if (to_complement ^ isGCB(before, after)) {
2091 if (reginfo->intuit || regtry(reginfo, &s)) {
2099 else { /* Not utf8. Everything is a GCB except between CR and
2101 while (s < strend) {
2102 if (to_complement ^ (UCHARAT(s - 1) != '\r'
2103 || UCHARAT(s) != '\n'))
2105 if (reginfo->intuit || regtry(reginfo, &s)) {
2113 if (to_complement ^ cBOOL(reginfo->intuit || regtry(reginfo, &s))) {
2119 if (s == reginfo->strbeg) { /* SB always matches at beginning */
2121 ^ cBOOL(reginfo->intuit || regtry(reginfo, &s)))
2126 /* Didn't match. Go try at the next position */
2127 s += (utf8_target) ? UTF8SKIP(s) : 1;
2131 SB_enum before = getSB_VAL_UTF8(reghop3((U8*)s,
2133 (U8*)(reginfo->strbeg)),
2134 (U8*) reginfo->strend);
2135 while (s < strend) {
2136 SB_enum after = getSB_VAL_UTF8((U8*) s,
2137 (U8*) reginfo->strend);
2138 if (to_complement ^ isSB(before,
2140 (U8*) reginfo->strbeg,
2142 (U8*) reginfo->strend,
2145 if (reginfo->intuit || regtry(reginfo, &s)) {
2153 else { /* Not utf8. */
2154 SB_enum before = getSB_VAL_CP((U8) *(s -1));
2155 while (s < strend) {
2156 SB_enum after = getSB_VAL_CP((U8) *s);
2157 if (to_complement ^ isSB(before,
2159 (U8*) reginfo->strbeg,
2161 (U8*) reginfo->strend,
2164 if (reginfo->intuit || regtry(reginfo, &s)) {
2173 /* Here are at the final position in the target string. The SB
2174 * value is always true here, so matches, depending on other
2176 if (to_complement ^ cBOOL(reginfo->intuit
2177 || regtry(reginfo, &s)))
2185 if (s == reginfo->strbeg) {
2186 if (to_complement ^ cBOOL(reginfo->intuit
2187 || regtry(reginfo, &s)))
2191 s += (utf8_target) ? UTF8SKIP(s) : 1;
2195 /* We are at a boundary between char_sub_0 and char_sub_1.
2196 * We also keep track of the value for char_sub_-1 as we
2197 * loop through the line. Context may be needed to make a
2198 * determination, and if so, this can save having to
2200 WB_enum previous = WB_UNKNOWN;
2201 WB_enum before = getWB_VAL_UTF8(
2204 (U8*)(reginfo->strbeg)),
2205 (U8*) reginfo->strend);
2206 while (s < strend) {
2207 WB_enum after = getWB_VAL_UTF8((U8*) s,
2208 (U8*) reginfo->strend);
2209 if (to_complement ^ isWB(previous,
2212 (U8*) reginfo->strbeg,
2214 (U8*) reginfo->strend,
2217 if (reginfo->intuit || regtry(reginfo, &s)) {
2226 else { /* Not utf8. */
2227 WB_enum previous = WB_UNKNOWN;
2228 WB_enum before = getWB_VAL_CP((U8) *(s -1));
2229 while (s < strend) {
2230 WB_enum after = getWB_VAL_CP((U8) *s);
2231 if (to_complement ^ isWB(previous,
2234 (U8*) reginfo->strbeg,
2236 (U8*) reginfo->strend,
2239 if (reginfo->intuit || regtry(reginfo, &s)) {
2249 if (to_complement ^ cBOOL(reginfo->intuit
2250 || regtry(reginfo, &s)))
2260 REXEC_FBC_CSCAN(is_LNBREAK_utf8_safe(s, strend),
2261 is_LNBREAK_latin1_safe(s, strend)
2265 /* The argument to all the POSIX node types is the class number to pass to
2266 * _generic_isCC() to build a mask for searching in PL_charclass[] */
2273 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2274 REXEC_FBC_CSCAN(to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(c), (U8 *) s)),
2275 to_complement ^ cBOOL(isFOO_lc(FLAGS(c), *s)));
2290 /* The complement of something that matches only ASCII matches all
2291 * non-ASCII, plus everything in ASCII that isn't in the class. */
2292 REXEC_FBC_UTF8_CLASS_SCAN(! isASCII_utf8(s)
2293 || ! _generic_isCC_A(*s, FLAGS(c)));
2302 /* Don't need to worry about utf8, as it can match only a single
2303 * byte invariant character. */
2304 REXEC_FBC_CLASS_SCAN(
2305 to_complement ^ cBOOL(_generic_isCC_A(*s, FLAGS(c))));
2313 if (! utf8_target) {
2314 REXEC_FBC_CLASS_SCAN(to_complement ^ cBOOL(_generic_isCC(*s,
2320 classnum = (_char_class_number) FLAGS(c);
2321 if (classnum < _FIRST_NON_SWASH_CC) {
2322 while (s < strend) {
2324 /* We avoid loading in the swash as long as possible, but
2325 * should we have to, we jump to a separate loop. This
2326 * extra 'if' statement is what keeps this code from being
2327 * just a call to REXEC_FBC_UTF8_CLASS_SCAN() */
2328 if (UTF8_IS_ABOVE_LATIN1(*s)) {
2329 goto found_above_latin1;
2331 if ((UTF8_IS_INVARIANT(*s)
2332 && to_complement ^ cBOOL(_generic_isCC((U8) *s,
2334 || (UTF8_IS_DOWNGRADEABLE_START(*s)
2335 && to_complement ^ cBOOL(
2336 _generic_isCC(TWO_BYTE_UTF8_TO_NATIVE(*s,
2340 if (tmp && (reginfo->intuit || regtry(reginfo, &s)))
2352 else switch (classnum) { /* These classes are implemented as
2354 case _CC_ENUM_SPACE:
2355 REXEC_FBC_UTF8_CLASS_SCAN(
2356 to_complement ^ cBOOL(isSPACE_utf8(s)));
2359 case _CC_ENUM_BLANK:
2360 REXEC_FBC_UTF8_CLASS_SCAN(
2361 to_complement ^ cBOOL(isBLANK_utf8(s)));
2364 case _CC_ENUM_XDIGIT:
2365 REXEC_FBC_UTF8_CLASS_SCAN(
2366 to_complement ^ cBOOL(isXDIGIT_utf8(s)));
2369 case _CC_ENUM_VERTSPACE:
2370 REXEC_FBC_UTF8_CLASS_SCAN(
2371 to_complement ^ cBOOL(isVERTWS_utf8(s)));
2374 case _CC_ENUM_CNTRL:
2375 REXEC_FBC_UTF8_CLASS_SCAN(
2376 to_complement ^ cBOOL(isCNTRL_utf8(s)));
2380 Perl_croak(aTHX_ "panic: find_byclass() node %d='%s' has an unexpected character class '%d'", OP(c), PL_reg_name[OP(c)], classnum);
2381 NOT_REACHED; /* NOTREACHED */
2386 found_above_latin1: /* Here we have to load a swash to get the result
2387 for the current code point */
2388 if (! PL_utf8_swash_ptrs[classnum]) {
2389 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
2390 PL_utf8_swash_ptrs[classnum] =
2391 _core_swash_init("utf8",
2394 PL_XPosix_ptrs[classnum], &flags);
2397 /* This is a copy of the loop above for swash classes, though using the
2398 * FBC macro instead of being expanded out. Since we've loaded the
2399 * swash, we don't have to check for that each time through the loop */
2400 REXEC_FBC_UTF8_CLASS_SCAN(
2401 to_complement ^ cBOOL(_generic_utf8(
2404 swash_fetch(PL_utf8_swash_ptrs[classnum],
2412 /* what trie are we using right now */
2413 reg_ac_data *aho = (reg_ac_data*)progi->data->data[ ARG( c ) ];
2414 reg_trie_data *trie = (reg_trie_data*)progi->data->data[ aho->trie ];
2415 HV *widecharmap = MUTABLE_HV(progi->data->data[ aho->trie + 1 ]);
2417 const char *last_start = strend - trie->minlen;
2419 const char *real_start = s;
2421 STRLEN maxlen = trie->maxlen;
2423 U8 **points; /* map of where we were in the input string
2424 when reading a given char. For ASCII this
2425 is unnecessary overhead as the relationship
2426 is always 1:1, but for Unicode, especially
2427 case folded Unicode this is not true. */
2428 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
2432 GET_RE_DEBUG_FLAGS_DECL;
2434 /* We can't just allocate points here. We need to wrap it in
2435 * an SV so it gets freed properly if there is a croak while
2436 * running the match */
2439 sv_points=newSV(maxlen * sizeof(U8 *));
2440 SvCUR_set(sv_points,
2441 maxlen * sizeof(U8 *));
2442 SvPOK_on(sv_points);
2443 sv_2mortal(sv_points);
2444 points=(U8**)SvPV_nolen(sv_points );
2445 if ( trie_type != trie_utf8_fold
2446 && (trie->bitmap || OP(c)==AHOCORASICKC) )
2449 bitmap=(U8*)trie->bitmap;
2451 bitmap=(U8*)ANYOF_BITMAP(c);
2453 /* this is the Aho-Corasick algorithm modified a touch
2454 to include special handling for long "unknown char" sequences.
2455 The basic idea being that we use AC as long as we are dealing
2456 with a possible matching char, when we encounter an unknown char
2457 (and we have not encountered an accepting state) we scan forward
2458 until we find a legal starting char.
2459 AC matching is basically that of trie matching, except that when
2460 we encounter a failing transition, we fall back to the current
2461 states "fail state", and try the current char again, a process
2462 we repeat until we reach the root state, state 1, or a legal
2463 transition. If we fail on the root state then we can either
2464 terminate if we have reached an accepting state previously, or
2465 restart the entire process from the beginning if we have not.
2468 while (s <= last_start) {
2469 const U32 uniflags = UTF8_ALLOW_DEFAULT;
2477 U8 *uscan = (U8*)NULL;
2478 U8 *leftmost = NULL;
2480 U32 accepted_word= 0;
2484 while ( state && uc <= (U8*)strend ) {
2486 U32 word = aho->states[ state ].wordnum;
2490 DEBUG_TRIE_EXECUTE_r(
2491 if ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2492 dump_exec_pos( (char *)uc, c, strend, real_start,
2493 (char *)uc, utf8_target );
2494 PerlIO_printf( Perl_debug_log,
2495 " Scanning for legal start char...\n");
2499 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2503 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2509 if (uc >(U8*)last_start) break;
2513 U8 *lpos= points[ (pointpos - trie->wordinfo[word].len) % maxlen ];
2514 if (!leftmost || lpos < leftmost) {
2515 DEBUG_r(accepted_word=word);
2521 points[pointpos++ % maxlen]= uc;
2522 if (foldlen || uc < (U8*)strend) {
2523 REXEC_TRIE_READ_CHAR(trie_type, trie,
2525 uscan, len, uvc, charid, foldlen,
2527 DEBUG_TRIE_EXECUTE_r({
2528 dump_exec_pos( (char *)uc, c, strend,
2529 real_start, s, utf8_target);
2530 PerlIO_printf(Perl_debug_log,
2531 " Charid:%3u CP:%4"UVxf" ",
2543 word = aho->states[ state ].wordnum;
2545 base = aho->states[ state ].trans.base;
2547 DEBUG_TRIE_EXECUTE_r({
2549 dump_exec_pos( (char *)uc, c, strend, real_start,
2551 PerlIO_printf( Perl_debug_log,
2552 "%sState: %4"UVxf", word=%"UVxf,
2553 failed ? " Fail transition to " : "",
2554 (UV)state, (UV)word);
2560 ( ((offset = base + charid
2561 - 1 - trie->uniquecharcount)) >= 0)
2562 && ((U32)offset < trie->lasttrans)
2563 && trie->trans[offset].check == state
2564 && (tmp=trie->trans[offset].next))
2566 DEBUG_TRIE_EXECUTE_r(
2567 PerlIO_printf( Perl_debug_log," - legal\n"));
2572 DEBUG_TRIE_EXECUTE_r(
2573 PerlIO_printf( Perl_debug_log," - fail\n"));
2575 state = aho->fail[state];
2579 /* we must be accepting here */
2580 DEBUG_TRIE_EXECUTE_r(
2581 PerlIO_printf( Perl_debug_log," - accepting\n"));
2590 if (!state) state = 1;
2593 if ( aho->states[ state ].wordnum ) {
2594 U8 *lpos = points[ (pointpos - trie->wordinfo[aho->states[ state ].wordnum].len) % maxlen ];
2595 if (!leftmost || lpos < leftmost) {
2596 DEBUG_r(accepted_word=aho->states[ state ].wordnum);
2601 s = (char*)leftmost;
2602 DEBUG_TRIE_EXECUTE_r({
2604 Perl_debug_log,"Matches word #%"UVxf" at position %"IVdf". Trying full pattern...\n",
2605 (UV)accepted_word, (IV)(s - real_start)
2608 if (reginfo->intuit || regtry(reginfo, &s)) {
2614 DEBUG_TRIE_EXECUTE_r({
2615 PerlIO_printf( Perl_debug_log,"Pattern failed. Looking for new start point...\n");
2618 DEBUG_TRIE_EXECUTE_r(
2619 PerlIO_printf( Perl_debug_log,"No match.\n"));
2628 Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
2635 /* set RX_SAVED_COPY, RX_SUBBEG etc.
2636 * flags have same meanings as with regexec_flags() */
2639 S_reg_set_capture_string(pTHX_ REGEXP * const rx,
2646 struct regexp *const prog = ReANY(rx);
2648 if (flags & REXEC_COPY_STR) {
2652 PerlIO_printf(Perl_debug_log,
2653 "Copy on write: regexp capture, type %d\n",
2656 /* Create a new COW SV to share the match string and store
2657 * in saved_copy, unless the current COW SV in saved_copy
2658 * is valid and suitable for our purpose */
2659 if (( prog->saved_copy
2660 && SvIsCOW(prog->saved_copy)
2661 && SvPOKp(prog->saved_copy)
2664 && SvPVX(sv) == SvPVX(prog->saved_copy)))
2666 /* just reuse saved_copy SV */
2667 if (RXp_MATCH_COPIED(prog)) {
2668 Safefree(prog->subbeg);
2669 RXp_MATCH_COPIED_off(prog);
2673 /* create new COW SV to share string */
2674 RX_MATCH_COPY_FREE(rx);
2675 prog->saved_copy = sv_setsv_cow(prog->saved_copy, sv);
2677 prog->subbeg = (char *)SvPVX_const(prog->saved_copy);
2678 assert (SvPOKp(prog->saved_copy));
2679 prog->sublen = strend - strbeg;
2680 prog->suboffset = 0;
2681 prog->subcoffset = 0;
2686 SSize_t max = strend - strbeg;
2689 if ( (flags & REXEC_COPY_SKIP_POST)
2690 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2691 && !(PL_sawampersand & SAWAMPERSAND_RIGHT)
2692 ) { /* don't copy $' part of string */
2695 /* calculate the right-most part of the string covered
2696 * by a capture. Due to look-ahead, this may be to
2697 * the right of $&, so we have to scan all captures */
2698 while (n <= prog->lastparen) {
2699 if (prog->offs[n].end > max)
2700 max = prog->offs[n].end;
2704 max = (PL_sawampersand & SAWAMPERSAND_LEFT)
2705 ? prog->offs[0].start
2707 assert(max >= 0 && max <= strend - strbeg);
2710 if ( (flags & REXEC_COPY_SKIP_PRE)
2711 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2712 && !(PL_sawampersand & SAWAMPERSAND_LEFT)
2713 ) { /* don't copy $` part of string */
2716 /* calculate the left-most part of the string covered
2717 * by a capture. Due to look-behind, this may be to
2718 * the left of $&, so we have to scan all captures */
2719 while (min && n <= prog->lastparen) {
2720 if ( prog->offs[n].start != -1
2721 && prog->offs[n].start < min)
2723 min = prog->offs[n].start;
2727 if ((PL_sawampersand & SAWAMPERSAND_RIGHT)
2728 && min > prog->offs[0].end
2730 min = prog->offs[0].end;
2734 assert(min >= 0 && min <= max && min <= strend - strbeg);
2737 if (RX_MATCH_COPIED(rx)) {
2738 if (sublen > prog->sublen)
2740 (char*)saferealloc(prog->subbeg, sublen+1);
2743 prog->subbeg = (char*)safemalloc(sublen+1);
2744 Copy(strbeg + min, prog->subbeg, sublen, char);
2745 prog->subbeg[sublen] = '\0';
2746 prog->suboffset = min;
2747 prog->sublen = sublen;
2748 RX_MATCH_COPIED_on(rx);
2750 prog->subcoffset = prog->suboffset;
2751 if (prog->suboffset && utf8_target) {
2752 /* Convert byte offset to chars.
2753 * XXX ideally should only compute this if @-/@+
2754 * has been seen, a la PL_sawampersand ??? */
2756 /* If there's a direct correspondence between the
2757 * string which we're matching and the original SV,
2758 * then we can use the utf8 len cache associated with
2759 * the SV. In particular, it means that under //g,
2760 * sv_pos_b2u() will use the previously cached
2761 * position to speed up working out the new length of
2762 * subcoffset, rather than counting from the start of
2763 * the string each time. This stops
2764 * $x = "\x{100}" x 1E6; 1 while $x =~ /(.)/g;
2765 * from going quadratic */
2766 if (SvPOKp(sv) && SvPVX(sv) == strbeg)
2767 prog->subcoffset = sv_pos_b2u_flags(sv, prog->subcoffset,
2768 SV_GMAGIC|SV_CONST_RETURN);
2770 prog->subcoffset = utf8_length((U8*)strbeg,
2771 (U8*)(strbeg+prog->suboffset));
2775 RX_MATCH_COPY_FREE(rx);
2776 prog->subbeg = strbeg;
2777 prog->suboffset = 0;
2778 prog->subcoffset = 0;
2779 prog->sublen = strend - strbeg;
2787 - regexec_flags - match a regexp against a string
2790 Perl_regexec_flags(pTHX_ REGEXP * const rx, char *stringarg, char *strend,
2791 char *strbeg, SSize_t minend, SV *sv, void *data, U32 flags)
2792 /* stringarg: the point in the string at which to begin matching */
2793 /* strend: pointer to null at end of string */
2794 /* strbeg: real beginning of string */
2795 /* minend: end of match must be >= minend bytes after stringarg. */
2796 /* sv: SV being matched: only used for utf8 flag, pos() etc; string
2797 * itself is accessed via the pointers above */
2798 /* data: May be used for some additional optimizations.
2799 Currently unused. */
2800 /* flags: For optimizations. See REXEC_* in regexp.h */
2803 struct regexp *const prog = ReANY(rx);
2807 SSize_t minlen; /* must match at least this many chars */
2808 SSize_t dontbother = 0; /* how many characters not to try at end */
2809 const bool utf8_target = cBOOL(DO_UTF8(sv));
2811 RXi_GET_DECL(prog,progi);
2812 regmatch_info reginfo_buf; /* create some info to pass to regtry etc */
2813 regmatch_info *const reginfo = ®info_buf;
2814 regexp_paren_pair *swap = NULL;
2816 GET_RE_DEBUG_FLAGS_DECL;
2818 PERL_ARGS_ASSERT_REGEXEC_FLAGS;
2819 PERL_UNUSED_ARG(data);
2821 /* Be paranoid... */
2823 Perl_croak(aTHX_ "NULL regexp parameter");
2827 debug_start_match(rx, utf8_target, stringarg, strend,
2831 startpos = stringarg;
2833 if (prog->intflags & PREGf_GPOS_SEEN) {
2836 /* set reginfo->ganch, the position where \G can match */
2839 (flags & REXEC_IGNOREPOS)
2840 ? stringarg /* use start pos rather than pos() */
2841 : ((mg = mg_find_mglob(sv)) && mg->mg_len >= 0)
2842 /* Defined pos(): */
2843 ? strbeg + MgBYTEPOS(mg, sv, strbeg, strend-strbeg)
2844 : strbeg; /* pos() not defined; use start of string */
2846 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
2847 "GPOS ganch set to strbeg[%"IVdf"]\n", (IV)(reginfo->ganch - strbeg)));
2849 /* in the presence of \G, we may need to start looking earlier in
2850 * the string than the suggested start point of stringarg:
2851 * if prog->gofs is set, then that's a known, fixed minimum
2854 * /ab|c\G/: gofs = 1
2855 * or if the minimum offset isn't known, then we have to go back
2856 * to the start of the string, e.g. /w+\G/
2859 if (prog->intflags & PREGf_ANCH_GPOS) {
2860 startpos = reginfo->ganch - prog->gofs;
2862 ((flags & REXEC_FAIL_ON_UNDERFLOW) ? stringarg : strbeg))
2864 DEBUG_r(PerlIO_printf(Perl_debug_log,
2865 "fail: ganch-gofs before earliest possible start\n"));
2869 else if (prog->gofs) {
2870 if (startpos - prog->gofs < strbeg)
2873 startpos -= prog->gofs;
2875 else if (prog->intflags & PREGf_GPOS_FLOAT)
2879 minlen = prog->minlen;
2880 if ((startpos + minlen) > strend || startpos < strbeg) {
2881 DEBUG_r(PerlIO_printf(Perl_debug_log,
2882 "Regex match can't succeed, so not even tried\n"));
2886 /* at the end of this function, we'll do a LEAVE_SCOPE(oldsave),
2887 * which will call destuctors to reset PL_regmatch_state, free higher
2888 * PL_regmatch_slabs, and clean up regmatch_info_aux and
2889 * regmatch_info_aux_eval */
2891 oldsave = PL_savestack_ix;
2895 if ((prog->extflags & RXf_USE_INTUIT)
2896 && !(flags & REXEC_CHECKED))
2898 s = re_intuit_start(rx, sv, strbeg, startpos, strend,
2903 if (prog->extflags & RXf_CHECK_ALL) {
2904 /* we can match based purely on the result of INTUIT.
2905 * Set up captures etc just for $& and $-[0]
2906 * (an intuit-only match wont have $1,$2,..) */
2907 assert(!prog->nparens);
2909 /* s/// doesn't like it if $& is earlier than where we asked it to
2910 * start searching (which can happen on something like /.\G/) */
2911 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
2914 /* this should only be possible under \G */
2915 assert(prog->intflags & PREGf_GPOS_SEEN);
2916 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
2917 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
2921 /* match via INTUIT shouldn't have any captures.
2922 * Let @-, @+, $^N know */
2923 prog->lastparen = prog->lastcloseparen = 0;
2924 RX_MATCH_UTF8_set(rx, utf8_target);
2925 prog->offs[0].start = s - strbeg;
2926 prog->offs[0].end = utf8_target
2927 ? (char*)utf8_hop((U8*)s, prog->minlenret) - strbeg
2928 : s - strbeg + prog->minlenret;
2929 if ( !(flags & REXEC_NOT_FIRST) )
2930 S_reg_set_capture_string(aTHX_ rx,
2932 sv, flags, utf8_target);
2938 multiline = prog->extflags & RXf_PMf_MULTILINE;
2940 if (strend - s < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
2941 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
2942 "String too short [regexec_flags]...\n"));
2946 /* Check validity of program. */
2947 if (UCHARAT(progi->program) != REG_MAGIC) {
2948 Perl_croak(aTHX_ "corrupted regexp program");
2951 RX_MATCH_TAINTED_off(rx);
2952 RX_MATCH_UTF8_set(rx, utf8_target);
2954 reginfo->prog = rx; /* Yes, sorry that this is confusing. */
2955 reginfo->intuit = 0;
2956 reginfo->is_utf8_target = cBOOL(utf8_target);
2957 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
2958 reginfo->warned = FALSE;
2959 reginfo->strbeg = strbeg;
2961 reginfo->poscache_maxiter = 0; /* not yet started a countdown */
2962 reginfo->strend = strend;
2963 /* see how far we have to get to not match where we matched before */
2964 reginfo->till = stringarg + minend;
2966 if (prog->extflags & RXf_EVAL_SEEN && SvPADTMP(sv)) {
2967 /* SAVEFREESV, not sv_mortalcopy, as this SV must last until after
2968 S_cleanup_regmatch_info_aux has executed (registered by
2969 SAVEDESTRUCTOR_X below). S_cleanup_regmatch_info_aux modifies
2970 magic belonging to this SV.
2971 Not newSVsv, either, as it does not COW.
2973 reginfo->sv = newSV(0);
2974 SvSetSV_nosteal(reginfo->sv, sv);
2975 SAVEFREESV(reginfo->sv);
2978 /* reserve next 2 or 3 slots in PL_regmatch_state:
2979 * slot N+0: may currently be in use: skip it
2980 * slot N+1: use for regmatch_info_aux struct
2981 * slot N+2: use for regmatch_info_aux_eval struct if we have (?{})'s
2982 * slot N+3: ready for use by regmatch()
2986 regmatch_state *old_regmatch_state;
2987 regmatch_slab *old_regmatch_slab;
2988 int i, max = (prog->extflags & RXf_EVAL_SEEN) ? 2 : 1;
2990 /* on first ever match, allocate first slab */
2991 if (!PL_regmatch_slab) {
2992 Newx(PL_regmatch_slab, 1, regmatch_slab);
2993 PL_regmatch_slab->prev = NULL;
2994 PL_regmatch_slab->next = NULL;
2995 PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
2998 old_regmatch_state = PL_regmatch_state;
2999 old_regmatch_slab = PL_regmatch_slab;
3001 for (i=0; i <= max; i++) {
3003 reginfo->info_aux = &(PL_regmatch_state->u.info_aux);
3005 reginfo->info_aux_eval =
3006 reginfo->info_aux->info_aux_eval =
3007 &(PL_regmatch_state->u.info_aux_eval);
3009 if (++PL_regmatch_state > SLAB_LAST(PL_regmatch_slab))
3010 PL_regmatch_state = S_push_slab(aTHX);
3013 /* note initial PL_regmatch_state position; at end of match we'll
3014 * pop back to there and free any higher slabs */
3016 reginfo->info_aux->old_regmatch_state = old_regmatch_state;
3017 reginfo->info_aux->old_regmatch_slab = old_regmatch_slab;
3018 reginfo->info_aux->poscache = NULL;
3020 SAVEDESTRUCTOR_X(S_cleanup_regmatch_info_aux, reginfo->info_aux);
3022 if ((prog->extflags & RXf_EVAL_SEEN))
3023 S_setup_eval_state(aTHX_ reginfo);
3025 reginfo->info_aux_eval = reginfo->info_aux->info_aux_eval = NULL;
3028 /* If there is a "must appear" string, look for it. */
3030 if (PL_curpm && (PM_GETRE(PL_curpm) == rx)) {
3031 /* We have to be careful. If the previous successful match
3032 was from this regex we don't want a subsequent partially
3033 successful match to clobber the old results.
3034 So when we detect this possibility we add a swap buffer
3035 to the re, and switch the buffer each match. If we fail,
3036 we switch it back; otherwise we leave it swapped.
3039 /* do we need a save destructor here for eval dies? */
3040 Newxz(prog->offs, (prog->nparens + 1), regexp_paren_pair);
3041 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
3042 "rex=0x%"UVxf" saving offs: orig=0x%"UVxf" new=0x%"UVxf"\n",
3049 /* Simplest case: anchored match need be tried only once, or with
3050 * MBOL, only at the beginning of each line.
3052 * Note that /.*.../ sets PREGf_IMPLICIT|MBOL, while /.*.../s sets
3053 * PREGf_IMPLICIT|SBOL. The idea is that with /.*.../s, if it doesn't
3054 * match at the start of the string then it won't match anywhere else
3055 * either; while with /.*.../, if it doesn't match at the beginning,
3056 * the earliest it could match is at the start of the next line */
3058 if (prog->intflags & (PREGf_ANCH & ~PREGf_ANCH_GPOS)) {
3061 if (regtry(reginfo, &s))
3064 if (!(prog->intflags & PREGf_ANCH_MBOL))
3067 /* didn't match at start, try at other newline positions */
3070 dontbother = minlen - 1;
3071 end = HOP3c(strend, -dontbother, strbeg) - 1;
3073 /* skip to next newline */
3075 while (s <= end) { /* note it could be possible to match at the end of the string */
3076 /* NB: newlines are the same in unicode as they are in latin */
3079 if (prog->check_substr || prog->check_utf8) {
3080 /* note that with PREGf_IMPLICIT, intuit can only fail
3081 * or return the start position, so it's of limited utility.
3082 * Nevertheless, I made the decision that the potential for
3083 * quick fail was still worth it - DAPM */
3084 s = re_intuit_start(rx, sv, strbeg, s, strend, flags, NULL);
3088 if (regtry(reginfo, &s))
3092 } /* end anchored search */
3094 if (prog->intflags & PREGf_ANCH_GPOS)
3096 /* PREGf_ANCH_GPOS should never be true if PREGf_GPOS_SEEN is not true */
3097 assert(prog->intflags & PREGf_GPOS_SEEN);
3098 /* For anchored \G, the only position it can match from is
3099 * (ganch-gofs); we already set startpos to this above; if intuit
3100 * moved us on from there, we can't possibly succeed */
3101 assert(startpos == reginfo->ganch - prog->gofs);
3102 if (s == startpos && regtry(reginfo, &s))
3107 /* Messy cases: unanchored match. */
3108 if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
3109 /* we have /x+whatever/ */
3110 /* it must be a one character string (XXXX Except is_utf8_pat?) */
3116 if (! prog->anchored_utf8) {
3117 to_utf8_substr(prog);
3119 ch = SvPVX_const(prog->anchored_utf8)[0];
3122 DEBUG_EXECUTE_r( did_match = 1 );
3123 if (regtry(reginfo, &s)) goto got_it;
3125 while (s < strend && *s == ch)
3132 if (! prog->anchored_substr) {
3133 if (! to_byte_substr(prog)) {
3134 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3137 ch = SvPVX_const(prog->anchored_substr)[0];
3140 DEBUG_EXECUTE_r( did_match = 1 );
3141 if (regtry(reginfo, &s)) goto got_it;
3143 while (s < strend && *s == ch)
3148 DEBUG_EXECUTE_r(if (!did_match)
3149 PerlIO_printf(Perl_debug_log,
3150 "Did not find anchored character...\n")
3153 else if (prog->anchored_substr != NULL
3154 || prog->anchored_utf8 != NULL
3155 || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
3156 && prog->float_max_offset < strend - s)) {
3161 char *last1; /* Last position checked before */
3165 if (prog->anchored_substr || prog->anchored_utf8) {
3167 if (! prog->anchored_utf8) {
3168 to_utf8_substr(prog);
3170 must = prog->anchored_utf8;
3173 if (! prog->anchored_substr) {
3174 if (! to_byte_substr(prog)) {
3175 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3178 must = prog->anchored_substr;
3180 back_max = back_min = prog->anchored_offset;
3183 if (! prog->float_utf8) {
3184 to_utf8_substr(prog);
3186 must = prog->float_utf8;
3189 if (! prog->float_substr) {
3190 if (! to_byte_substr(prog)) {
3191 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3194 must = prog->float_substr;
3196 back_max = prog->float_max_offset;
3197 back_min = prog->float_min_offset;
3203 last = HOP3c(strend, /* Cannot start after this */
3204 -(SSize_t)(CHR_SVLEN(must)
3205 - (SvTAIL(must) != 0) + back_min), strbeg);
3207 if (s > reginfo->strbeg)
3208 last1 = HOPc(s, -1);
3210 last1 = s - 1; /* bogus */
3212 /* XXXX check_substr already used to find "s", can optimize if
3213 check_substr==must. */
3215 strend = HOPc(strend, -dontbother);
3216 while ( (s <= last) &&
3217 (s = fbm_instr((unsigned char*)HOP4c(s, back_min, strbeg, strend),
3218 (unsigned char*)strend, must,
3219 multiline ? FBMrf_MULTILINE : 0)) ) {
3220 DEBUG_EXECUTE_r( did_match = 1 );
3221 if (HOPc(s, -back_max) > last1) {
3222 last1 = HOPc(s, -back_min);
3223 s = HOPc(s, -back_max);
3226 char * const t = (last1 >= reginfo->strbeg)
3227 ? HOPc(last1, 1) : last1 + 1;
3229 last1 = HOPc(s, -back_min);
3233 while (s <= last1) {
3234 if (regtry(reginfo, &s))
3237 s++; /* to break out of outer loop */
3244 while (s <= last1) {
3245 if (regtry(reginfo, &s))
3251 DEBUG_EXECUTE_r(if (!did_match) {
3252 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
3253 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
3254 PerlIO_printf(Perl_debug_log, "Did not find %s substr %s%s...\n",
3255 ((must == prog->anchored_substr || must == prog->anchored_utf8)
3256 ? "anchored" : "floating"),
3257 quoted, RE_SV_TAIL(must));
3261 else if ( (c = progi->regstclass) ) {
3263 const OPCODE op = OP(progi->regstclass);
3264 /* don't bother with what can't match */
3265 if (PL_regkind[op] != EXACT && op != CANY && PL_regkind[op] != TRIE)
3266 strend = HOPc(strend, -(minlen - 1));
3269 SV * const prop = sv_newmortal();
3270 regprop(prog, prop, c, reginfo, NULL);
3272 RE_PV_QUOTED_DECL(quoted,utf8_target,PERL_DEBUG_PAD_ZERO(1),
3274 PerlIO_printf(Perl_debug_log,
3275 "Matching stclass %.*s against %s (%d bytes)\n",
3276 (int)SvCUR(prop), SvPVX_const(prop),
3277 quoted, (int)(strend - s));
3280 if (find_byclass(prog, c, s, strend, reginfo))
3282 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Contradicts stclass... [regexec_flags]\n"));
3286 if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
3294 if (! prog->float_utf8) {
3295 to_utf8_substr(prog);
3297 float_real = prog->float_utf8;
3300 if (! prog->float_substr) {
3301 if (! to_byte_substr(prog)) {
3302 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3305 float_real = prog->float_substr;
3308 little = SvPV_const(float_real, len);
3309 if (SvTAIL(float_real)) {
3310 /* This means that float_real contains an artificial \n on
3311 * the end due to the presence of something like this:
3312 * /foo$/ where we can match both "foo" and "foo\n" at the
3313 * end of the string. So we have to compare the end of the
3314 * string first against the float_real without the \n and
3315 * then against the full float_real with the string. We
3316 * have to watch out for cases where the string might be
3317 * smaller than the float_real or the float_real without
3319 char *checkpos= strend - len;
3321 PerlIO_printf(Perl_debug_log,
3322 "%sChecking for float_real.%s\n",
3323 PL_colors[4], PL_colors[5]));
3324 if (checkpos + 1 < strbeg) {
3325 /* can't match, even if we remove the trailing \n
3326 * string is too short to match */
3328 PerlIO_printf(Perl_debug_log,
3329 "%sString shorter than required trailing substring, cannot match.%s\n",
3330 PL_colors[4], PL_colors[5]));
3332 } else if (memEQ(checkpos + 1, little, len - 1)) {
3333 /* can match, the end of the string matches without the
3335 last = checkpos + 1;
3336 } else if (checkpos < strbeg) {
3337 /* cant match, string is too short when the "\n" is
3340 PerlIO_printf(Perl_debug_log,
3341 "%sString does not contain required trailing substring, cannot match.%s\n",
3342 PL_colors[4], PL_colors[5]));
3344 } else if (!multiline) {
3345 /* non multiline match, so compare with the "\n" at the
3346 * end of the string */
3347 if (memEQ(checkpos, little, len)) {
3351 PerlIO_printf(Perl_debug_log,
3352 "%sString does not contain required trailing substring, cannot match.%s\n",
3353 PL_colors[4], PL_colors[5]));
3357 /* multiline match, so we have to search for a place
3358 * where the full string is located */
3364 last = rninstr(s, strend, little, little + len);
3366 last = strend; /* matching "$" */
3369 /* at one point this block contained a comment which was
3370 * probably incorrect, which said that this was a "should not
3371 * happen" case. Even if it was true when it was written I am
3372 * pretty sure it is not anymore, so I have removed the comment
3373 * and replaced it with this one. Yves */
3375 PerlIO_printf(Perl_debug_log,
3376 "%sString does not contain required substring, cannot match.%s\n",
3377 PL_colors[4], PL_colors[5]
3381 dontbother = strend - last + prog->float_min_offset;
3383 if (minlen && (dontbother < minlen))
3384 dontbother = minlen - 1;
3385 strend -= dontbother; /* this one's always in bytes! */
3386 /* We don't know much -- general case. */
3389 if (regtry(reginfo, &s))
3398 if (regtry(reginfo, &s))
3400 } while (s++ < strend);
3408 /* s/// doesn't like it if $& is earlier than where we asked it to
3409 * start searching (which can happen on something like /.\G/) */
3410 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
3411 && (prog->offs[0].start < stringarg - strbeg))
3413 /* this should only be possible under \G */
3414 assert(prog->intflags & PREGf_GPOS_SEEN);
3415 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
3416 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3422 PerlIO_printf(Perl_debug_log,
3423 "rex=0x%"UVxf" freeing offs: 0x%"UVxf"\n",
3430 /* clean up; this will trigger destructors that will free all slabs
3431 * above the current one, and cleanup the regmatch_info_aux
3432 * and regmatch_info_aux_eval sructs */
3434 LEAVE_SCOPE(oldsave);
3436 if (RXp_PAREN_NAMES(prog))
3437 (void)hv_iterinit(RXp_PAREN_NAMES(prog));
3439 /* make sure $`, $&, $', and $digit will work later */
3440 if ( !(flags & REXEC_NOT_FIRST) )
3441 S_reg_set_capture_string(aTHX_ rx,
3442 strbeg, reginfo->strend,
3443 sv, flags, utf8_target);
3448 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch failed%s\n",
3449 PL_colors[4], PL_colors[5]));
3451 /* clean up; this will trigger destructors that will free all slabs
3452 * above the current one, and cleanup the regmatch_info_aux
3453 * and regmatch_info_aux_eval sructs */
3455 LEAVE_SCOPE(oldsave);
3458 /* we failed :-( roll it back */
3459 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
3460 "rex=0x%"UVxf" rolling back offs: freeing=0x%"UVxf" restoring=0x%"UVxf"\n",
3465 Safefree(prog->offs);
3472 /* Set which rex is pointed to by PL_reg_curpm, handling ref counting.
3473 * Do inc before dec, in case old and new rex are the same */
3474 #define SET_reg_curpm(Re2) \
3475 if (reginfo->info_aux_eval) { \
3476 (void)ReREFCNT_inc(Re2); \
3477 ReREFCNT_dec(PM_GETRE(PL_reg_curpm)); \
3478 PM_SETRE((PL_reg_curpm), (Re2)); \
3483 - regtry - try match at specific point
3485 STATIC I32 /* 0 failure, 1 success */
3486 S_regtry(pTHX_ regmatch_info *reginfo, char **startposp)
3489 REGEXP *const rx = reginfo->prog;
3490 regexp *const prog = ReANY(rx);
3492 RXi_GET_DECL(prog,progi);
3493 GET_RE_DEBUG_FLAGS_DECL;
3495 PERL_ARGS_ASSERT_REGTRY;
3497 reginfo->cutpoint=NULL;
3499 prog->offs[0].start = *startposp - reginfo->strbeg;
3500 prog->lastparen = 0;
3501 prog->lastcloseparen = 0;
3503 /* XXXX What this code is doing here?!!! There should be no need
3504 to do this again and again, prog->lastparen should take care of
3507 /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
3508 * Actually, the code in regcppop() (which Ilya may be meaning by
3509 * prog->lastparen), is not needed at all by the test suite
3510 * (op/regexp, op/pat, op/split), but that code is needed otherwise
3511 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
3512 * Meanwhile, this code *is* needed for the
3513 * above-mentioned test suite tests to succeed. The common theme
3514 * on those tests seems to be returning null fields from matches.
3515 * --jhi updated by dapm */
3517 if (prog->nparens) {
3518 regexp_paren_pair *pp = prog->offs;
3520 for (i = prog->nparens; i > (I32)prog->lastparen; i--) {
3528 result = regmatch(reginfo, *startposp, progi->program + 1);
3530 prog->offs[0].end = result;
3533 if (reginfo->cutpoint)
3534 *startposp= reginfo->cutpoint;
3535 REGCP_UNWIND(lastcp);
3540 #define sayYES goto yes
3541 #define sayNO goto no
3542 #define sayNO_SILENT goto no_silent
3544 /* we dont use STMT_START/END here because it leads to
3545 "unreachable code" warnings, which are bogus, but distracting. */
3546 #define CACHEsayNO \
3547 if (ST.cache_mask) \
3548 reginfo->info_aux->poscache[ST.cache_offset] |= ST.cache_mask; \
3551 /* this is used to determine how far from the left messages like
3552 'failed...' are printed. It should be set such that messages
3553 are inline with the regop output that created them.
3555 #define REPORT_CODE_OFF 32
3558 #define CHRTEST_UNINIT -1001 /* c1/c2 haven't been calculated yet */
3559 #define CHRTEST_VOID -1000 /* the c1/c2 "next char" test should be skipped */
3560 #define CHRTEST_NOT_A_CP_1 -999
3561 #define CHRTEST_NOT_A_CP_2 -998
3563 /* grab a new slab and return the first slot in it */
3565 STATIC regmatch_state *
3568 #if PERL_VERSION < 9 && !defined(PERL_CORE)
3571 regmatch_slab *s = PL_regmatch_slab->next;
3573 Newx(s, 1, regmatch_slab);
3574 s->prev = PL_regmatch_slab;
3576 PL_regmatch_slab->next = s;
3578 PL_regmatch_slab = s;
3579 return SLAB_FIRST(s);
3583 /* push a new state then goto it */
3585 #define PUSH_STATE_GOTO(state, node, input) \
3586 pushinput = input; \
3588 st->resume_state = state; \
3591 /* push a new state with success backtracking, then goto it */
3593 #define PUSH_YES_STATE_GOTO(state, node, input) \
3594 pushinput = input; \
3596 st->resume_state = state; \
3597 goto push_yes_state;
3604 regmatch() - main matching routine
3606 This is basically one big switch statement in a loop. We execute an op,
3607 set 'next' to point the next op, and continue. If we come to a point which
3608 we may need to backtrack to on failure such as (A|B|C), we push a
3609 backtrack state onto the backtrack stack. On failure, we pop the top
3610 state, and re-enter the loop at the state indicated. If there are no more
3611 states to pop, we return failure.
3613 Sometimes we also need to backtrack on success; for example /A+/, where
3614 after successfully matching one A, we need to go back and try to
3615 match another one; similarly for lookahead assertions: if the assertion
3616 completes successfully, we backtrack to the state just before the assertion
3617 and then carry on. In these cases, the pushed state is marked as
3618 'backtrack on success too'. This marking is in fact done by a chain of
3619 pointers, each pointing to the previous 'yes' state. On success, we pop to
3620 the nearest yes state, discarding any intermediate failure-only states.
3621 Sometimes a yes state is pushed just to force some cleanup code to be
3622 called at the end of a successful match or submatch; e.g. (??{$re}) uses
3623 it to free the inner regex.
3625 Note that failure backtracking rewinds the cursor position, while
3626 success backtracking leaves it alone.
3628 A pattern is complete when the END op is executed, while a subpattern
3629 such as (?=foo) is complete when the SUCCESS op is executed. Both of these
3630 ops trigger the "pop to last yes state if any, otherwise return true"
3633 A common convention in this function is to use A and B to refer to the two
3634 subpatterns (or to the first nodes thereof) in patterns like /A*B/: so A is
3635 the subpattern to be matched possibly multiple times, while B is the entire
3636 rest of the pattern. Variable and state names reflect this convention.
3638 The states in the main switch are the union of ops and failure/success of
3639 substates associated with with that op. For example, IFMATCH is the op
3640 that does lookahead assertions /(?=A)B/ and so the IFMATCH state means
3641 'execute IFMATCH'; while IFMATCH_A is a state saying that we have just
3642 successfully matched A and IFMATCH_A_fail is a state saying that we have
3643 just failed to match A. Resume states always come in pairs. The backtrack
3644 state we push is marked as 'IFMATCH_A', but when that is popped, we resume
3645 at IFMATCH_A or IFMATCH_A_fail, depending on whether we are backtracking
3646 on success or failure.
3648 The struct that holds a backtracking state is actually a big union, with
3649 one variant for each major type of op. The variable st points to the
3650 top-most backtrack struct. To make the code clearer, within each
3651 block of code we #define ST to alias the relevant union.
3653 Here's a concrete example of a (vastly oversimplified) IFMATCH
3659 #define ST st->u.ifmatch
3661 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3662 ST.foo = ...; // some state we wish to save
3664 // push a yes backtrack state with a resume value of
3665 // IFMATCH_A/IFMATCH_A_fail, then continue execution at the
3667 PUSH_YES_STATE_GOTO(IFMATCH_A, A, newinput);
3670 case IFMATCH_A: // we have successfully executed A; now continue with B
3672 bar = ST.foo; // do something with the preserved value
3675 case IFMATCH_A_fail: // A failed, so the assertion failed
3676 ...; // do some housekeeping, then ...
3677 sayNO; // propagate the failure
3684 For any old-timers reading this who are familiar with the old recursive
3685 approach, the code above is equivalent to:
3687 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3696 ...; // do some housekeeping, then ...
3697 sayNO; // propagate the failure
3700 The topmost backtrack state, pointed to by st, is usually free. If you
3701 want to claim it, populate any ST.foo fields in it with values you wish to
3702 save, then do one of
3704 PUSH_STATE_GOTO(resume_state, node, newinput);
3705 PUSH_YES_STATE_GOTO(resume_state, node, newinput);
3707 which sets that backtrack state's resume value to 'resume_state', pushes a
3708 new free entry to the top of the backtrack stack, then goes to 'node'.
3709 On backtracking, the free slot is popped, and the saved state becomes the
3710 new free state. An ST.foo field in this new top state can be temporarily
3711 accessed to retrieve values, but once the main loop is re-entered, it
3712 becomes available for reuse.
3714 Note that the depth of the backtrack stack constantly increases during the
3715 left-to-right execution of the pattern, rather than going up and down with
3716 the pattern nesting. For example the stack is at its maximum at Z at the
3717 end of the pattern, rather than at X in the following:
3719 /(((X)+)+)+....(Y)+....Z/
3721 The only exceptions to this are lookahead/behind assertions and the cut,
3722 (?>A), which pop all the backtrack states associated with A before
3725 Backtrack state structs are allocated in slabs of about 4K in size.
3726 PL_regmatch_state and st always point to the currently active state,
3727 and PL_regmatch_slab points to the slab currently containing
3728 PL_regmatch_state. The first time regmatch() is called, the first slab is
3729 allocated, and is never freed until interpreter destruction. When the slab
3730 is full, a new one is allocated and chained to the end. At exit from
3731 regmatch(), slabs allocated since entry are freed.
3736 #define DEBUG_STATE_pp(pp) \
3738 DUMP_EXEC_POS(locinput, scan, utf8_target); \
3739 PerlIO_printf(Perl_debug_log, \
3740 " %*s"pp" %s%s%s%s%s\n", \
3742 PL_reg_name[st->resume_state], \
3743 ((st==yes_state||st==mark_state) ? "[" : ""), \
3744 ((st==yes_state) ? "Y" : ""), \
3745 ((st==mark_state) ? "M" : ""), \
3746 ((st==yes_state||st==mark_state) ? "]" : "") \
3751 #define REG_NODE_NUM(x) ((x) ? (int)((x)-prog) : -1)
3756 S_debug_start_match(pTHX_ const REGEXP *prog, const bool utf8_target,
3757 const char *start, const char *end, const char *blurb)
3759 const bool utf8_pat = RX_UTF8(prog) ? 1 : 0;
3761 PERL_ARGS_ASSERT_DEBUG_START_MATCH;
3766 RE_PV_QUOTED_DECL(s0, utf8_pat, PERL_DEBUG_PAD_ZERO(0),
3767 RX_PRECOMP_const(prog), RX_PRELEN(prog), 60);
3769 RE_PV_QUOTED_DECL(s1, utf8_target, PERL_DEBUG_PAD_ZERO(1),
3770 start, end - start, 60);
3772 PerlIO_printf(Perl_debug_log,
3773 "%s%s REx%s %s against %s\n",
3774 PL_colors[4], blurb, PL_colors[5], s0, s1);
3776 if (utf8_target||utf8_pat)
3777 PerlIO_printf(Perl_debug_log, "UTF-8 %s%s%s...\n",
3778 utf8_pat ? "pattern" : "",
3779 utf8_pat && utf8_target ? " and " : "",
3780 utf8_target ? "string" : ""
3786 S_dump_exec_pos(pTHX_ const char *locinput,
3787 const regnode *scan,
3788 const char *loc_regeol,
3789 const char *loc_bostr,
3790 const char *loc_reg_starttry,
3791 const bool utf8_target)
3793 const int docolor = *PL_colors[0] || *PL_colors[2] || *PL_colors[4];
3794 const int taill = (docolor ? 10 : 7); /* 3 chars for "> <" */
3795 int l = (loc_regeol - locinput) > taill ? taill : (loc_regeol - locinput);
3796 /* The part of the string before starttry has one color
3797 (pref0_len chars), between starttry and current
3798 position another one (pref_len - pref0_len chars),
3799 after the current position the third one.
3800 We assume that pref0_len <= pref_len, otherwise we
3801 decrease pref0_len. */
3802 int pref_len = (locinput - loc_bostr) > (5 + taill) - l
3803 ? (5 + taill) - l : locinput - loc_bostr;
3806 PERL_ARGS_ASSERT_DUMP_EXEC_POS;
3808 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput - pref_len)))
3810 pref0_len = pref_len - (locinput - loc_reg_starttry);
3811 if (l + pref_len < (5 + taill) && l < loc_regeol - locinput)
3812 l = ( loc_regeol - locinput > (5 + taill) - pref_len
3813 ? (5 + taill) - pref_len : loc_regeol - locinput);
3814 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput + l)))
3818 if (pref0_len > pref_len)
3819 pref0_len = pref_len;
3821 const int is_uni = (utf8_target && OP(scan) != CANY) ? 1 : 0;
3823 RE_PV_COLOR_DECL(s0,len0,is_uni,PERL_DEBUG_PAD(0),
3824 (locinput - pref_len),pref0_len, 60, 4, 5);
3826 RE_PV_COLOR_DECL(s1,len1,is_uni,PERL_DEBUG_PAD(1),
3827 (locinput - pref_len + pref0_len),
3828 pref_len - pref0_len, 60, 2, 3);
3830 RE_PV_COLOR_DECL(s2,len2,is_uni,PERL_DEBUG_PAD(2),
3831 locinput, loc_regeol - locinput, 10, 0, 1);
3833 const STRLEN tlen=len0+len1+len2;
3834 PerlIO_printf(Perl_debug_log,
3835 "%4"IVdf" <%.*s%.*s%s%.*s>%*s|",
3836 (IV)(locinput - loc_bostr),
3839 (docolor ? "" : "> <"),
3841 (int)(tlen > 19 ? 0 : 19 - tlen),
3848 /* reg_check_named_buff_matched()
3849 * Checks to see if a named buffer has matched. The data array of
3850 * buffer numbers corresponding to the buffer is expected to reside
3851 * in the regexp->data->data array in the slot stored in the ARG() of
3852 * node involved. Note that this routine doesn't actually care about the
3853 * name, that information is not preserved from compilation to execution.
3854 * Returns the index of the leftmost defined buffer with the given name
3855 * or 0 if non of the buffers matched.
3858 S_reg_check_named_buff_matched(const regexp *rex, const regnode *scan)
3861 RXi_GET_DECL(rex,rexi);
3862 SV *sv_dat= MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
3863 I32 *nums=(I32*)SvPVX(sv_dat);