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 non_utf8_target_but_utf8_required[]
96 = "Can't match, because target string needs to be in UTF-8\n";
99 #define NON_UTF8_TARGET_BUT_UTF8_REQUIRED(target) STMT_START { \
100 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%s", non_utf8_target_but_utf8_required));\
104 #define HAS_NONLATIN1_FOLD_CLOSURE(i) _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
107 #define STATIC static
114 #define CHR_SVLEN(sv) (utf8_target ? sv_len_utf8(sv) : SvCUR(sv))
116 #define HOPc(pos,off) \
117 (char *)(reginfo->is_utf8_target \
118 ? reghop3((U8*)pos, off, \
119 (U8*)(off >= 0 ? reginfo->strend : reginfo->strbeg)) \
122 /* like HOPMAYBE3 but backwards. lim must be +ve. Returns NULL on overshoot */
123 #define HOPBACK3(pos, off, lim) \
124 (reginfo->is_utf8_target \
125 ? reghopmaybe3((U8*)pos, (SSize_t)0-off, (U8*)(lim)) \
126 : (pos - off >= lim) \
130 #define HOPBACKc(pos, off) ((char*)HOPBACK3(pos, off, reginfo->strbeg))
132 #define HOP3(pos,off,lim) (reginfo->is_utf8_target ? reghop3((U8*)(pos), off, (U8*)(lim)) : (U8*)(pos + off))
133 #define HOP3c(pos,off,lim) ((char*)HOP3(pos,off,lim))
135 /* lim must be +ve. Returns NULL on overshoot */
136 #define HOPMAYBE3(pos,off,lim) \
137 (reginfo->is_utf8_target \
138 ? reghopmaybe3((U8*)pos, off, (U8*)(lim)) \
139 : ((U8*)pos + off <= lim) \
143 /* like HOP3, but limits the result to <= lim even for the non-utf8 case.
144 * off must be >=0; args should be vars rather than expressions */
145 #define HOP3lim(pos,off,lim) (reginfo->is_utf8_target \
146 ? reghop3((U8*)(pos), off, (U8*)(lim)) \
147 : (U8*)((pos + off) > lim ? lim : (pos + off)))
148 #define HOP3clim(pos,off,lim) ((char*)HOP3lim(pos,off,lim))
150 #define HOP4(pos,off,llim, rlim) (reginfo->is_utf8_target \
151 ? reghop4((U8*)(pos), off, (U8*)(llim), (U8*)(rlim)) \
153 #define HOP4c(pos,off,llim, rlim) ((char*)HOP4(pos,off,llim, rlim))
155 #define PLACEHOLDER /* Something for the preprocessor to grab onto */
156 /* TODO: Combine JUMPABLE and HAS_TEXT to cache OP(rn) */
158 /* for use after a quantifier and before an EXACT-like node -- japhy */
159 /* it would be nice to rework regcomp.sym to generate this stuff. sigh
161 * NOTE that *nothing* that affects backtracking should be in here, specifically
162 * VERBS must NOT be included. JUMPABLE is used to determine if we can ignore a
163 * node that is in between two EXACT like nodes when ascertaining what the required
164 * "follow" character is. This should probably be moved to regex compile time
165 * although it may be done at run time beause of the REF possibility - more
166 * investigation required. -- demerphq
168 #define JUMPABLE(rn) ( \
170 (OP(rn) == CLOSE && \
171 !EVAL_CLOSE_PAREN_IS(cur_eval,ARG(rn)) ) || \
173 OP(rn) == SUSPEND || OP(rn) == IFMATCH || \
174 OP(rn) == PLUS || OP(rn) == MINMOD || \
176 (PL_regkind[OP(rn)] == CURLY && ARG1(rn) > 0) \
178 #define IS_EXACT(rn) (PL_regkind[OP(rn)] == EXACT)
180 #define HAS_TEXT(rn) ( IS_EXACT(rn) || PL_regkind[OP(rn)] == REF )
183 Search for mandatory following text node; for lookahead, the text must
184 follow but for lookbehind (rn->flags != 0) we skip to the next step.
186 #define FIND_NEXT_IMPT(rn) STMT_START { \
187 while (JUMPABLE(rn)) { \
188 const OPCODE type = OP(rn); \
189 if (type == SUSPEND || PL_regkind[type] == CURLY) \
190 rn = NEXTOPER(NEXTOPER(rn)); \
191 else if (type == PLUS) \
193 else if (type == IFMATCH) \
194 rn = (rn->flags == 0) ? NEXTOPER(NEXTOPER(rn)) : rn + ARG(rn); \
195 else rn += NEXT_OFF(rn); \
199 #define SLAB_FIRST(s) (&(s)->states[0])
200 #define SLAB_LAST(s) (&(s)->states[PERL_REGMATCH_SLAB_SLOTS-1])
202 static void S_setup_eval_state(pTHX_ regmatch_info *const reginfo);
203 static void S_cleanup_regmatch_info_aux(pTHX_ void *arg);
204 static regmatch_state * S_push_slab(pTHX);
206 #define REGCP_PAREN_ELEMS 3
207 #define REGCP_OTHER_ELEMS 3
208 #define REGCP_FRAME_ELEMS 1
209 /* REGCP_FRAME_ELEMS are not part of the REGCP_OTHER_ELEMS and
210 * are needed for the regexp context stack bookkeeping. */
213 S_regcppush(pTHX_ const regexp *rex, I32 parenfloor, U32 maxopenparen _pDEPTH)
215 const int retval = PL_savestack_ix;
216 const int paren_elems_to_push =
217 (maxopenparen - parenfloor) * REGCP_PAREN_ELEMS;
218 const UV total_elems = paren_elems_to_push + REGCP_OTHER_ELEMS;
219 const UV elems_shifted = total_elems << SAVE_TIGHT_SHIFT;
221 DECLARE_AND_GET_RE_DEBUG_FLAGS;
223 PERL_ARGS_ASSERT_REGCPPUSH;
225 if (paren_elems_to_push < 0)
226 Perl_croak(aTHX_ "panic: paren_elems_to_push, %i < 0, maxopenparen: %i parenfloor: %i REGCP_PAREN_ELEMS: %u",
227 (int)paren_elems_to_push, (int)maxopenparen,
228 (int)parenfloor, (unsigned)REGCP_PAREN_ELEMS);
230 if ((elems_shifted >> SAVE_TIGHT_SHIFT) != total_elems)
231 Perl_croak(aTHX_ "panic: paren_elems_to_push offset %" UVuf
232 " out of range (%lu-%ld)",
234 (unsigned long)maxopenparen,
237 SSGROW(total_elems + REGCP_FRAME_ELEMS);
240 if ((int)maxopenparen > (int)parenfloor)
241 Perl_re_exec_indentf( aTHX_
242 "rex=0x%" UVxf " offs=0x%" UVxf ": saving capture indices:\n",
248 for (p = parenfloor+1; p <= (I32)maxopenparen; p++) {
249 /* REGCP_PARENS_ELEMS are pushed per pairs of parentheses. */
250 SSPUSHIV(rex->offs[p].end);
251 SSPUSHIV(rex->offs[p].start);
252 SSPUSHINT(rex->offs[p].start_tmp);
253 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_
254 " \\%" UVuf ": %" IVdf "(%" IVdf ")..%" IVdf "\n",
257 (IV)rex->offs[p].start,
258 (IV)rex->offs[p].start_tmp,
262 /* REGCP_OTHER_ELEMS are pushed in any case, parentheses or no. */
263 SSPUSHINT(maxopenparen);
264 SSPUSHINT(rex->lastparen);
265 SSPUSHINT(rex->lastcloseparen);
266 SSPUSHUV(SAVEt_REGCONTEXT | elems_shifted); /* Magic cookie. */
271 /* These are needed since we do not localize EVAL nodes: */
272 #define REGCP_SET(cp) \
274 Perl_re_exec_indentf( aTHX_ \
275 "Setting an EVAL scope, savestack=%" IVdf ",\n", \
276 depth, (IV)PL_savestack_ix \
281 #define REGCP_UNWIND(cp) \
283 if (cp != PL_savestack_ix) \
284 Perl_re_exec_indentf( aTHX_ \
285 "Clearing an EVAL scope, savestack=%" \
286 IVdf "..%" IVdf "\n", \
287 depth, (IV)(cp), (IV)PL_savestack_ix \
292 /* set the start and end positions of capture ix */
293 #define CLOSE_CAPTURE(ix, s, e) \
294 rex->offs[ix].start = s; \
295 rex->offs[ix].end = e; \
296 if (ix > rex->lastparen) \
297 rex->lastparen = ix; \
298 rex->lastcloseparen = ix; \
299 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_ \
300 "CLOSE: rex=0x%" UVxf " offs=0x%" UVxf ": \\%" UVuf ": set %" IVdf "..%" IVdf " max: %" UVuf "\n", \
305 (IV)rex->offs[ix].start, \
306 (IV)rex->offs[ix].end, \
310 #define UNWIND_PAREN(lp, lcp) \
311 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_ \
312 "UNWIND_PAREN: rex=0x%" UVxf " offs=0x%" UVxf ": invalidate (%" UVuf "..%" UVuf "] set lcp: %" UVuf "\n", \
317 (UV)(rex->lastparen), \
320 for (n = rex->lastparen; n > lp; n--) \
321 rex->offs[n].end = -1; \
322 rex->lastparen = n; \
323 rex->lastcloseparen = lcp;
327 S_regcppop(pTHX_ regexp *rex, U32 *maxopenparen_p _pDEPTH)
331 DECLARE_AND_GET_RE_DEBUG_FLAGS;
333 PERL_ARGS_ASSERT_REGCPPOP;
335 /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
337 assert((i & SAVE_MASK) == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
338 i >>= SAVE_TIGHT_SHIFT; /* Parentheses elements to pop. */
339 rex->lastcloseparen = SSPOPINT;
340 rex->lastparen = SSPOPINT;
341 *maxopenparen_p = SSPOPINT;
343 i -= REGCP_OTHER_ELEMS;
344 /* Now restore the parentheses context. */
346 if (i || rex->lastparen + 1 <= rex->nparens)
347 Perl_re_exec_indentf( aTHX_
348 "rex=0x%" UVxf " offs=0x%" UVxf ": restoring capture indices to:\n",
354 paren = *maxopenparen_p;
355 for ( ; i > 0; i -= REGCP_PAREN_ELEMS) {
357 rex->offs[paren].start_tmp = SSPOPINT;
358 rex->offs[paren].start = SSPOPIV;
360 if (paren <= rex->lastparen)
361 rex->offs[paren].end = tmps;
362 DEBUG_BUFFERS_r( Perl_re_exec_indentf( aTHX_
363 " \\%" UVuf ": %" IVdf "(%" IVdf ")..%" IVdf "%s\n",
366 (IV)rex->offs[paren].start,
367 (IV)rex->offs[paren].start_tmp,
368 (IV)rex->offs[paren].end,
369 (paren > rex->lastparen ? "(skipped)" : ""));
374 /* It would seem that the similar code in regtry()
375 * already takes care of this, and in fact it is in
376 * a better location to since this code can #if 0-ed out
377 * but the code in regtry() is needed or otherwise tests
378 * requiring null fields (pat.t#187 and split.t#{13,14}
379 * (as of patchlevel 7877) will fail. Then again,
380 * this code seems to be necessary or otherwise
381 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
382 * --jhi updated by dapm */
383 for (i = rex->lastparen + 1; i <= rex->nparens; i++) {
384 if (i > *maxopenparen_p)
385 rex->offs[i].start = -1;
386 rex->offs[i].end = -1;
387 DEBUG_BUFFERS_r( Perl_re_exec_indentf( aTHX_
388 " \\%" UVuf ": %s ..-1 undeffing\n",
391 (i > *maxopenparen_p) ? "-1" : " "
397 /* restore the parens and associated vars at savestack position ix,
398 * but without popping the stack */
401 S_regcp_restore(pTHX_ regexp *rex, I32 ix, U32 *maxopenparen_p _pDEPTH)
403 I32 tmpix = PL_savestack_ix;
404 PERL_ARGS_ASSERT_REGCP_RESTORE;
406 PL_savestack_ix = ix;
407 regcppop(rex, maxopenparen_p);
408 PL_savestack_ix = tmpix;
411 #define regcpblow(cp) LEAVE_SCOPE(cp) /* Ignores regcppush()ed data. */
413 #ifndef PERL_IN_XSUB_RE
416 Perl_isFOO_lc(pTHX_ const U8 classnum, const U8 character)
418 /* Returns a boolean as to whether or not 'character' is a member of the
419 * Posix character class given by 'classnum' that should be equivalent to a
420 * value in the typedef '_char_class_number'.
422 * Ideally this could be replaced by a just an array of function pointers
423 * to the C library functions that implement the macros this calls.
424 * However, to compile, the precise function signatures are required, and
425 * these may vary from platform to platform. To avoid having to figure
426 * out what those all are on each platform, I (khw) am using this method,
427 * which adds an extra layer of function call overhead (unless the C
428 * optimizer strips it away). But we don't particularly care about
429 * performance with locales anyway. */
431 switch ((_char_class_number) classnum) {
432 case _CC_ENUM_ALPHANUMERIC: return isALPHANUMERIC_LC(character);
433 case _CC_ENUM_ALPHA: return isALPHA_LC(character);
434 case _CC_ENUM_ASCII: return isASCII_LC(character);
435 case _CC_ENUM_BLANK: return isBLANK_LC(character);
436 case _CC_ENUM_CASED: return isLOWER_LC(character)
437 || isUPPER_LC(character);
438 case _CC_ENUM_CNTRL: return isCNTRL_LC(character);
439 case _CC_ENUM_DIGIT: return isDIGIT_LC(character);
440 case _CC_ENUM_GRAPH: return isGRAPH_LC(character);
441 case _CC_ENUM_LOWER: return isLOWER_LC(character);
442 case _CC_ENUM_PRINT: return isPRINT_LC(character);
443 case _CC_ENUM_PUNCT: return isPUNCT_LC(character);
444 case _CC_ENUM_SPACE: return isSPACE_LC(character);
445 case _CC_ENUM_UPPER: return isUPPER_LC(character);
446 case _CC_ENUM_WORDCHAR: return isWORDCHAR_LC(character);
447 case _CC_ENUM_XDIGIT: return isXDIGIT_LC(character);
448 default: /* VERTSPACE should never occur in locales */
449 Perl_croak(aTHX_ "panic: isFOO_lc() has an unexpected character class '%d'", classnum);
452 NOT_REACHED; /* NOTREACHED */
458 PERL_STATIC_INLINE I32
459 S_foldEQ_latin1_s2_folded(const char *s1, const char *s2, I32 len)
461 /* Compare non-UTF-8 using Unicode (Latin1) semantics. s2 must already be
462 * folded. Works on all folds representable without UTF-8, except for
463 * LATIN_SMALL_LETTER_SHARP_S, and does not check for this. Nor does it
464 * check that the strings each have at least 'len' characters.
466 * There is almost an identical API function where s2 need not be folded:
467 * Perl_foldEQ_latin1() */
469 const U8 *a = (const U8 *)s1;
470 const U8 *b = (const U8 *)s2;
472 PERL_ARGS_ASSERT_FOLDEQ_LATIN1_S2_FOLDED;
477 assert(! isUPPER_L1(*b));
478 if (toLOWER_L1(*a) != *b) {
487 S_isFOO_utf8_lc(pTHX_ const U8 classnum, const U8* character, const U8* e)
489 /* Returns a boolean as to whether or not the (well-formed) UTF-8-encoded
490 * 'character' is a member of the Posix character class given by 'classnum'
491 * that should be equivalent to a value in the typedef
492 * '_char_class_number'.
494 * This just calls isFOO_lc on the code point for the character if it is in
495 * the range 0-255. Outside that range, all characters use Unicode
496 * rules, ignoring any locale. So use the Unicode function if this class
497 * requires an inversion list, and use the Unicode macro otherwise. */
500 PERL_ARGS_ASSERT_ISFOO_UTF8_LC;
502 if (UTF8_IS_INVARIANT(*character)) {
503 return isFOO_lc(classnum, *character);
505 else if (UTF8_IS_DOWNGRADEABLE_START(*character)) {
506 return isFOO_lc(classnum,
507 EIGHT_BIT_UTF8_TO_NATIVE(*character, *(character + 1)));
510 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(character, e);
512 switch ((_char_class_number) classnum) {
513 case _CC_ENUM_SPACE: return is_XPERLSPACE_high(character);
514 case _CC_ENUM_BLANK: return is_HORIZWS_high(character);
515 case _CC_ENUM_XDIGIT: return is_XDIGIT_high(character);
516 case _CC_ENUM_VERTSPACE: return is_VERTWS_high(character);
518 return _invlist_contains_cp(PL_XPosix_ptrs[classnum],
519 utf8_to_uvchr_buf(character, e, NULL));
522 return FALSE; /* Things like CNTRL are always below 256 */
526 S_find_span_end(U8 * s, const U8 * send, const U8 span_byte)
528 /* Returns the position of the first byte in the sequence between 's' and
529 * 'send-1' inclusive that isn't 'span_byte'; returns 'send' if none found.
532 PERL_ARGS_ASSERT_FIND_SPAN_END;
536 if ((STRLEN) (send - s) >= PERL_WORDSIZE
537 + PERL_WORDSIZE * PERL_IS_SUBWORD_ADDR(s)
538 - (PTR2nat(s) & PERL_WORD_BOUNDARY_MASK))
540 PERL_UINTMAX_T span_word;
542 /* Process per-byte until reach word boundary. XXX This loop could be
543 * eliminated if we knew that this platform had fast unaligned reads */
544 while (PTR2nat(s) & PERL_WORD_BOUNDARY_MASK) {
545 if (*s != span_byte) {
551 /* Create a word filled with the bytes we are spanning */
552 span_word = PERL_COUNT_MULTIPLIER * span_byte;
554 /* Process per-word as long as we have at least a full word left */
557 /* Keep going if the whole word is composed of 'span_byte's */
558 if ((* (PERL_UINTMAX_T *) s) == span_word) {
563 /* Here, at least one byte in the word isn't 'span_byte'. */
571 /* This xor leaves 1 bits only in those non-matching bytes */
572 span_word ^= * (PERL_UINTMAX_T *) s;
574 /* Make sure the upper bit of each non-matching byte is set. This
575 * makes each such byte look like an ASCII platform variant byte */
576 span_word |= span_word << 1;
577 span_word |= span_word << 2;
578 span_word |= span_word << 4;
580 /* That reduces the problem to what this function solves */
581 return s + variant_byte_number(span_word);
585 } while (s + PERL_WORDSIZE <= send);
588 /* Process the straggler bytes beyond the final word boundary */
590 if (*s != span_byte) {
600 S_find_next_masked(U8 * s, const U8 * send, const U8 byte, const U8 mask)
602 /* Returns the position of the first byte in the sequence between 's'
603 * and 'send-1' inclusive that when ANDed with 'mask' yields 'byte';
604 * returns 'send' if none found. It uses word-level operations instead of
605 * byte to speed up the process */
607 PERL_ARGS_ASSERT_FIND_NEXT_MASKED;
610 assert((byte & mask) == byte);
614 if ((STRLEN) (send - s) >= PERL_WORDSIZE
615 + PERL_WORDSIZE * PERL_IS_SUBWORD_ADDR(s)
616 - (PTR2nat(s) & PERL_WORD_BOUNDARY_MASK))
618 PERL_UINTMAX_T word, mask_word;
620 while (PTR2nat(s) & PERL_WORD_BOUNDARY_MASK) {
621 if (((*s) & mask) == byte) {
627 word = PERL_COUNT_MULTIPLIER * byte;
628 mask_word = PERL_COUNT_MULTIPLIER * mask;
631 PERL_UINTMAX_T masked = (* (PERL_UINTMAX_T *) s) & mask_word;
633 /* If 'masked' contains bytes with the bit pattern of 'byte' within
634 * it, xoring with 'word' will leave each of the 8 bits in such
635 * bytes be 0, and no byte containing any other bit pattern will be
639 /* This causes the most significant bit to be set to 1 for any
640 * bytes in the word that aren't completely 0 */
641 masked |= masked << 1;
642 masked |= masked << 2;
643 masked |= masked << 4;
645 /* The msbits are the same as what marks a byte as variant, so we
646 * can use this mask. If all msbits are 1, the word doesn't
648 if ((masked & PERL_VARIANTS_WORD_MASK) == PERL_VARIANTS_WORD_MASK) {
653 /* Here, the msbit of bytes in the word that aren't 'byte' are 1,
654 * and any that are, are 0. Complement and re-AND to swap that */
656 masked &= PERL_VARIANTS_WORD_MASK;
658 /* This reduces the problem to that solved by this function */
659 s += variant_byte_number(masked);
662 } while (s + PERL_WORDSIZE <= send);
668 if (((*s) & mask) == byte) {
678 S_find_span_end_mask(U8 * s, const U8 * send, const U8 span_byte, const U8 mask)
680 /* Returns the position of the first byte in the sequence between 's' and
681 * 'send-1' inclusive that when ANDed with 'mask' isn't 'span_byte'.
682 * 'span_byte' should have been ANDed with 'mask' in the call of this
683 * function. Returns 'send' if none found. Works like find_span_end(),
684 * except for the AND */
686 PERL_ARGS_ASSERT_FIND_SPAN_END_MASK;
689 assert((span_byte & mask) == span_byte);
691 if ((STRLEN) (send - s) >= PERL_WORDSIZE
692 + PERL_WORDSIZE * PERL_IS_SUBWORD_ADDR(s)
693 - (PTR2nat(s) & PERL_WORD_BOUNDARY_MASK))
695 PERL_UINTMAX_T span_word, mask_word;
697 while (PTR2nat(s) & PERL_WORD_BOUNDARY_MASK) {
698 if (((*s) & mask) != span_byte) {
704 span_word = PERL_COUNT_MULTIPLIER * span_byte;
705 mask_word = PERL_COUNT_MULTIPLIER * mask;
708 PERL_UINTMAX_T masked = (* (PERL_UINTMAX_T *) s) & mask_word;
710 if (masked == span_word) {
722 masked |= masked << 1;
723 masked |= masked << 2;
724 masked |= masked << 4;
725 return s + variant_byte_number(masked);
729 } while (s + PERL_WORDSIZE <= send);
733 if (((*s) & mask) != span_byte) {
743 * pregexec and friends
746 #ifndef PERL_IN_XSUB_RE
748 - pregexec - match a regexp against a string
751 Perl_pregexec(pTHX_ REGEXP * const prog, char* stringarg, char *strend,
752 char *strbeg, SSize_t minend, SV *screamer, U32 nosave)
753 /* stringarg: the point in the string at which to begin matching */
754 /* strend: pointer to null at end of string */
755 /* strbeg: real beginning of string */
756 /* minend: end of match must be >= minend bytes after stringarg. */
757 /* screamer: SV being matched: only used for utf8 flag, pos() etc; string
758 * itself is accessed via the pointers above */
759 /* nosave: For optimizations. */
761 PERL_ARGS_ASSERT_PREGEXEC;
764 regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
765 nosave ? 0 : REXEC_COPY_STR);
771 /* re_intuit_start():
773 * Based on some optimiser hints, try to find the earliest position in the
774 * string where the regex could match.
776 * rx: the regex to match against
777 * sv: the SV being matched: only used for utf8 flag; the string
778 * itself is accessed via the pointers below. Note that on
779 * something like an overloaded SV, SvPOK(sv) may be false
780 * and the string pointers may point to something unrelated to
782 * strbeg: real beginning of string
783 * strpos: the point in the string at which to begin matching
784 * strend: pointer to the byte following the last char of the string
785 * flags currently unused; set to 0
786 * data: currently unused; set to NULL
788 * The basic idea of re_intuit_start() is to use some known information
789 * about the pattern, namely:
791 * a) the longest known anchored substring (i.e. one that's at a
792 * constant offset from the beginning of the pattern; but not
793 * necessarily at a fixed offset from the beginning of the
795 * b) the longest floating substring (i.e. one that's not at a constant
796 * offset from the beginning of the pattern);
797 * c) Whether the pattern is anchored to the string; either
798 * an absolute anchor: /^../, or anchored to \n: /^.../m,
799 * or anchored to pos(): /\G/;
800 * d) A start class: a real or synthetic character class which
801 * represents which characters are legal at the start of the pattern;
803 * to either quickly reject the match, or to find the earliest position
804 * within the string at which the pattern might match, thus avoiding
805 * running the full NFA engine at those earlier locations, only to
806 * eventually fail and retry further along.
808 * Returns NULL if the pattern can't match, or returns the address within
809 * the string which is the earliest place the match could occur.
811 * The longest of the anchored and floating substrings is called 'check'
812 * and is checked first. The other is called 'other' and is checked
813 * second. The 'other' substring may not be present. For example,
815 * /(abc|xyz)ABC\d{0,3}DEFG/
819 * check substr (float) = "DEFG", offset 6..9 chars
820 * other substr (anchored) = "ABC", offset 3..3 chars
823 * Be aware that during the course of this function, sometimes 'anchored'
824 * refers to a substring being anchored relative to the start of the
825 * pattern, and sometimes to the pattern itself being anchored relative to
826 * the string. For example:
828 * /\dabc/: "abc" is anchored to the pattern;
829 * /^\dabc/: "abc" is anchored to the pattern and the string;
830 * /\d+abc/: "abc" is anchored to neither the pattern nor the string;
831 * /^\d+abc/: "abc" is anchored to neither the pattern nor the string,
832 * but the pattern is anchored to the string.
836 Perl_re_intuit_start(pTHX_
839 const char * const strbeg,
843 re_scream_pos_data *data)
845 struct regexp *const prog = ReANY(rx);
846 SSize_t start_shift = prog->check_offset_min;
847 /* Should be nonnegative! */
848 SSize_t end_shift = 0;
849 /* current lowest pos in string where the regex can start matching */
850 char *rx_origin = strpos;
852 const bool utf8_target = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
853 U8 other_ix = 1 - prog->substrs->check_ix;
855 char *other_last = strpos;/* latest pos 'other' substr already checked to */
856 char *check_at = NULL; /* check substr found at this pos */
857 const I32 multiline = prog->extflags & RXf_PMf_MULTILINE;
858 RXi_GET_DECL(prog,progi);
859 regmatch_info reginfo_buf; /* create some info to pass to find_byclass */
860 regmatch_info *const reginfo = ®info_buf;
861 DECLARE_AND_GET_RE_DEBUG_FLAGS;
863 PERL_ARGS_ASSERT_RE_INTUIT_START;
864 PERL_UNUSED_ARG(flags);
865 PERL_UNUSED_ARG(data);
867 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
868 "Intuit: trying to determine minimum start position...\n"));
870 /* for now, assume that all substr offsets are positive. If at some point
871 * in the future someone wants to do clever things with lookbehind and
872 * -ve offsets, they'll need to fix up any code in this function
873 * which uses these offsets. See the thread beginning
874 * <20140113145929.GF27210@iabyn.com>
876 assert(prog->substrs->data[0].min_offset >= 0);
877 assert(prog->substrs->data[0].max_offset >= 0);
878 assert(prog->substrs->data[1].min_offset >= 0);
879 assert(prog->substrs->data[1].max_offset >= 0);
880 assert(prog->substrs->data[2].min_offset >= 0);
881 assert(prog->substrs->data[2].max_offset >= 0);
883 /* for now, assume that if both present, that the floating substring
884 * doesn't start before the anchored substring.
885 * If you break this assumption (e.g. doing better optimisations
886 * with lookahead/behind), then you'll need to audit the code in this
887 * function carefully first
890 ! ( (prog->anchored_utf8 || prog->anchored_substr)
891 && (prog->float_utf8 || prog->float_substr))
892 || (prog->float_min_offset >= prog->anchored_offset));
894 /* byte rather than char calculation for efficiency. It fails
895 * to quickly reject some cases that can't match, but will reject
896 * them later after doing full char arithmetic */
897 if (prog->minlen > strend - strpos) {
898 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
899 " String too short...\n"));
903 RXp_MATCH_UTF8_set(prog, utf8_target);
904 reginfo->is_utf8_target = cBOOL(utf8_target);
905 reginfo->info_aux = NULL;
906 reginfo->strbeg = strbeg;
907 reginfo->strend = strend;
908 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
910 /* not actually used within intuit, but zero for safety anyway */
911 reginfo->poscache_maxiter = 0;
914 if ((!prog->anchored_utf8 && prog->anchored_substr)
915 || (!prog->float_utf8 && prog->float_substr))
916 to_utf8_substr(prog);
917 check = prog->check_utf8;
919 if (!prog->check_substr && prog->check_utf8) {
920 if (! to_byte_substr(prog)) {
921 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(fail);
924 check = prog->check_substr;
927 /* dump the various substring data */
928 DEBUG_OPTIMISE_MORE_r({
930 for (i=0; i<=2; i++) {
931 SV *sv = (utf8_target ? prog->substrs->data[i].utf8_substr
932 : prog->substrs->data[i].substr);
936 Perl_re_printf( aTHX_
937 " substrs[%d]: min=%" IVdf " max=%" IVdf " end shift=%" IVdf
938 " useful=%" IVdf " utf8=%d [%s]\n",
940 (IV)prog->substrs->data[i].min_offset,
941 (IV)prog->substrs->data[i].max_offset,
942 (IV)prog->substrs->data[i].end_shift,
949 if (prog->intflags & PREGf_ANCH) { /* Match at \G, beg-of-str or after \n */
951 /* ml_anch: check after \n?
953 * A note about PREGf_IMPLICIT: on an un-anchored pattern beginning
954 * with /.*.../, these flags will have been added by the
956 * /.*abc/, /.*abc/m: PREGf_IMPLICIT | PREGf_ANCH_MBOL
957 * /.*abc/s: PREGf_IMPLICIT | PREGf_ANCH_SBOL
959 ml_anch = (prog->intflags & PREGf_ANCH_MBOL)
960 && !(prog->intflags & PREGf_IMPLICIT);
962 if (!ml_anch && !(prog->intflags & PREGf_IMPLICIT)) {
963 /* we are only allowed to match at BOS or \G */
965 /* trivially reject if there's a BOS anchor and we're not at BOS.
967 * Note that we don't try to do a similar quick reject for
968 * \G, since generally the caller will have calculated strpos
969 * based on pos() and gofs, so the string is already correctly
970 * anchored by definition; and handling the exceptions would
971 * be too fiddly (e.g. REXEC_IGNOREPOS).
973 if ( strpos != strbeg
974 && (prog->intflags & PREGf_ANCH_SBOL))
976 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
977 " Not at start...\n"));
981 /* in the presence of an anchor, the anchored (relative to the
982 * start of the regex) substr must also be anchored relative
983 * to strpos. So quickly reject if substr isn't found there.
984 * This works for \G too, because the caller will already have
985 * subtracted gofs from pos, and gofs is the offset from the
986 * \G to the start of the regex. For example, in /.abc\Gdef/,
987 * where substr="abcdef", pos()=3, gofs=4, offset_min=1:
988 * caller will have set strpos=pos()-4; we look for the substr
989 * at position pos()-4+1, which lines up with the "a" */
991 if (prog->check_offset_min == prog->check_offset_max) {
992 /* Substring at constant offset from beg-of-str... */
993 SSize_t slen = SvCUR(check);
994 char *s = HOP3c(strpos, prog->check_offset_min, strend);
996 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
997 " Looking for check substr at fixed offset %" IVdf "...\n",
998 (IV)prog->check_offset_min));
1000 if (SvTAIL(check)) {
1001 /* In this case, the regex is anchored at the end too.
1002 * Unless it's a multiline match, the lengths must match
1003 * exactly, give or take a \n. NB: slen >= 1 since
1004 * the last char of check is \n */
1006 && ( strend - s > slen
1007 || strend - s < slen - 1
1008 || (strend - s == slen && strend[-1] != '\n')))
1010 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1011 " String too long...\n"));
1014 /* Now should match s[0..slen-2] */
1017 if (slen && (strend - s < slen
1018 || *SvPVX_const(check) != *s
1019 || (slen > 1 && (memNE(SvPVX_const(check), s, slen)))))
1021 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1022 " String not equal...\n"));
1027 goto success_at_start;
1032 end_shift = prog->check_end_shift;
1034 #ifdef DEBUGGING /* 7/99: reports of failure (with the older version) */
1036 Perl_croak(aTHX_ "panic: end_shift: %" IVdf " pattern:\n%s\n ",
1037 (IV)end_shift, RX_PRECOMP(rx));
1042 /* This is the (re)entry point of the main loop in this function.
1043 * The goal of this loop is to:
1044 * 1) find the "check" substring in the region rx_origin..strend
1045 * (adjusted by start_shift / end_shift). If not found, reject
1047 * 2) If it exists, look for the "other" substr too if defined; for
1048 * example, if the check substr maps to the anchored substr, then
1049 * check the floating substr, and vice-versa. If not found, go
1050 * back to (1) with rx_origin suitably incremented.
1051 * 3) If we find an rx_origin position that doesn't contradict
1052 * either of the substrings, then check the possible additional
1053 * constraints on rx_origin of /^.../m or a known start class.
1054 * If these fail, then depending on which constraints fail, jump
1055 * back to here, or to various other re-entry points further along
1056 * that skip some of the first steps.
1057 * 4) If we pass all those tests, update the BmUSEFUL() count on the
1058 * substring. If the start position was determined to be at the
1059 * beginning of the string - so, not rejected, but not optimised,
1060 * since we have to run regmatch from position 0 - decrement the
1061 * BmUSEFUL() count. Otherwise increment it.
1065 /* first, look for the 'check' substring */
1071 DEBUG_OPTIMISE_MORE_r({
1072 Perl_re_printf( aTHX_
1073 " At restart: rx_origin=%" IVdf " Check offset min: %" IVdf
1074 " Start shift: %" IVdf " End shift %" IVdf
1075 " Real end Shift: %" IVdf "\n",
1076 (IV)(rx_origin - strbeg),
1077 (IV)prog->check_offset_min,
1080 (IV)prog->check_end_shift);
1083 end_point = HOPBACK3(strend, end_shift, rx_origin);
1086 start_point = HOPMAYBE3(rx_origin, start_shift, end_point);
1091 /* If the regex is absolutely anchored to either the start of the
1092 * string (SBOL) or to pos() (ANCH_GPOS), then
1093 * check_offset_max represents an upper bound on the string where
1094 * the substr could start. For the ANCH_GPOS case, we assume that
1095 * the caller of intuit will have already set strpos to
1096 * pos()-gofs, so in this case strpos + offset_max will still be
1097 * an upper bound on the substr.
1100 && prog->intflags & PREGf_ANCH
1101 && prog->check_offset_max != SSize_t_MAX)
1103 SSize_t check_len = SvCUR(check) - !!SvTAIL(check);
1104 const char * const anchor =
1105 (prog->intflags & PREGf_ANCH_GPOS ? strpos : strbeg);
1106 SSize_t targ_len = (char*)end_point - anchor;
1108 if (check_len > targ_len) {
1109 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1110 "Target string too short to match required substring...\n"));
1114 /* do a bytes rather than chars comparison. It's conservative;
1115 * so it skips doing the HOP if the result can't possibly end
1116 * up earlier than the old value of end_point.
1118 assert(anchor + check_len <= (char *)end_point);
1119 if (prog->check_offset_max + check_len < targ_len) {
1120 end_point = HOP3lim((U8*)anchor,
1121 prog->check_offset_max,
1122 end_point - check_len
1125 if (end_point < start_point)
1130 check_at = fbm_instr( start_point, end_point,
1131 check, multiline ? FBMrf_MULTILINE : 0);
1133 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1134 " doing 'check' fbm scan, [%" IVdf "..%" IVdf "] gave %" IVdf "\n",
1135 (IV)((char*)start_point - strbeg),
1136 (IV)((char*)end_point - strbeg),
1137 (IV)(check_at ? check_at - strbeg : -1)
1140 /* Update the count-of-usability, remove useless subpatterns,
1144 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
1145 SvPVX_const(check), RE_SV_DUMPLEN(check), 30);
1146 Perl_re_printf( aTHX_ " %s %s substr %s%s%s",
1147 (check_at ? "Found" : "Did not find"),
1148 (check == (utf8_target ? prog->anchored_utf8 : prog->anchored_substr)
1149 ? "anchored" : "floating"),
1152 (check_at ? " at offset " : "...\n") );
1157 /* set rx_origin to the minimum position where the regex could start
1158 * matching, given the constraint of the just-matched check substring.
1159 * But don't set it lower than previously.
1162 if (check_at - rx_origin > prog->check_offset_max)
1163 rx_origin = HOP3c(check_at, -prog->check_offset_max, rx_origin);
1164 /* Finish the diagnostic message */
1165 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1166 "%ld (rx_origin now %" IVdf ")...\n",
1167 (long)(check_at - strbeg),
1168 (IV)(rx_origin - strbeg)
1173 /* now look for the 'other' substring if defined */
1175 if (prog->substrs->data[other_ix].utf8_substr
1176 || prog->substrs->data[other_ix].substr)
1178 /* Take into account the "other" substring. */
1182 struct reg_substr_datum *other;
1185 other = &prog->substrs->data[other_ix];
1186 if (!utf8_target && !other->substr) {
1187 if (!to_byte_substr(prog)) {
1188 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(fail);
1192 /* if "other" is anchored:
1193 * we've previously found a floating substr starting at check_at.
1194 * This means that the regex origin must lie somewhere
1195 * between min (rx_origin): HOP3(check_at, -check_offset_max)
1196 * and max: HOP3(check_at, -check_offset_min)
1197 * (except that min will be >= strpos)
1198 * So the fixed substr must lie somewhere between
1199 * HOP3(min, anchored_offset)
1200 * HOP3(max, anchored_offset) + SvCUR(substr)
1203 /* if "other" is floating
1204 * Calculate last1, the absolute latest point where the
1205 * floating substr could start in the string, ignoring any
1206 * constraints from the earlier fixed match. It is calculated
1209 * strend - prog->minlen (in chars) is the absolute latest
1210 * position within the string where the origin of the regex
1211 * could appear. The latest start point for the floating
1212 * substr is float_min_offset(*) on from the start of the
1213 * regex. last1 simply combines thee two offsets.
1215 * (*) You might think the latest start point should be
1216 * float_max_offset from the regex origin, and technically
1217 * you'd be correct. However, consider
1219 * Here, float min, max are 3,5 and minlen is 7.
1220 * This can match either
1224 * In the first case, the regex matches minlen chars; in the
1225 * second, minlen+1, in the third, minlen+2.
1226 * In the first case, the floating offset is 3 (which equals
1227 * float_min), in the second, 4, and in the third, 5 (which
1228 * equals float_max). In all cases, the floating string bcd
1229 * can never start more than 4 chars from the end of the
1230 * string, which equals minlen - float_min. As the substring
1231 * starts to match more than float_min from the start of the
1232 * regex, it makes the regex match more than minlen chars,
1233 * and the two cancel each other out. So we can always use
1234 * float_min - minlen, rather than float_max - minlen for the
1235 * latest position in the string.
1237 * Note that -minlen + float_min_offset is equivalent (AFAIKT)
1238 * to CHR_SVLEN(must) - !!SvTAIL(must) + prog->float_end_shift
1241 assert(prog->minlen >= other->min_offset);
1242 last1 = HOP3c(strend,
1243 other->min_offset - prog->minlen, strbeg);
1245 if (other_ix) {/* i.e. if (other-is-float) */
1246 /* last is the latest point where the floating substr could
1247 * start, *given* any constraints from the earlier fixed
1248 * match. This constraint is that the floating string starts
1249 * <= float_max_offset chars from the regex origin (rx_origin).
1250 * If this value is less than last1, use it instead.
1252 assert(rx_origin <= last1);
1254 /* this condition handles the offset==infinity case, and
1255 * is a short-cut otherwise. Although it's comparing a
1256 * byte offset to a char length, it does so in a safe way,
1257 * since 1 char always occupies 1 or more bytes,
1258 * so if a string range is (last1 - rx_origin) bytes,
1259 * it will be less than or equal to (last1 - rx_origin)
1260 * chars; meaning it errs towards doing the accurate HOP3
1261 * rather than just using last1 as a short-cut */
1262 (last1 - rx_origin) < other->max_offset
1264 : (char*)HOP3lim(rx_origin, other->max_offset, last1);
1267 assert(strpos + start_shift <= check_at);
1268 last = HOP4c(check_at, other->min_offset - start_shift,
1272 s = HOP3c(rx_origin, other->min_offset, strend);
1273 if (s < other_last) /* These positions already checked */
1276 must = utf8_target ? other->utf8_substr : other->substr;
1277 assert(SvPOK(must));
1280 char *to = last + SvCUR(must) - (SvTAIL(must)!=0);
1286 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1287 " skipping 'other' fbm scan: %" IVdf " > %" IVdf "\n",
1288 (IV)(from - strbeg),
1294 (unsigned char*)from,
1297 multiline ? FBMrf_MULTILINE : 0
1299 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1300 " doing 'other' fbm scan, [%" IVdf "..%" IVdf "] gave %" IVdf "\n",
1301 (IV)(from - strbeg),
1303 (IV)(s ? s - strbeg : -1)
1309 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
1310 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
1311 Perl_re_printf( aTHX_ " %s %s substr %s%s",
1312 s ? "Found" : "Contradicts",
1313 other_ix ? "floating" : "anchored",
1314 quoted, RE_SV_TAIL(must));
1319 /* last1 is latest possible substr location. If we didn't
1320 * find it before there, we never will */
1321 if (last >= last1) {
1322 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1323 "; giving up...\n"));
1327 /* try to find the check substr again at a later
1328 * position. Maybe next time we'll find the "other" substr
1330 other_last = HOP3c(last, 1, strend) /* highest failure */;
1332 other_ix /* i.e. if other-is-float */
1333 ? HOP3c(rx_origin, 1, strend)
1334 : HOP4c(last, 1 - other->min_offset, strbeg, strend);
1335 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1336 "; about to retry %s at offset %ld (rx_origin now %" IVdf ")...\n",
1337 (other_ix ? "floating" : "anchored"),
1338 (long)(HOP3c(check_at, 1, strend) - strbeg),
1339 (IV)(rx_origin - strbeg)
1344 if (other_ix) { /* if (other-is-float) */
1345 /* other_last is set to s, not s+1, since its possible for
1346 * a floating substr to fail first time, then succeed
1347 * second time at the same floating position; e.g.:
1348 * "-AB--AABZ" =~ /\wAB\d*Z/
1349 * The first time round, anchored and float match at
1350 * "-(AB)--AAB(Z)" then fail on the initial \w character
1351 * class. Second time round, they match at "-AB--A(AB)(Z)".
1356 rx_origin = HOP3c(s, -other->min_offset, strbeg);
1357 other_last = HOP3c(s, 1, strend);
1359 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1360 " at offset %ld (rx_origin now %" IVdf ")...\n",
1362 (IV)(rx_origin - strbeg)
1368 DEBUG_OPTIMISE_MORE_r(
1369 Perl_re_printf( aTHX_
1370 " Check-only match: offset min:%" IVdf " max:%" IVdf
1371 " check_at:%" IVdf " rx_origin:%" IVdf " rx_origin-check_at:%" IVdf
1372 " strend:%" IVdf "\n",
1373 (IV)prog->check_offset_min,
1374 (IV)prog->check_offset_max,
1375 (IV)(check_at-strbeg),
1376 (IV)(rx_origin-strbeg),
1377 (IV)(rx_origin-check_at),
1383 postprocess_substr_matches:
1385 /* handle the extra constraint of /^.../m if present */
1387 if (ml_anch && rx_origin != strbeg && rx_origin[-1] != '\n') {
1390 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1391 " looking for /^/m anchor"));
1393 /* we have failed the constraint of a \n before rx_origin.
1394 * Find the next \n, if any, even if it's beyond the current
1395 * anchored and/or floating substrings. Whether we should be
1396 * scanning ahead for the next \n or the next substr is debatable.
1397 * On the one hand you'd expect rare substrings to appear less
1398 * often than \n's. On the other hand, searching for \n means
1399 * we're effectively flipping between check_substr and "\n" on each
1400 * iteration as the current "rarest" string candidate, which
1401 * means for example that we'll quickly reject the whole string if
1402 * hasn't got a \n, rather than trying every substr position
1406 s = HOP3c(strend, - prog->minlen, strpos);
1407 if (s <= rx_origin ||
1408 ! ( rx_origin = (char *)memchr(rx_origin, '\n', s - rx_origin)))
1410 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1411 " Did not find /%s^%s/m...\n",
1412 PL_colors[0], PL_colors[1]));
1416 /* earliest possible origin is 1 char after the \n.
1417 * (since *rx_origin == '\n', it's safe to ++ here rather than
1418 * HOP(rx_origin, 1)) */
1421 if (prog->substrs->check_ix == 0 /* check is anchored */
1422 || rx_origin >= HOP3c(check_at, - prog->check_offset_min, strpos))
1424 /* Position contradicts check-string; either because
1425 * check was anchored (and thus has no wiggle room),
1426 * or check was float and rx_origin is above the float range */
1427 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1428 " Found /%s^%s/m, about to restart lookup for check-string with rx_origin %ld...\n",
1429 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1433 /* if we get here, the check substr must have been float,
1434 * is in range, and we may or may not have had an anchored
1435 * "other" substr which still contradicts */
1436 assert(prog->substrs->check_ix); /* check is float */
1438 if (utf8_target ? prog->anchored_utf8 : prog->anchored_substr) {
1439 /* whoops, the anchored "other" substr exists, so we still
1440 * contradict. On the other hand, the float "check" substr
1441 * didn't contradict, so just retry the anchored "other"
1443 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1444 " Found /%s^%s/m, rescanning for anchored from offset %" IVdf " (rx_origin now %" IVdf ")...\n",
1445 PL_colors[0], PL_colors[1],
1446 (IV)(rx_origin - strbeg + prog->anchored_offset),
1447 (IV)(rx_origin - strbeg)
1449 goto do_other_substr;
1452 /* success: we don't contradict the found floating substring
1453 * (and there's no anchored substr). */
1454 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1455 " Found /%s^%s/m with rx_origin %ld...\n",
1456 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1459 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1460 " (multiline anchor test skipped)\n"));
1466 /* if we have a starting character class, then test that extra constraint.
1467 * (trie stclasses are too expensive to use here, we are better off to
1468 * leave it to regmatch itself) */
1470 if (progi->regstclass && PL_regkind[OP(progi->regstclass)]!=TRIE) {
1471 const U8* const str = (U8*)STRING(progi->regstclass);
1473 /* XXX this value could be pre-computed */
1474 const SSize_t cl_l = (PL_regkind[OP(progi->regstclass)] == EXACT
1475 ? (reginfo->is_utf8_pat
1476 ? (SSize_t)utf8_distance(str + STR_LEN(progi->regstclass), str)
1477 : (SSize_t)STR_LEN(progi->regstclass))
1481 /* latest pos that a matching float substr constrains rx start to */
1482 char *rx_max_float = NULL;
1484 /* if the current rx_origin is anchored, either by satisfying an
1485 * anchored substring constraint, or a /^.../m constraint, then we
1486 * can reject the current origin if the start class isn't found
1487 * at the current position. If we have a float-only match, then
1488 * rx_origin is constrained to a range; so look for the start class
1489 * in that range. if neither, then look for the start class in the
1490 * whole rest of the string */
1492 /* XXX DAPM it's not clear what the minlen test is for, and why
1493 * it's not used in the floating case. Nothing in the test suite
1494 * causes minlen == 0 here. See <20140313134639.GS12844@iabyn.com>.
1495 * Here are some old comments, which may or may not be correct:
1497 * minlen == 0 is possible if regstclass is \b or \B,
1498 * and the fixed substr is ''$.
1499 * Since minlen is already taken into account, rx_origin+1 is
1500 * before strend; accidentally, minlen >= 1 guaranties no false
1501 * positives at rx_origin + 1 even for \b or \B. But (minlen? 1 :
1502 * 0) below assumes that regstclass does not come from lookahead...
1503 * If regstclass takes bytelength more than 1: If charlength==1, OK.
1504 * This leaves EXACTF-ish only, which are dealt with in
1508 if (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
1509 endpos = HOP3clim(rx_origin, (prog->minlen ? cl_l : 0), strend);
1510 else if (prog->float_substr || prog->float_utf8) {
1511 rx_max_float = HOP3c(check_at, -start_shift, strbeg);
1512 endpos = HOP3clim(rx_max_float, cl_l, strend);
1517 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1518 " looking for class: start_shift: %" IVdf " check_at: %" IVdf
1519 " rx_origin: %" IVdf " endpos: %" IVdf "\n",
1520 (IV)start_shift, (IV)(check_at - strbeg),
1521 (IV)(rx_origin - strbeg), (IV)(endpos - strbeg)));
1523 s = find_byclass(prog, progi->regstclass, rx_origin, endpos,
1526 if (endpos == strend) {
1527 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1528 " Could not match STCLASS...\n") );
1531 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1532 " This position contradicts STCLASS...\n") );
1533 if ((prog->intflags & PREGf_ANCH) && !ml_anch
1534 && !(prog->intflags & PREGf_IMPLICIT))
1537 /* Contradict one of substrings */
1538 if (prog->anchored_substr || prog->anchored_utf8) {
1539 if (prog->substrs->check_ix == 1) { /* check is float */
1540 /* Have both, check_string is floating */
1541 assert(rx_origin + start_shift <= check_at);
1542 if (rx_origin + start_shift != check_at) {
1543 /* not at latest position float substr could match:
1544 * Recheck anchored substring, but not floating.
1545 * The condition above is in bytes rather than
1546 * chars for efficiency. It's conservative, in
1547 * that it errs on the side of doing 'goto
1548 * do_other_substr'. In this case, at worst,
1549 * an extra anchored search may get done, but in
1550 * practice the extra fbm_instr() is likely to
1551 * get skipped anyway. */
1552 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1553 " about to retry anchored at offset %ld (rx_origin now %" IVdf ")...\n",
1554 (long)(other_last - strbeg),
1555 (IV)(rx_origin - strbeg)
1557 goto do_other_substr;
1565 /* In the presence of ml_anch, we might be able to
1566 * find another \n without breaking the current float
1569 /* strictly speaking this should be HOP3c(..., 1, ...),
1570 * but since we goto a block of code that's going to
1571 * search for the next \n if any, its safe here */
1573 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1574 " about to look for /%s^%s/m starting at rx_origin %ld...\n",
1575 PL_colors[0], PL_colors[1],
1576 (long)(rx_origin - strbeg)) );
1577 goto postprocess_substr_matches;
1580 /* strictly speaking this can never be true; but might
1581 * be if we ever allow intuit without substrings */
1582 if (!(utf8_target ? prog->float_utf8 : prog->float_substr))
1585 rx_origin = rx_max_float;
1588 /* at this point, any matching substrings have been
1589 * contradicted. Start again... */
1591 rx_origin = HOP3c(rx_origin, 1, strend);
1593 /* uses bytes rather than char calculations for efficiency.
1594 * It's conservative: it errs on the side of doing 'goto restart',
1595 * where there is code that does a proper char-based test */
1596 if (rx_origin + start_shift + end_shift > strend) {
1597 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1598 " Could not match STCLASS...\n") );
1601 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1602 " about to look for %s substr starting at offset %ld (rx_origin now %" IVdf ")...\n",
1603 (prog->substrs->check_ix ? "floating" : "anchored"),
1604 (long)(rx_origin + start_shift - strbeg),
1605 (IV)(rx_origin - strbeg)
1612 if (rx_origin != s) {
1613 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1614 " By STCLASS: moving %ld --> %ld\n",
1615 (long)(rx_origin - strbeg), (long)(s - strbeg))
1619 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1620 " Does not contradict STCLASS...\n");
1625 /* Decide whether using the substrings helped */
1627 if (rx_origin != strpos) {
1628 /* Fixed substring is found far enough so that the match
1629 cannot start at strpos. */
1631 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ " try at offset...\n"));
1632 ++BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr); /* hooray/5 */
1635 /* The found rx_origin position does not prohibit matching at
1636 * strpos, so calling intuit didn't gain us anything. Decrement
1637 * the BmUSEFUL() count on the check substring, and if we reach
1639 if (!(prog->intflags & PREGf_NAUGHTY)
1641 prog->check_utf8 /* Could be deleted already */
1642 && --BmUSEFUL(prog->check_utf8) < 0
1643 && (prog->check_utf8 == prog->float_utf8)
1645 prog->check_substr /* Could be deleted already */
1646 && --BmUSEFUL(prog->check_substr) < 0
1647 && (prog->check_substr == prog->float_substr)
1650 /* If flags & SOMETHING - do not do it many times on the same match */
1651 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ " ... Disabling check substring...\n"));
1652 /* XXX Does the destruction order has to change with utf8_target? */
1653 SvREFCNT_dec(utf8_target ? prog->check_utf8 : prog->check_substr);
1654 SvREFCNT_dec(utf8_target ? prog->check_substr : prog->check_utf8);
1655 prog->check_substr = prog->check_utf8 = NULL; /* disable */
1656 prog->float_substr = prog->float_utf8 = NULL; /* clear */
1657 check = NULL; /* abort */
1658 /* XXXX This is a remnant of the old implementation. It
1659 looks wasteful, since now INTUIT can use many
1660 other heuristics. */
1661 prog->extflags &= ~RXf_USE_INTUIT;
1665 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1666 "Intuit: %sSuccessfully guessed:%s match at offset %ld\n",
1667 PL_colors[4], PL_colors[5], (long)(rx_origin - strbeg)) );
1671 fail_finish: /* Substring not found */
1672 if (prog->check_substr || prog->check_utf8) /* could be removed already */
1673 BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
1675 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%sMatch rejected by optimizer%s\n",
1676 PL_colors[4], PL_colors[5]));
1681 #define DECL_TRIE_TYPE(scan) \
1682 const enum { trie_plain, trie_utf8, trie_utf8_fold, trie_latin_utf8_fold, \
1683 trie_utf8_exactfa_fold, trie_latin_utf8_exactfa_fold, \
1684 trie_utf8l, trie_flu8, trie_flu8_latin } \
1685 trie_type = ((scan->flags == EXACT) \
1686 ? (utf8_target ? trie_utf8 : trie_plain) \
1687 : (scan->flags == EXACTL) \
1688 ? (utf8_target ? trie_utf8l : trie_plain) \
1689 : (scan->flags == EXACTFAA) \
1691 ? trie_utf8_exactfa_fold \
1692 : trie_latin_utf8_exactfa_fold) \
1693 : (scan->flags == EXACTFLU8 \
1696 : trie_flu8_latin) \
1699 : trie_latin_utf8_fold)))
1701 /* 'uscan' is set to foldbuf, and incremented, so below the end of uscan is
1702 * 'foldbuf+sizeof(foldbuf)' */
1703 #define REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc, uc_end, uscan, len, uvc, charid, foldlen, foldbuf, uniflags) \
1706 U8 flags = FOLD_FLAGS_FULL; \
1707 switch (trie_type) { \
1709 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1710 if (UTF8_IS_ABOVE_LATIN1(*uc)) { \
1711 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc_end); \
1713 goto do_trie_utf8_fold; \
1714 case trie_utf8_exactfa_fold: \
1715 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1717 case trie_utf8_fold: \
1718 do_trie_utf8_fold: \
1719 if ( foldlen>0 ) { \
1720 uvc = utf8n_to_uvchr( (const U8*) uscan, foldlen, &len, uniflags ); \
1725 uvc = _toFOLD_utf8_flags( (const U8*) uc, uc_end, foldbuf, &foldlen, \
1727 len = UTF8_SAFE_SKIP(uc, uc_end); \
1728 skiplen = UVCHR_SKIP( uvc ); \
1729 foldlen -= skiplen; \
1730 uscan = foldbuf + skiplen; \
1733 case trie_flu8_latin: \
1734 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1735 goto do_trie_latin_utf8_fold; \
1736 case trie_latin_utf8_exactfa_fold: \
1737 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1739 case trie_latin_utf8_fold: \
1740 do_trie_latin_utf8_fold: \
1741 if ( foldlen>0 ) { \
1742 uvc = utf8n_to_uvchr( (const U8*) uscan, foldlen, &len, uniflags ); \
1748 uvc = _to_fold_latin1( (U8) *uc, foldbuf, &foldlen, flags); \
1749 skiplen = UVCHR_SKIP( uvc ); \
1750 foldlen -= skiplen; \
1751 uscan = foldbuf + skiplen; \
1755 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1756 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1757 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc_end); \
1761 uvc = utf8n_to_uvchr( (const U8*) uc, uc_end - uc, &len, uniflags ); \
1768 charid = trie->charmap[ uvc ]; \
1772 if (widecharmap) { \
1773 SV** const svpp = hv_fetch(widecharmap, \
1774 (char*)&uvc, sizeof(UV), 0); \
1776 charid = (U16)SvIV(*svpp); \
1781 #define DUMP_EXEC_POS(li,s,doutf8,depth) \
1782 dump_exec_pos(li,s,(reginfo->strend),(reginfo->strbeg), \
1783 startpos, doutf8, depth)
1785 #define REXEC_FBC_SCAN(UTF8, CODE) \
1787 while (s < strend) { \
1790 ? UTF8_SAFE_SKIP(s, reginfo->strend) \
1795 #define REXEC_FBC_CLASS_SCAN(UTF8, COND) \
1797 while (s < strend) { \
1798 REXEC_FBC_CLASS_SCAN_GUTS(UTF8, COND) \
1802 #define REXEC_FBC_CLASS_SCAN_GUTS(UTF8, COND) \
1805 s += ((UTF8) ? UTF8_SAFE_SKIP(s, reginfo->strend) : 1);\
1806 previous_occurrence_end = s; \
1809 s += ((UTF8) ? UTF8SKIP(s) : 1); \
1812 #define REXEC_FBC_CSCAN(CONDUTF8,COND) \
1813 if (utf8_target) { \
1814 REXEC_FBC_CLASS_SCAN(1, CONDUTF8); \
1817 REXEC_FBC_CLASS_SCAN(0, COND); \
1820 /* We keep track of where the next character should start after an occurrence
1821 * of the one we're looking for. Knowing that, we can see right away if the
1822 * next occurrence is adjacent to the previous. When 'doevery' is FALSE, we
1823 * don't accept the 2nd and succeeding adjacent occurrences */
1824 #define FBC_CHECK_AND_TRY \
1826 || s != previous_occurrence_end) \
1827 && ( reginfo->intuit \
1828 || (s <= reginfo->strend && regtry(reginfo, &s)))) \
1834 /* This differs from the above macros in that it calls a function which returns
1835 * the next occurrence of the thing being looked for in 's'; and 'strend' if
1836 * there is no such occurrence. */
1837 #define REXEC_FBC_FIND_NEXT_SCAN(UTF8, f) \
1838 while (s < strend) { \
1840 if (s >= strend) { \
1845 s += (UTF8) ? UTF8SKIP(s) : 1; \
1846 previous_occurrence_end = s; \
1849 /* This differs from the above macros in that it is passed a single byte that
1850 * is known to begin the next occurrence of the thing being looked for in 's'.
1851 * It does a memchr to find the next occurrence of 'byte', before trying 'COND'
1852 * at that position. */
1853 #define REXEC_FBC_FIND_NEXT_UTF8_BYTE_SCAN(byte, COND) \
1854 while (s < strend) { \
1855 s = (char *) memchr(s, byte, strend -s); \
1857 s = (char *) strend; \
1863 s += UTF8_SAFE_SKIP(s, reginfo->strend); \
1864 previous_occurrence_end = s; \
1871 /* The three macros below are slightly different versions of the same logic.
1873 * The first is for /a and /aa when the target string is UTF-8. This can only
1874 * match ascii, but it must advance based on UTF-8. The other two handle the
1875 * non-UTF-8 and the more generic UTF-8 cases. In all three, we are looking
1876 * for the boundary (or non-boundary) between a word and non-word character.
1877 * The utf8 and non-utf8 cases have the same logic, but the details must be
1878 * different. Find the "wordness" of the character just prior to this one, and
1879 * compare it with the wordness of this one. If they differ, we have a
1880 * boundary. At the beginning of the string, pretend that the previous
1881 * character was a new-line.
1883 * All these macros uncleanly have side-effects with each other and outside
1884 * variables. So far it's been too much trouble to clean-up
1886 * TEST_NON_UTF8 is the macro or function to call to test if its byte input is
1887 * a word character or not.
1888 * IF_SUCCESS is code to do if it finds that we are at a boundary between
1890 * IF_FAIL is code to do if we aren't at a boundary between word/non-word
1892 * Exactly one of the two IF_FOO parameters is a no-op, depending on whether we
1893 * are looking for a boundary or for a non-boundary. If we are looking for a
1894 * boundary, we want IF_FAIL to be the no-op, and for IF_SUCCESS to go out and
1895 * see if this tentative match actually works, and if so, to quit the loop
1896 * here. And vice-versa if we are looking for a non-boundary.
1898 * 'tmp' below in the next three macros in the REXEC_FBC_SCAN and
1899 * REXEC_FBC_SCAN loops is a loop invariant, a bool giving the return of
1900 * TEST_NON_UTF8(s-1). To see this, note that that's what it is defined to be
1901 * at entry to the loop, and to get to the IF_FAIL branch, tmp must equal
1902 * TEST_NON_UTF8(s), and in the opposite branch, IF_SUCCESS, tmp is that
1903 * complement. But in that branch we complement tmp, meaning that at the
1904 * bottom of the loop tmp is always going to be equal to TEST_NON_UTF8(s),
1905 * which means at the top of the loop in the next iteration, it is
1906 * TEST_NON_UTF8(s-1) */
1907 #define FBC_UTF8_A(TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1908 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1909 tmp = TEST_NON_UTF8(tmp); \
1910 REXEC_FBC_SCAN(1, /* 1=>is-utf8; advances s while s < strend */ \
1911 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1913 IF_SUCCESS; /* Is a boundary if values for s-1 and s differ */ \
1920 /* Like FBC_UTF8_A, but TEST_UV is a macro which takes a UV as its input, and
1921 * TEST_UTF8 is a macro that for the same input code points returns identically
1922 * to TEST_UV, but takes a pointer to a UTF-8 encoded string instead (and an
1923 * end pointer as well) */
1924 #define FBC_UTF8(TEST_UV, TEST_UTF8, IF_SUCCESS, IF_FAIL) \
1925 if (s == reginfo->strbeg) { \
1928 else { /* Back-up to the start of the previous character */ \
1929 U8 * const r = reghop3((U8*)s, -1, (U8*)reginfo->strbeg); \
1930 tmp = utf8n_to_uvchr(r, (U8*) reginfo->strend - r, \
1931 0, UTF8_ALLOW_DEFAULT); \
1933 tmp = TEST_UV(tmp); \
1934 REXEC_FBC_SCAN(1, /* 1=>is-utf8; advances s while s < strend */ \
1935 if (tmp == ! (TEST_UTF8((U8 *) s, (U8 *) reginfo->strend))) { \
1944 /* Like the above two macros. UTF8_CODE is the complete code for handling
1945 * UTF-8. Common to the BOUND and NBOUND cases, set-up by the FBC_BOUND, etc
1947 #define FBC_BOUND_COMMON(UTF8_CODE, TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1948 if (utf8_target) { \
1951 else { /* Not utf8 */ \
1952 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1953 tmp = TEST_NON_UTF8(tmp); \
1954 REXEC_FBC_SCAN(0, /* 0=>not-utf8; advances s while s < strend */ \
1955 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1964 /* Here, things have been set up by the previous code so that tmp is the \
1965 * return of TEST_NON_UTF(s-1) or TEST_UTF8(s-1) (depending on the \
1966 * utf8ness of the target). We also have to check if this matches against \
1967 * the EOS, which we treat as a \n (which is the same value in both UTF-8 \
1968 * or non-UTF8, so can use the non-utf8 test condition even for a UTF-8 \
1970 if (tmp == ! TEST_NON_UTF8('\n')) { \
1977 /* This is the macro to use when we want to see if something that looks like it
1978 * could match, actually does, and if so exits the loop. It needs to be used
1979 * only for bounds checking macros, as it allows for matching beyond the end of
1980 * string (which should be zero length without having to look at the string
1982 #define REXEC_FBC_TRYIT \
1983 if (reginfo->intuit || (s <= reginfo->strend && regtry(reginfo, &s))) \
1986 /* The only difference between the BOUND and NBOUND cases is that
1987 * REXEC_FBC_TRYIT is called when matched in BOUND, and when non-matched in
1988 * NBOUND. This is accomplished by passing it as either the if or else clause,
1989 * with the other one being empty (PLACEHOLDER is defined as empty).
1991 * The TEST_FOO parameters are for operating on different forms of input, but
1992 * all should be ones that return identically for the same underlying code
1994 #define FBC_BOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1996 FBC_UTF8(TEST_UV, TEST_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1997 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1999 #define FBC_BOUND_A(TEST_NON_UTF8) \
2001 FBC_UTF8_A(TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
2002 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
2004 #define FBC_NBOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
2006 FBC_UTF8(TEST_UV, TEST_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
2007 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
2009 #define FBC_NBOUND_A(TEST_NON_UTF8) \
2011 FBC_UTF8_A(TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
2012 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
2016 S_get_break_val_cp_checked(SV* const invlist, const UV cp_in) {
2017 IV cp_out = _invlist_search(invlist, cp_in);
2018 assert(cp_out >= 0);
2021 # define _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp) \
2022 invmap[S_get_break_val_cp_checked(invlist, cp)]
2024 # define _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp) \
2025 invmap[_invlist_search(invlist, cp)]
2028 /* Takes a pointer to an inversion list, a pointer to its corresponding
2029 * inversion map, and a code point, and returns the code point's value
2030 * according to the two arrays. It assumes that all code points have a value.
2031 * This is used as the base macro for macros for particular properties */
2032 #define _generic_GET_BREAK_VAL_CP(invlist, invmap, cp) \
2033 _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp)
2035 /* Same as above, but takes begin, end ptrs to a UTF-8 encoded string instead
2036 * of a code point, returning the value for the first code point in the string.
2037 * And it takes the particular macro name that finds the desired value given a
2038 * code point. Merely convert the UTF-8 to code point and call the cp macro */
2039 #define _generic_GET_BREAK_VAL_UTF8(cp_macro, pos, strend) \
2040 (__ASSERT_(pos < strend) \
2041 /* Note assumes is valid UTF-8 */ \
2042 (cp_macro(utf8_to_uvchr_buf((pos), (strend), NULL))))
2044 /* Returns the GCB value for the input code point */
2045 #define getGCB_VAL_CP(cp) \
2046 _generic_GET_BREAK_VAL_CP( \
2051 /* Returns the GCB value for the first code point in the UTF-8 encoded string
2052 * bounded by pos and strend */
2053 #define getGCB_VAL_UTF8(pos, strend) \
2054 _generic_GET_BREAK_VAL_UTF8(getGCB_VAL_CP, pos, strend)
2056 /* Returns the LB value for the input code point */
2057 #define getLB_VAL_CP(cp) \
2058 _generic_GET_BREAK_VAL_CP( \
2063 /* Returns the LB value for the first code point in the UTF-8 encoded string
2064 * bounded by pos and strend */
2065 #define getLB_VAL_UTF8(pos, strend) \
2066 _generic_GET_BREAK_VAL_UTF8(getLB_VAL_CP, pos, strend)
2069 /* Returns the SB value for the input code point */
2070 #define getSB_VAL_CP(cp) \
2071 _generic_GET_BREAK_VAL_CP( \
2076 /* Returns the SB value for the first code point in the UTF-8 encoded string
2077 * bounded by pos and strend */
2078 #define getSB_VAL_UTF8(pos, strend) \
2079 _generic_GET_BREAK_VAL_UTF8(getSB_VAL_CP, pos, strend)
2081 /* Returns the WB value for the input code point */
2082 #define getWB_VAL_CP(cp) \
2083 _generic_GET_BREAK_VAL_CP( \
2088 /* Returns the WB value for the first code point in the UTF-8 encoded string
2089 * bounded by pos and strend */
2090 #define getWB_VAL_UTF8(pos, strend) \
2091 _generic_GET_BREAK_VAL_UTF8(getWB_VAL_CP, pos, strend)
2093 /* We know what class REx starts with. Try to find this position... */
2094 /* if reginfo->intuit, its a dryrun */
2095 /* annoyingly all the vars in this routine have different names from their counterparts
2096 in regmatch. /grrr */
2098 S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
2099 const char *strend, regmatch_info *reginfo)
2102 /* TRUE if x+ need not match at just the 1st pos of run of x's */
2103 const I32 doevery = (prog->intflags & PREGf_SKIP) == 0;
2105 char *pat_string; /* The pattern's exactish string */
2106 char *pat_end; /* ptr to end char of pat_string */
2107 re_fold_t folder; /* Function for computing non-utf8 folds */
2108 const U8 *fold_array; /* array for folding ords < 256 */
2115 /* In some cases we accept only the first occurence of 'x' in a sequence of
2116 * them. This variable points to just beyond the end of the previous
2117 * occurrence of 'x', hence we can tell if we are in a sequence. (Having
2118 * it point to beyond the 'x' allows us to work for UTF-8 without having to
2120 char * previous_occurrence_end = 0;
2122 I32 tmp; /* Scratch variable */
2123 const bool utf8_target = reginfo->is_utf8_target;
2124 UV utf8_fold_flags = 0;
2125 const bool is_utf8_pat = reginfo->is_utf8_pat;
2126 bool to_complement = FALSE; /* Invert the result? Taking the xor of this
2127 with a result inverts that result, as 0^1 =
2129 _char_class_number classnum;
2131 RXi_GET_DECL(prog,progi);
2133 PERL_ARGS_ASSERT_FIND_BYCLASS;
2135 /* We know what class it must start with. */
2139 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2141 if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(c)) && ! IN_UTF8_CTYPE_LOCALE) {
2142 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
2149 REXEC_FBC_CLASS_SCAN(1, /* 1=>is-utf8 */
2150 reginclass(prog, c, (U8*)s, (U8*) strend, utf8_target));
2152 else if (ANYOF_FLAGS(c) & ~ ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
2153 /* We know that s is in the bitmap range since the target isn't
2154 * UTF-8, so what happens for out-of-range values is not relevant,
2155 * so exclude that from the flags */
2156 REXEC_FBC_CLASS_SCAN(0, reginclass(prog,c, (U8*)s, (U8*)s+1, 0));
2159 REXEC_FBC_CLASS_SCAN(0, ANYOF_BITMAP_TEST(c, *((U8*)s)));
2163 case ANYOFM: /* ARG() is the base byte; FLAGS() the mask byte */
2164 /* UTF-8ness doesn't matter because only matches UTF-8 invariants, so
2166 REXEC_FBC_FIND_NEXT_SCAN(0,
2167 (char *) find_next_masked((U8 *) s, (U8 *) strend,
2168 (U8) ARG(c), FLAGS(c)));
2171 case NANYOFM: /* UTF-8ness does matter because can match UTF-8 variants.
2173 REXEC_FBC_FIND_NEXT_SCAN(utf8_target,
2174 (char *) find_span_end_mask((U8 *) s, (U8 *) strend,
2175 (U8) ARG(c), FLAGS(c)));
2179 if (utf8_target) { /* Can't possibly match a non-UTF-8 target */
2180 REXEC_FBC_CLASS_SCAN(TRUE,
2181 ( (U8) NATIVE_UTF8_TO_I8(*s) >= ANYOF_FLAGS(c)
2182 && reginclass(prog, c, (U8*)s, (U8*) strend, utf8_target)));
2187 if (utf8_target) { /* Can't possibly match a non-UTF-8 target */
2189 /* We know what the first byte of any matched string should be */
2190 U8 first_byte = FLAGS(c);
2192 REXEC_FBC_FIND_NEXT_UTF8_BYTE_SCAN(first_byte,
2193 reginclass(prog, c, (U8*)s, (U8*) strend, utf8_target));
2198 if (utf8_target) { /* Can't possibly match a non-UTF-8 target */
2199 REXEC_FBC_CLASS_SCAN(TRUE,
2200 ( inRANGE(NATIVE_UTF8_TO_I8(*s),
2201 LOWEST_ANYOF_HRx_BYTE(ANYOF_FLAGS(c)),
2202 HIGHEST_ANYOF_HRx_BYTE(ANYOF_FLAGS(c)))
2203 && reginclass(prog, c, (U8*)s, (U8*) strend, utf8_target)));
2208 if (utf8_target) { /* Can't possibly match a non-UTF-8 target */
2209 REXEC_FBC_CLASS_SCAN(TRUE,
2210 ( strend -s >= FLAGS(c)
2211 && memEQ(s, ((struct regnode_anyofhs *) c)->string, FLAGS(c))
2212 && reginclass(prog, c, (U8*)s, (U8*) strend, utf8_target)));
2218 REXEC_FBC_CLASS_SCAN(TRUE,
2219 ( NATIVE_UTF8_TO_I8(*s) >= ANYOF_FLAGS(c)
2220 && withinCOUNT(utf8_to_uvchr_buf((U8 *) s,
2223 ANYOFRbase(c), ANYOFRdelta(c))));
2226 REXEC_FBC_CLASS_SCAN(0, withinCOUNT((U8) *s,
2227 ANYOFRbase(c), ANYOFRdelta(c)));
2234 /* We know what the first byte of any matched string should be */
2235 U8 first_byte = FLAGS(c);
2237 REXEC_FBC_FIND_NEXT_UTF8_BYTE_SCAN(first_byte,
2238 withinCOUNT(utf8_to_uvchr_buf((U8 *) s,
2241 ANYOFRbase(c), ANYOFRdelta(c)));
2244 REXEC_FBC_CLASS_SCAN(0, withinCOUNT((U8) *s,
2245 ANYOFRbase(c), ANYOFRdelta(c)));
2249 case EXACTFAA_NO_TRIE: /* This node only generated for non-utf8 patterns */
2250 assert(! is_utf8_pat);
2254 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII
2255 |FOLDEQ_S2_ALREADY_FOLDED|FOLDEQ_S2_FOLDS_SANE;
2256 goto do_exactf_utf8;
2258 else if (utf8_target) {
2260 /* Here, and elsewhere in this file, the reason we can't consider a
2261 * non-UTF-8 pattern already folded in the presence of a UTF-8
2262 * target is because any MICRO SIGN in the pattern won't be folded.
2263 * Since the fold of the MICRO SIGN requires UTF-8 to represent, we
2264 * can consider a non-UTF-8 pattern folded when matching a
2265 * non-UTF-8 target */
2266 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
2267 goto do_exactf_utf8;
2270 /* Latin1 folds are not affected by /a, except it excludes the sharp s,
2271 * which these functions don't handle anyway */
2272 fold_array = PL_fold_latin1;
2273 folder = foldEQ_latin1_s2_folded;
2274 goto do_exactf_non_utf8;
2276 case EXACTF: /* This node only generated for non-utf8 patterns */
2277 assert(! is_utf8_pat);
2279 goto do_exactf_utf8;
2281 fold_array = PL_fold;
2283 goto do_exactf_non_utf8;
2286 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2287 if (is_utf8_pat || utf8_target || IN_UTF8_CTYPE_LOCALE) {
2288 utf8_fold_flags = FOLDEQ_LOCALE;
2289 goto do_exactf_utf8;
2291 fold_array = PL_fold_locale;
2292 folder = foldEQ_locale;
2293 goto do_exactf_non_utf8;
2295 case EXACTFUP: /* Problematic even though pattern isn't UTF-8. Use
2296 full functionality normally not done except for
2298 assert(! is_utf8_pat);
2299 goto do_exactf_utf8;
2302 if (! utf8_target) { /* All code points in this node require
2303 UTF-8 to express. */
2306 utf8_fold_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
2307 | FOLDEQ_S2_FOLDS_SANE;
2308 goto do_exactf_utf8;
2311 if (! utf8_target) {
2314 assert(is_utf8_pat);
2315 utf8_fold_flags = FOLDEQ_S2_ALREADY_FOLDED;
2316 goto do_exactf_utf8;
2319 if (is_utf8_pat || utf8_target) {
2320 utf8_fold_flags = FOLDEQ_S2_ALREADY_FOLDED;
2321 goto do_exactf_utf8;
2324 /* Any 'ss' in the pattern should have been replaced by regcomp,
2325 * so we don't have to worry here about this single special case
2326 * in the Latin1 range */
2327 fold_array = PL_fold_latin1;
2328 folder = foldEQ_latin1_s2_folded;
2332 do_exactf_non_utf8: /* Neither pattern nor string are UTF8, and there
2333 are no glitches with fold-length differences
2334 between the target string and pattern */
2336 /* The idea in the non-utf8 EXACTF* cases is to first find the
2337 * first character of the EXACTF* node and then, if necessary,
2338 * case-insensitively compare the full text of the node. c1 is the
2339 * first character. c2 is its fold. This logic will not work for
2340 * Unicode semantics and the german sharp ss, which hence should
2341 * not be compiled into a node that gets here. */
2342 pat_string = STRINGs(c);
2343 ln = STR_LENs(c); /* length to match in octets/bytes */
2345 /* We know that we have to match at least 'ln' bytes (which is the
2346 * same as characters, since not utf8). If we have to match 3
2347 * characters, and there are only 2 availabe, we know without
2348 * trying that it will fail; so don't start a match past the
2349 * required minimum number from the far end */
2350 e = HOP3c(strend, -((SSize_t)ln), s);
2355 c2 = fold_array[c1];
2356 if (c1 == c2) { /* If char and fold are the same */
2358 s = (char *) memchr(s, c1, e + 1 - s);
2363 /* Check that the rest of the node matches */
2364 if ( (ln == 1 || folder(s + 1, pat_string + 1, ln - 1))
2365 && (reginfo->intuit || regtry(reginfo, &s)) )
2373 U8 bits_differing = c1 ^ c2;
2375 /* If the folds differ in one bit position only, we can mask to
2376 * match either of them, and can use this faster find method. Both
2377 * ASCII and EBCDIC tend to have their case folds differ in only
2378 * one position, so this is very likely */
2379 if (LIKELY(PL_bitcount[bits_differing] == 1)) {
2380 bits_differing = ~ bits_differing;
2382 s = (char *) find_next_masked((U8 *) s, (U8 *) e + 1,
2383 (c1 & bits_differing), bits_differing);
2388 if ( (ln == 1 || folder(s + 1, pat_string + 1, ln - 1))
2389 && (reginfo->intuit || regtry(reginfo, &s)) )
2396 else { /* Otherwise, stuck with looking byte-at-a-time. This
2397 should actually happen only in EXACTFL nodes */
2399 if ( (*(U8*)s == c1 || *(U8*)s == c2)
2400 && (ln == 1 || folder(s + 1, pat_string + 1, ln - 1))
2401 && (reginfo->intuit || regtry(reginfo, &s)) )
2415 /* If one of the operands is in utf8, we can't use the simpler folding
2416 * above, due to the fact that many different characters can have the
2417 * same fold, or portion of a fold, or different- length fold */
2418 pat_string = STRINGs(c);
2419 ln = STR_LENs(c); /* length to match in octets/bytes */
2420 pat_end = pat_string + ln;
2421 lnc = is_utf8_pat /* length to match in characters */
2422 ? utf8_length((U8 *) pat_string, (U8 *) pat_end)
2425 /* We have 'lnc' characters to match in the pattern, but because of
2426 * multi-character folding, each character in the target can match
2427 * up to 3 characters (Unicode guarantees it will never exceed
2428 * this) if it is utf8-encoded; and up to 2 if not (based on the
2429 * fact that the Latin 1 folds are already determined, and the
2430 * only multi-char fold in that range is the sharp-s folding to
2431 * 'ss'. Thus, a pattern character can match as little as 1/3 of a
2432 * string character. Adjust lnc accordingly, rounding up, so that
2433 * if we need to match at least 4+1/3 chars, that really is 5. */
2434 expansion = (utf8_target) ? UTF8_MAX_FOLD_CHAR_EXPAND : 2;
2435 lnc = (lnc + expansion - 1) / expansion;
2437 /* As in the non-UTF8 case, if we have to match 3 characters, and
2438 * only 2 are left, it's guaranteed to fail, so don't start a
2439 * match that would require us to go beyond the end of the string
2441 e = HOP3c(strend, -((SSize_t)lnc), s);
2443 /* XXX Note that we could recalculate e to stop the loop earlier,
2444 * as the worst case expansion above will rarely be met, and as we
2445 * go along we would usually find that e moves further to the left.
2446 * This would happen only after we reached the point in the loop
2447 * where if there were no expansion we should fail. Unclear if
2448 * worth the expense */
2451 char *my_strend= (char *)strend;
2452 if (foldEQ_utf8_flags(s, &my_strend, 0, utf8_target,
2453 pat_string, NULL, ln, is_utf8_pat, utf8_fold_flags)
2454 && (reginfo->intuit || regtry(reginfo, &s)) )
2458 s += (utf8_target) ? UTF8_SAFE_SKIP(s, reginfo->strend) : 1;
2464 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2465 if (FLAGS(c) != TRADITIONAL_BOUND) {
2466 if (! IN_UTF8_CTYPE_LOCALE) {
2467 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2468 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2473 FBC_BOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8_safe);
2477 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2478 if (FLAGS(c) != TRADITIONAL_BOUND) {
2479 if (! IN_UTF8_CTYPE_LOCALE) {
2480 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2481 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2486 FBC_NBOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8_safe);
2489 case BOUND: /* regcomp.c makes sure that this only has the traditional \b
2491 assert(FLAGS(c) == TRADITIONAL_BOUND);
2493 FBC_BOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8_safe);
2496 case BOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2498 assert(FLAGS(c) == TRADITIONAL_BOUND);
2500 FBC_BOUND_A(isWORDCHAR_A);
2503 case NBOUND: /* regcomp.c makes sure that this only has the traditional \b
2505 assert(FLAGS(c) == TRADITIONAL_BOUND);
2507 FBC_NBOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8_safe);
2510 case NBOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2512 assert(FLAGS(c) == TRADITIONAL_BOUND);
2514 FBC_NBOUND_A(isWORDCHAR_A);
2518 if ((bound_type) FLAGS(c) == TRADITIONAL_BOUND) {
2519 FBC_NBOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8_safe);
2530 switch((bound_type) FLAGS(c)) {
2531 case TRADITIONAL_BOUND:
2532 FBC_BOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8_safe);
2535 if (s == reginfo->strbeg) {
2536 if (reginfo->intuit || regtry(reginfo, &s))
2541 /* Didn't match. Try at the next position (if there is one) */
2542 s += (utf8_target) ? UTF8_SAFE_SKIP(s, reginfo->strend) : 1;
2543 if (UNLIKELY(s >= reginfo->strend)) {
2549 GCB_enum before = getGCB_VAL_UTF8(
2551 (U8*)(reginfo->strbeg)),
2552 (U8*) reginfo->strend);
2553 while (s < strend) {
2554 GCB_enum after = getGCB_VAL_UTF8((U8*) s,
2555 (U8*) reginfo->strend);
2556 if ( (to_complement ^ isGCB(before,
2558 (U8*) reginfo->strbeg,
2561 && (reginfo->intuit || regtry(reginfo, &s)))
2566 s += UTF8_SAFE_SKIP(s, reginfo->strend);
2569 else { /* Not utf8. Everything is a GCB except between CR and
2571 while (s < strend) {
2572 if ((to_complement ^ ( UCHARAT(s - 1) != '\r'
2573 || UCHARAT(s) != '\n'))
2574 && (reginfo->intuit || regtry(reginfo, &s)))
2582 /* And, since this is a bound, it can match after the final
2583 * character in the string */
2584 if ( reginfo->intuit
2585 || (s <= reginfo->strend && regtry(reginfo, &s)))
2592 if (s == reginfo->strbeg) {
2593 if (reginfo->intuit || regtry(reginfo, &s)) {
2596 s += (utf8_target) ? UTF8_SAFE_SKIP(s, reginfo->strend) : 1;
2597 if (UNLIKELY(s >= reginfo->strend)) {
2603 LB_enum before = getLB_VAL_UTF8(reghop3((U8*)s,
2605 (U8*)(reginfo->strbeg)),
2606 (U8*) reginfo->strend);
2607 while (s < strend) {
2608 LB_enum after = getLB_VAL_UTF8((U8*) s, (U8*) reginfo->strend);
2609 if (to_complement ^ isLB(before,
2611 (U8*) reginfo->strbeg,
2613 (U8*) reginfo->strend,
2615 && (reginfo->intuit || regtry(reginfo, &s)))
2620 s += UTF8_SAFE_SKIP(s, reginfo->strend);
2623 else { /* Not utf8. */
2624 LB_enum before = getLB_VAL_CP((U8) *(s -1));
2625 while (s < strend) {
2626 LB_enum after = getLB_VAL_CP((U8) *s);
2627 if (to_complement ^ isLB(before,
2629 (U8*) reginfo->strbeg,
2631 (U8*) reginfo->strend,
2633 && (reginfo->intuit || regtry(reginfo, &s)))
2642 if ( reginfo->intuit
2643 || (s <= reginfo->strend && regtry(reginfo, &s)))
2651 if (s == reginfo->strbeg) {
2652 if (reginfo->intuit || regtry(reginfo, &s)) {
2655 s += (utf8_target) ? UTF8_SAFE_SKIP(s, reginfo->strend) : 1;
2656 if (UNLIKELY(s >= reginfo->strend)) {
2662 SB_enum before = getSB_VAL_UTF8(reghop3((U8*)s,
2664 (U8*)(reginfo->strbeg)),
2665 (U8*) reginfo->strend);
2666 while (s < strend) {
2667 SB_enum after = getSB_VAL_UTF8((U8*) s,
2668 (U8*) reginfo->strend);
2669 if ((to_complement ^ isSB(before,
2671 (U8*) reginfo->strbeg,
2673 (U8*) reginfo->strend,
2675 && (reginfo->intuit || regtry(reginfo, &s)))
2680 s += UTF8_SAFE_SKIP(s, reginfo->strend);
2683 else { /* Not utf8. */
2684 SB_enum before = getSB_VAL_CP((U8) *(s -1));
2685 while (s < strend) {
2686 SB_enum after = getSB_VAL_CP((U8) *s);
2687 if ((to_complement ^ isSB(before,
2689 (U8*) reginfo->strbeg,
2691 (U8*) reginfo->strend,
2693 && (reginfo->intuit || regtry(reginfo, &s)))
2702 /* Here are at the final position in the target string. The SB
2703 * value is always true here, so matches, depending on other
2705 if ( reginfo->intuit
2706 || (s <= reginfo->strend && regtry(reginfo, &s)))
2714 if (s == reginfo->strbeg) {
2715 if (reginfo->intuit || regtry(reginfo, &s)) {
2718 s += (utf8_target) ? UTF8_SAFE_SKIP(s, reginfo->strend) : 1;
2719 if (UNLIKELY(s >= reginfo->strend)) {
2725 /* We are at a boundary between char_sub_0 and char_sub_1.
2726 * We also keep track of the value for char_sub_-1 as we
2727 * loop through the line. Context may be needed to make a
2728 * determination, and if so, this can save having to
2730 WB_enum previous = WB_UNKNOWN;
2731 WB_enum before = getWB_VAL_UTF8(
2734 (U8*)(reginfo->strbeg)),
2735 (U8*) reginfo->strend);
2736 while (s < strend) {
2737 WB_enum after = getWB_VAL_UTF8((U8*) s,
2738 (U8*) reginfo->strend);
2739 if ((to_complement ^ isWB(previous,
2742 (U8*) reginfo->strbeg,
2744 (U8*) reginfo->strend,
2746 && (reginfo->intuit || regtry(reginfo, &s)))
2752 s += UTF8_SAFE_SKIP(s, reginfo->strend);
2755 else { /* Not utf8. */
2756 WB_enum previous = WB_UNKNOWN;
2757 WB_enum before = getWB_VAL_CP((U8) *(s -1));
2758 while (s < strend) {
2759 WB_enum after = getWB_VAL_CP((U8) *s);
2760 if ((to_complement ^ isWB(previous,
2763 (U8*) reginfo->strbeg,
2765 (U8*) reginfo->strend,
2767 && (reginfo->intuit || regtry(reginfo, &s)))
2777 if ( reginfo->intuit
2778 || (s <= reginfo->strend && regtry(reginfo, &s)))
2786 REXEC_FBC_CSCAN(is_LNBREAK_utf8_safe(s, strend),
2787 is_LNBREAK_latin1_safe(s, strend)
2791 /* The argument to all the POSIX node types is the class number to pass to
2792 * _generic_isCC() to build a mask for searching in PL_charclass[] */
2799 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2800 REXEC_FBC_CSCAN(to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(c), (U8 *) s, (U8 *) strend)),
2801 to_complement ^ cBOOL(isFOO_lc(FLAGS(c), *s)));
2816 /* The complement of something that matches only ASCII matches all
2817 * non-ASCII, plus everything in ASCII that isn't in the class. */
2818 REXEC_FBC_CLASS_SCAN(1, ! isASCII_utf8_safe(s, strend)
2819 || ! _generic_isCC_A(*s, FLAGS(c)));
2827 /* Don't need to worry about utf8, as it can match only a single
2828 * byte invariant character. But we do anyway for performance reasons,
2829 * as otherwise we would have to examine all the continuation
2832 REXEC_FBC_CLASS_SCAN(1, _generic_isCC_A(*s, FLAGS(c)));
2837 REXEC_FBC_CLASS_SCAN(0, /* 0=>not-utf8 */
2838 to_complement ^ cBOOL(_generic_isCC_A(*s, FLAGS(c))));
2846 if (! utf8_target) {
2847 REXEC_FBC_CLASS_SCAN(0, /* 0=>not-utf8 */
2848 to_complement ^ cBOOL(_generic_isCC(*s,
2854 classnum = (_char_class_number) FLAGS(c);
2857 REXEC_FBC_CLASS_SCAN(1, /* 1=>is-utf8 */
2858 to_complement ^ cBOOL(_invlist_contains_cp(
2859 PL_XPosix_ptrs[classnum],
2860 utf8_to_uvchr_buf((U8 *) s,
2864 case _CC_ENUM_SPACE:
2865 REXEC_FBC_CLASS_SCAN(1, /* 1=>is-utf8 */
2866 to_complement ^ cBOOL(isSPACE_utf8_safe(s, strend)));
2869 case _CC_ENUM_BLANK:
2870 REXEC_FBC_CLASS_SCAN(1,
2871 to_complement ^ cBOOL(isBLANK_utf8_safe(s, strend)));
2874 case _CC_ENUM_XDIGIT:
2875 REXEC_FBC_CLASS_SCAN(1,
2876 to_complement ^ cBOOL(isXDIGIT_utf8_safe(s, strend)));
2879 case _CC_ENUM_VERTSPACE:
2880 REXEC_FBC_CLASS_SCAN(1,
2881 to_complement ^ cBOOL(isVERTWS_utf8_safe(s, strend)));
2884 case _CC_ENUM_CNTRL:
2885 REXEC_FBC_CLASS_SCAN(1,
2886 to_complement ^ cBOOL(isCNTRL_utf8_safe(s, strend)));
2896 /* what trie are we using right now */
2897 reg_ac_data *aho = (reg_ac_data*)progi->data->data[ ARG( c ) ];
2898 reg_trie_data *trie = (reg_trie_data*)progi->data->data[ aho->trie ];
2899 HV *widecharmap = MUTABLE_HV(progi->data->data[ aho->trie + 1 ]);
2901 const char *last_start = strend - trie->minlen;
2903 const char *real_start = s;
2905 STRLEN maxlen = trie->maxlen;
2907 U8 **points; /* map of where we were in the input string
2908 when reading a given char. For ASCII this
2909 is unnecessary overhead as the relationship
2910 is always 1:1, but for Unicode, especially
2911 case folded Unicode this is not true. */
2912 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
2916 DECLARE_AND_GET_RE_DEBUG_FLAGS;
2918 /* We can't just allocate points here. We need to wrap it in
2919 * an SV so it gets freed properly if there is a croak while
2920 * running the match */
2923 sv_points=newSV(maxlen * sizeof(U8 *));
2924 SvCUR_set(sv_points,
2925 maxlen * sizeof(U8 *));
2926 SvPOK_on(sv_points);
2927 sv_2mortal(sv_points);
2928 points=(U8**)SvPV_nolen(sv_points );
2929 if ( trie_type != trie_utf8_fold
2930 && (trie->bitmap || OP(c)==AHOCORASICKC) )
2933 bitmap=(U8*)trie->bitmap;
2935 bitmap=(U8*)ANYOF_BITMAP(c);
2937 /* this is the Aho-Corasick algorithm modified a touch
2938 to include special handling for long "unknown char" sequences.
2939 The basic idea being that we use AC as long as we are dealing
2940 with a possible matching char, when we encounter an unknown char
2941 (and we have not encountered an accepting state) we scan forward
2942 until we find a legal starting char.
2943 AC matching is basically that of trie matching, except that when
2944 we encounter a failing transition, we fall back to the current
2945 states "fail state", and try the current char again, a process
2946 we repeat until we reach the root state, state 1, or a legal
2947 transition. If we fail on the root state then we can either
2948 terminate if we have reached an accepting state previously, or
2949 restart the entire process from the beginning if we have not.
2952 while (s <= last_start) {
2953 const U32 uniflags = UTF8_ALLOW_DEFAULT;
2961 U8 *uscan = (U8*)NULL;
2962 U8 *leftmost = NULL;
2964 U32 accepted_word= 0;
2968 while ( state && uc <= (U8*)strend ) {
2970 U32 word = aho->states[ state ].wordnum;
2974 DEBUG_TRIE_EXECUTE_r(
2975 if ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2976 dump_exec_pos( (char *)uc, c, strend, real_start,
2977 (char *)uc, utf8_target, 0 );
2978 Perl_re_printf( aTHX_
2979 " Scanning for legal start char...\n");
2983 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2987 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2993 if (uc >(U8*)last_start) break;
2997 U8 *lpos= points[ (pointpos - trie->wordinfo[word].len) % maxlen ];
2998 if (!leftmost || lpos < leftmost) {
2999 DEBUG_r(accepted_word=word);
3005 points[pointpos++ % maxlen]= uc;
3006 if (foldlen || uc < (U8*)strend) {
3007 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
3008 (U8 *) strend, uscan, len, uvc,
3009 charid, foldlen, foldbuf,
3011 DEBUG_TRIE_EXECUTE_r({
3012 dump_exec_pos( (char *)uc, c, strend,
3013 real_start, s, utf8_target, 0);
3014 Perl_re_printf( aTHX_
3015 " Charid:%3u CP:%4" UVxf " ",
3027 word = aho->states[ state ].wordnum;
3029 base = aho->states[ state ].trans.base;
3031 DEBUG_TRIE_EXECUTE_r({
3033 dump_exec_pos( (char *)uc, c, strend, real_start,
3034 s, utf8_target, 0 );
3035 Perl_re_printf( aTHX_
3036 "%sState: %4" UVxf ", word=%" UVxf,
3037 failed ? " Fail transition to " : "",
3038 (UV)state, (UV)word);
3044 ( ((offset = base + charid
3045 - 1 - trie->uniquecharcount)) >= 0)
3046 && ((U32)offset < trie->lasttrans)
3047 && trie->trans[offset].check == state
3048 && (tmp=trie->trans[offset].next))
3050 DEBUG_TRIE_EXECUTE_r(
3051 Perl_re_printf( aTHX_ " - legal\n"));
3056 DEBUG_TRIE_EXECUTE_r(
3057 Perl_re_printf( aTHX_ " - fail\n"));
3059 state = aho->fail[state];
3063 /* we must be accepting here */
3064 DEBUG_TRIE_EXECUTE_r(
3065 Perl_re_printf( aTHX_ " - accepting\n"));
3074 if (!state) state = 1;
3077 if ( aho->states[ state ].wordnum ) {
3078 U8 *lpos = points[ (pointpos - trie->wordinfo[aho->states[ state ].wordnum].len) % maxlen ];
3079 if (!leftmost || lpos < leftmost) {
3080 DEBUG_r(accepted_word=aho->states[ state ].wordnum);
3085 s = (char*)leftmost;
3086 DEBUG_TRIE_EXECUTE_r({
3087 Perl_re_printf( aTHX_ "Matches word #%" UVxf " at position %" IVdf ". Trying full pattern...\n",
3088 (UV)accepted_word, (IV)(s - real_start)
3091 if (reginfo->intuit || regtry(reginfo, &s)) {
3096 if (s < reginfo->strend) {
3099 DEBUG_TRIE_EXECUTE_r({
3100 Perl_re_printf( aTHX_ "Pattern failed. Looking for new start point...\n");
3103 DEBUG_TRIE_EXECUTE_r(
3104 Perl_re_printf( aTHX_ "No match.\n"));
3113 Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
3120 /* set RX_SAVED_COPY, RX_SUBBEG etc.
3121 * flags have same meanings as with regexec_flags() */
3124 S_reg_set_capture_string(pTHX_ REGEXP * const rx,
3131 struct regexp *const prog = ReANY(rx);
3133 if (flags & REXEC_COPY_STR) {
3136 DEBUG_C(Perl_re_printf( aTHX_
3137 "Copy on write: regexp capture, type %d\n",
3139 /* Create a new COW SV to share the match string and store
3140 * in saved_copy, unless the current COW SV in saved_copy
3141 * is valid and suitable for our purpose */
3142 if (( prog->saved_copy
3143 && SvIsCOW(prog->saved_copy)
3144 && SvPOKp(prog->saved_copy)
3147 && SvPVX(sv) == SvPVX(prog->saved_copy)))
3149 /* just reuse saved_copy SV */
3150 if (RXp_MATCH_COPIED(prog)) {
3151 Safefree(prog->subbeg);
3152 RXp_MATCH_COPIED_off(prog);
3156 /* create new COW SV to share string */
3157 RXp_MATCH_COPY_FREE(prog);
3158 prog->saved_copy = sv_setsv_cow(prog->saved_copy, sv);
3160 prog->subbeg = (char *)SvPVX_const(prog->saved_copy);
3161 assert (SvPOKp(prog->saved_copy));
3162 prog->sublen = strend - strbeg;
3163 prog->suboffset = 0;
3164 prog->subcoffset = 0;
3169 SSize_t max = strend - strbeg;
3172 if ( (flags & REXEC_COPY_SKIP_POST)
3173 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
3174 && !(PL_sawampersand & SAWAMPERSAND_RIGHT)
3175 ) { /* don't copy $' part of string */
3178 /* calculate the right-most part of the string covered
3179 * by a capture. Due to lookahead, this may be to
3180 * the right of $&, so we have to scan all captures */
3181 while (n <= prog->lastparen) {
3182 if (prog->offs[n].end > max)
3183 max = prog->offs[n].end;
3187 max = (PL_sawampersand & SAWAMPERSAND_LEFT)
3188 ? prog->offs[0].start
3190 assert(max >= 0 && max <= strend - strbeg);
3193 if ( (flags & REXEC_COPY_SKIP_PRE)
3194 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
3195 && !(PL_sawampersand & SAWAMPERSAND_LEFT)
3196 ) { /* don't copy $` part of string */
3199 /* calculate the left-most part of the string covered
3200 * by a capture. Due to lookbehind, this may be to
3201 * the left of $&, so we have to scan all captures */
3202 while (min && n <= prog->lastparen) {
3203 if ( prog->offs[n].start != -1
3204 && prog->offs[n].start < min)
3206 min = prog->offs[n].start;
3210 if ((PL_sawampersand & SAWAMPERSAND_RIGHT)
3211 && min > prog->offs[0].end
3213 min = prog->offs[0].end;
3217 assert(min >= 0 && min <= max && min <= strend - strbeg);
3220 if (RXp_MATCH_COPIED(prog)) {
3221 if (sublen > prog->sublen)
3223 (char*)saferealloc(prog->subbeg, sublen+1);
3226 prog->subbeg = (char*)safemalloc(sublen+1);
3227 Copy(strbeg + min, prog->subbeg, sublen, char);
3228 prog->subbeg[sublen] = '\0';
3229 prog->suboffset = min;
3230 prog->sublen = sublen;
3231 RXp_MATCH_COPIED_on(prog);
3233 prog->subcoffset = prog->suboffset;
3234 if (prog->suboffset && utf8_target) {
3235 /* Convert byte offset to chars.
3236 * XXX ideally should only compute this if @-/@+
3237 * has been seen, a la PL_sawampersand ??? */
3239 /* If there's a direct correspondence between the
3240 * string which we're matching and the original SV,
3241 * then we can use the utf8 len cache associated with
3242 * the SV. In particular, it means that under //g,
3243 * sv_pos_b2u() will use the previously cached
3244 * position to speed up working out the new length of
3245 * subcoffset, rather than counting from the start of
3246 * the string each time. This stops
3247 * $x = "\x{100}" x 1E6; 1 while $x =~ /(.)/g;
3248 * from going quadratic */
3249 if (SvPOKp(sv) && SvPVX(sv) == strbeg)
3250 prog->subcoffset = sv_pos_b2u_flags(sv, prog->subcoffset,
3251 SV_GMAGIC|SV_CONST_RETURN);
3253 prog->subcoffset = utf8_length((U8*)strbeg,
3254 (U8*)(strbeg+prog->suboffset));
3258 RXp_MATCH_COPY_FREE(prog);
3259 prog->subbeg = strbeg;
3260 prog->suboffset = 0;
3261 prog->subcoffset = 0;
3262 prog->sublen = strend - strbeg;
3270 - regexec_flags - match a regexp against a string
3273 Perl_regexec_flags(pTHX_ REGEXP * const rx, char *stringarg, char *strend,
3274 char *strbeg, SSize_t minend, SV *sv, void *data, U32 flags)
3275 /* stringarg: the point in the string at which to begin matching */
3276 /* strend: pointer to null at end of string */
3277 /* strbeg: real beginning of string */
3278 /* minend: end of match must be >= minend bytes after stringarg. */
3279 /* sv: SV being matched: only used for utf8 flag, pos() etc; string
3280 * itself is accessed via the pointers above */
3281 /* data: May be used for some additional optimizations.
3282 Currently unused. */
3283 /* flags: For optimizations. See REXEC_* in regexp.h */
3286 struct regexp *const prog = ReANY(rx);
3290 SSize_t minlen; /* must match at least this many chars */
3291 SSize_t dontbother = 0; /* how many characters not to try at end */
3292 const bool utf8_target = cBOOL(DO_UTF8(sv));
3294 RXi_GET_DECL(prog,progi);
3295 regmatch_info reginfo_buf; /* create some info to pass to regtry etc */
3296 regmatch_info *const reginfo = ®info_buf;
3297 regexp_paren_pair *swap = NULL;
3299 DECLARE_AND_GET_RE_DEBUG_FLAGS;
3301 PERL_ARGS_ASSERT_REGEXEC_FLAGS;
3302 PERL_UNUSED_ARG(data);
3304 /* Be paranoid... */
3306 Perl_croak(aTHX_ "NULL regexp parameter");
3310 debug_start_match(rx, utf8_target, stringarg, strend,
3314 startpos = stringarg;
3316 /* set these early as they may be used by the HOP macros below */
3317 reginfo->strbeg = strbeg;
3318 reginfo->strend = strend;
3319 reginfo->is_utf8_target = cBOOL(utf8_target);
3321 if (prog->intflags & PREGf_GPOS_SEEN) {
3324 /* set reginfo->ganch, the position where \G can match */
3327 (flags & REXEC_IGNOREPOS)
3328 ? stringarg /* use start pos rather than pos() */
3329 : ((mg = mg_find_mglob(sv)) && mg->mg_len >= 0)
3330 /* Defined pos(): */
3331 ? strbeg + MgBYTEPOS(mg, sv, strbeg, strend-strbeg)
3332 : strbeg; /* pos() not defined; use start of string */
3334 DEBUG_GPOS_r(Perl_re_printf( aTHX_
3335 "GPOS ganch set to strbeg[%" IVdf "]\n", (IV)(reginfo->ganch - strbeg)));
3337 /* in the presence of \G, we may need to start looking earlier in
3338 * the string than the suggested start point of stringarg:
3339 * if prog->gofs is set, then that's a known, fixed minimum
3342 * /ab|c\G/: gofs = 1
3343 * or if the minimum offset isn't known, then we have to go back
3344 * to the start of the string, e.g. /w+\G/
3347 if (prog->intflags & PREGf_ANCH_GPOS) {
3349 startpos = HOPBACKc(reginfo->ganch, prog->gofs);
3351 ((flags & REXEC_FAIL_ON_UNDERFLOW) && startpos < stringarg))
3353 DEBUG_GPOS_r(Perl_re_printf( aTHX_
3354 "fail: ganch-gofs before earliest possible start\n"));
3359 startpos = reginfo->ganch;
3361 else if (prog->gofs) {
3362 startpos = HOPBACKc(startpos, prog->gofs);
3366 else if (prog->intflags & PREGf_GPOS_FLOAT)
3370 minlen = prog->minlen;
3371 if ((startpos + minlen) > strend || startpos < strbeg) {
3372 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
3373 "Regex match can't succeed, so not even tried\n"));
3377 /* at the end of this function, we'll do a LEAVE_SCOPE(oldsave),
3378 * which will call destuctors to reset PL_regmatch_state, free higher
3379 * PL_regmatch_slabs, and clean up regmatch_info_aux and
3380 * regmatch_info_aux_eval */
3382 oldsave = PL_savestack_ix;
3386 if ((prog->extflags & RXf_USE_INTUIT)
3387 && !(flags & REXEC_CHECKED))
3389 s = re_intuit_start(rx, sv, strbeg, startpos, strend,
3394 if (prog->extflags & RXf_CHECK_ALL) {
3395 /* we can match based purely on the result of INTUIT.
3396 * Set up captures etc just for $& and $-[0]
3397 * (an intuit-only match wont have $1,$2,..) */
3398 assert(!prog->nparens);
3400 /* s/// doesn't like it if $& is earlier than where we asked it to
3401 * start searching (which can happen on something like /.\G/) */
3402 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
3405 /* this should only be possible under \G */
3406 assert(prog->intflags & PREGf_GPOS_SEEN);
3407 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
3408 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3412 /* match via INTUIT shouldn't have any captures.
3413 * Let @-, @+, $^N know */
3414 prog->lastparen = prog->lastcloseparen = 0;
3415 RXp_MATCH_UTF8_set(prog, utf8_target);
3416 prog->offs[0].start = s - strbeg;
3417 prog->offs[0].end = utf8_target
3418 ? (char*)utf8_hop_forward((U8*)s, prog->minlenret, (U8 *) strend) - strbeg
3419 : s - strbeg + prog->minlenret;
3420 if ( !(flags & REXEC_NOT_FIRST) )
3421 S_reg_set_capture_string(aTHX_ rx,
3423 sv, flags, utf8_target);
3429 multiline = prog->extflags & RXf_PMf_MULTILINE;
3431 if (strend - s < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
3432 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
3433 "String too short [regexec_flags]...\n"));
3437 /* Check validity of program. */
3438 if (UCHARAT(progi->program) != REG_MAGIC) {
3439 Perl_croak(aTHX_ "corrupted regexp program");
3442 RXp_MATCH_TAINTED_off(prog);
3443 RXp_MATCH_UTF8_set(prog, utf8_target);
3445 reginfo->prog = rx; /* Yes, sorry that this is confusing. */
3446 reginfo->intuit = 0;
3447 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
3448 reginfo->warned = FALSE;
3450 reginfo->poscache_maxiter = 0; /* not yet started a countdown */
3451 /* see how far we have to get to not match where we matched before */
3452 reginfo->till = stringarg + minend;
3454 if (prog->extflags & RXf_EVAL_SEEN && SvPADTMP(sv)) {
3455 /* SAVEFREESV, not sv_mortalcopy, as this SV must last until after
3456 S_cleanup_regmatch_info_aux has executed (registered by
3457 SAVEDESTRUCTOR_X below). S_cleanup_regmatch_info_aux modifies
3458 magic belonging to this SV.
3459 Not newSVsv, either, as it does not COW.
3461 reginfo->sv = newSV(0);
3462 SvSetSV_nosteal(reginfo->sv, sv);
3463 SAVEFREESV(reginfo->sv);
3466 /* reserve next 2 or 3 slots in PL_regmatch_state:
3467 * slot N+0: may currently be in use: skip it
3468 * slot N+1: use for regmatch_info_aux struct
3469 * slot N+2: use for regmatch_info_aux_eval struct if we have (?{})'s
3470 * slot N+3: ready for use by regmatch()
3474 regmatch_state *old_regmatch_state;
3475 regmatch_slab *old_regmatch_slab;
3476 int i, max = (prog->extflags & RXf_EVAL_SEEN) ? 2 : 1;
3478 /* on first ever match, allocate first slab */
3479 if (!PL_regmatch_slab) {
3480 Newx(PL_regmatch_slab, 1, regmatch_slab);
3481 PL_regmatch_slab->prev = NULL;
3482 PL_regmatch_slab->next = NULL;
3483 PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
3486 old_regmatch_state = PL_regmatch_state;
3487 old_regmatch_slab = PL_regmatch_slab;
3489 for (i=0; i <= max; i++) {
3491 reginfo->info_aux = &(PL_regmatch_state->u.info_aux);
3493 reginfo->info_aux_eval =
3494 reginfo->info_aux->info_aux_eval =
3495 &(PL_regmatch_state->u.info_aux_eval);
3497 if (++PL_regmatch_state > SLAB_LAST(PL_regmatch_slab))
3498 PL_regmatch_state = S_push_slab(aTHX);
3501 /* note initial PL_regmatch_state position; at end of match we'll
3502 * pop back to there and free any higher slabs */
3504 reginfo->info_aux->old_regmatch_state = old_regmatch_state;
3505 reginfo->info_aux->old_regmatch_slab = old_regmatch_slab;
3506 reginfo->info_aux->poscache = NULL;
3508 SAVEDESTRUCTOR_X(S_cleanup_regmatch_info_aux, reginfo->info_aux);
3510 if ((prog->extflags & RXf_EVAL_SEEN))
3511 S_setup_eval_state(aTHX_ reginfo);
3513 reginfo->info_aux_eval = reginfo->info_aux->info_aux_eval = NULL;
3516 /* If there is a "must appear" string, look for it. */
3518 if (PL_curpm && (PM_GETRE(PL_curpm) == rx)) {
3519 /* We have to be careful. If the previous successful match
3520 was from this regex we don't want a subsequent partially
3521 successful match to clobber the old results.
3522 So when we detect this possibility we add a swap buffer
3523 to the re, and switch the buffer each match. If we fail,
3524 we switch it back; otherwise we leave it swapped.
3527 /* avoid leak if we die, or clean up anyway if match completes */
3529 Newxz(prog->offs, (prog->nparens + 1), regexp_paren_pair);
3530 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_
3531 "rex=0x%" UVxf " saving offs: orig=0x%" UVxf " new=0x%" UVxf "\n",
3539 if (prog->recurse_locinput)
3540 Zero(prog->recurse_locinput,prog->nparens + 1, char *);
3542 /* Simplest case: anchored match need be tried only once, or with
3543 * MBOL, only at the beginning of each line.
3545 * Note that /.*.../ sets PREGf_IMPLICIT|MBOL, while /.*.../s sets
3546 * PREGf_IMPLICIT|SBOL. The idea is that with /.*.../s, if it doesn't
3547 * match at the start of the string then it won't match anywhere else
3548 * either; while with /.*.../, if it doesn't match at the beginning,
3549 * the earliest it could match is at the start of the next line */
3551 if (prog->intflags & (PREGf_ANCH & ~PREGf_ANCH_GPOS)) {
3554 if (regtry(reginfo, &s))
3557 if (!(prog->intflags & PREGf_ANCH_MBOL))
3560 /* didn't match at start, try at other newline positions */
3563 dontbother = minlen - 1;
3564 end = HOP3c(strend, -dontbother, strbeg) - 1;
3566 /* skip to next newline */
3568 while (s <= end) { /* note it could be possible to match at the end of the string */
3569 /* NB: newlines are the same in unicode as they are in latin */
3572 if (prog->check_substr || prog->check_utf8) {
3573 /* note that with PREGf_IMPLICIT, intuit can only fail
3574 * or return the start position, so it's of limited utility.
3575 * Nevertheless, I made the decision that the potential for
3576 * quick fail was still worth it - DAPM */
3577 s = re_intuit_start(rx, sv, strbeg, s, strend, flags, NULL);
3581 if (regtry(reginfo, &s))
3585 } /* end anchored search */
3587 if (prog->intflags & PREGf_ANCH_GPOS)
3589 /* PREGf_ANCH_GPOS should never be true if PREGf_GPOS_SEEN is not true */
3590 assert(prog->intflags & PREGf_GPOS_SEEN);
3591 /* For anchored \G, the only position it can match from is
3592 * (ganch-gofs); we already set startpos to this above; if intuit
3593 * moved us on from there, we can't possibly succeed */
3594 assert(startpos == HOPBACKc(reginfo->ganch, prog->gofs));
3595 if (s == startpos && regtry(reginfo, &s))
3600 /* Messy cases: unanchored match. */
3601 if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
3602 /* we have /x+whatever/ */
3603 /* it must be a one character string (XXXX Except is_utf8_pat?) */
3609 if (! prog->anchored_utf8) {
3610 to_utf8_substr(prog);
3612 ch = SvPVX_const(prog->anchored_utf8)[0];
3613 REXEC_FBC_SCAN(1, /* 1=>utf8 */
3615 DEBUG_EXECUTE_r( did_match = 1 );
3616 if (regtry(reginfo, &s)) goto got_it;
3617 s += UTF8_SAFE_SKIP(s, strend);
3618 while (s < strend && *s == ch)
3625 if (! prog->anchored_substr) {
3626 if (! to_byte_substr(prog)) {
3627 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3630 ch = SvPVX_const(prog->anchored_substr)[0];
3631 REXEC_FBC_SCAN(0, /* 0=>not-utf8 */
3633 DEBUG_EXECUTE_r( did_match = 1 );
3634 if (regtry(reginfo, &s)) goto got_it;
3636 while (s < strend && *s == ch)
3641 DEBUG_EXECUTE_r(if (!did_match)
3642 Perl_re_printf( aTHX_
3643 "Did not find anchored character...\n")
3646 else if (prog->anchored_substr != NULL
3647 || prog->anchored_utf8 != NULL
3648 || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
3649 && prog->float_max_offset < strend - s)) {
3654 char *last1; /* Last position checked before */
3658 if (prog->anchored_substr || prog->anchored_utf8) {
3660 if (! prog->anchored_utf8) {
3661 to_utf8_substr(prog);
3663 must = prog->anchored_utf8;
3666 if (! prog->anchored_substr) {
3667 if (! to_byte_substr(prog)) {
3668 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3671 must = prog->anchored_substr;
3673 back_max = back_min = prog->anchored_offset;
3676 if (! prog->float_utf8) {
3677 to_utf8_substr(prog);
3679 must = prog->float_utf8;
3682 if (! prog->float_substr) {
3683 if (! to_byte_substr(prog)) {
3684 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3687 must = prog->float_substr;
3689 back_max = prog->float_max_offset;
3690 back_min = prog->float_min_offset;
3696 last = HOP3c(strend, /* Cannot start after this */
3697 -(SSize_t)(CHR_SVLEN(must)
3698 - (SvTAIL(must) != 0) + back_min), strbeg);
3700 if (s > reginfo->strbeg)
3701 last1 = HOPc(s, -1);
3703 last1 = s - 1; /* bogus */
3705 /* XXXX check_substr already used to find "s", can optimize if
3706 check_substr==must. */
3708 strend = HOPc(strend, -dontbother);
3709 while ( (s <= last) &&
3710 (s = fbm_instr((unsigned char*)HOP4c(s, back_min, strbeg, strend),
3711 (unsigned char*)strend, must,
3712 multiline ? FBMrf_MULTILINE : 0)) ) {
3713 DEBUG_EXECUTE_r( did_match = 1 );
3714 if (HOPc(s, -back_max) > last1) {
3715 last1 = HOPc(s, -back_min);
3716 s = HOPc(s, -back_max);
3719 char * const t = (last1 >= reginfo->strbeg)
3720 ? HOPc(last1, 1) : last1 + 1;
3722 last1 = HOPc(s, -back_min);
3726 while (s <= last1) {
3727 if (regtry(reginfo, &s))
3730 s++; /* to break out of outer loop */
3737 while (s <= last1) {
3738 if (regtry(reginfo, &s))
3744 DEBUG_EXECUTE_r(if (!did_match) {
3745 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
3746 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
3747 Perl_re_printf( aTHX_ "Did not find %s substr %s%s...\n",
3748 ((must == prog->anchored_substr || must == prog->anchored_utf8)
3749 ? "anchored" : "floating"),
3750 quoted, RE_SV_TAIL(must));
3754 else if ( (c = progi->regstclass) ) {
3756 const OPCODE op = OP(progi->regstclass);
3757 /* don't bother with what can't match */
3758 if (PL_regkind[op] != EXACT && PL_regkind[op] != TRIE)
3759 strend = HOPc(strend, -(minlen - 1));
3762 SV * const prop = sv_newmortal();
3763 regprop(prog, prop, c, reginfo, NULL);
3765 RE_PV_QUOTED_DECL(quoted,utf8_target,PERL_DEBUG_PAD_ZERO(1),
3766 s,strend-s,PL_dump_re_max_len);
3767 Perl_re_printf( aTHX_
3768 "Matching stclass %.*s against %s (%d bytes)\n",
3769 (int)SvCUR(prop), SvPVX_const(prop),
3770 quoted, (int)(strend - s));
3773 if (find_byclass(prog, c, s, strend, reginfo))
3775 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "Contradicts stclass... [regexec_flags]\n"));
3779 if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
3787 if (! prog->float_utf8) {
3788 to_utf8_substr(prog);
3790 float_real = prog->float_utf8;
3793 if (! prog->float_substr) {
3794 if (! to_byte_substr(prog)) {
3795 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3798 float_real = prog->float_substr;
3801 little = SvPV_const(float_real, len);
3802 if (SvTAIL(float_real)) {
3803 /* This means that float_real contains an artificial \n on
3804 * the end due to the presence of something like this:
3805 * /foo$/ where we can match both "foo" and "foo\n" at the
3806 * end of the string. So we have to compare the end of the
3807 * string first against the float_real without the \n and
3808 * then against the full float_real with the string. We
3809 * have to watch out for cases where the string might be
3810 * smaller than the float_real or the float_real without
3812 char *checkpos= strend - len;
3814 Perl_re_printf( aTHX_
3815 "%sChecking for float_real.%s\n",
3816 PL_colors[4], PL_colors[5]));
3817 if (checkpos + 1 < strbeg) {
3818 /* can't match, even if we remove the trailing \n
3819 * string is too short to match */
3821 Perl_re_printf( aTHX_