5 * One Ring to rule them all, One Ring to find them
7 * [p.v of _The Lord of the Rings_, opening poem]
8 * [p.50 of _The Lord of the Rings_, I/iii: "The Shadow of the Past"]
9 * [p.254 of _The Lord of the Rings_, II/ii: "The Council of Elrond"]
12 /* This file contains functions for executing a regular expression. See
13 * also regcomp.c which funnily enough, contains functions for compiling
14 * a regular expression.
16 * This file is also copied at build time to ext/re/re_exec.c, where
17 * it's built with -DPERL_EXT_RE_BUILD -DPERL_EXT_RE_DEBUG -DPERL_EXT.
18 * This causes the main functions to be compiled under new names and with
19 * debugging support added, which makes "use re 'debug'" work.
22 /* NOTE: this is derived from Henry Spencer's regexp code, and should not
23 * confused with the original package (see point 3 below). Thanks, Henry!
26 /* Additional note: this code is very heavily munged from Henry's version
27 * in places. In some spots I've traded clarity for efficiency, so don't
28 * blame Henry for some of the lack of readability.
31 /* The names of the functions have been changed from regcomp and
32 * regexec to pregcomp and pregexec in order to avoid conflicts
33 * with the POSIX routines of the same names.
36 #ifdef PERL_EXT_RE_BUILD
41 * pregcomp and pregexec -- regsub and regerror are not used in perl
43 * Copyright (c) 1986 by University of Toronto.
44 * Written by Henry Spencer. Not derived from licensed software.
46 * Permission is granted to anyone to use this software for any
47 * purpose on any computer system, and to redistribute it freely,
48 * subject to the following restrictions:
50 * 1. The author is not responsible for the consequences of use of
51 * this software, no matter how awful, even if they arise
54 * 2. The origin of this software must not be misrepresented, either
55 * by explicit claim or by omission.
57 * 3. Altered versions must be plainly marked as such, and must not
58 * be misrepresented as being the original software.
60 **** Alterations to Henry's code are...
62 **** Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
63 **** 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
64 **** by Larry Wall and others
66 **** You may distribute under the terms of either the GNU General Public
67 **** License or the Artistic License, as specified in the README file.
69 * Beware that some of this code is subtly aware of the way operator
70 * precedence is structured in regular expressions. Serious changes in
71 * regular-expression syntax might require a total rethink.
74 #define PERL_IN_REGEXEC_C
77 #ifdef PERL_IN_XSUB_RE
83 #include "invlist_inline.h"
84 #include "unicode_constants.h"
86 #define B_ON_NON_UTF8_LOCALE_IS_WRONG \
87 "Use of \\b{} or \\B{} for non-UTF-8 locale is wrong. Assuming a UTF-8 locale"
89 static const char utf8_locale_required[] =
90 "Use of (?[ ]) for non-UTF-8 locale is wrong. Assuming a UTF-8 locale";
93 /* At least one required character in the target string is expressible only in
95 static const char* const non_utf8_target_but_utf8_required
96 = "Can't match, because target string needs to be in UTF-8\n";
99 /* Returns a boolean as to whether the input unsigned number is a power of 2
100 * (2**0, 2**1, etc). In other words if it has just a single bit set.
101 * If not, subtracting 1 would leave the uppermost bit set, so the & would
103 #define isPOWER_OF_2(n) ((n & (n-1)) == 0)
105 #define NON_UTF8_TARGET_BUT_UTF8_REQUIRED(target) STMT_START { \
106 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%s", non_utf8_target_but_utf8_required));\
110 #define HAS_NONLATIN1_FOLD_CLOSURE(i) _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
113 #define STATIC static
116 /* Valid only if 'c', the character being looke-up, is an invariant under
117 * UTF-8: it avoids the reginclass call if there are no complications: i.e., if
118 * everything matchable is straight forward in the bitmap */
119 #define REGINCLASS(prog,p,c,u) (ANYOF_FLAGS(p) \
120 ? reginclass(prog,p,c,c+1,u) \
121 : ANYOF_BITMAP_TEST(p,*(c)))
127 #define CHR_SVLEN(sv) (utf8_target ? sv_len_utf8(sv) : SvCUR(sv))
129 #define HOPc(pos,off) \
130 (char *)(reginfo->is_utf8_target \
131 ? reghop3((U8*)pos, off, \
132 (U8*)(off >= 0 ? reginfo->strend : reginfo->strbeg)) \
135 /* like HOPMAYBE3 but backwards. lim must be +ve. Returns NULL on overshoot */
136 #define HOPBACK3(pos, off, lim) \
137 (reginfo->is_utf8_target \
138 ? reghopmaybe3((U8*)pos, (SSize_t)0-off, (U8*)(lim)) \
139 : (pos - off >= lim) \
143 #define HOPBACKc(pos, off) ((char*)HOPBACK3(pos, off, reginfo->strbeg))
145 #define HOP3(pos,off,lim) (reginfo->is_utf8_target ? reghop3((U8*)(pos), off, (U8*)(lim)) : (U8*)(pos + off))
146 #define HOP3c(pos,off,lim) ((char*)HOP3(pos,off,lim))
148 /* lim must be +ve. Returns NULL on overshoot */
149 #define HOPMAYBE3(pos,off,lim) \
150 (reginfo->is_utf8_target \
151 ? reghopmaybe3((U8*)pos, off, (U8*)(lim)) \
152 : ((U8*)pos + off <= lim) \
156 /* like HOP3, but limits the result to <= lim even for the non-utf8 case.
157 * off must be >=0; args should be vars rather than expressions */
158 #define HOP3lim(pos,off,lim) (reginfo->is_utf8_target \
159 ? reghop3((U8*)(pos), off, (U8*)(lim)) \
160 : (U8*)((pos + off) > lim ? lim : (pos + off)))
161 #define HOP3clim(pos,off,lim) ((char*)HOP3lim(pos,off,lim))
163 #define HOP4(pos,off,llim, rlim) (reginfo->is_utf8_target \
164 ? reghop4((U8*)(pos), off, (U8*)(llim), (U8*)(rlim)) \
166 #define HOP4c(pos,off,llim, rlim) ((char*)HOP4(pos,off,llim, rlim))
168 #define NEXTCHR_EOS -10 /* nextchr has fallen off the end */
169 #define NEXTCHR_IS_EOS (nextchr < 0)
171 #define SET_nextchr \
172 nextchr = ((locinput < reginfo->strend) ? UCHARAT(locinput) : NEXTCHR_EOS)
174 #define SET_locinput(p) \
179 #define LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist) STMT_START { \
181 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST; \
182 swash_ptr = _core_swash_init("utf8", property_name, &PL_sv_undef, \
183 1, 0, invlist, &flags); \
188 /* If in debug mode, we test that a known character properly matches */
190 # define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
193 utf8_char_in_property) \
194 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist); \
195 assert(swash_fetch(swash_ptr, (U8 *) utf8_char_in_property, TRUE));
197 # define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
200 utf8_char_in_property) \
201 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist)
204 #define LOAD_UTF8_CHARCLASS_ALNUM() LOAD_UTF8_CHARCLASS_DEBUG_TEST( \
205 PL_utf8_swash_ptrs[_CC_WORDCHAR], \
207 PL_XPosix_ptrs[_CC_WORDCHAR], \
208 LATIN_SMALL_LIGATURE_LONG_S_T_UTF8);
210 #define PLACEHOLDER /* Something for the preprocessor to grab onto */
211 /* TODO: Combine JUMPABLE and HAS_TEXT to cache OP(rn) */
213 /* for use after a quantifier and before an EXACT-like node -- japhy */
214 /* it would be nice to rework regcomp.sym to generate this stuff. sigh
216 * NOTE that *nothing* that affects backtracking should be in here, specifically
217 * VERBS must NOT be included. JUMPABLE is used to determine if we can ignore a
218 * node that is in between two EXACT like nodes when ascertaining what the required
219 * "follow" character is. This should probably be moved to regex compile time
220 * although it may be done at run time beause of the REF possibility - more
221 * investigation required. -- demerphq
223 #define JUMPABLE(rn) ( \
225 (OP(rn) == CLOSE && \
226 !EVAL_CLOSE_PAREN_IS(cur_eval,ARG(rn)) ) || \
228 OP(rn) == SUSPEND || OP(rn) == IFMATCH || \
229 OP(rn) == PLUS || OP(rn) == MINMOD || \
231 (PL_regkind[OP(rn)] == CURLY && ARG1(rn) > 0) \
233 #define IS_EXACT(rn) (PL_regkind[OP(rn)] == EXACT)
235 #define HAS_TEXT(rn) ( IS_EXACT(rn) || PL_regkind[OP(rn)] == REF )
238 /* Currently these are only used when PL_regkind[OP(rn)] == EXACT so
239 we don't need this definition. XXX These are now out-of-sync*/
240 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==REF || OP(rn)==NREF )
241 #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 )
242 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL || OP(rn)==REFFL || OP(rn)==NREFFL )
245 /* ... so we use this as its faster. */
246 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==EXACTL )
247 #define IS_TEXTFU(rn) ( OP(rn)==EXACTFU || OP(rn)==EXACTFLU8 || OP(rn)==EXACTFU_SS || OP(rn) == EXACTFA || OP(rn) == EXACTFA_NO_TRIE)
248 #define IS_TEXTF(rn) ( OP(rn)==EXACTF )
249 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL )
254 Search for mandatory following text node; for lookahead, the text must
255 follow but for lookbehind (rn->flags != 0) we skip to the next step.
257 #define FIND_NEXT_IMPT(rn) STMT_START { \
258 while (JUMPABLE(rn)) { \
259 const OPCODE type = OP(rn); \
260 if (type == SUSPEND || PL_regkind[type] == CURLY) \
261 rn = NEXTOPER(NEXTOPER(rn)); \
262 else if (type == PLUS) \
264 else if (type == IFMATCH) \
265 rn = (rn->flags == 0) ? NEXTOPER(NEXTOPER(rn)) : rn + ARG(rn); \
266 else rn += NEXT_OFF(rn); \
270 #define SLAB_FIRST(s) (&(s)->states[0])
271 #define SLAB_LAST(s) (&(s)->states[PERL_REGMATCH_SLAB_SLOTS-1])
273 static void S_setup_eval_state(pTHX_ regmatch_info *const reginfo);
274 static void S_cleanup_regmatch_info_aux(pTHX_ void *arg);
275 static regmatch_state * S_push_slab(pTHX);
277 #define REGCP_PAREN_ELEMS 3
278 #define REGCP_OTHER_ELEMS 3
279 #define REGCP_FRAME_ELEMS 1
280 /* REGCP_FRAME_ELEMS are not part of the REGCP_OTHER_ELEMS and
281 * are needed for the regexp context stack bookkeeping. */
284 S_regcppush(pTHX_ const regexp *rex, I32 parenfloor, U32 maxopenparen _pDEPTH)
286 const int retval = PL_savestack_ix;
287 const int paren_elems_to_push =
288 (maxopenparen - parenfloor) * REGCP_PAREN_ELEMS;
289 const UV total_elems = paren_elems_to_push + REGCP_OTHER_ELEMS;
290 const UV elems_shifted = total_elems << SAVE_TIGHT_SHIFT;
292 GET_RE_DEBUG_FLAGS_DECL;
294 PERL_ARGS_ASSERT_REGCPPUSH;
296 if (paren_elems_to_push < 0)
297 Perl_croak(aTHX_ "panic: paren_elems_to_push, %i < 0, maxopenparen: %i parenfloor: %i REGCP_PAREN_ELEMS: %u",
298 (int)paren_elems_to_push, (int)maxopenparen,
299 (int)parenfloor, (unsigned)REGCP_PAREN_ELEMS);
301 if ((elems_shifted >> SAVE_TIGHT_SHIFT) != total_elems)
302 Perl_croak(aTHX_ "panic: paren_elems_to_push offset %" UVuf
303 " out of range (%lu-%ld)",
305 (unsigned long)maxopenparen,
308 SSGROW(total_elems + REGCP_FRAME_ELEMS);
311 if ((int)maxopenparen > (int)parenfloor)
312 Perl_re_exec_indentf( aTHX_
313 "rex=0x%" UVxf " offs=0x%" UVxf ": saving capture indices:\n",
319 for (p = parenfloor+1; p <= (I32)maxopenparen; p++) {
320 /* REGCP_PARENS_ELEMS are pushed per pairs of parentheses. */
321 SSPUSHIV(rex->offs[p].end);
322 SSPUSHIV(rex->offs[p].start);
323 SSPUSHINT(rex->offs[p].start_tmp);
324 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_
325 " \\%" UVuf ": %" IVdf "(%" IVdf ")..%" IVdf "\n",
328 (IV)rex->offs[p].start,
329 (IV)rex->offs[p].start_tmp,
333 /* REGCP_OTHER_ELEMS are pushed in any case, parentheses or no. */
334 SSPUSHINT(maxopenparen);
335 SSPUSHINT(rex->lastparen);
336 SSPUSHINT(rex->lastcloseparen);
337 SSPUSHUV(SAVEt_REGCONTEXT | elems_shifted); /* Magic cookie. */
342 /* These are needed since we do not localize EVAL nodes: */
343 #define REGCP_SET(cp) \
345 Perl_re_exec_indentf( aTHX_ \
346 "Setting an EVAL scope, savestack=%" IVdf ",\n", \
347 depth, (IV)PL_savestack_ix \
352 #define REGCP_UNWIND(cp) \
354 if (cp != PL_savestack_ix) \
355 Perl_re_exec_indentf( aTHX_ \
356 "Clearing an EVAL scope, savestack=%" \
357 IVdf "..%" IVdf "\n", \
358 depth, (IV)(cp), (IV)PL_savestack_ix \
363 #define UNWIND_PAREN(lp, lcp) \
364 for (n = rex->lastparen; n > lp; n--) \
365 rex->offs[n].end = -1; \
366 rex->lastparen = n; \
367 rex->lastcloseparen = lcp;
371 S_regcppop(pTHX_ regexp *rex, U32 *maxopenparen_p _pDEPTH)
375 GET_RE_DEBUG_FLAGS_DECL;
377 PERL_ARGS_ASSERT_REGCPPOP;
379 /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
381 assert((i & SAVE_MASK) == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
382 i >>= SAVE_TIGHT_SHIFT; /* Parentheses elements to pop. */
383 rex->lastcloseparen = SSPOPINT;
384 rex->lastparen = SSPOPINT;
385 *maxopenparen_p = SSPOPINT;
387 i -= REGCP_OTHER_ELEMS;
388 /* Now restore the parentheses context. */
390 if (i || rex->lastparen + 1 <= rex->nparens)
391 Perl_re_exec_indentf( aTHX_
392 "rex=0x%" UVxf " offs=0x%" UVxf ": restoring capture indices to:\n",
398 paren = *maxopenparen_p;
399 for ( ; i > 0; i -= REGCP_PAREN_ELEMS) {
401 rex->offs[paren].start_tmp = SSPOPINT;
402 rex->offs[paren].start = SSPOPIV;
404 if (paren <= rex->lastparen)
405 rex->offs[paren].end = tmps;
406 DEBUG_BUFFERS_r( Perl_re_exec_indentf( aTHX_
407 " \\%" UVuf ": %" IVdf "(%" IVdf ")..%" IVdf "%s\n",
410 (IV)rex->offs[paren].start,
411 (IV)rex->offs[paren].start_tmp,
412 (IV)rex->offs[paren].end,
413 (paren > rex->lastparen ? "(skipped)" : ""));
418 /* It would seem that the similar code in regtry()
419 * already takes care of this, and in fact it is in
420 * a better location to since this code can #if 0-ed out
421 * but the code in regtry() is needed or otherwise tests
422 * requiring null fields (pat.t#187 and split.t#{13,14}
423 * (as of patchlevel 7877) will fail. Then again,
424 * this code seems to be necessary or otherwise
425 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
426 * --jhi updated by dapm */
427 for (i = rex->lastparen + 1; i <= rex->nparens; i++) {
428 if (i > *maxopenparen_p)
429 rex->offs[i].start = -1;
430 rex->offs[i].end = -1;
431 DEBUG_BUFFERS_r( Perl_re_exec_indentf( aTHX_
432 " \\%" UVuf ": %s ..-1 undeffing\n",
435 (i > *maxopenparen_p) ? "-1" : " "
441 /* restore the parens and associated vars at savestack position ix,
442 * but without popping the stack */
445 S_regcp_restore(pTHX_ regexp *rex, I32 ix, U32 *maxopenparen_p _pDEPTH)
447 I32 tmpix = PL_savestack_ix;
448 PERL_ARGS_ASSERT_REGCP_RESTORE;
450 PL_savestack_ix = ix;
451 regcppop(rex, maxopenparen_p);
452 PL_savestack_ix = tmpix;
455 #define regcpblow(cp) LEAVE_SCOPE(cp) /* Ignores regcppush()ed data. */
457 #ifndef PERL_IN_XSUB_RE
460 Perl_isFOO_lc(pTHX_ const U8 classnum, const U8 character)
462 /* Returns a boolean as to whether or not 'character' is a member of the
463 * Posix character class given by 'classnum' that should be equivalent to a
464 * value in the typedef '_char_class_number'.
466 * Ideally this could be replaced by a just an array of function pointers
467 * to the C library functions that implement the macros this calls.
468 * However, to compile, the precise function signatures are required, and
469 * these may vary from platform to to platform. To avoid having to figure
470 * out what those all are on each platform, I (khw) am using this method,
471 * which adds an extra layer of function call overhead (unless the C
472 * optimizer strips it away). But we don't particularly care about
473 * performance with locales anyway. */
475 switch ((_char_class_number) classnum) {
476 case _CC_ENUM_ALPHANUMERIC: return isALPHANUMERIC_LC(character);
477 case _CC_ENUM_ALPHA: return isALPHA_LC(character);
478 case _CC_ENUM_ASCII: return isASCII_LC(character);
479 case _CC_ENUM_BLANK: return isBLANK_LC(character);
480 case _CC_ENUM_CASED: return isLOWER_LC(character)
481 || isUPPER_LC(character);
482 case _CC_ENUM_CNTRL: return isCNTRL_LC(character);
483 case _CC_ENUM_DIGIT: return isDIGIT_LC(character);
484 case _CC_ENUM_GRAPH: return isGRAPH_LC(character);
485 case _CC_ENUM_LOWER: return isLOWER_LC(character);
486 case _CC_ENUM_PRINT: return isPRINT_LC(character);
487 case _CC_ENUM_PUNCT: return isPUNCT_LC(character);
488 case _CC_ENUM_SPACE: return isSPACE_LC(character);
489 case _CC_ENUM_UPPER: return isUPPER_LC(character);
490 case _CC_ENUM_WORDCHAR: return isWORDCHAR_LC(character);
491 case _CC_ENUM_XDIGIT: return isXDIGIT_LC(character);
492 default: /* VERTSPACE should never occur in locales */
493 Perl_croak(aTHX_ "panic: isFOO_lc() has an unexpected character class '%d'", classnum);
496 NOT_REACHED; /* NOTREACHED */
503 S_isFOO_utf8_lc(pTHX_ const U8 classnum, const U8* character)
505 /* Returns a boolean as to whether or not the (well-formed) UTF-8-encoded
506 * 'character' is a member of the Posix character class given by 'classnum'
507 * that should be equivalent to a value in the typedef
508 * '_char_class_number'.
510 * This just calls isFOO_lc on the code point for the character if it is in
511 * the range 0-255. Outside that range, all characters use Unicode
512 * rules, ignoring any locale. So use the Unicode function if this class
513 * requires a swash, and use the Unicode macro otherwise. */
515 PERL_ARGS_ASSERT_ISFOO_UTF8_LC;
517 if (UTF8_IS_INVARIANT(*character)) {
518 return isFOO_lc(classnum, *character);
520 else if (UTF8_IS_DOWNGRADEABLE_START(*character)) {
521 return isFOO_lc(classnum,
522 EIGHT_BIT_UTF8_TO_NATIVE(*character, *(character + 1)));
525 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(character, character + UTF8SKIP(character));
527 if (classnum < _FIRST_NON_SWASH_CC) {
529 /* Initialize the swash unless done already */
530 if (! PL_utf8_swash_ptrs[classnum]) {
531 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
532 PL_utf8_swash_ptrs[classnum] =
533 _core_swash_init("utf8",
536 PL_XPosix_ptrs[classnum], &flags);
539 return cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum], (U8 *)
541 TRUE /* is UTF */ ));
544 switch ((_char_class_number) classnum) {
545 case _CC_ENUM_SPACE: return is_XPERLSPACE_high(character);
546 case _CC_ENUM_BLANK: return is_HORIZWS_high(character);
547 case _CC_ENUM_XDIGIT: return is_XDIGIT_high(character);
548 case _CC_ENUM_VERTSPACE: return is_VERTWS_high(character);
552 return FALSE; /* Things like CNTRL are always below 256 */
556 S_find_next_ascii(char * s, const char * send, const bool utf8_target)
558 /* Returns the position of the first ASCII byte in the sequence between 's'
559 * and 'send-1' inclusive; returns 'send' if none found */
561 PERL_ARGS_ASSERT_FIND_NEXT_ASCII;
565 if ((STRLEN) (send - s) >= PERL_WORDSIZE
567 /* This term is wordsize if subword; 0 if not */
568 + PERL_WORDSIZE * PERL_IS_SUBWORD_ADDR(s)
571 - (PTR2nat(s) & PERL_WORD_BOUNDARY_MASK))
574 /* Process per-byte until reach word boundary. XXX This loop could be
575 * eliminated if we knew that this platform had fast unaligned reads */
576 while (PTR2nat(s) & PERL_WORD_BOUNDARY_MASK) {
580 s++; /* khw didn't bother creating a separate loop for
584 /* Here, we know we have at least one full word to process. Process
585 * per-word as long as we have at least a full word left */
587 if ((* (PERL_UINTMAX_T *) s) & ~ PERL_VARIANTS_WORD_MASK) {
591 } while (s + PERL_WORDSIZE <= send);
596 /* Process per-character */
618 S_find_next_non_ascii(char * s, const char * send, const bool utf8_target)
620 /* Returns the position of the first non-ASCII byte in the sequence between
621 * 's' and 'send-1' inclusive; returns 'send' if none found */
625 PERL_ARGS_ASSERT_FIND_NEXT_NON_ASCII;
629 if ( ! isASCII(*s)) {
637 if ( ! isASCII(*s)) {
648 const U8 * next_non_ascii = NULL;
650 PERL_ARGS_ASSERT_FIND_NEXT_NON_ASCII;
651 PERL_UNUSED_ARG(utf8_target);
653 /* On ASCII platforms invariants and ASCII are identical, so if the string
654 * is entirely invariants, there is no non-ASCII character */
655 return (is_utf8_invariant_string_loc((U8 *) s,
659 : (char *) next_non_ascii;
666 * pregexec and friends
669 #ifndef PERL_IN_XSUB_RE
671 - pregexec - match a regexp against a string
674 Perl_pregexec(pTHX_ REGEXP * const prog, char* stringarg, char *strend,
675 char *strbeg, SSize_t minend, SV *screamer, U32 nosave)
676 /* stringarg: the point in the string at which to begin matching */
677 /* strend: pointer to null at end of string */
678 /* strbeg: real beginning of string */
679 /* minend: end of match must be >= minend bytes after stringarg. */
680 /* screamer: SV being matched: only used for utf8 flag, pos() etc; string
681 * itself is accessed via the pointers above */
682 /* nosave: For optimizations. */
684 PERL_ARGS_ASSERT_PREGEXEC;
687 regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
688 nosave ? 0 : REXEC_COPY_STR);
694 /* re_intuit_start():
696 * Based on some optimiser hints, try to find the earliest position in the
697 * string where the regex could match.
699 * rx: the regex to match against
700 * sv: the SV being matched: only used for utf8 flag; the string
701 * itself is accessed via the pointers below. Note that on
702 * something like an overloaded SV, SvPOK(sv) may be false
703 * and the string pointers may point to something unrelated to
705 * strbeg: real beginning of string
706 * strpos: the point in the string at which to begin matching
707 * strend: pointer to the byte following the last char of the string
708 * flags currently unused; set to 0
709 * data: currently unused; set to NULL
711 * The basic idea of re_intuit_start() is to use some known information
712 * about the pattern, namely:
714 * a) the longest known anchored substring (i.e. one that's at a
715 * constant offset from the beginning of the pattern; but not
716 * necessarily at a fixed offset from the beginning of the
718 * b) the longest floating substring (i.e. one that's not at a constant
719 * offset from the beginning of the pattern);
720 * c) Whether the pattern is anchored to the string; either
721 * an absolute anchor: /^../, or anchored to \n: /^.../m,
722 * or anchored to pos(): /\G/;
723 * d) A start class: a real or synthetic character class which
724 * represents which characters are legal at the start of the pattern;
726 * to either quickly reject the match, or to find the earliest position
727 * within the string at which the pattern might match, thus avoiding
728 * running the full NFA engine at those earlier locations, only to
729 * eventually fail and retry further along.
731 * Returns NULL if the pattern can't match, or returns the address within
732 * the string which is the earliest place the match could occur.
734 * The longest of the anchored and floating substrings is called 'check'
735 * and is checked first. The other is called 'other' and is checked
736 * second. The 'other' substring may not be present. For example,
738 * /(abc|xyz)ABC\d{0,3}DEFG/
742 * check substr (float) = "DEFG", offset 6..9 chars
743 * other substr (anchored) = "ABC", offset 3..3 chars
746 * Be aware that during the course of this function, sometimes 'anchored'
747 * refers to a substring being anchored relative to the start of the
748 * pattern, and sometimes to the pattern itself being anchored relative to
749 * the string. For example:
751 * /\dabc/: "abc" is anchored to the pattern;
752 * /^\dabc/: "abc" is anchored to the pattern and the string;
753 * /\d+abc/: "abc" is anchored to neither the pattern nor the string;
754 * /^\d+abc/: "abc" is anchored to neither the pattern nor the string,
755 * but the pattern is anchored to the string.
759 Perl_re_intuit_start(pTHX_
762 const char * const strbeg,
766 re_scream_pos_data *data)
768 struct regexp *const prog = ReANY(rx);
769 SSize_t start_shift = prog->check_offset_min;
770 /* Should be nonnegative! */
771 SSize_t end_shift = 0;
772 /* current lowest pos in string where the regex can start matching */
773 char *rx_origin = strpos;
775 const bool utf8_target = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
776 U8 other_ix = 1 - prog->substrs->check_ix;
778 char *other_last = strpos;/* latest pos 'other' substr already checked to */
779 char *check_at = NULL; /* check substr found at this pos */
780 const I32 multiline = prog->extflags & RXf_PMf_MULTILINE;
781 RXi_GET_DECL(prog,progi);
782 regmatch_info reginfo_buf; /* create some info to pass to find_byclass */
783 regmatch_info *const reginfo = ®info_buf;
784 GET_RE_DEBUG_FLAGS_DECL;
786 PERL_ARGS_ASSERT_RE_INTUIT_START;
787 PERL_UNUSED_ARG(flags);
788 PERL_UNUSED_ARG(data);
790 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
791 "Intuit: trying to determine minimum start position...\n"));
793 /* for now, assume that all substr offsets are positive. If at some point
794 * in the future someone wants to do clever things with lookbehind and
795 * -ve offsets, they'll need to fix up any code in this function
796 * which uses these offsets. See the thread beginning
797 * <20140113145929.GF27210@iabyn.com>
799 assert(prog->substrs->data[0].min_offset >= 0);
800 assert(prog->substrs->data[0].max_offset >= 0);
801 assert(prog->substrs->data[1].min_offset >= 0);
802 assert(prog->substrs->data[1].max_offset >= 0);
803 assert(prog->substrs->data[2].min_offset >= 0);
804 assert(prog->substrs->data[2].max_offset >= 0);
806 /* for now, assume that if both present, that the floating substring
807 * doesn't start before the anchored substring.
808 * If you break this assumption (e.g. doing better optimisations
809 * with lookahead/behind), then you'll need to audit the code in this
810 * function carefully first
813 ! ( (prog->anchored_utf8 || prog->anchored_substr)
814 && (prog->float_utf8 || prog->float_substr))
815 || (prog->float_min_offset >= prog->anchored_offset));
817 /* byte rather than char calculation for efficiency. It fails
818 * to quickly reject some cases that can't match, but will reject
819 * them later after doing full char arithmetic */
820 if (prog->minlen > strend - strpos) {
821 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
822 " String too short...\n"));
826 RXp_MATCH_UTF8_set(prog, utf8_target);
827 reginfo->is_utf8_target = cBOOL(utf8_target);
828 reginfo->info_aux = NULL;
829 reginfo->strbeg = strbeg;
830 reginfo->strend = strend;
831 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
833 /* not actually used within intuit, but zero for safety anyway */
834 reginfo->poscache_maxiter = 0;
837 if ((!prog->anchored_utf8 && prog->anchored_substr)
838 || (!prog->float_utf8 && prog->float_substr))
839 to_utf8_substr(prog);
840 check = prog->check_utf8;
842 if (!prog->check_substr && prog->check_utf8) {
843 if (! to_byte_substr(prog)) {
844 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(fail);
847 check = prog->check_substr;
850 /* dump the various substring data */
851 DEBUG_OPTIMISE_MORE_r({
853 for (i=0; i<=2; i++) {
854 SV *sv = (utf8_target ? prog->substrs->data[i].utf8_substr
855 : prog->substrs->data[i].substr);
859 Perl_re_printf( aTHX_
860 " substrs[%d]: min=%" IVdf " max=%" IVdf " end shift=%" IVdf
861 " useful=%" IVdf " utf8=%d [%s]\n",
863 (IV)prog->substrs->data[i].min_offset,
864 (IV)prog->substrs->data[i].max_offset,
865 (IV)prog->substrs->data[i].end_shift,
872 if (prog->intflags & PREGf_ANCH) { /* Match at \G, beg-of-str or after \n */
874 /* ml_anch: check after \n?
876 * A note about PREGf_IMPLICIT: on an un-anchored pattern beginning
877 * with /.*.../, these flags will have been added by the
879 * /.*abc/, /.*abc/m: PREGf_IMPLICIT | PREGf_ANCH_MBOL
880 * /.*abc/s: PREGf_IMPLICIT | PREGf_ANCH_SBOL
882 ml_anch = (prog->intflags & PREGf_ANCH_MBOL)
883 && !(prog->intflags & PREGf_IMPLICIT);
885 if (!ml_anch && !(prog->intflags & PREGf_IMPLICIT)) {
886 /* we are only allowed to match at BOS or \G */
888 /* trivially reject if there's a BOS anchor and we're not at BOS.
890 * Note that we don't try to do a similar quick reject for
891 * \G, since generally the caller will have calculated strpos
892 * based on pos() and gofs, so the string is already correctly
893 * anchored by definition; and handling the exceptions would
894 * be too fiddly (e.g. REXEC_IGNOREPOS).
896 if ( strpos != strbeg
897 && (prog->intflags & PREGf_ANCH_SBOL))
899 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
900 " Not at start...\n"));
904 /* in the presence of an anchor, the anchored (relative to the
905 * start of the regex) substr must also be anchored relative
906 * to strpos. So quickly reject if substr isn't found there.
907 * This works for \G too, because the caller will already have
908 * subtracted gofs from pos, and gofs is the offset from the
909 * \G to the start of the regex. For example, in /.abc\Gdef/,
910 * where substr="abcdef", pos()=3, gofs=4, offset_min=1:
911 * caller will have set strpos=pos()-4; we look for the substr
912 * at position pos()-4+1, which lines up with the "a" */
914 if (prog->check_offset_min == prog->check_offset_max) {
915 /* Substring at constant offset from beg-of-str... */
916 SSize_t slen = SvCUR(check);
917 char *s = HOP3c(strpos, prog->check_offset_min, strend);
919 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
920 " Looking for check substr at fixed offset %" IVdf "...\n",
921 (IV)prog->check_offset_min));
924 /* In this case, the regex is anchored at the end too.
925 * Unless it's a multiline match, the lengths must match
926 * exactly, give or take a \n. NB: slen >= 1 since
927 * the last char of check is \n */
929 && ( strend - s > slen
930 || strend - s < slen - 1
931 || (strend - s == slen && strend[-1] != '\n')))
933 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
934 " String too long...\n"));
937 /* Now should match s[0..slen-2] */
940 if (slen && (strend - s < slen
941 || *SvPVX_const(check) != *s
942 || (slen > 1 && (memNE(SvPVX_const(check), s, slen)))))
944 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
945 " String not equal...\n"));
950 goto success_at_start;
955 end_shift = prog->check_end_shift;
957 #ifdef DEBUGGING /* 7/99: reports of failure (with the older version) */
959 Perl_croak(aTHX_ "panic: end_shift: %" IVdf " pattern:\n%s\n ",
960 (IV)end_shift, RX_PRECOMP(rx));
965 /* This is the (re)entry point of the main loop in this function.
966 * The goal of this loop is to:
967 * 1) find the "check" substring in the region rx_origin..strend
968 * (adjusted by start_shift / end_shift). If not found, reject
970 * 2) If it exists, look for the "other" substr too if defined; for
971 * example, if the check substr maps to the anchored substr, then
972 * check the floating substr, and vice-versa. If not found, go
973 * back to (1) with rx_origin suitably incremented.
974 * 3) If we find an rx_origin position that doesn't contradict
975 * either of the substrings, then check the possible additional
976 * constraints on rx_origin of /^.../m or a known start class.
977 * If these fail, then depending on which constraints fail, jump
978 * back to here, or to various other re-entry points further along
979 * that skip some of the first steps.
980 * 4) If we pass all those tests, update the BmUSEFUL() count on the
981 * substring. If the start position was determined to be at the
982 * beginning of the string - so, not rejected, but not optimised,
983 * since we have to run regmatch from position 0 - decrement the
984 * BmUSEFUL() count. Otherwise increment it.
988 /* first, look for the 'check' substring */
994 DEBUG_OPTIMISE_MORE_r({
995 Perl_re_printf( aTHX_
996 " At restart: rx_origin=%" IVdf " Check offset min: %" IVdf
997 " Start shift: %" IVdf " End shift %" IVdf
998 " Real end Shift: %" IVdf "\n",
999 (IV)(rx_origin - strbeg),
1000 (IV)prog->check_offset_min,
1003 (IV)prog->check_end_shift);
1006 end_point = HOPBACK3(strend, end_shift, rx_origin);
1009 start_point = HOPMAYBE3(rx_origin, start_shift, end_point);
1014 /* If the regex is absolutely anchored to either the start of the
1015 * string (SBOL) or to pos() (ANCH_GPOS), then
1016 * check_offset_max represents an upper bound on the string where
1017 * the substr could start. For the ANCH_GPOS case, we assume that
1018 * the caller of intuit will have already set strpos to
1019 * pos()-gofs, so in this case strpos + offset_max will still be
1020 * an upper bound on the substr.
1023 && prog->intflags & PREGf_ANCH
1024 && prog->check_offset_max != SSize_t_MAX)
1026 SSize_t check_len = SvCUR(check) - !!SvTAIL(check);
1027 const char * const anchor =
1028 (prog->intflags & PREGf_ANCH_GPOS ? strpos : strbeg);
1029 SSize_t targ_len = (char*)end_point - anchor;
1031 if (check_len > targ_len) {
1032 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1033 "Anchored string too short...\n"));
1037 /* do a bytes rather than chars comparison. It's conservative;
1038 * so it skips doing the HOP if the result can't possibly end
1039 * up earlier than the old value of end_point.
1041 assert(anchor + check_len <= (char *)end_point);
1042 if (prog->check_offset_max + check_len < targ_len) {
1043 end_point = HOP3lim((U8*)anchor,
1044 prog->check_offset_max,
1045 end_point - check_len
1051 check_at = fbm_instr( start_point, end_point,
1052 check, multiline ? FBMrf_MULTILINE : 0);
1054 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1055 " doing 'check' fbm scan, [%" IVdf "..%" IVdf "] gave %" IVdf "\n",
1056 (IV)((char*)start_point - strbeg),
1057 (IV)((char*)end_point - strbeg),
1058 (IV)(check_at ? check_at - strbeg : -1)
1061 /* Update the count-of-usability, remove useless subpatterns,
1065 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
1066 SvPVX_const(check), RE_SV_DUMPLEN(check), 30);
1067 Perl_re_printf( aTHX_ " %s %s substr %s%s%s",
1068 (check_at ? "Found" : "Did not find"),
1069 (check == (utf8_target ? prog->anchored_utf8 : prog->anchored_substr)
1070 ? "anchored" : "floating"),
1073 (check_at ? " at offset " : "...\n") );
1078 /* set rx_origin to the minimum position where the regex could start
1079 * matching, given the constraint of the just-matched check substring.
1080 * But don't set it lower than previously.
1083 if (check_at - rx_origin > prog->check_offset_max)
1084 rx_origin = HOP3c(check_at, -prog->check_offset_max, rx_origin);
1085 /* Finish the diagnostic message */
1086 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1087 "%ld (rx_origin now %" IVdf ")...\n",
1088 (long)(check_at - strbeg),
1089 (IV)(rx_origin - strbeg)
1094 /* now look for the 'other' substring if defined */
1096 if (utf8_target ? prog->substrs->data[other_ix].utf8_substr
1097 : prog->substrs->data[other_ix].substr)
1099 /* Take into account the "other" substring. */
1103 struct reg_substr_datum *other;
1106 other = &prog->substrs->data[other_ix];
1108 /* if "other" is anchored:
1109 * we've previously found a floating substr starting at check_at.
1110 * This means that the regex origin must lie somewhere
1111 * between min (rx_origin): HOP3(check_at, -check_offset_max)
1112 * and max: HOP3(check_at, -check_offset_min)
1113 * (except that min will be >= strpos)
1114 * So the fixed substr must lie somewhere between
1115 * HOP3(min, anchored_offset)
1116 * HOP3(max, anchored_offset) + SvCUR(substr)
1119 /* if "other" is floating
1120 * Calculate last1, the absolute latest point where the
1121 * floating substr could start in the string, ignoring any
1122 * constraints from the earlier fixed match. It is calculated
1125 * strend - prog->minlen (in chars) is the absolute latest
1126 * position within the string where the origin of the regex
1127 * could appear. The latest start point for the floating
1128 * substr is float_min_offset(*) on from the start of the
1129 * regex. last1 simply combines thee two offsets.
1131 * (*) You might think the latest start point should be
1132 * float_max_offset from the regex origin, and technically
1133 * you'd be correct. However, consider
1135 * Here, float min, max are 3,5 and minlen is 7.
1136 * This can match either
1140 * In the first case, the regex matches minlen chars; in the
1141 * second, minlen+1, in the third, minlen+2.
1142 * In the first case, the floating offset is 3 (which equals
1143 * float_min), in the second, 4, and in the third, 5 (which
1144 * equals float_max). In all cases, the floating string bcd
1145 * can never start more than 4 chars from the end of the
1146 * string, which equals minlen - float_min. As the substring
1147 * starts to match more than float_min from the start of the
1148 * regex, it makes the regex match more than minlen chars,
1149 * and the two cancel each other out. So we can always use
1150 * float_min - minlen, rather than float_max - minlen for the
1151 * latest position in the string.
1153 * Note that -minlen + float_min_offset is equivalent (AFAIKT)
1154 * to CHR_SVLEN(must) - !!SvTAIL(must) + prog->float_end_shift
1157 assert(prog->minlen >= other->min_offset);
1158 last1 = HOP3c(strend,
1159 other->min_offset - prog->minlen, strbeg);
1161 if (other_ix) {/* i.e. if (other-is-float) */
1162 /* last is the latest point where the floating substr could
1163 * start, *given* any constraints from the earlier fixed
1164 * match. This constraint is that the floating string starts
1165 * <= float_max_offset chars from the regex origin (rx_origin).
1166 * If this value is less than last1, use it instead.
1168 assert(rx_origin <= last1);
1170 /* this condition handles the offset==infinity case, and
1171 * is a short-cut otherwise. Although it's comparing a
1172 * byte offset to a char length, it does so in a safe way,
1173 * since 1 char always occupies 1 or more bytes,
1174 * so if a string range is (last1 - rx_origin) bytes,
1175 * it will be less than or equal to (last1 - rx_origin)
1176 * chars; meaning it errs towards doing the accurate HOP3
1177 * rather than just using last1 as a short-cut */
1178 (last1 - rx_origin) < other->max_offset
1180 : (char*)HOP3lim(rx_origin, other->max_offset, last1);
1183 assert(strpos + start_shift <= check_at);
1184 last = HOP4c(check_at, other->min_offset - start_shift,
1188 s = HOP3c(rx_origin, other->min_offset, strend);
1189 if (s < other_last) /* These positions already checked */
1192 must = utf8_target ? other->utf8_substr : other->substr;
1193 assert(SvPOK(must));
1196 char *to = last + SvCUR(must) - (SvTAIL(must)!=0);
1202 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1203 " skipping 'other' fbm scan: %" IVdf " > %" IVdf "\n",
1204 (IV)(from - strbeg),
1210 (unsigned char*)from,
1213 multiline ? FBMrf_MULTILINE : 0
1215 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1216 " doing 'other' fbm scan, [%" IVdf "..%" IVdf "] gave %" IVdf "\n",
1217 (IV)(from - strbeg),
1219 (IV)(s ? s - strbeg : -1)
1225 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
1226 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
1227 Perl_re_printf( aTHX_ " %s %s substr %s%s",
1228 s ? "Found" : "Contradicts",
1229 other_ix ? "floating" : "anchored",
1230 quoted, RE_SV_TAIL(must));
1235 /* last1 is latest possible substr location. If we didn't
1236 * find it before there, we never will */
1237 if (last >= last1) {
1238 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1239 "; giving up...\n"));
1243 /* try to find the check substr again at a later
1244 * position. Maybe next time we'll find the "other" substr
1246 other_last = HOP3c(last, 1, strend) /* highest failure */;
1248 other_ix /* i.e. if other-is-float */
1249 ? HOP3c(rx_origin, 1, strend)
1250 : HOP4c(last, 1 - other->min_offset, strbeg, strend);
1251 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1252 "; about to retry %s at offset %ld (rx_origin now %" IVdf ")...\n",
1253 (other_ix ? "floating" : "anchored"),
1254 (long)(HOP3c(check_at, 1, strend) - strbeg),
1255 (IV)(rx_origin - strbeg)
1260 if (other_ix) { /* if (other-is-float) */
1261 /* other_last is set to s, not s+1, since its possible for
1262 * a floating substr to fail first time, then succeed
1263 * second time at the same floating position; e.g.:
1264 * "-AB--AABZ" =~ /\wAB\d*Z/
1265 * The first time round, anchored and float match at
1266 * "-(AB)--AAB(Z)" then fail on the initial \w character
1267 * class. Second time round, they match at "-AB--A(AB)(Z)".
1272 rx_origin = HOP3c(s, -other->min_offset, strbeg);
1273 other_last = HOP3c(s, 1, strend);
1275 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1276 " at offset %ld (rx_origin now %" IVdf ")...\n",
1278 (IV)(rx_origin - strbeg)
1284 DEBUG_OPTIMISE_MORE_r(
1285 Perl_re_printf( aTHX_
1286 " Check-only match: offset min:%" IVdf " max:%" IVdf
1287 " check_at:%" IVdf " rx_origin:%" IVdf " rx_origin-check_at:%" IVdf
1288 " strend:%" IVdf "\n",
1289 (IV)prog->check_offset_min,
1290 (IV)prog->check_offset_max,
1291 (IV)(check_at-strbeg),
1292 (IV)(rx_origin-strbeg),
1293 (IV)(rx_origin-check_at),
1299 postprocess_substr_matches:
1301 /* handle the extra constraint of /^.../m if present */
1303 if (ml_anch && rx_origin != strbeg && rx_origin[-1] != '\n') {
1306 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1307 " looking for /^/m anchor"));
1309 /* we have failed the constraint of a \n before rx_origin.
1310 * Find the next \n, if any, even if it's beyond the current
1311 * anchored and/or floating substrings. Whether we should be
1312 * scanning ahead for the next \n or the next substr is debatable.
1313 * On the one hand you'd expect rare substrings to appear less
1314 * often than \n's. On the other hand, searching for \n means
1315 * we're effectively flipping between check_substr and "\n" on each
1316 * iteration as the current "rarest" string candidate, which
1317 * means for example that we'll quickly reject the whole string if
1318 * hasn't got a \n, rather than trying every substr position
1322 s = HOP3c(strend, - prog->minlen, strpos);
1323 if (s <= rx_origin ||
1324 ! ( rx_origin = (char *)memchr(rx_origin, '\n', s - rx_origin)))
1326 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1327 " Did not find /%s^%s/m...\n",
1328 PL_colors[0], PL_colors[1]));
1332 /* earliest possible origin is 1 char after the \n.
1333 * (since *rx_origin == '\n', it's safe to ++ here rather than
1334 * HOP(rx_origin, 1)) */
1337 if (prog->substrs->check_ix == 0 /* check is anchored */
1338 || rx_origin >= HOP3c(check_at, - prog->check_offset_min, strpos))
1340 /* Position contradicts check-string; either because
1341 * check was anchored (and thus has no wiggle room),
1342 * or check was float and rx_origin is above the float range */
1343 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1344 " Found /%s^%s/m, about to restart lookup for check-string with rx_origin %ld...\n",
1345 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1349 /* if we get here, the check substr must have been float,
1350 * is in range, and we may or may not have had an anchored
1351 * "other" substr which still contradicts */
1352 assert(prog->substrs->check_ix); /* check is float */
1354 if (utf8_target ? prog->anchored_utf8 : prog->anchored_substr) {
1355 /* whoops, the anchored "other" substr exists, so we still
1356 * contradict. On the other hand, the float "check" substr
1357 * didn't contradict, so just retry the anchored "other"
1359 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1360 " Found /%s^%s/m, rescanning for anchored from offset %" IVdf " (rx_origin now %" IVdf ")...\n",
1361 PL_colors[0], PL_colors[1],
1362 (IV)(rx_origin - strbeg + prog->anchored_offset),
1363 (IV)(rx_origin - strbeg)
1365 goto do_other_substr;
1368 /* success: we don't contradict the found floating substring
1369 * (and there's no anchored substr). */
1370 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1371 " Found /%s^%s/m with rx_origin %ld...\n",
1372 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1375 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1376 " (multiline anchor test skipped)\n"));
1382 /* if we have a starting character class, then test that extra constraint.
1383 * (trie stclasses are too expensive to use here, we are better off to
1384 * leave it to regmatch itself) */
1386 if (progi->regstclass && PL_regkind[OP(progi->regstclass)]!=TRIE) {
1387 const U8* const str = (U8*)STRING(progi->regstclass);
1389 /* XXX this value could be pre-computed */
1390 const int cl_l = (PL_regkind[OP(progi->regstclass)] == EXACT
1391 ? (reginfo->is_utf8_pat
1392 ? utf8_distance(str + STR_LEN(progi->regstclass), str)
1393 : STR_LEN(progi->regstclass))
1397 /* latest pos that a matching float substr constrains rx start to */
1398 char *rx_max_float = NULL;
1400 /* if the current rx_origin is anchored, either by satisfying an
1401 * anchored substring constraint, or a /^.../m constraint, then we
1402 * can reject the current origin if the start class isn't found
1403 * at the current position. If we have a float-only match, then
1404 * rx_origin is constrained to a range; so look for the start class
1405 * in that range. if neither, then look for the start class in the
1406 * whole rest of the string */
1408 /* XXX DAPM it's not clear what the minlen test is for, and why
1409 * it's not used in the floating case. Nothing in the test suite
1410 * causes minlen == 0 here. See <20140313134639.GS12844@iabyn.com>.
1411 * Here are some old comments, which may or may not be correct:
1413 * minlen == 0 is possible if regstclass is \b or \B,
1414 * and the fixed substr is ''$.
1415 * Since minlen is already taken into account, rx_origin+1 is
1416 * before strend; accidentally, minlen >= 1 guaranties no false
1417 * positives at rx_origin + 1 even for \b or \B. But (minlen? 1 :
1418 * 0) below assumes that regstclass does not come from lookahead...
1419 * If regstclass takes bytelength more than 1: If charlength==1, OK.
1420 * This leaves EXACTF-ish only, which are dealt with in
1424 if (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
1425 endpos = HOP3clim(rx_origin, (prog->minlen ? cl_l : 0), strend);
1426 else if (prog->float_substr || prog->float_utf8) {
1427 rx_max_float = HOP3c(check_at, -start_shift, strbeg);
1428 endpos = HOP3clim(rx_max_float, cl_l, strend);
1433 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1434 " looking for class: start_shift: %" IVdf " check_at: %" IVdf
1435 " rx_origin: %" IVdf " endpos: %" IVdf "\n",
1436 (IV)start_shift, (IV)(check_at - strbeg),
1437 (IV)(rx_origin - strbeg), (IV)(endpos - strbeg)));
1439 s = find_byclass(prog, progi->regstclass, rx_origin, endpos,
1442 if (endpos == strend) {
1443 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1444 " Could not match STCLASS...\n") );
1447 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1448 " This position contradicts STCLASS...\n") );
1449 if ((prog->intflags & PREGf_ANCH) && !ml_anch
1450 && !(prog->intflags & PREGf_IMPLICIT))
1453 /* Contradict one of substrings */
1454 if (prog->anchored_substr || prog->anchored_utf8) {
1455 if (prog->substrs->check_ix == 1) { /* check is float */
1456 /* Have both, check_string is floating */
1457 assert(rx_origin + start_shift <= check_at);
1458 if (rx_origin + start_shift != check_at) {
1459 /* not at latest position float substr could match:
1460 * Recheck anchored substring, but not floating.
1461 * The condition above is in bytes rather than
1462 * chars for efficiency. It's conservative, in
1463 * that it errs on the side of doing 'goto
1464 * do_other_substr'. In this case, at worst,
1465 * an extra anchored search may get done, but in
1466 * practice the extra fbm_instr() is likely to
1467 * get skipped anyway. */
1468 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1469 " about to retry anchored at offset %ld (rx_origin now %" IVdf ")...\n",
1470 (long)(other_last - strbeg),
1471 (IV)(rx_origin - strbeg)
1473 goto do_other_substr;
1481 /* In the presence of ml_anch, we might be able to
1482 * find another \n without breaking the current float
1485 /* strictly speaking this should be HOP3c(..., 1, ...),
1486 * but since we goto a block of code that's going to
1487 * search for the next \n if any, its safe here */
1489 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1490 " about to look for /%s^%s/m starting at rx_origin %ld...\n",
1491 PL_colors[0], PL_colors[1],
1492 (long)(rx_origin - strbeg)) );
1493 goto postprocess_substr_matches;
1496 /* strictly speaking this can never be true; but might
1497 * be if we ever allow intuit without substrings */
1498 if (!(utf8_target ? prog->float_utf8 : prog->float_substr))
1501 rx_origin = rx_max_float;
1504 /* at this point, any matching substrings have been
1505 * contradicted. Start again... */
1507 rx_origin = HOP3c(rx_origin, 1, strend);
1509 /* uses bytes rather than char calculations for efficiency.
1510 * It's conservative: it errs on the side of doing 'goto restart',
1511 * where there is code that does a proper char-based test */
1512 if (rx_origin + start_shift + end_shift > strend) {
1513 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1514 " Could not match STCLASS...\n") );
1517 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1518 " about to look for %s substr starting at offset %ld (rx_origin now %" IVdf ")...\n",
1519 (prog->substrs->check_ix ? "floating" : "anchored"),
1520 (long)(rx_origin + start_shift - strbeg),
1521 (IV)(rx_origin - strbeg)
1528 if (rx_origin != s) {
1529 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1530 " By STCLASS: moving %ld --> %ld\n",
1531 (long)(rx_origin - strbeg), (long)(s - strbeg))
1535 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1536 " Does not contradict STCLASS...\n");
1541 /* Decide whether using the substrings helped */
1543 if (rx_origin != strpos) {
1544 /* Fixed substring is found far enough so that the match
1545 cannot start at strpos. */
1547 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ " try at offset...\n"));
1548 ++BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr); /* hooray/5 */
1551 /* The found rx_origin position does not prohibit matching at
1552 * strpos, so calling intuit didn't gain us anything. Decrement
1553 * the BmUSEFUL() count on the check substring, and if we reach
1555 if (!(prog->intflags & PREGf_NAUGHTY)
1557 prog->check_utf8 /* Could be deleted already */
1558 && --BmUSEFUL(prog->check_utf8) < 0
1559 && (prog->check_utf8 == prog->float_utf8)
1561 prog->check_substr /* Could be deleted already */
1562 && --BmUSEFUL(prog->check_substr) < 0
1563 && (prog->check_substr == prog->float_substr)
1566 /* If flags & SOMETHING - do not do it many times on the same match */
1567 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ " ... Disabling check substring...\n"));
1568 /* XXX Does the destruction order has to change with utf8_target? */
1569 SvREFCNT_dec(utf8_target ? prog->check_utf8 : prog->check_substr);
1570 SvREFCNT_dec(utf8_target ? prog->check_substr : prog->check_utf8);
1571 prog->check_substr = prog->check_utf8 = NULL; /* disable */
1572 prog->float_substr = prog->float_utf8 = NULL; /* clear */
1573 check = NULL; /* abort */
1574 /* XXXX This is a remnant of the old implementation. It
1575 looks wasteful, since now INTUIT can use many
1576 other heuristics. */
1577 prog->extflags &= ~RXf_USE_INTUIT;
1581 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1582 "Intuit: %sSuccessfully guessed:%s match at offset %ld\n",
1583 PL_colors[4], PL_colors[5], (long)(rx_origin - strbeg)) );
1587 fail_finish: /* Substring not found */
1588 if (prog->check_substr || prog->check_utf8) /* could be removed already */
1589 BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
1591 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%sMatch rejected by optimizer%s\n",
1592 PL_colors[4], PL_colors[5]));
1597 #define DECL_TRIE_TYPE(scan) \
1598 const enum { trie_plain, trie_utf8, trie_utf8_fold, trie_latin_utf8_fold, \
1599 trie_utf8_exactfa_fold, trie_latin_utf8_exactfa_fold, \
1600 trie_utf8l, trie_flu8 } \
1601 trie_type = ((scan->flags == EXACT) \
1602 ? (utf8_target ? trie_utf8 : trie_plain) \
1603 : (scan->flags == EXACTL) \
1604 ? (utf8_target ? trie_utf8l : trie_plain) \
1605 : (scan->flags == EXACTFA) \
1607 ? trie_utf8_exactfa_fold \
1608 : trie_latin_utf8_exactfa_fold) \
1609 : (scan->flags == EXACTFLU8 \
1613 : trie_latin_utf8_fold)))
1615 #define REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc, uscan, len, uvc, charid, foldlen, foldbuf, uniflags) \
1618 U8 flags = FOLD_FLAGS_FULL; \
1619 switch (trie_type) { \
1621 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1622 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1623 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1625 goto do_trie_utf8_fold; \
1626 case trie_utf8_exactfa_fold: \
1627 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1629 case trie_utf8_fold: \
1630 do_trie_utf8_fold: \
1631 if ( foldlen>0 ) { \
1632 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1637 len = UTF8SKIP(uc); \
1638 uvc = _toFOLD_utf8_flags( (const U8*) uc, uc + len, foldbuf, &foldlen, \
1640 skiplen = UVCHR_SKIP( uvc ); \
1641 foldlen -= skiplen; \
1642 uscan = foldbuf + skiplen; \
1645 case trie_latin_utf8_exactfa_fold: \
1646 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1648 case trie_latin_utf8_fold: \
1649 if ( foldlen>0 ) { \
1650 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1656 uvc = _to_fold_latin1( (U8) *uc, foldbuf, &foldlen, flags); \
1657 skiplen = UVCHR_SKIP( uvc ); \
1658 foldlen -= skiplen; \
1659 uscan = foldbuf + skiplen; \
1663 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1664 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1665 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1669 uvc = utf8n_to_uvchr( (const U8*) uc, UTF8_MAXLEN, &len, uniflags ); \
1676 charid = trie->charmap[ uvc ]; \
1680 if (widecharmap) { \
1681 SV** const svpp = hv_fetch(widecharmap, \
1682 (char*)&uvc, sizeof(UV), 0); \
1684 charid = (U16)SvIV(*svpp); \
1689 #define DUMP_EXEC_POS(li,s,doutf8,depth) \
1690 dump_exec_pos(li,s,(reginfo->strend),(reginfo->strbeg), \
1691 startpos, doutf8, depth)
1693 #define REXEC_FBC_EXACTISH_SCAN(COND) \
1697 && (ln == 1 || folder(s, pat_string, ln)) \
1698 && (reginfo->intuit || regtry(reginfo, &s)) )\
1704 #define REXEC_FBC_UTF8_SCAN(CODE) \
1706 while (s < strend) { \
1712 #define REXEC_FBC_SCAN(CODE) \
1714 while (s < strend) { \
1720 #define REXEC_FBC_UTF8_CLASS_SCAN(COND) \
1721 REXEC_FBC_UTF8_SCAN( /* Loops while (s < strend) */ \
1723 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1732 #define REXEC_FBC_CLASS_SCAN(COND) \
1733 REXEC_FBC_SCAN( /* Loops while (s < strend) */ \
1735 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1744 #define REXEC_FBC_CSCAN(CONDUTF8,COND) \
1745 if (utf8_target) { \
1746 REXEC_FBC_UTF8_CLASS_SCAN(CONDUTF8); \
1749 REXEC_FBC_CLASS_SCAN(COND); \
1752 /* The three macros below are slightly different versions of the same logic.
1754 * The first is for /a and /aa when the target string is UTF-8. This can only
1755 * match ascii, but it must advance based on UTF-8. The other two handle the
1756 * non-UTF-8 and the more generic UTF-8 cases. In all three, we are looking
1757 * for the boundary (or non-boundary) between a word and non-word character.
1758 * The utf8 and non-utf8 cases have the same logic, but the details must be
1759 * different. Find the "wordness" of the character just prior to this one, and
1760 * compare it with the wordness of this one. If they differ, we have a
1761 * boundary. At the beginning of the string, pretend that the previous
1762 * character was a new-line.
1764 * All these macros uncleanly have side-effects with each other and outside
1765 * variables. So far it's been too much trouble to clean-up
1767 * TEST_NON_UTF8 is the macro or function to call to test if its byte input is
1768 * a word character or not.
1769 * IF_SUCCESS is code to do if it finds that we are at a boundary between
1771 * IF_FAIL is code to do if we aren't at a boundary between word/non-word
1773 * Exactly one of the two IF_FOO parameters is a no-op, depending on whether we
1774 * are looking for a boundary or for a non-boundary. If we are looking for a
1775 * boundary, we want IF_FAIL to be the no-op, and for IF_SUCCESS to go out and
1776 * see if this tentative match actually works, and if so, to quit the loop
1777 * here. And vice-versa if we are looking for a non-boundary.
1779 * 'tmp' below in the next three macros in the REXEC_FBC_SCAN and
1780 * REXEC_FBC_UTF8_SCAN loops is a loop invariant, a bool giving the return of
1781 * TEST_NON_UTF8(s-1). To see this, note that that's what it is defined to be
1782 * at entry to the loop, and to get to the IF_FAIL branch, tmp must equal
1783 * TEST_NON_UTF8(s), and in the opposite branch, IF_SUCCESS, tmp is that
1784 * complement. But in that branch we complement tmp, meaning that at the
1785 * bottom of the loop tmp is always going to be equal to TEST_NON_UTF8(s),
1786 * which means at the top of the loop in the next iteration, it is
1787 * TEST_NON_UTF8(s-1) */
1788 #define FBC_UTF8_A(TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1789 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1790 tmp = TEST_NON_UTF8(tmp); \
1791 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1792 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1794 IF_SUCCESS; /* Is a boundary if values for s-1 and s differ */ \
1801 /* Like FBC_UTF8_A, but TEST_UV is a macro which takes a UV as its input, and
1802 * TEST_UTF8 is a macro that for the same input code points returns identically
1803 * to TEST_UV, but takes a pointer to a UTF-8 encoded string instead */
1804 #define FBC_UTF8(TEST_UV, TEST_UTF8, IF_SUCCESS, IF_FAIL) \
1805 if (s == reginfo->strbeg) { \
1808 else { /* Back-up to the start of the previous character */ \
1809 U8 * const r = reghop3((U8*)s, -1, (U8*)reginfo->strbeg); \
1810 tmp = utf8n_to_uvchr(r, (U8*) reginfo->strend - r, \
1811 0, UTF8_ALLOW_DEFAULT); \
1813 tmp = TEST_UV(tmp); \
1814 LOAD_UTF8_CHARCLASS_ALNUM(); \
1815 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1816 if (tmp == ! (TEST_UTF8((U8 *) s, (U8 *) reginfo->strend))) { \
1825 /* Like the above two macros. UTF8_CODE is the complete code for handling
1826 * UTF-8. Common to the BOUND and NBOUND cases, set-up by the FBC_BOUND, etc
1828 #define FBC_BOUND_COMMON(UTF8_CODE, TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1829 if (utf8_target) { \
1832 else { /* Not utf8 */ \
1833 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1834 tmp = TEST_NON_UTF8(tmp); \
1835 REXEC_FBC_SCAN( /* advances s while s < strend */ \
1836 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1845 /* Here, things have been set up by the previous code so that tmp is the \
1846 * return of TEST_NON_UTF(s-1) or TEST_UTF8(s-1) (depending on the \
1847 * utf8ness of the target). We also have to check if this matches against \
1848 * the EOS, which we treat as a \n (which is the same value in both UTF-8 \
1849 * or non-UTF8, so can use the non-utf8 test condition even for a UTF-8 \
1851 if (tmp == ! TEST_NON_UTF8('\n')) { \
1858 /* This is the macro to use when we want to see if something that looks like it
1859 * could match, actually does, and if so exits the loop */
1860 #define REXEC_FBC_TRYIT \
1861 if ((reginfo->intuit || regtry(reginfo, &s))) \
1864 /* The only difference between the BOUND and NBOUND cases is that
1865 * REXEC_FBC_TRYIT is called when matched in BOUND, and when non-matched in
1866 * NBOUND. This is accomplished by passing it as either the if or else clause,
1867 * with the other one being empty (PLACEHOLDER is defined as empty).
1869 * The TEST_FOO parameters are for operating on different forms of input, but
1870 * all should be ones that return identically for the same underlying code
1872 #define FBC_BOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1874 FBC_UTF8(TEST_UV, TEST_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1875 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1877 #define FBC_BOUND_A(TEST_NON_UTF8) \
1879 FBC_UTF8_A(TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1880 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1882 #define FBC_NBOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1884 FBC_UTF8(TEST_UV, TEST_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1885 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1887 #define FBC_NBOUND_A(TEST_NON_UTF8) \
1889 FBC_UTF8_A(TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1890 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1894 S_get_break_val_cp_checked(SV* const invlist, const UV cp_in) {
1895 IV cp_out = Perl__invlist_search(invlist, cp_in);
1896 assert(cp_out >= 0);
1899 # define _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp) \
1900 invmap[S_get_break_val_cp_checked(invlist, cp)]
1902 # define _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp) \
1903 invmap[_invlist_search(invlist, cp)]
1906 /* Takes a pointer to an inversion list, a pointer to its corresponding
1907 * inversion map, and a code point, and returns the code point's value
1908 * according to the two arrays. It assumes that all code points have a value.
1909 * This is used as the base macro for macros for particular properties */
1910 #define _generic_GET_BREAK_VAL_CP(invlist, invmap, cp) \
1911 _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp)
1913 /* Same as above, but takes begin, end ptrs to a UTF-8 encoded string instead
1914 * of a code point, returning the value for the first code point in the string.
1915 * And it takes the particular macro name that finds the desired value given a
1916 * code point. Merely convert the UTF-8 to code point and call the cp macro */
1917 #define _generic_GET_BREAK_VAL_UTF8(cp_macro, pos, strend) \
1918 (__ASSERT_(pos < strend) \
1919 /* Note assumes is valid UTF-8 */ \
1920 (cp_macro(utf8_to_uvchr_buf((pos), (strend), NULL))))
1922 /* Returns the GCB value for the input code point */
1923 #define getGCB_VAL_CP(cp) \
1924 _generic_GET_BREAK_VAL_CP( \
1929 /* Returns the GCB value for the first code point in the UTF-8 encoded string
1930 * bounded by pos and strend */
1931 #define getGCB_VAL_UTF8(pos, strend) \
1932 _generic_GET_BREAK_VAL_UTF8(getGCB_VAL_CP, pos, strend)
1934 /* Returns the LB value for the input code point */
1935 #define getLB_VAL_CP(cp) \
1936 _generic_GET_BREAK_VAL_CP( \
1941 /* Returns the LB value for the first code point in the UTF-8 encoded string
1942 * bounded by pos and strend */
1943 #define getLB_VAL_UTF8(pos, strend) \
1944 _generic_GET_BREAK_VAL_UTF8(getLB_VAL_CP, pos, strend)
1947 /* Returns the SB value for the input code point */
1948 #define getSB_VAL_CP(cp) \
1949 _generic_GET_BREAK_VAL_CP( \
1954 /* Returns the SB value for the first code point in the UTF-8 encoded string
1955 * bounded by pos and strend */
1956 #define getSB_VAL_UTF8(pos, strend) \
1957 _generic_GET_BREAK_VAL_UTF8(getSB_VAL_CP, pos, strend)
1959 /* Returns the WB value for the input code point */
1960 #define getWB_VAL_CP(cp) \
1961 _generic_GET_BREAK_VAL_CP( \
1966 /* Returns the WB value for the first code point in the UTF-8 encoded string
1967 * bounded by pos and strend */
1968 #define getWB_VAL_UTF8(pos, strend) \
1969 _generic_GET_BREAK_VAL_UTF8(getWB_VAL_CP, pos, strend)
1971 /* We know what class REx starts with. Try to find this position... */
1972 /* if reginfo->intuit, its a dryrun */
1973 /* annoyingly all the vars in this routine have different names from their counterparts
1974 in regmatch. /grrr */
1976 S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
1977 const char *strend, regmatch_info *reginfo)
1980 const I32 doevery = (prog->intflags & PREGf_SKIP) == 0;
1981 char *pat_string; /* The pattern's exactish string */
1982 char *pat_end; /* ptr to end char of pat_string */
1983 re_fold_t folder; /* Function for computing non-utf8 folds */
1984 const U8 *fold_array; /* array for folding ords < 256 */
1990 I32 tmp = 1; /* Scratch variable? */
1991 const bool utf8_target = reginfo->is_utf8_target;
1992 UV utf8_fold_flags = 0;
1993 const bool is_utf8_pat = reginfo->is_utf8_pat;
1994 bool to_complement = FALSE; /* Invert the result? Taking the xor of this
1995 with a result inverts that result, as 0^1 =
1997 _char_class_number classnum;
1999 RXi_GET_DECL(prog,progi);
2001 PERL_ARGS_ASSERT_FIND_BYCLASS;
2003 /* We know what class it must start with. */
2006 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2008 if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(c)) && ! IN_UTF8_CTYPE_LOCALE) {
2009 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
2016 REXEC_FBC_UTF8_CLASS_SCAN(
2017 reginclass(prog, c, (U8*)s, (U8*) strend, utf8_target));
2019 else if (ANYOF_FLAGS(c)) {
2020 REXEC_FBC_CLASS_SCAN(reginclass(prog,c, (U8*)s, (U8*)s+1, 0));
2023 REXEC_FBC_CLASS_SCAN(ANYOF_BITMAP_TEST(c, *((U8*)s)));
2027 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
2028 assert(! is_utf8_pat);
2031 if (is_utf8_pat || utf8_target) {
2032 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
2033 goto do_exactf_utf8;
2035 fold_array = PL_fold_latin1; /* Latin1 folds are not affected by */
2036 folder = foldEQ_latin1; /* /a, except the sharp s one which */
2037 goto do_exactf_non_utf8; /* isn't dealt with by these */
2039 case EXACTF: /* This node only generated for non-utf8 patterns */
2040 assert(! is_utf8_pat);
2042 utf8_fold_flags = 0;
2043 goto do_exactf_utf8;
2045 fold_array = PL_fold;
2047 goto do_exactf_non_utf8;
2050 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2051 if (is_utf8_pat || utf8_target || IN_UTF8_CTYPE_LOCALE) {
2052 utf8_fold_flags = FOLDEQ_LOCALE;
2053 goto do_exactf_utf8;
2055 fold_array = PL_fold_locale;
2056 folder = foldEQ_locale;
2057 goto do_exactf_non_utf8;
2061 utf8_fold_flags = FOLDEQ_S2_ALREADY_FOLDED;
2063 goto do_exactf_utf8;
2066 if (! utf8_target) { /* All code points in this node require
2067 UTF-8 to express. */
2070 utf8_fold_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
2071 | FOLDEQ_S2_FOLDS_SANE;
2072 goto do_exactf_utf8;
2075 if (is_utf8_pat || utf8_target) {
2076 utf8_fold_flags = is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
2077 goto do_exactf_utf8;
2080 /* Any 'ss' in the pattern should have been replaced by regcomp,
2081 * so we don't have to worry here about this single special case
2082 * in the Latin1 range */
2083 fold_array = PL_fold_latin1;
2084 folder = foldEQ_latin1;
2088 do_exactf_non_utf8: /* Neither pattern nor string are UTF8, and there
2089 are no glitches with fold-length differences
2090 between the target string and pattern */
2092 /* The idea in the non-utf8 EXACTF* cases is to first find the
2093 * first character of the EXACTF* node and then, if necessary,
2094 * case-insensitively compare the full text of the node. c1 is the
2095 * first character. c2 is its fold. This logic will not work for
2096 * Unicode semantics and the german sharp ss, which hence should
2097 * not be compiled into a node that gets here. */
2098 pat_string = STRING(c);
2099 ln = STR_LEN(c); /* length to match in octets/bytes */
2101 /* We know that we have to match at least 'ln' bytes (which is the
2102 * same as characters, since not utf8). If we have to match 3
2103 * characters, and there are only 2 availabe, we know without
2104 * trying that it will fail; so don't start a match past the
2105 * required minimum number from the far end */
2106 e = HOP3c(strend, -((SSize_t)ln), s);
2111 c2 = fold_array[c1];
2112 if (c1 == c2) { /* If char and fold are the same */
2113 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1);
2116 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1 || *(U8*)s == c2);
2124 /* If one of the operands is in utf8, we can't use the simpler folding
2125 * above, due to the fact that many different characters can have the
2126 * same fold, or portion of a fold, or different- length fold */
2127 pat_string = STRING(c);
2128 ln = STR_LEN(c); /* length to match in octets/bytes */
2129 pat_end = pat_string + ln;
2130 lnc = is_utf8_pat /* length to match in characters */
2131 ? utf8_length((U8 *) pat_string, (U8 *) pat_end)
2134 /* We have 'lnc' characters to match in the pattern, but because of
2135 * multi-character folding, each character in the target can match
2136 * up to 3 characters (Unicode guarantees it will never exceed
2137 * this) if it is utf8-encoded; and up to 2 if not (based on the
2138 * fact that the Latin 1 folds are already determined, and the
2139 * only multi-char fold in that range is the sharp-s folding to
2140 * 'ss'. Thus, a pattern character can match as little as 1/3 of a
2141 * string character. Adjust lnc accordingly, rounding up, so that
2142 * if we need to match at least 4+1/3 chars, that really is 5. */
2143 expansion = (utf8_target) ? UTF8_MAX_FOLD_CHAR_EXPAND : 2;
2144 lnc = (lnc + expansion - 1) / expansion;
2146 /* As in the non-UTF8 case, if we have to match 3 characters, and
2147 * only 2 are left, it's guaranteed to fail, so don't start a
2148 * match that would require us to go beyond the end of the string
2150 e = HOP3c(strend, -((SSize_t)lnc), s);
2152 /* XXX Note that we could recalculate e to stop the loop earlier,
2153 * as the worst case expansion above will rarely be met, and as we
2154 * go along we would usually find that e moves further to the left.
2155 * This would happen only after we reached the point in the loop
2156 * where if there were no expansion we should fail. Unclear if
2157 * worth the expense */
2160 char *my_strend= (char *)strend;
2161 if (foldEQ_utf8_flags(s, &my_strend, 0, utf8_target,
2162 pat_string, NULL, ln, is_utf8_pat, utf8_fold_flags)
2163 && (reginfo->intuit || regtry(reginfo, &s)) )
2167 s += (utf8_target) ? UTF8SKIP(s) : 1;
2173 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2174 if (FLAGS(c) != TRADITIONAL_BOUND) {
2175 if (! IN_UTF8_CTYPE_LOCALE) {
2176 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2177 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2182 FBC_BOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8_safe);
2186 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2187 if (FLAGS(c) != TRADITIONAL_BOUND) {
2188 if (! IN_UTF8_CTYPE_LOCALE) {
2189 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2190 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2195 FBC_NBOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8_safe);
2198 case BOUND: /* regcomp.c makes sure that this only has the traditional \b
2200 assert(FLAGS(c) == TRADITIONAL_BOUND);
2202 FBC_BOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8_safe);
2205 case BOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2207 assert(FLAGS(c) == TRADITIONAL_BOUND);
2209 FBC_BOUND_A(isWORDCHAR_A);
2212 case NBOUND: /* regcomp.c makes sure that this only has the traditional \b
2214 assert(FLAGS(c) == TRADITIONAL_BOUND);
2216 FBC_NBOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8_safe);
2219 case NBOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2221 assert(FLAGS(c) == TRADITIONAL_BOUND);
2223 FBC_NBOUND_A(isWORDCHAR_A);
2227 if ((bound_type) FLAGS(c) == TRADITIONAL_BOUND) {
2228 FBC_NBOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8_safe);
2239 switch((bound_type) FLAGS(c)) {
2240 case TRADITIONAL_BOUND:
2241 FBC_BOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8_safe);
2244 if (s == reginfo->strbeg) {
2245 if (reginfo->intuit || regtry(reginfo, &s))
2250 /* Didn't match. Try at the next position (if there is one) */
2251 s += (utf8_target) ? UTF8SKIP(s) : 1;
2252 if (UNLIKELY(s >= reginfo->strend)) {
2258 GCB_enum before = getGCB_VAL_UTF8(
2260 (U8*)(reginfo->strbeg)),
2261 (U8*) reginfo->strend);
2262 while (s < strend) {
2263 GCB_enum after = getGCB_VAL_UTF8((U8*) s,
2264 (U8*) reginfo->strend);
2265 if ( (to_complement ^ isGCB(before,
2267 (U8*) reginfo->strbeg,
2270 && (reginfo->intuit || regtry(reginfo, &s)))
2278 else { /* Not utf8. Everything is a GCB except between CR and
2280 while (s < strend) {
2281 if ((to_complement ^ ( UCHARAT(s - 1) != '\r'
2282 || UCHARAT(s) != '\n'))
2283 && (reginfo->intuit || regtry(reginfo, &s)))
2291 /* And, since this is a bound, it can match after the final
2292 * character in the string */
2293 if ((reginfo->intuit || regtry(reginfo, &s))) {
2299 if (s == reginfo->strbeg) {
2300 if (reginfo->intuit || regtry(reginfo, &s)) {
2303 s += (utf8_target) ? UTF8SKIP(s) : 1;
2304 if (UNLIKELY(s >= reginfo->strend)) {
2310 LB_enum before = getLB_VAL_UTF8(reghop3((U8*)s,
2312 (U8*)(reginfo->strbeg)),
2313 (U8*) reginfo->strend);
2314 while (s < strend) {
2315 LB_enum after = getLB_VAL_UTF8((U8*) s, (U8*) reginfo->strend);
2316 if (to_complement ^ isLB(before,
2318 (U8*) reginfo->strbeg,
2320 (U8*) reginfo->strend,
2322 && (reginfo->intuit || regtry(reginfo, &s)))
2330 else { /* Not utf8. */
2331 LB_enum before = getLB_VAL_CP((U8) *(s -1));
2332 while (s < strend) {
2333 LB_enum after = getLB_VAL_CP((U8) *s);
2334 if (to_complement ^ isLB(before,
2336 (U8*) reginfo->strbeg,
2338 (U8*) reginfo->strend,
2340 && (reginfo->intuit || regtry(reginfo, &s)))
2349 if (reginfo->intuit || regtry(reginfo, &s)) {
2356 if (s == reginfo->strbeg) {
2357 if (reginfo->intuit || regtry(reginfo, &s)) {
2360 s += (utf8_target) ? UTF8SKIP(s) : 1;
2361 if (UNLIKELY(s >= reginfo->strend)) {
2367 SB_enum before = getSB_VAL_UTF8(reghop3((U8*)s,
2369 (U8*)(reginfo->strbeg)),
2370 (U8*) reginfo->strend);
2371 while (s < strend) {
2372 SB_enum after = getSB_VAL_UTF8((U8*) s,
2373 (U8*) reginfo->strend);
2374 if ((to_complement ^ isSB(before,
2376 (U8*) reginfo->strbeg,
2378 (U8*) reginfo->strend,
2380 && (reginfo->intuit || regtry(reginfo, &s)))
2388 else { /* Not utf8. */
2389 SB_enum before = getSB_VAL_CP((U8) *(s -1));
2390 while (s < strend) {
2391 SB_enum after = getSB_VAL_CP((U8) *s);
2392 if ((to_complement ^ isSB(before,
2394 (U8*) reginfo->strbeg,
2396 (U8*) reginfo->strend,
2398 && (reginfo->intuit || regtry(reginfo, &s)))
2407 /* Here are at the final position in the target string. The SB
2408 * value is always true here, so matches, depending on other
2410 if (reginfo->intuit || regtry(reginfo, &s)) {
2417 if (s == reginfo->strbeg) {
2418 if (reginfo->intuit || regtry(reginfo, &s)) {
2421 s += (utf8_target) ? UTF8SKIP(s) : 1;
2422 if (UNLIKELY(s >= reginfo->strend)) {
2428 /* We are at a boundary between char_sub_0 and char_sub_1.
2429 * We also keep track of the value for char_sub_-1 as we
2430 * loop through the line. Context may be needed to make a
2431 * determination, and if so, this can save having to
2433 WB_enum previous = WB_UNKNOWN;
2434 WB_enum before = getWB_VAL_UTF8(
2437 (U8*)(reginfo->strbeg)),
2438 (U8*) reginfo->strend);
2439 while (s < strend) {
2440 WB_enum after = getWB_VAL_UTF8((U8*) s,
2441 (U8*) reginfo->strend);
2442 if ((to_complement ^ isWB(previous,
2445 (U8*) reginfo->strbeg,
2447 (U8*) reginfo->strend,
2449 && (reginfo->intuit || regtry(reginfo, &s)))
2458 else { /* Not utf8. */
2459 WB_enum previous = WB_UNKNOWN;
2460 WB_enum before = getWB_VAL_CP((U8) *(s -1));
2461 while (s < strend) {
2462 WB_enum after = getWB_VAL_CP((U8) *s);
2463 if ((to_complement ^ isWB(previous,
2466 (U8*) reginfo->strbeg,
2468 (U8*) reginfo->strend,
2470 && (reginfo->intuit || regtry(reginfo, &s)))
2480 if (reginfo->intuit || regtry(reginfo, &s)) {
2487 REXEC_FBC_CSCAN(is_LNBREAK_utf8_safe(s, strend),
2488 is_LNBREAK_latin1_safe(s, strend)
2493 s = find_next_ascii(s, strend, utf8_target);
2494 if (s < strend && (reginfo->intuit || regtry(reginfo, &s))) {
2501 s = find_next_non_ascii(s, strend, utf8_target);
2502 if (s < strend && (reginfo->intuit || regtry(reginfo, &s))) {
2508 /* The argument to all the POSIX node types is the class number to pass to
2509 * _generic_isCC() to build a mask for searching in PL_charclass[] */
2516 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2517 REXEC_FBC_CSCAN(to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(c), (U8 *) s)),
2518 to_complement ^ cBOOL(isFOO_lc(FLAGS(c), *s)));
2533 /* The complement of something that matches only ASCII matches all
2534 * non-ASCII, plus everything in ASCII that isn't in the class. */
2535 REXEC_FBC_UTF8_CLASS_SCAN( ! isASCII_utf8_safe(s, strend)
2536 || ! _generic_isCC_A(*s, FLAGS(c)));
2544 /* Don't need to worry about utf8, as it can match only a single
2545 * byte invariant character. But we do anyway for performance reasons,
2546 * as otherwise we would have to examine all the continuation
2549 REXEC_FBC_UTF8_CLASS_SCAN(_generic_isCC_A(*s, FLAGS(c)));
2554 REXEC_FBC_CLASS_SCAN(
2555 to_complement ^ cBOOL(_generic_isCC_A(*s, FLAGS(c))));
2563 if (! utf8_target) {
2564 REXEC_FBC_CLASS_SCAN(to_complement ^ cBOOL(_generic_isCC(*s,
2570 classnum = (_char_class_number) FLAGS(c);
2571 if (classnum < _FIRST_NON_SWASH_CC) {
2572 while (s < strend) {
2574 /* We avoid loading in the swash as long as possible, but
2575 * should we have to, we jump to a separate loop. This
2576 * extra 'if' statement is what keeps this code from being
2577 * just a call to REXEC_FBC_UTF8_CLASS_SCAN() */
2578 if (UTF8_IS_ABOVE_LATIN1(*s)) {
2579 goto found_above_latin1;
2581 if ((UTF8_IS_INVARIANT(*s)
2582 && to_complement ^ cBOOL(_generic_isCC((U8) *s,
2584 || ( UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(s, strend)
2585 && to_complement ^ cBOOL(
2586 _generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(*s,
2590 if (tmp && (reginfo->intuit || regtry(reginfo, &s)))
2602 else switch (classnum) { /* These classes are implemented as
2604 case _CC_ENUM_SPACE:
2605 REXEC_FBC_UTF8_CLASS_SCAN(
2606 to_complement ^ cBOOL(isSPACE_utf8_safe(s, strend)));
2609 case _CC_ENUM_BLANK:
2610 REXEC_FBC_UTF8_CLASS_SCAN(
2611 to_complement ^ cBOOL(isBLANK_utf8_safe(s, strend)));
2614 case _CC_ENUM_XDIGIT:
2615 REXEC_FBC_UTF8_CLASS_SCAN(
2616 to_complement ^ cBOOL(isXDIGIT_utf8_safe(s, strend)));
2619 case _CC_ENUM_VERTSPACE:
2620 REXEC_FBC_UTF8_CLASS_SCAN(
2621 to_complement ^ cBOOL(isVERTWS_utf8_safe(s, strend)));
2624 case _CC_ENUM_CNTRL:
2625 REXEC_FBC_UTF8_CLASS_SCAN(
2626 to_complement ^ cBOOL(isCNTRL_utf8_safe(s, strend)));
2630 Perl_croak(aTHX_ "panic: find_byclass() node %d='%s' has an unexpected character class '%d'", OP(c), PL_reg_name[OP(c)], classnum);
2631 NOT_REACHED; /* NOTREACHED */
2636 found_above_latin1: /* Here we have to load a swash to get the result
2637 for the current code point */
2638 if (! PL_utf8_swash_ptrs[classnum]) {
2639 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
2640 PL_utf8_swash_ptrs[classnum] =
2641 _core_swash_init("utf8",
2644 PL_XPosix_ptrs[classnum], &flags);
2647 /* This is a copy of the loop above for swash classes, though using the
2648 * FBC macro instead of being expanded out. Since we've loaded the
2649 * swash, we don't have to check for that each time through the loop */
2650 REXEC_FBC_UTF8_CLASS_SCAN(
2651 to_complement ^ cBOOL(_generic_utf8_safe(
2655 swash_fetch(PL_utf8_swash_ptrs[classnum],
2663 /* what trie are we using right now */
2664 reg_ac_data *aho = (reg_ac_data*)progi->data->data[ ARG( c ) ];
2665 reg_trie_data *trie = (reg_trie_data*)progi->data->data[ aho->trie ];
2666 HV *widecharmap = MUTABLE_HV(progi->data->data[ aho->trie + 1 ]);
2668 const char *last_start = strend - trie->minlen;
2670 const char *real_start = s;
2672 STRLEN maxlen = trie->maxlen;
2674 U8 **points; /* map of where we were in the input string
2675 when reading a given char. For ASCII this
2676 is unnecessary overhead as the relationship
2677 is always 1:1, but for Unicode, especially
2678 case folded Unicode this is not true. */
2679 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
2683 GET_RE_DEBUG_FLAGS_DECL;
2685 /* We can't just allocate points here. We need to wrap it in
2686 * an SV so it gets freed properly if there is a croak while
2687 * running the match */
2690 sv_points=newSV(maxlen * sizeof(U8 *));
2691 SvCUR_set(sv_points,
2692 maxlen * sizeof(U8 *));
2693 SvPOK_on(sv_points);
2694 sv_2mortal(sv_points);
2695 points=(U8**)SvPV_nolen(sv_points );
2696 if ( trie_type != trie_utf8_fold
2697 && (trie->bitmap || OP(c)==AHOCORASICKC) )
2700 bitmap=(U8*)trie->bitmap;
2702 bitmap=(U8*)ANYOF_BITMAP(c);
2704 /* this is the Aho-Corasick algorithm modified a touch
2705 to include special handling for long "unknown char" sequences.
2706 The basic idea being that we use AC as long as we are dealing
2707 with a possible matching char, when we encounter an unknown char
2708 (and we have not encountered an accepting state) we scan forward
2709 until we find a legal starting char.
2710 AC matching is basically that of trie matching, except that when
2711 we encounter a failing transition, we fall back to the current
2712 states "fail state", and try the current char again, a process
2713 we repeat until we reach the root state, state 1, or a legal
2714 transition. If we fail on the root state then we can either
2715 terminate if we have reached an accepting state previously, or
2716 restart the entire process from the beginning if we have not.
2719 while (s <= last_start) {
2720 const U32 uniflags = UTF8_ALLOW_DEFAULT;
2728 U8 *uscan = (U8*)NULL;
2729 U8 *leftmost = NULL;
2731 U32 accepted_word= 0;
2735 while ( state && uc <= (U8*)strend ) {
2737 U32 word = aho->states[ state ].wordnum;
2741 DEBUG_TRIE_EXECUTE_r(
2742 if ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2743 dump_exec_pos( (char *)uc, c, strend, real_start,
2744 (char *)uc, utf8_target, 0 );
2745 Perl_re_printf( aTHX_
2746 " Scanning for legal start char...\n");
2750 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2754 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2760 if (uc >(U8*)last_start) break;
2764 U8 *lpos= points[ (pointpos - trie->wordinfo[word].len) % maxlen ];
2765 if (!leftmost || lpos < leftmost) {
2766 DEBUG_r(accepted_word=word);
2772 points[pointpos++ % maxlen]= uc;
2773 if (foldlen || uc < (U8*)strend) {
2774 REXEC_TRIE_READ_CHAR(trie_type, trie,
2776 uscan, len, uvc, charid, foldlen,
2778 DEBUG_TRIE_EXECUTE_r({
2779 dump_exec_pos( (char *)uc, c, strend,
2780 real_start, s, utf8_target, 0);
2781 Perl_re_printf( aTHX_
2782 " Charid:%3u CP:%4" UVxf " ",
2794 word = aho->states[ state ].wordnum;
2796 base = aho->states[ state ].trans.base;
2798 DEBUG_TRIE_EXECUTE_r({
2800 dump_exec_pos( (char *)uc, c, strend, real_start,
2801 s, utf8_target, 0 );
2802 Perl_re_printf( aTHX_
2803 "%sState: %4" UVxf ", word=%" UVxf,
2804 failed ? " Fail transition to " : "",
2805 (UV)state, (UV)word);
2811 ( ((offset = base + charid
2812 - 1 - trie->uniquecharcount)) >= 0)
2813 && ((U32)offset < trie->lasttrans)
2814 && trie->trans[offset].check == state
2815 && (tmp=trie->trans[offset].next))
2817 DEBUG_TRIE_EXECUTE_r(
2818 Perl_re_printf( aTHX_ " - legal\n"));
2823 DEBUG_TRIE_EXECUTE_r(
2824 Perl_re_printf( aTHX_ " - fail\n"));
2826 state = aho->fail[state];
2830 /* we must be accepting here */
2831 DEBUG_TRIE_EXECUTE_r(
2832 Perl_re_printf( aTHX_ " - accepting\n"));
2841 if (!state) state = 1;
2844 if ( aho->states[ state ].wordnum ) {
2845 U8 *lpos = points[ (pointpos - trie->wordinfo[aho->states[ state ].wordnum].len) % maxlen ];
2846 if (!leftmost || lpos < leftmost) {
2847 DEBUG_r(accepted_word=aho->states[ state ].wordnum);
2852 s = (char*)leftmost;
2853 DEBUG_TRIE_EXECUTE_r({
2854 Perl_re_printf( aTHX_ "Matches word #%" UVxf " at position %" IVdf ". Trying full pattern...\n",
2855 (UV)accepted_word, (IV)(s - real_start)
2858 if (reginfo->intuit || regtry(reginfo, &s)) {
2864 DEBUG_TRIE_EXECUTE_r({
2865 Perl_re_printf( aTHX_ "Pattern failed. Looking for new start point...\n");
2868 DEBUG_TRIE_EXECUTE_r(
2869 Perl_re_printf( aTHX_ "No match.\n"));
2878 Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
2885 /* set RX_SAVED_COPY, RX_SUBBEG etc.
2886 * flags have same meanings as with regexec_flags() */
2889 S_reg_set_capture_string(pTHX_ REGEXP * const rx,
2896 struct regexp *const prog = ReANY(rx);
2898 if (flags & REXEC_COPY_STR) {
2901 DEBUG_C(Perl_re_printf( aTHX_
2902 "Copy on write: regexp capture, type %d\n",
2904 /* Create a new COW SV to share the match string and store
2905 * in saved_copy, unless the current COW SV in saved_copy
2906 * is valid and suitable for our purpose */
2907 if (( prog->saved_copy
2908 && SvIsCOW(prog->saved_copy)
2909 && SvPOKp(prog->saved_copy)
2912 && SvPVX(sv) == SvPVX(prog->saved_copy)))
2914 /* just reuse saved_copy SV */
2915 if (RXp_MATCH_COPIED(prog)) {
2916 Safefree(prog->subbeg);
2917 RXp_MATCH_COPIED_off(prog);
2921 /* create new COW SV to share string */
2922 RXp_MATCH_COPY_FREE(prog);
2923 prog->saved_copy = sv_setsv_cow(prog->saved_copy, sv);
2925 prog->subbeg = (char *)SvPVX_const(prog->saved_copy);
2926 assert (SvPOKp(prog->saved_copy));
2927 prog->sublen = strend - strbeg;
2928 prog->suboffset = 0;
2929 prog->subcoffset = 0;
2934 SSize_t max = strend - strbeg;
2937 if ( (flags & REXEC_COPY_SKIP_POST)
2938 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2939 && !(PL_sawampersand & SAWAMPERSAND_RIGHT)
2940 ) { /* don't copy $' part of string */
2943 /* calculate the right-most part of the string covered
2944 * by a capture. Due to lookahead, this may be to
2945 * the right of $&, so we have to scan all captures */
2946 while (n <= prog->lastparen) {
2947 if (prog->offs[n].end > max)
2948 max = prog->offs[n].end;
2952 max = (PL_sawampersand & SAWAMPERSAND_LEFT)
2953 ? prog->offs[0].start
2955 assert(max >= 0 && max <= strend - strbeg);
2958 if ( (flags & REXEC_COPY_SKIP_PRE)
2959 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2960 && !(PL_sawampersand & SAWAMPERSAND_LEFT)
2961 ) { /* don't copy $` part of string */
2964 /* calculate the left-most part of the string covered
2965 * by a capture. Due to lookbehind, this may be to
2966 * the left of $&, so we have to scan all captures */
2967 while (min && n <= prog->lastparen) {
2968 if ( prog->offs[n].start != -1
2969 && prog->offs[n].start < min)
2971 min = prog->offs[n].start;
2975 if ((PL_sawampersand & SAWAMPERSAND_RIGHT)
2976 && min > prog->offs[0].end
2978 min = prog->offs[0].end;
2982 assert(min >= 0 && min <= max && min <= strend - strbeg);
2985 if (RXp_MATCH_COPIED(prog)) {
2986 if (sublen > prog->sublen)
2988 (char*)saferealloc(prog->subbeg, sublen+1);
2991 prog->subbeg = (char*)safemalloc(sublen+1);
2992 Copy(strbeg + min, prog->subbeg, sublen, char);
2993 prog->subbeg[sublen] = '\0';
2994 prog->suboffset = min;
2995 prog->sublen = sublen;
2996 RXp_MATCH_COPIED_on(prog);
2998 prog->subcoffset = prog->suboffset;
2999 if (prog->suboffset && utf8_target) {
3000 /* Convert byte offset to chars.
3001 * XXX ideally should only compute this if @-/@+
3002 * has been seen, a la PL_sawampersand ??? */
3004 /* If there's a direct correspondence between the
3005 * string which we're matching and the original SV,
3006 * then we can use the utf8 len cache associated with
3007 * the SV. In particular, it means that under //g,
3008 * sv_pos_b2u() will use the previously cached
3009 * position to speed up working out the new length of
3010 * subcoffset, rather than counting from the start of
3011 * the string each time. This stops
3012 * $x = "\x{100}" x 1E6; 1 while $x =~ /(.)/g;
3013 * from going quadratic */
3014 if (SvPOKp(sv) && SvPVX(sv) == strbeg)
3015 prog->subcoffset = sv_pos_b2u_flags(sv, prog->subcoffset,
3016 SV_GMAGIC|SV_CONST_RETURN);
3018 prog->subcoffset = utf8_length((U8*)strbeg,
3019 (U8*)(strbeg+prog->suboffset));
3023 RXp_MATCH_COPY_FREE(prog);
3024 prog->subbeg = strbeg;
3025 prog->suboffset = 0;
3026 prog->subcoffset = 0;
3027 prog->sublen = strend - strbeg;
3035 - regexec_flags - match a regexp against a string
3038 Perl_regexec_flags(pTHX_ REGEXP * const rx, char *stringarg, char *strend,
3039 char *strbeg, SSize_t minend, SV *sv, void *data, U32 flags)
3040 /* stringarg: the point in the string at which to begin matching */
3041 /* strend: pointer to null at end of string */
3042 /* strbeg: real beginning of string */
3043 /* minend: end of match must be >= minend bytes after stringarg. */
3044 /* sv: SV being matched: only used for utf8 flag, pos() etc; string
3045 * itself is accessed via the pointers above */
3046 /* data: May be used for some additional optimizations.
3047 Currently unused. */
3048 /* flags: For optimizations. See REXEC_* in regexp.h */
3051 struct regexp *const prog = ReANY(rx);
3055 SSize_t minlen; /* must match at least this many chars */
3056 SSize_t dontbother = 0; /* how many characters not to try at end */
3057 const bool utf8_target = cBOOL(DO_UTF8(sv));
3059 RXi_GET_DECL(prog,progi);
3060 regmatch_info reginfo_buf; /* create some info to pass to regtry etc */
3061 regmatch_info *const reginfo = ®info_buf;
3062 regexp_paren_pair *swap = NULL;
3064 GET_RE_DEBUG_FLAGS_DECL;
3066 PERL_ARGS_ASSERT_REGEXEC_FLAGS;
3067 PERL_UNUSED_ARG(data);
3069 /* Be paranoid... */
3071 Perl_croak(aTHX_ "NULL regexp parameter");
3075 debug_start_match(rx, utf8_target, stringarg, strend,
3079 startpos = stringarg;
3081 /* set these early as they may be used by the HOP macros below */
3082 reginfo->strbeg = strbeg;
3083 reginfo->strend = strend;
3084 reginfo->is_utf8_target = cBOOL(utf8_target);
3086 if (prog->intflags & PREGf_GPOS_SEEN) {
3089 /* set reginfo->ganch, the position where \G can match */
3092 (flags & REXEC_IGNOREPOS)
3093 ? stringarg /* use start pos rather than pos() */
3094 : ((mg = mg_find_mglob(sv)) && mg->mg_len >= 0)
3095 /* Defined pos(): */
3096 ? strbeg + MgBYTEPOS(mg, sv, strbeg, strend-strbeg)
3097 : strbeg; /* pos() not defined; use start of string */
3099 DEBUG_GPOS_r(Perl_re_printf( aTHX_
3100 "GPOS ganch set to strbeg[%" IVdf "]\n", (IV)(reginfo->ganch - strbeg)));
3102 /* in the presence of \G, we may need to start looking earlier in
3103 * the string than the suggested start point of stringarg:
3104 * if prog->gofs is set, then that's a known, fixed minimum
3107 * /ab|c\G/: gofs = 1
3108 * or if the minimum offset isn't known, then we have to go back
3109 * to the start of the string, e.g. /w+\G/
3112 if (prog->intflags & PREGf_ANCH_GPOS) {
3114 startpos = HOPBACKc(reginfo->ganch, prog->gofs);
3116 ((flags & REXEC_FAIL_ON_UNDERFLOW) && startpos < stringarg))
3118 DEBUG_r(Perl_re_printf( aTHX_
3119 "fail: ganch-gofs before earliest possible start\n"));
3124 startpos = reginfo->ganch;
3126 else if (prog->gofs) {
3127 startpos = HOPBACKc(startpos, prog->gofs);
3131 else if (prog->intflags & PREGf_GPOS_FLOAT)
3135 minlen = prog->minlen;
3136 if ((startpos + minlen) > strend || startpos < strbeg) {
3137 DEBUG_r(Perl_re_printf( aTHX_
3138 "Regex match can't succeed, so not even tried\n"));
3142 /* at the end of this function, we'll do a LEAVE_SCOPE(oldsave),
3143 * which will call destuctors to reset PL_regmatch_state, free higher
3144 * PL_regmatch_slabs, and clean up regmatch_info_aux and
3145 * regmatch_info_aux_eval */
3147 oldsave = PL_savestack_ix;
3151 if ((prog->extflags & RXf_USE_INTUIT)
3152 && !(flags & REXEC_CHECKED))
3154 s = re_intuit_start(rx, sv, strbeg, startpos, strend,
3159 if (prog->extflags & RXf_CHECK_ALL) {
3160 /* we can match based purely on the result of INTUIT.
3161 * Set up captures etc just for $& and $-[0]
3162 * (an intuit-only match wont have $1,$2,..) */
3163 assert(!prog->nparens);
3165 /* s/// doesn't like it if $& is earlier than where we asked it to
3166 * start searching (which can happen on something like /.\G/) */
3167 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
3170 /* this should only be possible under \G */
3171 assert(prog->intflags & PREGf_GPOS_SEEN);
3172 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
3173 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3177 /* match via INTUIT shouldn't have any captures.
3178 * Let @-, @+, $^N know */
3179 prog->lastparen = prog->lastcloseparen = 0;
3180 RXp_MATCH_UTF8_set(prog, utf8_target);
3181 prog->offs[0].start = s - strbeg;
3182 prog->offs[0].end = utf8_target
3183 ? (char*)utf8_hop((U8*)s, prog->minlenret) - strbeg
3184 : s - strbeg + prog->minlenret;
3185 if ( !(flags & REXEC_NOT_FIRST) )
3186 S_reg_set_capture_string(aTHX_ rx,
3188 sv, flags, utf8_target);
3194 multiline = prog->extflags & RXf_PMf_MULTILINE;
3196 if (strend - s < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
3197 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
3198 "String too short [regexec_flags]...\n"));
3202 /* Check validity of program. */
3203 if (UCHARAT(progi->program) != REG_MAGIC) {
3204 Perl_croak(aTHX_ "corrupted regexp program");
3207 RXp_MATCH_TAINTED_off(prog);
3208 RXp_MATCH_UTF8_set(prog, utf8_target);
3210 reginfo->prog = rx; /* Yes, sorry that this is confusing. */
3211 reginfo->intuit = 0;
3212 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
3213 reginfo->warned = FALSE;
3215 reginfo->poscache_maxiter = 0; /* not yet started a countdown */
3216 /* see how far we have to get to not match where we matched before */
3217 reginfo->till = stringarg + minend;
3219 if (prog->extflags & RXf_EVAL_SEEN && SvPADTMP(sv)) {
3220 /* SAVEFREESV, not sv_mortalcopy, as this SV must last until after
3221 S_cleanup_regmatch_info_aux has executed (registered by
3222 SAVEDESTRUCTOR_X below). S_cleanup_regmatch_info_aux modifies
3223 magic belonging to this SV.
3224 Not newSVsv, either, as it does not COW.
3226 reginfo->sv = newSV(0);
3227 SvSetSV_nosteal(reginfo->sv, sv);
3228 SAVEFREESV(reginfo->sv);
3231 /* reserve next 2 or 3 slots in PL_regmatch_state:
3232 * slot N+0: may currently be in use: skip it
3233 * slot N+1: use for regmatch_info_aux struct
3234 * slot N+2: use for regmatch_info_aux_eval struct if we have (?{})'s
3235 * slot N+3: ready for use by regmatch()
3239 regmatch_state *old_regmatch_state;
3240 regmatch_slab *old_regmatch_slab;
3241 int i, max = (prog->extflags & RXf_EVAL_SEEN) ? 2 : 1;
3243 /* on first ever match, allocate first slab */
3244 if (!PL_regmatch_slab) {
3245 Newx(PL_regmatch_slab, 1, regmatch_slab);
3246 PL_regmatch_slab->prev = NULL;
3247 PL_regmatch_slab->next = NULL;
3248 PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
3251 old_regmatch_state = PL_regmatch_state;
3252 old_regmatch_slab = PL_regmatch_slab;
3254 for (i=0; i <= max; i++) {
3256 reginfo->info_aux = &(PL_regmatch_state->u.info_aux);
3258 reginfo->info_aux_eval =
3259 reginfo->info_aux->info_aux_eval =
3260 &(PL_regmatch_state->u.info_aux_eval);
3262 if (++PL_regmatch_state > SLAB_LAST(PL_regmatch_slab))
3263 PL_regmatch_state = S_push_slab(aTHX);
3266 /* note initial PL_regmatch_state position; at end of match we'll
3267 * pop back to there and free any higher slabs */
3269 reginfo->info_aux->old_regmatch_state = old_regmatch_state;
3270 reginfo->info_aux->old_regmatch_slab = old_regmatch_slab;
3271 reginfo->info_aux->poscache = NULL;
3273 SAVEDESTRUCTOR_X(S_cleanup_regmatch_info_aux, reginfo->info_aux);
3275 if ((prog->extflags & RXf_EVAL_SEEN))
3276 S_setup_eval_state(aTHX_ reginfo);
3278 reginfo->info_aux_eval = reginfo->info_aux->info_aux_eval = NULL;
3281 /* If there is a "must appear" string, look for it. */
3283 if (PL_curpm && (PM_GETRE(PL_curpm) == rx)) {
3284 /* We have to be careful. If the previous successful match
3285 was from this regex we don't want a subsequent partially
3286 successful match to clobber the old results.
3287 So when we detect this possibility we add a swap buffer
3288 to the re, and switch the buffer each match. If we fail,
3289 we switch it back; otherwise we leave it swapped.
3292 /* do we need a save destructor here for eval dies? */
3293 Newxz(prog->offs, (prog->nparens + 1), regexp_paren_pair);
3294 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_
3295 "rex=0x%" UVxf " saving offs: orig=0x%" UVxf " new=0x%" UVxf "\n",
3303 if (prog->recurse_locinput)
3304 Zero(prog->recurse_locinput,prog->nparens + 1, char *);
3306 /* Simplest case: anchored match need be tried only once, or with
3307 * MBOL, only at the beginning of each line.
3309 * Note that /.*.../ sets PREGf_IMPLICIT|MBOL, while /.*.../s sets
3310 * PREGf_IMPLICIT|SBOL. The idea is that with /.*.../s, if it doesn't
3311 * match at the start of the string then it won't match anywhere else
3312 * either; while with /.*.../, if it doesn't match at the beginning,
3313 * the earliest it could match is at the start of the next line */
3315 if (prog->intflags & (PREGf_ANCH & ~PREGf_ANCH_GPOS)) {
3318 if (regtry(reginfo, &s))
3321 if (!(prog->intflags & PREGf_ANCH_MBOL))
3324 /* didn't match at start, try at other newline positions */
3327 dontbother = minlen - 1;
3328 end = HOP3c(strend, -dontbother, strbeg) - 1;
3330 /* skip to next newline */
3332 while (s <= end) { /* note it could be possible to match at the end of the string */
3333 /* NB: newlines are the same in unicode as they are in latin */
3336 if (prog->check_substr || prog->check_utf8) {
3337 /* note that with PREGf_IMPLICIT, intuit can only fail
3338 * or return the start position, so it's of limited utility.
3339 * Nevertheless, I made the decision that the potential for
3340 * quick fail was still worth it - DAPM */
3341 s = re_intuit_start(rx, sv, strbeg, s, strend, flags, NULL);
3345 if (regtry(reginfo, &s))
3349 } /* end anchored search */
3351 if (prog->intflags & PREGf_ANCH_GPOS)
3353 /* PREGf_ANCH_GPOS should never be true if PREGf_GPOS_SEEN is not true */
3354 assert(prog->intflags & PREGf_GPOS_SEEN);
3355 /* For anchored \G, the only position it can match from is
3356 * (ganch-gofs); we already set startpos to this above; if intuit
3357 * moved us on from there, we can't possibly succeed */
3358 assert(startpos == HOPBACKc(reginfo->ganch, prog->gofs));
3359 if (s == startpos && regtry(reginfo, &s))
3364 /* Messy cases: unanchored match. */
3365 if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
3366 /* we have /x+whatever/ */
3367 /* it must be a one character string (XXXX Except is_utf8_pat?) */
3373 if (! prog->anchored_utf8) {
3374 to_utf8_substr(prog);
3376 ch = SvPVX_const(prog->anchored_utf8)[0];
3379 DEBUG_EXECUTE_r( did_match = 1 );
3380 if (regtry(reginfo, &s)) goto got_it;
3382 while (s < strend && *s == ch)
3389 if (! prog->anchored_substr) {
3390 if (! to_byte_substr(prog)) {
3391 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3394 ch = SvPVX_const(prog->anchored_substr)[0];
3397 DEBUG_EXECUTE_r( did_match = 1 );
3398 if (regtry(reginfo, &s)) goto got_it;
3400 while (s < strend && *s == ch)
3405 DEBUG_EXECUTE_r(if (!did_match)
3406 Perl_re_printf( aTHX_
3407 "Did not find anchored character...\n")
3410 else if (prog->anchored_substr != NULL
3411 || prog->anchored_utf8 != NULL
3412 || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
3413 && prog->float_max_offset < strend - s)) {
3418 char *last1; /* Last position checked before */
3422 if (prog->anchored_substr || prog->anchored_utf8) {
3424 if (! prog->anchored_utf8) {
3425 to_utf8_substr(prog);
3427 must = prog->anchored_utf8;
3430 if (! prog->anchored_substr) {
3431 if (! to_byte_substr(prog)) {
3432 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3435 must = prog->anchored_substr;
3437 back_max = back_min = prog->anchored_offset;
3440 if (! prog->float_utf8) {
3441 to_utf8_substr(prog);
3443 must = prog->float_utf8;
3446 if (! prog->float_substr) {
3447 if (! to_byte_substr(prog)) {
3448 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3451 must = prog->float_substr;
3453 back_max = prog->float_max_offset;
3454 back_min = prog->float_min_offset;
3460 last = HOP3c(strend, /* Cannot start after this */
3461 -(SSize_t)(CHR_SVLEN(must)
3462 - (SvTAIL(must) != 0) + back_min), strbeg);
3464 if (s > reginfo->strbeg)
3465 last1 = HOPc(s, -1);
3467 last1 = s - 1; /* bogus */
3469 /* XXXX check_substr already used to find "s", can optimize if
3470 check_substr==must. */
3472 strend = HOPc(strend, -dontbother);
3473 while ( (s <= last) &&
3474 (s = fbm_instr((unsigned char*)HOP4c(s, back_min, strbeg, strend),
3475 (unsigned char*)strend, must,
3476 multiline ? FBMrf_MULTILINE : 0)) ) {
3477 DEBUG_EXECUTE_r( did_match = 1 );
3478 if (HOPc(s, -back_max) > last1) {
3479 last1 = HOPc(s, -back_min);
3480 s = HOPc(s, -back_max);
3483 char * const t = (last1 >= reginfo->strbeg)
3484 ? HOPc(last1, 1) : last1 + 1;
3486 last1 = HOPc(s, -back_min);
3490 while (s <= last1) {
3491 if (regtry(reginfo, &s))
3494 s++; /* to break out of outer loop */
3501 while (s <= last1) {
3502 if (regtry(reginfo, &s))
3508 DEBUG_EXECUTE_r(if (!did_match) {
3509 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
3510 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
3511 Perl_re_printf( aTHX_ "Did not find %s substr %s%s...\n",
3512 ((must == prog->anchored_substr || must == prog->anchored_utf8)
3513 ? "anchored" : "floating"),
3514 quoted, RE_SV_TAIL(must));
3518 else if ( (c = progi->regstclass) ) {
3520 const OPCODE op = OP(progi->regstclass);
3521 /* don't bother with what can't match */
3522 if (PL_regkind[op] != EXACT && PL_regkind[op] != TRIE)
3523 strend = HOPc(strend, -(minlen - 1));
3526 SV * const prop = sv_newmortal();
3527 regprop(prog, prop, c, reginfo, NULL);
3529 RE_PV_QUOTED_DECL(quoted,utf8_target,PERL_DEBUG_PAD_ZERO(1),
3530 s,strend-s,PL_dump_re_max_len);
3531 Perl_re_printf( aTHX_
3532 "Matching stclass %.*s against %s (%d bytes)\n",
3533 (int)SvCUR(prop), SvPVX_const(prop),
3534 quoted, (int)(strend - s));
3537 if (find_byclass(prog, c, s, strend, reginfo))
3539 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "Contradicts stclass... [regexec_flags]\n"));
3543 if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
3551 if (! prog->float_utf8) {
3552 to_utf8_substr(prog);
3554 float_real = prog->float_utf8;
3557 if (! prog->float_substr) {
3558 if (! to_byte_substr(prog)) {
3559 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3562 float_real = prog->float_substr;
3565 little = SvPV_const(float_real, len);
3566 if (SvTAIL(float_real)) {
3567 /* This means that float_real contains an artificial \n on
3568 * the end due to the presence of something like this:
3569 * /foo$/ where we can match both "foo" and "foo\n" at the
3570 * end of the string. So we have to compare the end of the
3571 * string first against the float_real without the \n and
3572 * then against the full float_real with the string. We
3573 * have to watch out for cases where the string might be
3574 * smaller than the float_real or the float_real without
3576 char *checkpos= strend - len;
3578 Perl_re_printf( aTHX_
3579 "%sChecking for float_real.%s\n",
3580 PL_colors[4], PL_colors[5]));
3581 if (checkpos + 1 < strbeg) {
3582 /* can't match, even if we remove the trailing \n
3583 * string is too short to match */
3585 Perl_re_printf( aTHX_
3586 "%sString shorter than required trailing substring, cannot match.%s\n",
3587 PL_colors[4], PL_colors[5]));
3589 } else if (memEQ(checkpos + 1, little, len - 1)) {
3590 /* can match, the end of the string matches without the
3592 last = checkpos + 1;
3593 } else if (checkpos < strbeg) {
3594 /* cant match, string is too short when the "\n" is
3597 Perl_re_printf( aTHX_
3598 "%sString does not contain required trailing substring, cannot match.%s\n",
3599 PL_colors[4], PL_colors[5]));
3601 } else if (!multiline) {
3602 /* non multiline match, so compare with the "\n" at the
3603 * end of the string */
3604 if (memEQ(checkpos, little, len)) {
3608 Perl_re_printf( aTHX_
3609 "%sString does not contain required trailing substring, cannot match.%s\n",
3610 PL_colors[4], PL_colors[5]));
3614 /* multiline match, so we have to search for a place
3615 * where the full string is located */
3621 last = rninstr(s, strend, little, little + len);
3623 last = strend; /* matching "$" */
3626 /* at one point this block contained a comment which was
3627 * probably incorrect, which said that this was a "should not
3628 * happen" case. Even if it was true when it was written I am
3629 * pretty sure it is not anymore, so I have removed the comment
3630 * and replaced it with this one. Yves */
3632 Perl_re_printf( aTHX_
3633 "%sString does not contain required substring, cannot match.%s\n",
3634 PL_colors[4], PL_colors[5]
3638 dontbother = strend - last + prog->float_min_offset;
3640 if (minlen && (dontbother < minlen))
3641 dontbother = minlen - 1;
3642 strend -= dontbother; /* this one's always in bytes! */
3643 /* We don't know much -- general case. */
3646 if (regtry(reginfo, &s))
3655 if (regtry(reginfo, &s))
3657 } while (s++ < strend);
3665 /* s/// doesn't like it if $& is earlier than where we asked it to
3666 * start searching (which can happen on something like /.\G/) */
3667 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
3668 && (prog->offs[0].start < stringarg - strbeg))
3670 /* this should only be possible under \G */
3671 assert(prog->intflags & PREGf_GPOS_SEEN);
3672 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
3673 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3679 Perl_re_exec_indentf( aTHX_
3680 "rex=0x%" UVxf " freeing offs: 0x%" UVxf "\n",
3688 /* clean up; this will trigger destructors that will free all slabs
3689 * above the current one, and cleanup the regmatch_info_aux
3690 * and regmatch_info_aux_eval sructs */
3692 LEAVE_SCOPE(oldsave);
3694 if (RXp_PAREN_NAMES(prog))
3695 (void)hv_iterinit(RXp_PAREN_NAMES(prog));
3697 /* make sure $`, $&, $', and $digit will work later */
3698 if ( !(flags & REXEC_NOT_FIRST) )
3699 S_reg_set_capture_string(aTHX_ rx,
3700 strbeg, reginfo->strend,
3701 sv, flags, utf8_target);
3706 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%sMatch failed%s\n",
3707 PL_colors[4], PL_colors[5]));
3709 /* clean up; this will trigger destructors that will free all slabs
3710 * above the current one, and cleanup the regmatch_info_aux
3711 * and regmatch_info_aux_eval sructs */
3713 LEAVE_SCOPE(oldsave);
3716 /* we failed :-( roll it back */
3717 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_
3718 "rex=0x%" UVxf " rolling back offs: freeing=0x%" UVxf " restoring=0x%" UVxf "\n",
3724 Safefree(prog->offs);
3731 /* Set which rex is pointed to by PL_reg_curpm, handling ref counting.
3732 * Do inc before dec, in case old and new rex are the same */
3733 #define SET_reg_curpm(Re2) \
3734 if (reginfo->info_aux_eval) { \
3735 (void)ReREFCNT_inc(Re2); \
3736 ReREFCNT_dec(PM_GETRE(PL_reg_curpm)); \
3737 PM_SETRE((PL_reg_curpm), (Re2)); \
3742 - regtry - try match at specific point
3744 STATIC bool /* 0 failure, 1 success */
3745 S_regtry(pTHX_ regmatch_info *reginfo, char **startposp)
3748 REGEXP *const rx = reginfo->prog;
3749 regexp *const prog = ReANY(rx);
3752 U32 depth = 0; /* used by REGCP_SET */
3754 RXi_GET_DECL(prog,progi);
3755 GET_RE_DEBUG_FLAGS_DECL;
3757 PERL_ARGS_ASSERT_REGTRY;
3759 reginfo->cutpoint=NULL;
3761 prog->offs[0].start = *startposp - reginfo->strbeg;
3762 prog->lastparen = 0;
3763 prog->lastcloseparen = 0;
3765 /* XXXX What this code is doing here?!!! There should be no need
3766 to do this again and again, prog->lastparen should take care of
3769 /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
3770 * Actually, the code in regcppop() (which Ilya may be meaning by
3771 * prog->lastparen), is not needed at all by the test suite
3772 * (op/regexp, op/pat, op/split), but that code is needed otherwise
3773 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
3774 * Meanwhile, this code *is* needed for the
3775 * above-mentioned test suite tests to succeed. The common theme
3776 * on those tests seems to be returning null fields from matches.
3777 * --jhi updated by dapm */
3779 /* After encountering a variant of the issue mentioned above I think
3780 * the point Ilya was making is that if we properly unwind whenever
3781 * we set lastparen to a smaller value then we should not need to do
3782 * this every time, only when needed. So if we have tests that fail if
3783 * we remove this, then it suggests somewhere else we are improperly
3784 * unwinding the lastparen/paren buffers. See UNWIND_PARENS() and
3785 * places it is called, and related regcp() routines. - Yves */
3787 if (prog->nparens) {
3788 regexp_paren_pair *pp = prog->offs;
3790 for (i = prog->nparens; i > (I32)prog->lastparen; i--) {
3798 result = regmatch(reginfo, *startposp, progi->program + 1);
3800 prog->offs[0].end = result;
3803 if (reginfo->cutpoint)
3804 *startposp= reginfo->cutpoint;
3805 REGCP_UNWIND(lastcp);
3810 #define sayYES goto yes
3811 #define sayNO goto no
3812 #define sayNO_SILENT goto no_silent
3814 /* we dont use STMT_START/END here because it leads to
3815 "unreachable code" warnings, which are bogus, but distracting. */
3816 #define CACHEsayNO \
3817 if (ST.cache_mask) \
3818 reginfo->info_aux->poscache[ST.cache_offset] |= ST.cache_mask; \
3821 /* this is used to determine how far from the left messages like
3822 'failed...' are printed in regexec.c. It should be set such that
3823 messages are inline with the regop output that created them.
3825 #define REPORT_CODE_OFF 29
3826 #define INDENT_CHARS(depth) ((int)(depth) % 20)
3829 Perl_re_exec_indentf(pTHX_ const char *fmt, U32 depth, ...)
3833 PerlIO *f= Perl_debug_log;
3834 PERL_ARGS_ASSERT_RE_EXEC_INDENTF;
3835 va_start(ap, depth);
3836 PerlIO_printf(f, "%*s|%4" UVuf "| %*s", REPORT_CODE_OFF, "", (UV)depth, INDENT_CHARS(depth), "" );
3837 result = PerlIO_vprintf(f, fmt, ap);
3841 #endif /* DEBUGGING */