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 static const char b_utf8_locale_required[] =
87 "Use of \\b{} or \\B{} for non-UTF-8 locale is wrong."
88 " Assuming a UTF-8 locale";
90 #define CHECK_AND_WARN_NON_UTF8_CTYPE_LOCALE_IN_BOUND \
92 if (! IN_UTF8_CTYPE_LOCALE) { \
93 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), \
94 b_utf8_locale_required); \
98 static const char sets_utf8_locale_required[] =
99 "Use of (?[ ]) for non-UTF-8 locale is wrong. Assuming a UTF-8 locale";
101 #define CHECK_AND_WARN_NON_UTF8_CTYPE_LOCALE_IN_SETS(n) \
103 if (! IN_UTF8_CTYPE_LOCALE && ANYOFL_UTF8_LOCALE_REQD(FLAGS(n))) { \
104 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), \
105 sets_utf8_locale_required); \
110 /* At least one required character in the target string is expressible only in
112 static const char non_utf8_target_but_utf8_required[]
113 = "Can't match, because target string needs to be in UTF-8\n";
116 #define NON_UTF8_TARGET_BUT_UTF8_REQUIRED(target) STMT_START { \
117 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%s", non_utf8_target_but_utf8_required));\
122 #define STATIC static
129 #define CHR_SVLEN(sv) (utf8_target ? sv_len_utf8(sv) : SvCUR(sv))
131 #define HOPc(pos,off) \
132 (char *)(reginfo->is_utf8_target \
133 ? reghop3((U8*)pos, off, \
134 (U8*)(off >= 0 ? reginfo->strend : reginfo->strbeg)) \
137 /* like HOPMAYBE3 but backwards. lim must be +ve. Returns NULL on overshoot */
138 #define HOPBACK3(pos, off, lim) \
139 (reginfo->is_utf8_target \
140 ? reghopmaybe3((U8*)pos, (SSize_t)0-off, (U8*)(lim)) \
141 : (pos - off >= lim) \
145 #define HOPBACKc(pos, off) ((char*)HOPBACK3(pos, off, reginfo->strbeg))
147 #define HOP3(pos,off,lim) (reginfo->is_utf8_target ? reghop3((U8*)(pos), off, (U8*)(lim)) : (U8*)(pos + off))
148 #define HOP3c(pos,off,lim) ((char*)HOP3(pos,off,lim))
150 /* lim must be +ve. Returns NULL on overshoot */
151 #define HOPMAYBE3(pos,off,lim) \
152 (reginfo->is_utf8_target \
153 ? reghopmaybe3((U8*)pos, off, (U8*)(lim)) \
154 : ((U8*)pos + off <= lim) \
158 /* like HOP3, but limits the result to <= lim even for the non-utf8 case.
159 * off must be >=0; args should be vars rather than expressions */
160 #define HOP3lim(pos,off,lim) (reginfo->is_utf8_target \
161 ? reghop3((U8*)(pos), off, (U8*)(lim)) \
162 : (U8*)((pos + off) > lim ? lim : (pos + off)))
163 #define HOP3clim(pos,off,lim) ((char*)HOP3lim(pos,off,lim))
165 #define HOP4(pos,off,llim, rlim) (reginfo->is_utf8_target \
166 ? reghop4((U8*)(pos), off, (U8*)(llim), (U8*)(rlim)) \
168 #define HOP4c(pos,off,llim, rlim) ((char*)HOP4(pos,off,llim, rlim))
170 #define PLACEHOLDER /* Something for the preprocessor to grab onto */
171 /* TODO: Combine JUMPABLE and HAS_TEXT to cache OP(rn) */
173 /* for use after a quantifier and before an EXACT-like node -- japhy */
174 /* it would be nice to rework regcomp.sym to generate this stuff. sigh
176 * NOTE that *nothing* that affects backtracking should be in here, specifically
177 * VERBS must NOT be included. JUMPABLE is used to determine if we can ignore a
178 * node that is in between two EXACT like nodes when ascertaining what the required
179 * "follow" character is. This should probably be moved to regex compile time
180 * although it may be done at run time beause of the REF possibility - more
181 * investigation required. -- demerphq
183 #define JUMPABLE(rn) ( \
185 (OP(rn) == CLOSE && \
186 !EVAL_CLOSE_PAREN_IS(cur_eval,ARG(rn)) ) || \
188 OP(rn) == SUSPEND || OP(rn) == IFMATCH || \
189 OP(rn) == PLUS || OP(rn) == MINMOD || \
191 (PL_regkind[OP(rn)] == CURLY && ARG1(rn) > 0) \
193 #define IS_EXACT(rn) (PL_regkind[OP(rn)] == EXACT)
195 #define HAS_TEXT(rn) ( IS_EXACT(rn) || PL_regkind[OP(rn)] == REF )
198 Search for mandatory following text node; for lookahead, the text must
199 follow but for lookbehind (rn->flags != 0) we skip to the next step.
201 #define FIND_NEXT_IMPT(rn) STMT_START { \
202 while (JUMPABLE(rn)) { \
203 const OPCODE type = OP(rn); \
204 if (type == SUSPEND || PL_regkind[type] == CURLY) \
205 rn = NEXTOPER(NEXTOPER(rn)); \
206 else if (type == PLUS) \
208 else if (type == IFMATCH) \
209 rn = (rn->flags == 0) ? NEXTOPER(NEXTOPER(rn)) : rn + ARG(rn); \
210 else rn += NEXT_OFF(rn); \
214 #define SLAB_FIRST(s) (&(s)->states[0])
215 #define SLAB_LAST(s) (&(s)->states[PERL_REGMATCH_SLAB_SLOTS-1])
217 static void S_setup_eval_state(pTHX_ regmatch_info *const reginfo);
218 static void S_cleanup_regmatch_info_aux(pTHX_ void *arg);
219 static regmatch_state * S_push_slab(pTHX);
221 #define REGCP_PAREN_ELEMS 3
222 #define REGCP_OTHER_ELEMS 3
223 #define REGCP_FRAME_ELEMS 1
224 /* REGCP_FRAME_ELEMS are not part of the REGCP_OTHER_ELEMS and
225 * are needed for the regexp context stack bookkeeping. */
228 S_regcppush(pTHX_ const regexp *rex, I32 parenfloor, U32 maxopenparen _pDEPTH)
230 const int retval = PL_savestack_ix;
231 const int paren_elems_to_push =
232 (maxopenparen - parenfloor) * REGCP_PAREN_ELEMS;
233 const UV total_elems = paren_elems_to_push + REGCP_OTHER_ELEMS;
234 const UV elems_shifted = total_elems << SAVE_TIGHT_SHIFT;
236 DECLARE_AND_GET_RE_DEBUG_FLAGS;
238 PERL_ARGS_ASSERT_REGCPPUSH;
240 if (paren_elems_to_push < 0)
241 Perl_croak(aTHX_ "panic: paren_elems_to_push, %i < 0, maxopenparen: %i parenfloor: %i REGCP_PAREN_ELEMS: %u",
242 (int)paren_elems_to_push, (int)maxopenparen,
243 (int)parenfloor, (unsigned)REGCP_PAREN_ELEMS);
245 if ((elems_shifted >> SAVE_TIGHT_SHIFT) != total_elems)
246 Perl_croak(aTHX_ "panic: paren_elems_to_push offset %" UVuf
247 " out of range (%lu-%ld)",
249 (unsigned long)maxopenparen,
252 SSGROW(total_elems + REGCP_FRAME_ELEMS);
255 if ((int)maxopenparen > (int)parenfloor)
256 Perl_re_exec_indentf( aTHX_
257 "rex=0x%" UVxf " offs=0x%" UVxf ": saving capture indices:\n",
263 for (p = parenfloor+1; p <= (I32)maxopenparen; p++) {
264 /* REGCP_PARENS_ELEMS are pushed per pairs of parentheses. */
265 SSPUSHIV(rex->offs[p].end);
266 SSPUSHIV(rex->offs[p].start);
267 SSPUSHINT(rex->offs[p].start_tmp);
268 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_
269 " \\%" UVuf ": %" IVdf "(%" IVdf ")..%" IVdf "\n",
272 (IV)rex->offs[p].start,
273 (IV)rex->offs[p].start_tmp,
277 /* REGCP_OTHER_ELEMS are pushed in any case, parentheses or no. */
278 SSPUSHINT(maxopenparen);
279 SSPUSHINT(rex->lastparen);
280 SSPUSHINT(rex->lastcloseparen);
281 SSPUSHUV(SAVEt_REGCONTEXT | elems_shifted); /* Magic cookie. */
286 /* These are needed since we do not localize EVAL nodes: */
287 #define REGCP_SET(cp) \
289 Perl_re_exec_indentf( aTHX_ \
290 "Setting an EVAL scope, savestack=%" IVdf ",\n", \
291 depth, (IV)PL_savestack_ix \
296 #define REGCP_UNWIND(cp) \
298 if (cp != PL_savestack_ix) \
299 Perl_re_exec_indentf( aTHX_ \
300 "Clearing an EVAL scope, savestack=%" \
301 IVdf "..%" IVdf "\n", \
302 depth, (IV)(cp), (IV)PL_savestack_ix \
307 /* set the start and end positions of capture ix */
308 #define CLOSE_CAPTURE(ix, s, e) \
309 rex->offs[ix].start = s; \
310 rex->offs[ix].end = e; \
311 if (ix > rex->lastparen) \
312 rex->lastparen = ix; \
313 rex->lastcloseparen = ix; \
314 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_ \
315 "CLOSE: rex=0x%" UVxf " offs=0x%" UVxf ": \\%" UVuf ": set %" IVdf "..%" IVdf " max: %" UVuf "\n", \
320 (IV)rex->offs[ix].start, \
321 (IV)rex->offs[ix].end, \
325 #define UNWIND_PAREN(lp, lcp) \
326 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_ \
327 "UNWIND_PAREN: rex=0x%" UVxf " offs=0x%" UVxf ": invalidate (%" UVuf "..%" UVuf "] set lcp: %" UVuf "\n", \
332 (UV)(rex->lastparen), \
335 for (n = rex->lastparen; n > lp; n--) \
336 rex->offs[n].end = -1; \
337 rex->lastparen = n; \
338 rex->lastcloseparen = lcp;
342 S_regcppop(pTHX_ regexp *rex, U32 *maxopenparen_p _pDEPTH)
346 DECLARE_AND_GET_RE_DEBUG_FLAGS;
348 PERL_ARGS_ASSERT_REGCPPOP;
350 /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
352 assert((i & SAVE_MASK) == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
353 i >>= SAVE_TIGHT_SHIFT; /* Parentheses elements to pop. */
354 rex->lastcloseparen = SSPOPINT;
355 rex->lastparen = SSPOPINT;
356 *maxopenparen_p = SSPOPINT;
358 i -= REGCP_OTHER_ELEMS;
359 /* Now restore the parentheses context. */
361 if (i || rex->lastparen + 1 <= rex->nparens)
362 Perl_re_exec_indentf( aTHX_
363 "rex=0x%" UVxf " offs=0x%" UVxf ": restoring capture indices to:\n",
369 paren = *maxopenparen_p;
370 for ( ; i > 0; i -= REGCP_PAREN_ELEMS) {
372 rex->offs[paren].start_tmp = SSPOPINT;
373 rex->offs[paren].start = SSPOPIV;
375 if (paren <= rex->lastparen)
376 rex->offs[paren].end = tmps;
377 DEBUG_BUFFERS_r( Perl_re_exec_indentf( aTHX_
378 " \\%" UVuf ": %" IVdf "(%" IVdf ")..%" IVdf "%s\n",
381 (IV)rex->offs[paren].start,
382 (IV)rex->offs[paren].start_tmp,
383 (IV)rex->offs[paren].end,
384 (paren > rex->lastparen ? "(skipped)" : ""));
389 /* It would seem that the similar code in regtry()
390 * already takes care of this, and in fact it is in
391 * a better location to since this code can #if 0-ed out
392 * but the code in regtry() is needed or otherwise tests
393 * requiring null fields (pat.t#187 and split.t#{13,14}
394 * (as of patchlevel 7877) will fail. Then again,
395 * this code seems to be necessary or otherwise
396 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
397 * --jhi updated by dapm */
398 for (i = rex->lastparen + 1; i <= rex->nparens; i++) {
399 if (i > *maxopenparen_p)
400 rex->offs[i].start = -1;
401 rex->offs[i].end = -1;
402 DEBUG_BUFFERS_r( Perl_re_exec_indentf( aTHX_
403 " \\%" UVuf ": %s ..-1 undeffing\n",
406 (i > *maxopenparen_p) ? "-1" : " "
412 /* restore the parens and associated vars at savestack position ix,
413 * but without popping the stack */
416 S_regcp_restore(pTHX_ regexp *rex, I32 ix, U32 *maxopenparen_p _pDEPTH)
418 I32 tmpix = PL_savestack_ix;
419 PERL_ARGS_ASSERT_REGCP_RESTORE;
421 PL_savestack_ix = ix;
422 regcppop(rex, maxopenparen_p);
423 PL_savestack_ix = tmpix;
426 #define regcpblow(cp) LEAVE_SCOPE(cp) /* Ignores regcppush()ed data. */
428 #ifndef PERL_IN_XSUB_RE
431 Perl_isFOO_lc(pTHX_ const U8 classnum, const U8 character)
433 /* Returns a boolean as to whether or not 'character' is a member of the
434 * Posix character class given by 'classnum' that should be equivalent to a
435 * value in the typedef '_char_class_number'.
437 * Ideally this could be replaced by a just an array of function pointers
438 * to the C library functions that implement the macros this calls.
439 * However, to compile, the precise function signatures are required, and
440 * these may vary from platform to platform. To avoid having to figure
441 * out what those all are on each platform, I (khw) am using this method,
442 * which adds an extra layer of function call overhead (unless the C
443 * optimizer strips it away). But we don't particularly care about
444 * performance with locales anyway. */
446 switch ((_char_class_number) classnum) {
447 case _CC_ENUM_ALPHANUMERIC: return isALPHANUMERIC_LC(character);
448 case _CC_ENUM_ALPHA: return isALPHA_LC(character);
449 case _CC_ENUM_ASCII: return isASCII_LC(character);
450 case _CC_ENUM_BLANK: return isBLANK_LC(character);
451 case _CC_ENUM_CASED: return isLOWER_LC(character)
452 || isUPPER_LC(character);
453 case _CC_ENUM_CNTRL: return isCNTRL_LC(character);
454 case _CC_ENUM_DIGIT: return isDIGIT_LC(character);
455 case _CC_ENUM_GRAPH: return isGRAPH_LC(character);
456 case _CC_ENUM_LOWER: return isLOWER_LC(character);
457 case _CC_ENUM_PRINT: return isPRINT_LC(character);
458 case _CC_ENUM_PUNCT: return isPUNCT_LC(character);
459 case _CC_ENUM_SPACE: return isSPACE_LC(character);
460 case _CC_ENUM_UPPER: return isUPPER_LC(character);
461 case _CC_ENUM_WORDCHAR: return isWORDCHAR_LC(character);
462 case _CC_ENUM_XDIGIT: return isXDIGIT_LC(character);
463 default: /* VERTSPACE should never occur in locales */
464 Perl_croak(aTHX_ "panic: isFOO_lc() has an unexpected character class '%d'", classnum);
467 NOT_REACHED; /* NOTREACHED */
473 PERL_STATIC_INLINE I32
474 S_foldEQ_latin1_s2_folded(const char *s1, const char *s2, I32 len)
476 /* Compare non-UTF-8 using Unicode (Latin1) semantics. s2 must already be
477 * folded. Works on all folds representable without UTF-8, except for
478 * LATIN_SMALL_LETTER_SHARP_S, and does not check for this. Nor does it
479 * check that the strings each have at least 'len' characters.
481 * There is almost an identical API function where s2 need not be folded:
482 * Perl_foldEQ_latin1() */
484 const U8 *a = (const U8 *)s1;
485 const U8 *b = (const U8 *)s2;
487 PERL_ARGS_ASSERT_FOLDEQ_LATIN1_S2_FOLDED;
492 assert(! isUPPER_L1(*b));
493 if (toLOWER_L1(*a) != *b) {
502 S_isFOO_utf8_lc(pTHX_ const U8 classnum, const U8* character, const U8* e)
504 /* Returns a boolean as to whether or not the (well-formed) UTF-8-encoded
505 * 'character' is a member of the Posix character class given by 'classnum'
506 * that should be equivalent to a value in the typedef
507 * '_char_class_number'.
509 * This just calls isFOO_lc on the code point for the character if it is in
510 * the range 0-255. Outside that range, all characters use Unicode
511 * rules, ignoring any locale. So use the Unicode function if this class
512 * requires an inversion list, and use the Unicode macro otherwise. */
515 PERL_ARGS_ASSERT_ISFOO_UTF8_LC;
517 if (UTF8_IS_INVARIANT(*character)) {
518 return isFOO_lc(classnum, *character);
520 else if (UTF8_IS_DOWNGRADEABLE_START(*character)) {
521 return isFOO_lc(classnum,
522 EIGHT_BIT_UTF8_TO_NATIVE(*character, *(character + 1)));
525 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(character, e);
527 switch ((_char_class_number) classnum) {
528 case _CC_ENUM_SPACE: return is_XPERLSPACE_high(character);
529 case _CC_ENUM_BLANK: return is_HORIZWS_high(character);
530 case _CC_ENUM_XDIGIT: return is_XDIGIT_high(character);
531 case _CC_ENUM_VERTSPACE: return is_VERTWS_high(character);
533 return _invlist_contains_cp(PL_XPosix_ptrs[classnum],
534 utf8_to_uvchr_buf(character, e, NULL));
537 return FALSE; /* Things like CNTRL are always below 256 */
541 S_find_span_end(U8 * s, const U8 * send, const U8 span_byte)
543 /* Returns the position of the first byte in the sequence between 's' and
544 * 'send-1' inclusive that isn't 'span_byte'; returns 'send' if none found.
547 PERL_ARGS_ASSERT_FIND_SPAN_END;
551 if ((STRLEN) (send - s) >= PERL_WORDSIZE
552 + PERL_WORDSIZE * PERL_IS_SUBWORD_ADDR(s)
553 - (PTR2nat(s) & PERL_WORD_BOUNDARY_MASK))
555 PERL_UINTMAX_T span_word;
557 /* Process per-byte until reach word boundary. XXX This loop could be
558 * eliminated if we knew that this platform had fast unaligned reads */
559 while (PTR2nat(s) & PERL_WORD_BOUNDARY_MASK) {
560 if (*s != span_byte) {
566 /* Create a word filled with the bytes we are spanning */
567 span_word = PERL_COUNT_MULTIPLIER * span_byte;
569 /* Process per-word as long as we have at least a full word left */
572 /* Keep going if the whole word is composed of 'span_byte's */
573 if ((* (PERL_UINTMAX_T *) s) == span_word) {
578 /* Here, at least one byte in the word isn't 'span_byte'. */
586 /* This xor leaves 1 bits only in those non-matching bytes */
587 span_word ^= * (PERL_UINTMAX_T *) s;
589 /* Make sure the upper bit of each non-matching byte is set. This
590 * makes each such byte look like an ASCII platform variant byte */
591 span_word |= span_word << 1;
592 span_word |= span_word << 2;
593 span_word |= span_word << 4;
595 /* That reduces the problem to what this function solves */
596 return s + variant_byte_number(span_word);
600 } while (s + PERL_WORDSIZE <= send);
603 /* Process the straggler bytes beyond the final word boundary */
605 if (*s != span_byte) {
615 S_find_next_masked(U8 * s, const U8 * send, const U8 byte, const U8 mask)
617 /* Returns the position of the first byte in the sequence between 's'
618 * and 'send-1' inclusive that when ANDed with 'mask' yields 'byte';
619 * returns 'send' if none found. It uses word-level operations instead of
620 * byte to speed up the process */
622 PERL_ARGS_ASSERT_FIND_NEXT_MASKED;
625 assert((byte & mask) == byte);
629 if ((STRLEN) (send - s) >= PERL_WORDSIZE
630 + PERL_WORDSIZE * PERL_IS_SUBWORD_ADDR(s)
631 - (PTR2nat(s) & PERL_WORD_BOUNDARY_MASK))
633 PERL_UINTMAX_T word, mask_word;
635 while (PTR2nat(s) & PERL_WORD_BOUNDARY_MASK) {
636 if (((*s) & mask) == byte) {
642 word = PERL_COUNT_MULTIPLIER * byte;
643 mask_word = PERL_COUNT_MULTIPLIER * mask;
646 PERL_UINTMAX_T masked = (* (PERL_UINTMAX_T *) s) & mask_word;
648 /* If 'masked' contains bytes with the bit pattern of 'byte' within
649 * it, xoring with 'word' will leave each of the 8 bits in such
650 * bytes be 0, and no byte containing any other bit pattern will be
654 /* This causes the most significant bit to be set to 1 for any
655 * bytes in the word that aren't completely 0 */
656 masked |= masked << 1;
657 masked |= masked << 2;
658 masked |= masked << 4;
660 /* The msbits are the same as what marks a byte as variant, so we
661 * can use this mask. If all msbits are 1, the word doesn't
663 if ((masked & PERL_VARIANTS_WORD_MASK) == PERL_VARIANTS_WORD_MASK) {
668 /* Here, the msbit of bytes in the word that aren't 'byte' are 1,
669 * and any that are, are 0. Complement and re-AND to swap that */
671 masked &= PERL_VARIANTS_WORD_MASK;
673 /* This reduces the problem to that solved by this function */
674 s += variant_byte_number(masked);
677 } while (s + PERL_WORDSIZE <= send);
683 if (((*s) & mask) == byte) {
693 S_find_span_end_mask(U8 * s, const U8 * send, const U8 span_byte, const U8 mask)
695 /* Returns the position of the first byte in the sequence between 's' and
696 * 'send-1' inclusive that when ANDed with 'mask' isn't 'span_byte'.
697 * 'span_byte' should have been ANDed with 'mask' in the call of this
698 * function. Returns 'send' if none found. Works like find_span_end(),
699 * except for the AND */
701 PERL_ARGS_ASSERT_FIND_SPAN_END_MASK;
704 assert((span_byte & mask) == span_byte);
706 if ((STRLEN) (send - s) >= PERL_WORDSIZE
707 + PERL_WORDSIZE * PERL_IS_SUBWORD_ADDR(s)
708 - (PTR2nat(s) & PERL_WORD_BOUNDARY_MASK))
710 PERL_UINTMAX_T span_word, mask_word;
712 while (PTR2nat(s) & PERL_WORD_BOUNDARY_MASK) {
713 if (((*s) & mask) != span_byte) {
719 span_word = PERL_COUNT_MULTIPLIER * span_byte;
720 mask_word = PERL_COUNT_MULTIPLIER * mask;
723 PERL_UINTMAX_T masked = (* (PERL_UINTMAX_T *) s) & mask_word;
725 if (masked == span_word) {
737 masked |= masked << 1;
738 masked |= masked << 2;
739 masked |= masked << 4;
740 return s + variant_byte_number(masked);
744 } while (s + PERL_WORDSIZE <= send);
748 if (((*s) & mask) != span_byte) {
758 * pregexec and friends
761 #ifndef PERL_IN_XSUB_RE
763 - pregexec - match a regexp against a string
766 Perl_pregexec(pTHX_ REGEXP * const prog, char* stringarg, char *strend,
767 char *strbeg, SSize_t minend, SV *screamer, U32 nosave)
768 /* stringarg: the point in the string at which to begin matching */
769 /* strend: pointer to null at end of string */
770 /* strbeg: real beginning of string */
771 /* minend: end of match must be >= minend bytes after stringarg. */
772 /* screamer: SV being matched: only used for utf8 flag, pos() etc; string
773 * itself is accessed via the pointers above */
774 /* nosave: For optimizations. */
776 PERL_ARGS_ASSERT_PREGEXEC;
779 regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
780 nosave ? 0 : REXEC_COPY_STR);
786 /* re_intuit_start():
788 * Based on some optimiser hints, try to find the earliest position in the
789 * string where the regex could match.
791 * rx: the regex to match against
792 * sv: the SV being matched: only used for utf8 flag; the string
793 * itself is accessed via the pointers below. Note that on
794 * something like an overloaded SV, SvPOK(sv) may be false
795 * and the string pointers may point to something unrelated to
797 * strbeg: real beginning of string
798 * strpos: the point in the string at which to begin matching
799 * strend: pointer to the byte following the last char of the string
800 * flags currently unused; set to 0
801 * data: currently unused; set to NULL
803 * The basic idea of re_intuit_start() is to use some known information
804 * about the pattern, namely:
806 * a) the longest known anchored substring (i.e. one that's at a
807 * constant offset from the beginning of the pattern; but not
808 * necessarily at a fixed offset from the beginning of the
810 * b) the longest floating substring (i.e. one that's not at a constant
811 * offset from the beginning of the pattern);
812 * c) Whether the pattern is anchored to the string; either
813 * an absolute anchor: /^../, or anchored to \n: /^.../m,
814 * or anchored to pos(): /\G/;
815 * d) A start class: a real or synthetic character class which
816 * represents which characters are legal at the start of the pattern;
818 * to either quickly reject the match, or to find the earliest position
819 * within the string at which the pattern might match, thus avoiding
820 * running the full NFA engine at those earlier locations, only to
821 * eventually fail and retry further along.
823 * Returns NULL if the pattern can't match, or returns the address within
824 * the string which is the earliest place the match could occur.
826 * The longest of the anchored and floating substrings is called 'check'
827 * and is checked first. The other is called 'other' and is checked
828 * second. The 'other' substring may not be present. For example,
830 * /(abc|xyz)ABC\d{0,3}DEFG/
834 * check substr (float) = "DEFG", offset 6..9 chars
835 * other substr (anchored) = "ABC", offset 3..3 chars
838 * Be aware that during the course of this function, sometimes 'anchored'
839 * refers to a substring being anchored relative to the start of the
840 * pattern, and sometimes to the pattern itself being anchored relative to
841 * the string. For example:
843 * /\dabc/: "abc" is anchored to the pattern;
844 * /^\dabc/: "abc" is anchored to the pattern and the string;
845 * /\d+abc/: "abc" is anchored to neither the pattern nor the string;
846 * /^\d+abc/: "abc" is anchored to neither the pattern nor the string,
847 * but the pattern is anchored to the string.
851 Perl_re_intuit_start(pTHX_
854 const char * const strbeg,
858 re_scream_pos_data *data)
860 struct regexp *const prog = ReANY(rx);
861 SSize_t start_shift = prog->check_offset_min;
862 /* Should be nonnegative! */
863 SSize_t end_shift = 0;
864 /* current lowest pos in string where the regex can start matching */
865 char *rx_origin = strpos;
867 const bool utf8_target = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
868 U8 other_ix = 1 - prog->substrs->check_ix;
870 char *other_last = strpos;/* latest pos 'other' substr already checked to */
871 char *check_at = NULL; /* check substr found at this pos */
872 const I32 multiline = prog->extflags & RXf_PMf_MULTILINE;
873 RXi_GET_DECL(prog,progi);
874 regmatch_info reginfo_buf; /* create some info to pass to find_byclass */
875 regmatch_info *const reginfo = ®info_buf;
876 DECLARE_AND_GET_RE_DEBUG_FLAGS;
878 PERL_ARGS_ASSERT_RE_INTUIT_START;
879 PERL_UNUSED_ARG(flags);
880 PERL_UNUSED_ARG(data);
882 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
883 "Intuit: trying to determine minimum start position...\n"));
885 /* for now, assume that all substr offsets are positive. If at some point
886 * in the future someone wants to do clever things with lookbehind and
887 * -ve offsets, they'll need to fix up any code in this function
888 * which uses these offsets. See the thread beginning
889 * <20140113145929.GF27210@iabyn.com>
891 assert(prog->substrs->data[0].min_offset >= 0);
892 assert(prog->substrs->data[0].max_offset >= 0);
893 assert(prog->substrs->data[1].min_offset >= 0);
894 assert(prog->substrs->data[1].max_offset >= 0);
895 assert(prog->substrs->data[2].min_offset >= 0);
896 assert(prog->substrs->data[2].max_offset >= 0);
898 /* for now, assume that if both present, that the floating substring
899 * doesn't start before the anchored substring.
900 * If you break this assumption (e.g. doing better optimisations
901 * with lookahead/behind), then you'll need to audit the code in this
902 * function carefully first
905 ! ( (prog->anchored_utf8 || prog->anchored_substr)
906 && (prog->float_utf8 || prog->float_substr))
907 || (prog->float_min_offset >= prog->anchored_offset));
909 /* byte rather than char calculation for efficiency. It fails
910 * to quickly reject some cases that can't match, but will reject
911 * them later after doing full char arithmetic */
912 if (prog->minlen > strend - strpos) {
913 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
914 " String too short...\n"));
918 RXp_MATCH_UTF8_set(prog, utf8_target);
919 reginfo->is_utf8_target = cBOOL(utf8_target);
920 reginfo->info_aux = NULL;
921 reginfo->strbeg = strbeg;
922 reginfo->strend = strend;
923 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
925 /* not actually used within intuit, but zero for safety anyway */
926 reginfo->poscache_maxiter = 0;
929 if ((!prog->anchored_utf8 && prog->anchored_substr)
930 || (!prog->float_utf8 && prog->float_substr))
931 to_utf8_substr(prog);
932 check = prog->check_utf8;
934 if (!prog->check_substr && prog->check_utf8) {
935 if (! to_byte_substr(prog)) {
936 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(fail);
939 check = prog->check_substr;
942 /* dump the various substring data */
943 DEBUG_OPTIMISE_MORE_r({
945 for (i=0; i<=2; i++) {
946 SV *sv = (utf8_target ? prog->substrs->data[i].utf8_substr
947 : prog->substrs->data[i].substr);
951 Perl_re_printf( aTHX_
952 " substrs[%d]: min=%" IVdf " max=%" IVdf " end shift=%" IVdf
953 " useful=%" IVdf " utf8=%d [%s]\n",
955 (IV)prog->substrs->data[i].min_offset,
956 (IV)prog->substrs->data[i].max_offset,
957 (IV)prog->substrs->data[i].end_shift,
964 if (prog->intflags & PREGf_ANCH) { /* Match at \G, beg-of-str or after \n */
966 /* ml_anch: check after \n?
968 * A note about PREGf_IMPLICIT: on an un-anchored pattern beginning
969 * with /.*.../, these flags will have been added by the
971 * /.*abc/, /.*abc/m: PREGf_IMPLICIT | PREGf_ANCH_MBOL
972 * /.*abc/s: PREGf_IMPLICIT | PREGf_ANCH_SBOL
974 ml_anch = (prog->intflags & PREGf_ANCH_MBOL)
975 && !(prog->intflags & PREGf_IMPLICIT);
977 if (!ml_anch && !(prog->intflags & PREGf_IMPLICIT)) {
978 /* we are only allowed to match at BOS or \G */
980 /* trivially reject if there's a BOS anchor and we're not at BOS.
982 * Note that we don't try to do a similar quick reject for
983 * \G, since generally the caller will have calculated strpos
984 * based on pos() and gofs, so the string is already correctly
985 * anchored by definition; and handling the exceptions would
986 * be too fiddly (e.g. REXEC_IGNOREPOS).
988 if ( strpos != strbeg
989 && (prog->intflags & PREGf_ANCH_SBOL))
991 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
992 " Not at start...\n"));
996 /* in the presence of an anchor, the anchored (relative to the
997 * start of the regex) substr must also be anchored relative
998 * to strpos. So quickly reject if substr isn't found there.
999 * This works for \G too, because the caller will already have
1000 * subtracted gofs from pos, and gofs is the offset from the
1001 * \G to the start of the regex. For example, in /.abc\Gdef/,
1002 * where substr="abcdef", pos()=3, gofs=4, offset_min=1:
1003 * caller will have set strpos=pos()-4; we look for the substr
1004 * at position pos()-4+1, which lines up with the "a" */
1006 if (prog->check_offset_min == prog->check_offset_max) {
1007 /* Substring at constant offset from beg-of-str... */
1008 SSize_t slen = SvCUR(check);
1009 char *s = HOP3c(strpos, prog->check_offset_min, strend);
1011 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1012 " Looking for check substr at fixed offset %" IVdf "...\n",
1013 (IV)prog->check_offset_min));
1015 if (SvTAIL(check)) {
1016 /* In this case, the regex is anchored at the end too.
1017 * Unless it's a multiline match, the lengths must match
1018 * exactly, give or take a \n. NB: slen >= 1 since
1019 * the last char of check is \n */
1021 && ( strend - s > slen
1022 || strend - s < slen - 1
1023 || (strend - s == slen && strend[-1] != '\n')))
1025 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1026 " String too long...\n"));
1029 /* Now should match s[0..slen-2] */
1032 if (slen && (strend - s < slen
1033 || *SvPVX_const(check) != *s
1034 || (slen > 1 && (memNE(SvPVX_const(check), s, slen)))))
1036 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1037 " String not equal...\n"));
1042 goto success_at_start;
1047 end_shift = prog->check_end_shift;
1049 #ifdef DEBUGGING /* 7/99: reports of failure (with the older version) */
1051 Perl_croak(aTHX_ "panic: end_shift: %" IVdf " pattern:\n%s\n ",
1052 (IV)end_shift, RX_PRECOMP(rx));
1057 /* This is the (re)entry point of the main loop in this function.
1058 * The goal of this loop is to:
1059 * 1) find the "check" substring in the region rx_origin..strend
1060 * (adjusted by start_shift / end_shift). If not found, reject
1062 * 2) If it exists, look for the "other" substr too if defined; for
1063 * example, if the check substr maps to the anchored substr, then
1064 * check the floating substr, and vice-versa. If not found, go
1065 * back to (1) with rx_origin suitably incremented.
1066 * 3) If we find an rx_origin position that doesn't contradict
1067 * either of the substrings, then check the possible additional
1068 * constraints on rx_origin of /^.../m or a known start class.
1069 * If these fail, then depending on which constraints fail, jump
1070 * back to here, or to various other re-entry points further along
1071 * that skip some of the first steps.
1072 * 4) If we pass all those tests, update the BmUSEFUL() count on the
1073 * substring. If the start position was determined to be at the
1074 * beginning of the string - so, not rejected, but not optimised,
1075 * since we have to run regmatch from position 0 - decrement the
1076 * BmUSEFUL() count. Otherwise increment it.
1080 /* first, look for the 'check' substring */
1086 DEBUG_OPTIMISE_MORE_r({
1087 Perl_re_printf( aTHX_
1088 " At restart: rx_origin=%" IVdf " Check offset min: %" IVdf
1089 " Start shift: %" IVdf " End shift %" IVdf
1090 " Real end Shift: %" IVdf "\n",
1091 (IV)(rx_origin - strbeg),
1092 (IV)prog->check_offset_min,
1095 (IV)prog->check_end_shift);
1098 end_point = HOPBACK3(strend, end_shift, rx_origin);
1101 start_point = HOPMAYBE3(rx_origin, start_shift, end_point);
1106 /* If the regex is absolutely anchored to either the start of the
1107 * string (SBOL) or to pos() (ANCH_GPOS), then
1108 * check_offset_max represents an upper bound on the string where
1109 * the substr could start. For the ANCH_GPOS case, we assume that
1110 * the caller of intuit will have already set strpos to
1111 * pos()-gofs, so in this case strpos + offset_max will still be
1112 * an upper bound on the substr.
1115 && prog->intflags & PREGf_ANCH
1116 && prog->check_offset_max != SSize_t_MAX)
1118 SSize_t check_len = SvCUR(check) - !!SvTAIL(check);
1119 const char * const anchor =
1120 (prog->intflags & PREGf_ANCH_GPOS ? strpos : strbeg);
1121 SSize_t targ_len = (char*)end_point - anchor;
1123 if (check_len > targ_len) {
1124 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1125 "Target string too short to match required substring...\n"));
1129 /* do a bytes rather than chars comparison. It's conservative;
1130 * so it skips doing the HOP if the result can't possibly end
1131 * up earlier than the old value of end_point.
1133 assert(anchor + check_len <= (char *)end_point);
1134 if (prog->check_offset_max + check_len < targ_len) {
1135 end_point = HOP3lim((U8*)anchor,
1136 prog->check_offset_max,
1137 end_point - check_len
1140 if (end_point < start_point)
1145 check_at = fbm_instr( start_point, end_point,
1146 check, multiline ? FBMrf_MULTILINE : 0);
1148 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1149 " doing 'check' fbm scan, [%" IVdf "..%" IVdf "] gave %" IVdf "\n",
1150 (IV)((char*)start_point - strbeg),
1151 (IV)((char*)end_point - strbeg),
1152 (IV)(check_at ? check_at - strbeg : -1)
1155 /* Update the count-of-usability, remove useless subpatterns,
1159 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
1160 SvPVX_const(check), RE_SV_DUMPLEN(check), 30);
1161 Perl_re_printf( aTHX_ " %s %s substr %s%s%s",
1162 (check_at ? "Found" : "Did not find"),
1163 (check == (utf8_target ? prog->anchored_utf8 : prog->anchored_substr)
1164 ? "anchored" : "floating"),
1167 (check_at ? " at offset " : "...\n") );
1172 /* set rx_origin to the minimum position where the regex could start
1173 * matching, given the constraint of the just-matched check substring.
1174 * But don't set it lower than previously.
1177 if (check_at - rx_origin > prog->check_offset_max)
1178 rx_origin = HOP3c(check_at, -prog->check_offset_max, rx_origin);
1179 /* Finish the diagnostic message */
1180 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1181 "%ld (rx_origin now %" IVdf ")...\n",
1182 (long)(check_at - strbeg),
1183 (IV)(rx_origin - strbeg)
1188 /* now look for the 'other' substring if defined */
1190 if (prog->substrs->data[other_ix].utf8_substr
1191 || prog->substrs->data[other_ix].substr)
1193 /* Take into account the "other" substring. */
1197 struct reg_substr_datum *other;
1200 other = &prog->substrs->data[other_ix];
1201 if (!utf8_target && !other->substr) {
1202 if (!to_byte_substr(prog)) {
1203 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(fail);
1207 /* if "other" is anchored:
1208 * we've previously found a floating substr starting at check_at.
1209 * This means that the regex origin must lie somewhere
1210 * between min (rx_origin): HOP3(check_at, -check_offset_max)
1211 * and max: HOP3(check_at, -check_offset_min)
1212 * (except that min will be >= strpos)
1213 * So the fixed substr must lie somewhere between
1214 * HOP3(min, anchored_offset)
1215 * HOP3(max, anchored_offset) + SvCUR(substr)
1218 /* if "other" is floating
1219 * Calculate last1, the absolute latest point where the
1220 * floating substr could start in the string, ignoring any
1221 * constraints from the earlier fixed match. It is calculated
1224 * strend - prog->minlen (in chars) is the absolute latest
1225 * position within the string where the origin of the regex
1226 * could appear. The latest start point for the floating
1227 * substr is float_min_offset(*) on from the start of the
1228 * regex. last1 simply combines thee two offsets.
1230 * (*) You might think the latest start point should be
1231 * float_max_offset from the regex origin, and technically
1232 * you'd be correct. However, consider
1234 * Here, float min, max are 3,5 and minlen is 7.
1235 * This can match either
1239 * In the first case, the regex matches minlen chars; in the
1240 * second, minlen+1, in the third, minlen+2.
1241 * In the first case, the floating offset is 3 (which equals
1242 * float_min), in the second, 4, and in the third, 5 (which
1243 * equals float_max). In all cases, the floating string bcd
1244 * can never start more than 4 chars from the end of the
1245 * string, which equals minlen - float_min. As the substring
1246 * starts to match more than float_min from the start of the
1247 * regex, it makes the regex match more than minlen chars,
1248 * and the two cancel each other out. So we can always use
1249 * float_min - minlen, rather than float_max - minlen for the
1250 * latest position in the string.
1252 * Note that -minlen + float_min_offset is equivalent (AFAIKT)
1253 * to CHR_SVLEN(must) - !!SvTAIL(must) + prog->float_end_shift
1256 assert(prog->minlen >= other->min_offset);
1257 last1 = HOP3c(strend,
1258 other->min_offset - prog->minlen, strbeg);
1260 if (other_ix) {/* i.e. if (other-is-float) */
1261 /* last is the latest point where the floating substr could
1262 * start, *given* any constraints from the earlier fixed
1263 * match. This constraint is that the floating string starts
1264 * <= float_max_offset chars from the regex origin (rx_origin).
1265 * If this value is less than last1, use it instead.
1267 assert(rx_origin <= last1);
1269 /* this condition handles the offset==infinity case, and
1270 * is a short-cut otherwise. Although it's comparing a
1271 * byte offset to a char length, it does so in a safe way,
1272 * since 1 char always occupies 1 or more bytes,
1273 * so if a string range is (last1 - rx_origin) bytes,
1274 * it will be less than or equal to (last1 - rx_origin)
1275 * chars; meaning it errs towards doing the accurate HOP3
1276 * rather than just using last1 as a short-cut */
1277 (last1 - rx_origin) < other->max_offset
1279 : (char*)HOP3lim(rx_origin, other->max_offset, last1);
1282 assert(strpos + start_shift <= check_at);
1283 last = HOP4c(check_at, other->min_offset - start_shift,
1287 s = HOP3c(rx_origin, other->min_offset, strend);
1288 if (s < other_last) /* These positions already checked */
1291 must = utf8_target ? other->utf8_substr : other->substr;
1292 assert(SvPOK(must));
1295 char *to = last + SvCUR(must) - (SvTAIL(must)!=0);
1301 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1302 " skipping 'other' fbm scan: %" IVdf " > %" IVdf "\n",
1303 (IV)(from - strbeg),
1309 (unsigned char*)from,
1312 multiline ? FBMrf_MULTILINE : 0
1314 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1315 " doing 'other' fbm scan, [%" IVdf "..%" IVdf "] gave %" IVdf "\n",
1316 (IV)(from - strbeg),
1318 (IV)(s ? s - strbeg : -1)
1324 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
1325 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
1326 Perl_re_printf( aTHX_ " %s %s substr %s%s",
1327 s ? "Found" : "Contradicts",
1328 other_ix ? "floating" : "anchored",
1329 quoted, RE_SV_TAIL(must));
1334 /* last1 is latest possible substr location. If we didn't
1335 * find it before there, we never will */
1336 if (last >= last1) {
1337 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1338 "; giving up...\n"));
1342 /* try to find the check substr again at a later
1343 * position. Maybe next time we'll find the "other" substr
1345 other_last = HOP3c(last, 1, strend) /* highest failure */;
1347 other_ix /* i.e. if other-is-float */
1348 ? HOP3c(rx_origin, 1, strend)
1349 : HOP4c(last, 1 - other->min_offset, strbeg, strend);
1350 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1351 "; about to retry %s at offset %ld (rx_origin now %" IVdf ")...\n",
1352 (other_ix ? "floating" : "anchored"),
1353 (long)(HOP3c(check_at, 1, strend) - strbeg),
1354 (IV)(rx_origin - strbeg)
1359 if (other_ix) { /* if (other-is-float) */
1360 /* other_last is set to s, not s+1, since its possible for
1361 * a floating substr to fail first time, then succeed
1362 * second time at the same floating position; e.g.:
1363 * "-AB--AABZ" =~ /\wAB\d*Z/
1364 * The first time round, anchored and float match at
1365 * "-(AB)--AAB(Z)" then fail on the initial \w character
1366 * class. Second time round, they match at "-AB--A(AB)(Z)".
1371 rx_origin = HOP3c(s, -other->min_offset, strbeg);
1372 other_last = HOP3c(s, 1, strend);
1374 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1375 " at offset %ld (rx_origin now %" IVdf ")...\n",
1377 (IV)(rx_origin - strbeg)
1383 DEBUG_OPTIMISE_MORE_r(
1384 Perl_re_printf( aTHX_
1385 " Check-only match: offset min:%" IVdf " max:%" IVdf
1386 " check_at:%" IVdf " rx_origin:%" IVdf " rx_origin-check_at:%" IVdf
1387 " strend:%" IVdf "\n",
1388 (IV)prog->check_offset_min,
1389 (IV)prog->check_offset_max,
1390 (IV)(check_at-strbeg),
1391 (IV)(rx_origin-strbeg),
1392 (IV)(rx_origin-check_at),
1398 postprocess_substr_matches:
1400 /* handle the extra constraint of /^.../m if present */
1402 if (ml_anch && rx_origin != strbeg && rx_origin[-1] != '\n') {
1405 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1406 " looking for /^/m anchor"));
1408 /* we have failed the constraint of a \n before rx_origin.
1409 * Find the next \n, if any, even if it's beyond the current
1410 * anchored and/or floating substrings. Whether we should be
1411 * scanning ahead for the next \n or the next substr is debatable.
1412 * On the one hand you'd expect rare substrings to appear less
1413 * often than \n's. On the other hand, searching for \n means
1414 * we're effectively flipping between check_substr and "\n" on each
1415 * iteration as the current "rarest" string candidate, which
1416 * means for example that we'll quickly reject the whole string if
1417 * hasn't got a \n, rather than trying every substr position
1421 s = HOP3c(strend, - prog->minlen, strpos);
1422 if (s <= rx_origin ||
1423 ! ( rx_origin = (char *)memchr(rx_origin, '\n', s - rx_origin)))
1425 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1426 " Did not find /%s^%s/m...\n",
1427 PL_colors[0], PL_colors[1]));
1431 /* earliest possible origin is 1 char after the \n.
1432 * (since *rx_origin == '\n', it's safe to ++ here rather than
1433 * HOP(rx_origin, 1)) */
1436 if (prog->substrs->check_ix == 0 /* check is anchored */
1437 || rx_origin >= HOP3c(check_at, - prog->check_offset_min, strpos))
1439 /* Position contradicts check-string; either because
1440 * check was anchored (and thus has no wiggle room),
1441 * or check was float and rx_origin is above the float range */
1442 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1443 " Found /%s^%s/m, about to restart lookup for check-string with rx_origin %ld...\n",
1444 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1448 /* if we get here, the check substr must have been float,
1449 * is in range, and we may or may not have had an anchored
1450 * "other" substr which still contradicts */
1451 assert(prog->substrs->check_ix); /* check is float */
1453 if (utf8_target ? prog->anchored_utf8 : prog->anchored_substr) {
1454 /* whoops, the anchored "other" substr exists, so we still
1455 * contradict. On the other hand, the float "check" substr
1456 * didn't contradict, so just retry the anchored "other"
1458 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1459 " Found /%s^%s/m, rescanning for anchored from offset %" IVdf " (rx_origin now %" IVdf ")...\n",
1460 PL_colors[0], PL_colors[1],
1461 (IV)(rx_origin - strbeg + prog->anchored_offset),
1462 (IV)(rx_origin - strbeg)
1464 goto do_other_substr;
1467 /* success: we don't contradict the found floating substring
1468 * (and there's no anchored substr). */
1469 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1470 " Found /%s^%s/m with rx_origin %ld...\n",
1471 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1474 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1475 " (multiline anchor test skipped)\n"));
1481 /* if we have a starting character class, then test that extra constraint.
1482 * (trie stclasses are too expensive to use here, we are better off to
1483 * leave it to regmatch itself) */
1485 if (progi->regstclass && PL_regkind[OP(progi->regstclass)]!=TRIE) {
1486 const U8* const str = (U8*)STRING(progi->regstclass);
1488 /* XXX this value could be pre-computed */
1489 const SSize_t cl_l = (PL_regkind[OP(progi->regstclass)] == EXACT
1490 ? (reginfo->is_utf8_pat
1491 ? (SSize_t)utf8_distance(str + STR_LEN(progi->regstclass), str)
1492 : (SSize_t)STR_LEN(progi->regstclass))
1496 /* latest pos that a matching float substr constrains rx start to */
1497 char *rx_max_float = NULL;
1499 /* if the current rx_origin is anchored, either by satisfying an
1500 * anchored substring constraint, or a /^.../m constraint, then we
1501 * can reject the current origin if the start class isn't found
1502 * at the current position. If we have a float-only match, then
1503 * rx_origin is constrained to a range; so look for the start class
1504 * in that range. if neither, then look for the start class in the
1505 * whole rest of the string */
1507 /* XXX DAPM it's not clear what the minlen test is for, and why
1508 * it's not used in the floating case. Nothing in the test suite
1509 * causes minlen == 0 here. See <20140313134639.GS12844@iabyn.com>.
1510 * Here are some old comments, which may or may not be correct:
1512 * minlen == 0 is possible if regstclass is \b or \B,
1513 * and the fixed substr is ''$.
1514 * Since minlen is already taken into account, rx_origin+1 is
1515 * before strend; accidentally, minlen >= 1 guaranties no false
1516 * positives at rx_origin + 1 even for \b or \B. But (minlen? 1 :
1517 * 0) below assumes that regstclass does not come from lookahead...
1518 * If regstclass takes bytelength more than 1: If charlength==1, OK.
1519 * This leaves EXACTF-ish only, which are dealt with in
1523 if (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
1524 endpos = HOP3clim(rx_origin, (prog->minlen ? cl_l : 0), strend);
1525 else if (prog->float_substr || prog->float_utf8) {
1526 rx_max_float = HOP3c(check_at, -start_shift, strbeg);
1527 endpos = HOP3clim(rx_max_float, cl_l, strend);
1532 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1533 " looking for class: start_shift: %" IVdf " check_at: %" IVdf
1534 " rx_origin: %" IVdf " endpos: %" IVdf "\n",
1535 (IV)start_shift, (IV)(check_at - strbeg),
1536 (IV)(rx_origin - strbeg), (IV)(endpos - strbeg)));
1538 s = find_byclass(prog, progi->regstclass, rx_origin, endpos,
1541 if (endpos == strend) {
1542 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1543 " Could not match STCLASS...\n") );
1546 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1547 " This position contradicts STCLASS...\n") );
1548 if ((prog->intflags & PREGf_ANCH) && !ml_anch
1549 && !(prog->intflags & PREGf_IMPLICIT))
1552 /* Contradict one of substrings */
1553 if (prog->anchored_substr || prog->anchored_utf8) {
1554 if (prog->substrs->check_ix == 1) { /* check is float */
1555 /* Have both, check_string is floating */
1556 assert(rx_origin + start_shift <= check_at);
1557 if (rx_origin + start_shift != check_at) {
1558 /* not at latest position float substr could match:
1559 * Recheck anchored substring, but not floating.
1560 * The condition above is in bytes rather than
1561 * chars for efficiency. It's conservative, in
1562 * that it errs on the side of doing 'goto
1563 * do_other_substr'. In this case, at worst,
1564 * an extra anchored search may get done, but in
1565 * practice the extra fbm_instr() is likely to
1566 * get skipped anyway. */
1567 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1568 " about to retry anchored at offset %ld (rx_origin now %" IVdf ")...\n",
1569 (long)(other_last - strbeg),
1570 (IV)(rx_origin - strbeg)
1572 goto do_other_substr;
1580 /* In the presence of ml_anch, we might be able to
1581 * find another \n without breaking the current float
1584 /* strictly speaking this should be HOP3c(..., 1, ...),
1585 * but since we goto a block of code that's going to
1586 * search for the next \n if any, its safe here */
1588 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1589 " about to look for /%s^%s/m starting at rx_origin %ld...\n",
1590 PL_colors[0], PL_colors[1],
1591 (long)(rx_origin - strbeg)) );
1592 goto postprocess_substr_matches;
1595 /* strictly speaking this can never be true; but might
1596 * be if we ever allow intuit without substrings */
1597 if (!(utf8_target ? prog->float_utf8 : prog->float_substr))
1600 rx_origin = rx_max_float;
1603 /* at this point, any matching substrings have been
1604 * contradicted. Start again... */
1606 rx_origin = HOP3c(rx_origin, 1, strend);
1608 /* uses bytes rather than char calculations for efficiency.
1609 * It's conservative: it errs on the side of doing 'goto restart',
1610 * where there is code that does a proper char-based test */
1611 if (rx_origin + start_shift + end_shift > strend) {
1612 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1613 " Could not match STCLASS...\n") );
1616 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1617 " about to look for %s substr starting at offset %ld (rx_origin now %" IVdf ")...\n",
1618 (prog->substrs->check_ix ? "floating" : "anchored"),
1619 (long)(rx_origin + start_shift - strbeg),
1620 (IV)(rx_origin - strbeg)
1627 if (rx_origin != s) {
1628 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1629 " By STCLASS: moving %ld --> %ld\n",
1630 (long)(rx_origin - strbeg), (long)(s - strbeg))
1634 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1635 " Does not contradict STCLASS...\n");
1640 /* Decide whether using the substrings helped */
1642 if (rx_origin != strpos) {
1643 /* Fixed substring is found far enough so that the match
1644 cannot start at strpos. */
1646 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ " try at offset...\n"));
1647 ++BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr); /* hooray/5 */
1650 /* The found rx_origin position does not prohibit matching at
1651 * strpos, so calling intuit didn't gain us anything. Decrement
1652 * the BmUSEFUL() count on the check substring, and if we reach
1654 if (!(prog->intflags & PREGf_NAUGHTY)
1656 prog->check_utf8 /* Could be deleted already */
1657 && --BmUSEFUL(prog->check_utf8) < 0
1658 && (prog->check_utf8 == prog->float_utf8)
1660 prog->check_substr /* Could be deleted already */
1661 && --BmUSEFUL(prog->check_substr) < 0
1662 && (prog->check_substr == prog->float_substr)
1665 /* If flags & SOMETHING - do not do it many times on the same match */
1666 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ " ... Disabling check substring...\n"));
1667 /* XXX Does the destruction order has to change with utf8_target? */
1668 SvREFCNT_dec(utf8_target ? prog->check_utf8 : prog->check_substr);
1669 SvREFCNT_dec(utf8_target ? prog->check_substr : prog->check_utf8);
1670 prog->check_substr = prog->check_utf8 = NULL; /* disable */
1671 prog->float_substr = prog->float_utf8 = NULL; /* clear */
1672 check = NULL; /* abort */
1673 /* XXXX This is a remnant of the old implementation. It
1674 looks wasteful, since now INTUIT can use many
1675 other heuristics. */
1676 prog->extflags &= ~RXf_USE_INTUIT;
1680 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1681 "Intuit: %sSuccessfully guessed:%s match at offset %ld\n",
1682 PL_colors[4], PL_colors[5], (long)(rx_origin - strbeg)) );
1686 fail_finish: /* Substring not found */
1687 if (prog->check_substr || prog->check_utf8) /* could be removed already */
1688 BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
1690 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%sMatch rejected by optimizer%s\n",
1691 PL_colors[4], PL_colors[5]));
1696 #define DECL_TRIE_TYPE(scan) \
1697 const enum { trie_plain, trie_utf8, trie_utf8_fold, trie_latin_utf8_fold, \
1698 trie_utf8_exactfa_fold, trie_latin_utf8_exactfa_fold, \
1699 trie_utf8l, trie_flu8, trie_flu8_latin } \
1700 trie_type = ((scan->flags == EXACT) \
1701 ? (utf8_target ? trie_utf8 : trie_plain) \
1702 : (scan->flags == EXACTL) \
1703 ? (utf8_target ? trie_utf8l : trie_plain) \
1704 : (scan->flags == EXACTFAA) \
1706 ? trie_utf8_exactfa_fold \
1707 : trie_latin_utf8_exactfa_fold) \
1708 : (scan->flags == EXACTFLU8 \
1711 : trie_flu8_latin) \
1714 : trie_latin_utf8_fold)))
1716 /* 'uscan' is set to foldbuf, and incremented, so below the end of uscan is
1717 * 'foldbuf+sizeof(foldbuf)' */
1718 #define REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc, uc_end, uscan, len, uvc, charid, foldlen, foldbuf, uniflags) \
1721 U8 flags = FOLD_FLAGS_FULL; \
1722 switch (trie_type) { \
1724 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1725 if (UTF8_IS_ABOVE_LATIN1(*uc)) { \
1726 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc_end); \
1728 goto do_trie_utf8_fold; \
1729 case trie_utf8_exactfa_fold: \
1730 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1732 case trie_utf8_fold: \
1733 do_trie_utf8_fold: \
1734 if ( foldlen>0 ) { \
1735 uvc = utf8n_to_uvchr( (const U8*) uscan, foldlen, &len, uniflags ); \
1740 uvc = _toFOLD_utf8_flags( (const U8*) uc, uc_end, foldbuf, &foldlen, \
1742 len = UTF8_SAFE_SKIP(uc, uc_end); \
1743 skiplen = UVCHR_SKIP( uvc ); \
1744 foldlen -= skiplen; \
1745 uscan = foldbuf + skiplen; \
1748 case trie_flu8_latin: \
1749 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1750 goto do_trie_latin_utf8_fold; \
1751 case trie_latin_utf8_exactfa_fold: \
1752 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1754 case trie_latin_utf8_fold: \
1755 do_trie_latin_utf8_fold: \
1756 if ( foldlen>0 ) { \
1757 uvc = utf8n_to_uvchr( (const U8*) uscan, foldlen, &len, uniflags ); \
1763 uvc = _to_fold_latin1( (U8) *uc, foldbuf, &foldlen, flags); \
1764 skiplen = UVCHR_SKIP( uvc ); \
1765 foldlen -= skiplen; \
1766 uscan = foldbuf + skiplen; \
1770 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1771 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1772 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc_end); \
1776 uvc = utf8n_to_uvchr( (const U8*) uc, uc_end - uc, &len, uniflags ); \
1783 charid = trie->charmap[ uvc ]; \
1787 if (widecharmap) { \
1788 SV** const svpp = hv_fetch(widecharmap, \
1789 (char*)&uvc, sizeof(UV), 0); \
1791 charid = (U16)SvIV(*svpp); \
1796 #define DUMP_EXEC_POS(li,s,doutf8,depth) \
1797 dump_exec_pos(li,s,(reginfo->strend),(reginfo->strbeg), \
1798 startpos, doutf8, depth)
1800 #define REXEC_FBC_UTF8_SCAN(CODE) \
1802 while (s < strend) { \
1804 s += UTF8_SAFE_SKIP(s, reginfo->strend); \
1808 #define REXEC_FBC_NON_UTF8_SCAN(CODE) \
1810 while (s < strend) { \
1816 #define REXEC_FBC_UTF8_CLASS_SCAN(COND) \
1818 while (s < strend) { \
1819 REXEC_FBC_UTF8_CLASS_SCAN_GUTS(COND) \
1823 #define REXEC_FBC_NON_UTF8_CLASS_SCAN(COND) \
1825 while (s < strend) { \
1826 REXEC_FBC_NON_UTF8_CLASS_SCAN_GUTS(COND) \
1830 #define REXEC_FBC_UTF8_CLASS_SCAN_GUTS(COND) \
1833 s += UTF8_SAFE_SKIP(s, reginfo->strend); \
1834 previous_occurrence_end = s; \
1840 #define REXEC_FBC_NON_UTF8_CLASS_SCAN_GUTS(COND) \
1844 previous_occurrence_end = s; \
1850 /* We keep track of where the next character should start after an occurrence
1851 * of the one we're looking for. Knowing that, we can see right away if the
1852 * next occurrence is adjacent to the previous. When 'doevery' is FALSE, we
1853 * don't accept the 2nd and succeeding adjacent occurrences */
1854 #define FBC_CHECK_AND_TRY \
1856 || s != previous_occurrence_end) \
1857 && ( reginfo->intuit \
1858 || (s <= reginfo->strend && regtry(reginfo, &s)))) \
1864 /* These differ from the above macros in that they call a function which
1865 * returns the next occurrence of the thing being looked for in 's'; and
1866 * 'strend' if there is no such occurrence. */
1867 #define REXEC_FBC_UTF8_FIND_NEXT_SCAN(f) \
1868 while (s < strend) { \
1870 if (s >= strend) { \
1876 previous_occurrence_end = s; \
1879 #define REXEC_FBC_NON_UTF8_FIND_NEXT_SCAN(f) \
1880 while (s < strend) { \
1882 if (s >= strend) { \
1888 previous_occurrence_end = s; \
1891 /* This differs from the above macros in that it is passed a single byte that
1892 * is known to begin the next occurrence of the thing being looked for in 's'.
1893 * It does a memchr to find the next occurrence of 'byte', before trying 'COND'
1894 * at that position. */
1895 #define REXEC_FBC_FIND_NEXT_UTF8_BYTE_SCAN(byte, COND) \
1896 while (s < strend) { \
1897 s = (char *) memchr(s, byte, strend -s); \
1899 s = (char *) strend; \
1905 s += UTF8_SAFE_SKIP(s, reginfo->strend); \
1906 previous_occurrence_end = s; \
1913 /* The four macros below are slightly different versions of the same logic.
1915 * The first is for /a and /aa when the target string is UTF-8. This can only
1916 * match ascii, but it must advance based on UTF-8. The other three handle
1917 * the non-UTF-8 and the more generic UTF-8 cases. In all four, we are
1918 * looking for the boundary (or non-boundary) between a word and non-word
1919 * character. The utf8 and non-utf8 cases have the same logic, but the details
1920 * must be different. Find the "wordness" of the character just prior to this
1921 * one, and compare it with the wordness of this one. If they differ, we have
1922 * a boundary. At the beginning of the string, pretend that the previous
1923 * character was a new-line.
1925 * All these macros uncleanly have side-effects with each other and outside
1926 * variables. So far it's been too much trouble to clean-up
1928 * TEST_NON_UTF8 is the macro or function to call to test if its byte input is
1929 * a word character or not.
1930 * IF_SUCCESS is code to do if it finds that we are at a boundary between
1932 * IF_FAIL is code to do if we aren't at a boundary between word/non-word
1934 * Exactly one of the two IF_FOO parameters is a no-op, depending on whether we
1935 * are looking for a boundary or for a non-boundary. If we are looking for a
1936 * boundary, we want IF_FAIL to be the no-op, and for IF_SUCCESS to go out and
1937 * see if this tentative match actually works, and if so, to quit the loop
1938 * here. And vice-versa if we are looking for a non-boundary.
1940 * 'tmp' below in the next four macros in the REXEC_FBC_UTF8_SCAN and
1941 * REXEC_FBC_UTF8_SCAN loops is a loop invariant, a bool giving the return of
1942 * TEST_NON_UTF8(s-1). To see this, note that that's what it is defined to be
1943 * at entry to the loop, and to get to the IF_FAIL branch, tmp must equal
1944 * TEST_NON_UTF8(s), and in the opposite branch, IF_SUCCESS, tmp is that
1945 * complement. But in that branch we complement tmp, meaning that at the
1946 * bottom of the loop tmp is always going to be equal to TEST_NON_UTF8(s),
1947 * which means at the top of the loop in the next iteration, it is
1948 * TEST_NON_UTF8(s-1) */
1949 #define FBC_UTF8_A(TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1950 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1951 tmp = TEST_NON_UTF8(tmp); \
1952 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1953 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1955 IF_SUCCESS; /* Is a boundary if values for s-1 and s differ */ \
1962 /* Like FBC_UTF8_A, but TEST_UV is a macro which takes a UV as its input, and
1963 * TEST_UTF8 is a macro that for the same input code points returns identically
1964 * to TEST_UV, but takes a pointer to a UTF-8 encoded string instead (and an
1965 * end pointer as well) */
1966 #define FBC_UTF8(TEST_UV, TEST_UTF8, IF_SUCCESS, IF_FAIL) \
1967 if (s == reginfo->strbeg) { \
1970 else { /* Back-up to the start of the previous character */ \
1971 U8 * const r = reghop3((U8*)s, -1, (U8*)reginfo->strbeg); \
1972 tmp = utf8n_to_uvchr(r, (U8*) reginfo->strend - r, \
1973 0, UTF8_ALLOW_DEFAULT); \
1975 tmp = TEST_UV(tmp); \
1976 REXEC_FBC_UTF8_SCAN(/* advances s while s < strend */ \
1977 if (tmp == ! (TEST_UTF8((U8 *) s, (U8 *) reginfo->strend))) { \
1986 /* Like the above two macros, for a UTF-8 target string. UTF8_CODE is the
1987 * complete code for handling UTF-8. Common to the BOUND and NBOUND cases,
1988 * set-up by the FBC_BOUND, etc macros below */
1989 #define FBC_BOUND_COMMON_UTF8(UTF8_CODE, TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1991 /* Here, things have been set up by the previous code so that tmp is the \
1992 * return of TEST_NON_UTF8(s-1). We also have to check if this matches \
1993 * against the EOS, which we treat as a \n */ \
1994 if (tmp == ! TEST_NON_UTF8('\n')) { \
2001 /* Same as the macro above, but the target isn't UTF-8 */
2002 #define FBC_BOUND_COMMON_NON_UTF8(TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
2003 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
2004 tmp = TEST_NON_UTF8(tmp); \
2005 REXEC_FBC_NON_UTF8_SCAN(/* advances s while s < strend */ \
2006 if (tmp == ! TEST_NON_UTF8(UCHARAT(s))) { \
2014 /* Here, things have been set up by the previous code so that tmp is \
2015 * the return of TEST_NON_UTF8(s-1). We also have to check if this \
2016 * matches against the EOS, which we treat as a \n */ \
2017 if (tmp == ! TEST_NON_UTF8('\n')) { \
2024 /* This is the macro to use when we want to see if something that looks like it
2025 * could match, actually does, and if so exits the loop. It needs to be used
2026 * only for bounds checking macros, as it allows for matching beyond the end of
2027 * string (which should be zero length without having to look at the string
2029 #define REXEC_FBC_TRYIT \
2030 if (reginfo->intuit || (s <= reginfo->strend && regtry(reginfo, &s))) \
2033 /* The only difference between the BOUND and NBOUND cases is that
2034 * REXEC_FBC_TRYIT is called when matched in BOUND, and when non-matched in
2035 * NBOUND. This is accomplished by passing it as either the if or else clause,
2036 * with the other one being empty (PLACEHOLDER is defined as empty).
2038 * The TEST_FOO parameters are for operating on different forms of input, but
2039 * all should be ones that return identically for the same underlying code
2042 #define FBC_BOUND_UTF8(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
2043 FBC_BOUND_COMMON_UTF8( \
2044 FBC_UTF8(TEST_UV, TEST_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
2045 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
2047 #define FBC_BOUND_NON_UTF8(TEST_NON_UTF8) \
2048 FBC_BOUND_COMMON_NON_UTF8(TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
2050 #define FBC_BOUND_A_UTF8(TEST_NON_UTF8) \
2051 FBC_BOUND_COMMON_UTF8( \
2052 FBC_UTF8_A(TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER),\
2053 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
2055 #define FBC_BOUND_A_NON_UTF8(TEST_NON_UTF8) \
2056 FBC_BOUND_COMMON_NON_UTF8(TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
2058 #define FBC_NBOUND_UTF8(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
2059 FBC_BOUND_COMMON_UTF8( \
2060 FBC_UTF8(TEST_UV, TEST_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
2061 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
2063 #define FBC_NBOUND_NON_UTF8(TEST_NON_UTF8) \
2064 FBC_BOUND_COMMON_NON_UTF8(TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
2066 #define FBC_NBOUND_A_UTF8(TEST_NON_UTF8) \
2067 FBC_BOUND_COMMON_UTF8( \
2068 FBC_UTF8_A(TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
2069 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
2071 #define FBC_NBOUND_A_NON_UTF8(TEST_NON_UTF8) \
2072 FBC_BOUND_COMMON_NON_UTF8(TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
2076 S_get_break_val_cp_checked(SV* const invlist, const UV cp_in) {
2077 IV cp_out = _invlist_search(invlist, cp_in);
2078 assert(cp_out >= 0);
2081 # define _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp) \
2082 invmap[S_get_break_val_cp_checked(invlist, cp)]
2084 # define _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp) \
2085 invmap[_invlist_search(invlist, cp)]
2088 /* Takes a pointer to an inversion list, a pointer to its corresponding
2089 * inversion map, and a code point, and returns the code point's value
2090 * according to the two arrays. It assumes that all code points have a value.
2091 * This is used as the base macro for macros for particular properties */
2092 #define _generic_GET_BREAK_VAL_CP(invlist, invmap, cp) \
2093 _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp)
2095 /* Same as above, but takes begin, end ptrs to a UTF-8 encoded string instead
2096 * of a code point, returning the value for the first code point in the string.
2097 * And it takes the particular macro name that finds the desired value given a
2098 * code point. Merely convert the UTF-8 to code point and call the cp macro */
2099 #define _generic_GET_BREAK_VAL_UTF8(cp_macro, pos, strend) \
2100 (__ASSERT_(pos < strend) \
2101 /* Note assumes is valid UTF-8 */ \
2102 (cp_macro(utf8_to_uvchr_buf((pos), (strend), NULL))))
2104 /* Returns the GCB value for the input code point */
2105 #define getGCB_VAL_CP(cp) \
2106 _generic_GET_BREAK_VAL_CP( \
2111 /* Returns the GCB value for the first code point in the UTF-8 encoded string
2112 * bounded by pos and strend */
2113 #define getGCB_VAL_UTF8(pos, strend) \
2114 _generic_GET_BREAK_VAL_UTF8(getGCB_VAL_CP, pos, strend)
2116 /* Returns the LB value for the input code point */
2117 #define getLB_VAL_CP(cp) \
2118 _generic_GET_BREAK_VAL_CP( \
2123 /* Returns the LB value for the first code point in the UTF-8 encoded string
2124 * bounded by pos and strend */
2125 #define getLB_VAL_UTF8(pos, strend) \
2126 _generic_GET_BREAK_VAL_UTF8(getLB_VAL_CP, pos, strend)
2129 /* Returns the SB value for the input code point */
2130 #define getSB_VAL_CP(cp) \
2131 _generic_GET_BREAK_VAL_CP( \
2136 /* Returns the SB value for the first code point in the UTF-8 encoded string
2137 * bounded by pos and strend */
2138 #define getSB_VAL_UTF8(pos, strend) \
2139 _generic_GET_BREAK_VAL_UTF8(getSB_VAL_CP, pos, strend)
2141 /* Returns the WB value for the input code point */
2142 #define getWB_VAL_CP(cp) \
2143 _generic_GET_BREAK_VAL_CP( \
2148 /* Returns the WB value for the first code point in the UTF-8 encoded string
2149 * bounded by pos and strend */
2150 #define getWB_VAL_UTF8(pos, strend) \
2151 _generic_GET_BREAK_VAL_UTF8(getWB_VAL_CP, pos, strend)
2153 /* We know what class REx starts with. Try to find this position... */
2154 /* if reginfo->intuit, its a dryrun */
2155 /* annoyingly all the vars in this routine have different names from their counterparts
2156 in regmatch. /grrr */
2158 S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
2159 const char *strend, regmatch_info *reginfo)
2162 /* TRUE if x+ need not match at just the 1st pos of run of x's */
2163 const I32 doevery = (prog->intflags & PREGf_SKIP) == 0;
2165 char *pat_string; /* The pattern's exactish string */
2166 char *pat_end; /* ptr to end char of pat_string */
2167 re_fold_t folder; /* Function for computing non-utf8 folds */
2168 const U8 *fold_array; /* array for folding ords < 256 */
2175 /* In some cases we accept only the first occurence of 'x' in a sequence of
2176 * them. This variable points to just beyond the end of the previous
2177 * occurrence of 'x', hence we can tell if we are in a sequence. (Having
2178 * it point to beyond the 'x' allows us to work for UTF-8 without having to
2180 char * previous_occurrence_end = 0;
2182 I32 tmp; /* Scratch variable */
2183 const bool utf8_target = reginfo->is_utf8_target;
2184 UV utf8_fold_flags = 0;
2185 const bool is_utf8_pat = reginfo->is_utf8_pat;
2186 bool to_complement = FALSE; /* Invert the result? Taking the xor of this
2187 with a result inverts that result, as 0^1 =
2189 _char_class_number classnum;
2191 RXi_GET_DECL(prog,progi);
2193 PERL_ARGS_ASSERT_FIND_BYCLASS;
2195 /* We know what class it must start with. The case statements below have
2196 * encoded the OP, and the UTF8ness of the target ('t8' for is UTF-8; 'tb'
2197 * for it isn't; 'b' stands for byte), and the UTF8ness of the pattern
2198 * ('p8' and 'pb'. */
2199 switch (with_tp_UTF8ness(OP(c), utf8_target, is_utf8_pat)) {
2201 case ANYOFPOSIXL_t8_pb:
2202 case ANYOFPOSIXL_t8_p8:
2205 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2206 CHECK_AND_WARN_NON_UTF8_CTYPE_LOCALE_IN_SETS(c);
2214 REXEC_FBC_UTF8_CLASS_SCAN(
2215 reginclass(prog, c, (U8*)s, (U8*) strend, 1 /* is utf8 */));
2218 case ANYOFPOSIXL_tb_pb:
2219 case ANYOFPOSIXL_tb_p8:
2222 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2223 CHECK_AND_WARN_NON_UTF8_CTYPE_LOCALE_IN_SETS(c);
2231 if (ANYOF_FLAGS(c) & ~ ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
2232 /* We know that s is in the bitmap range since the target isn't
2233 * UTF-8, so what happens for out-of-range values is not relevant,
2234 * so exclude that from the flags */
2235 REXEC_FBC_NON_UTF8_CLASS_SCAN(reginclass(prog,c, (U8*)s, (U8*)s+1,
2239 REXEC_FBC_NON_UTF8_CLASS_SCAN(ANYOF_BITMAP_TEST(c, *((U8*)s)));
2243 case ANYOFM_tb_pb: /* ARG() is the base byte; FLAGS() the mask byte */
2245 REXEC_FBC_NON_UTF8_FIND_NEXT_SCAN(
2246 (char *) find_next_masked((U8 *) s, (U8 *) strend,
2247 (U8) ARG(c), FLAGS(c)));
2252 /* UTF-8ness doesn't matter because only matches UTF-8 invariants. But
2253 * we do anyway for performance reasons, as otherwise we would have to
2254 * examine all the continuation characters */
2255 REXEC_FBC_UTF8_FIND_NEXT_SCAN(
2256 (char *) find_next_masked((U8 *) s, (U8 *) strend,
2257 (U8) ARG(c), FLAGS(c)));
2262 REXEC_FBC_NON_UTF8_FIND_NEXT_SCAN(
2263 (char *) find_span_end_mask((U8 *) s, (U8 *) strend,
2264 (U8) ARG(c), FLAGS(c)));
2268 case NANYOFM_t8_p8: /* UTF-8ness does matter because can match UTF-8
2270 REXEC_FBC_UTF8_FIND_NEXT_SCAN(
2271 (char *) find_span_end_mask((U8 *) s, (U8 *) strend,
2272 (U8) ARG(c), FLAGS(c)));
2275 /* These nodes all require at least one code point to be in UTF-8 to
2285 case EXACTFLU8_tb_pb:
2286 case EXACTFLU8_tb_p8:
2287 case EXACTFU_REQ8_tb_pb:
2288 case EXACTFU_REQ8_tb_p8:
2293 REXEC_FBC_UTF8_CLASS_SCAN(
2294 ( (U8) NATIVE_UTF8_TO_I8(*s) >= ANYOF_FLAGS(c)
2295 && reginclass(prog, c, (U8*)s, (U8*) strend, 1 /* is utf8 */)));
2301 /* We know what the first byte of any matched string should be. */
2302 U8 first_byte = FLAGS(c);
2304 REXEC_FBC_FIND_NEXT_UTF8_BYTE_SCAN(first_byte,
2305 reginclass(prog, c, (U8*)s, (U8*) strend, 1 /* is utf8 */));
2311 REXEC_FBC_UTF8_CLASS_SCAN(
2312 ( inRANGE(NATIVE_UTF8_TO_I8(*s),
2313 LOWEST_ANYOF_HRx_BYTE(ANYOF_FLAGS(c)),
2314 HIGHEST_ANYOF_HRx_BYTE(ANYOF_FLAGS(c)))
2315 && reginclass(prog, c, (U8*)s, (U8*) strend,
2321 REXEC_FBC_UTF8_CLASS_SCAN(
2322 ( strend -s >= FLAGS(c)
2323 && memEQ(s, ((struct regnode_anyofhs *) c)->string, FLAGS(c))
2324 && reginclass(prog, c, (U8*)s, (U8*) strend, 1 /* is utf8 */)));
2329 REXEC_FBC_NON_UTF8_CLASS_SCAN(withinCOUNT((U8) *s,
2330 ANYOFRbase(c), ANYOFRdelta(c)));
2335 REXEC_FBC_UTF8_CLASS_SCAN(
2336 ( NATIVE_UTF8_TO_I8(*s) >= ANYOF_FLAGS(c)
2337 && withinCOUNT(utf8_to_uvchr_buf((U8 *) s,
2340 ANYOFRbase(c), ANYOFRdelta(c))));
2345 REXEC_FBC_NON_UTF8_CLASS_SCAN(withinCOUNT((U8) *s,
2346 ANYOFRbase(c), ANYOFRdelta(c)));
2351 { /* We know what the first byte of any matched string should be */
2352 U8 first_byte = FLAGS(c);
2354 REXEC_FBC_FIND_NEXT_UTF8_BYTE_SCAN(first_byte,
2355 withinCOUNT(utf8_to_uvchr_buf((U8 *) s,
2358 ANYOFRbase(c), ANYOFRdelta(c)));
2362 case EXACTFAA_tb_pb:
2364 /* Latin1 folds are not affected by /a, except it excludes the sharp s,
2365 * which these functions don't handle anyway */
2366 fold_array = PL_fold_latin1;
2367 folder = foldEQ_latin1_s2_folded;
2368 goto do_exactf_non_utf8;
2371 fold_array = PL_fold;
2373 goto do_exactf_non_utf8;
2376 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2378 if (IN_UTF8_CTYPE_LOCALE) {
2379 utf8_fold_flags = FOLDEQ_LOCALE;
2380 goto do_exactf_utf8;
2383 fold_array = PL_fold_locale;
2384 folder = foldEQ_locale;
2385 goto do_exactf_non_utf8;
2388 /* Any 'ss' in the pattern should have been replaced by regcomp, so we
2389 * don't have to worry here about this single special case in the
2391 fold_array = PL_fold_latin1;
2392 folder = foldEQ_latin1_s2_folded;
2396 do_exactf_non_utf8: /* Neither pattern nor string are UTF8, and there
2397 are no glitches with fold-length differences
2398 between the target string and pattern */
2400 /* The idea in the non-utf8 EXACTF* cases is to first find the first
2401 * character of the EXACTF* node and then, if necessary,
2402 * case-insensitively compare the full text of the node. c1 is the
2403 * first character. c2 is its fold. This logic will not work for
2404 * Unicode semantics and the german sharp ss, which hence should not be
2405 * compiled into a node that gets here. */
2406 pat_string = STRINGs(c);
2407 ln = STR_LENs(c); /* length to match in octets/bytes */
2409 /* We know that we have to match at least 'ln' bytes (which is the same
2410 * as characters, since not utf8). If we have to match 3 characters,
2411 * and there are only 2 availabe, we know without trying that it will
2412 * fail; so don't start a match past the required minimum number from
2414 e = HOP3c(strend, -((SSize_t)ln), s);
2419 c2 = fold_array[c1];
2420 if (c1 == c2) { /* If char and fold are the same */
2422 s = (char *) memchr(s, c1, e + 1 - s);
2427 /* Check that the rest of the node matches */
2428 if ( (ln == 1 || folder(s + 1, pat_string + 1, ln - 1))
2429 && (reginfo->intuit || regtry(reginfo, &s)) )
2437 U8 bits_differing = c1 ^ c2;
2439 /* If the folds differ in one bit position only, we can mask to
2440 * match either of them, and can use this faster find method. Both
2441 * ASCII and EBCDIC tend to have their case folds differ in only
2442 * one position, so this is very likely */
2443 if (LIKELY(PL_bitcount[bits_differing] == 1)) {
2444 bits_differing = ~ bits_differing;
2446 s = (char *) find_next_masked((U8 *) s, (U8 *) e + 1,
2447 (c1 & bits_differing), bits_differing);
2452 if ( (ln == 1 || folder(s + 1, pat_string + 1, ln - 1))
2453 && (reginfo->intuit || regtry(reginfo, &s)) )
2460 else { /* Otherwise, stuck with looking byte-at-a-time. This
2461 should actually happen only in EXACTFL nodes */
2463 if ( (*(U8*)s == c1 || *(U8*)s == c2)
2464 && (ln == 1 || folder(s + 1, pat_string + 1, ln - 1))
2465 && (reginfo->intuit || regtry(reginfo, &s)) )
2475 case EXACTFAA_tb_p8:
2476 case EXACTFAA_t8_p8:
2477 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII
2478 |FOLDEQ_S2_ALREADY_FOLDED
2479 |FOLDEQ_S2_FOLDS_SANE;
2480 goto do_exactf_utf8;
2482 case EXACTFAA_NO_TRIE_tb_pb:
2483 case EXACTFAA_NO_TRIE_t8_pb:
2484 case EXACTFAA_t8_pb:
2486 /* Here, and elsewhere in this file, the reason we can't consider a
2487 * non-UTF-8 pattern already folded in the presence of a UTF-8 target
2488 * is because any MICRO SIGN in the pattern won't be folded. Since the
2489 * fold of the MICRO SIGN requires UTF-8 to represent, we can consider
2490 * a non-UTF-8 pattern folded when matching a non-UTF-8 target */
2491 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
2492 goto do_exactf_utf8;
2497 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2498 utf8_fold_flags = FOLDEQ_LOCALE;
2499 goto do_exactf_utf8;
2501 case EXACTFLU8_t8_pb:
2502 case EXACTFLU8_t8_p8:
2503 utf8_fold_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
2504 | FOLDEQ_S2_FOLDS_SANE;
2505 goto do_exactf_utf8;
2507 case EXACTFU_REQ8_t8_p8:
2508 utf8_fold_flags = FOLDEQ_S2_ALREADY_FOLDED;
2509 goto do_exactf_utf8;
2514 utf8_fold_flags = FOLDEQ_S2_ALREADY_FOLDED;
2515 goto do_exactf_utf8;
2517 /* The following are problematic even though pattern isn't UTF-8. Use
2518 * full functionality normally not done except for UTF-8. */
2520 case EXACTFUP_tb_pb:
2521 case EXACTFUP_t8_pb:
2527 /* If one of the operands is in utf8, we can't use the simpler
2528 * folding above, due to the fact that many different characters
2529 * can have the same fold, or portion of a fold, or different-
2531 pat_string = STRINGs(c);
2532 ln = STR_LENs(c); /* length to match in octets/bytes */
2533 pat_end = pat_string + ln;
2534 lnc = is_utf8_pat /* length to match in characters */
2535 ? utf8_length((U8 *) pat_string, (U8 *) pat_end)
2538 /* We have 'lnc' characters to match in the pattern, but because of
2539 * multi-character folding, each character in the target can match
2540 * up to 3 characters (Unicode guarantees it will never exceed
2541 * this) if it is utf8-encoded; and up to 2 if not (based on the
2542 * fact that the Latin 1 folds are already determined, and the only
2543 * multi-char fold in that range is the sharp-s folding to 'ss'.
2544 * Thus, a pattern character can match as little as 1/3 of a string
2545 * character. Adjust lnc accordingly, rounding up, so that if we
2546 * need to match at least 4+1/3 chars, that really is 5. */
2547 expansion = (utf8_target) ? UTF8_MAX_FOLD_CHAR_EXPAND : 2;
2548 lnc = (lnc + expansion - 1) / expansion;
2550 /* As in the non-UTF8 case, if we have to match 3 characters, and
2551 * only 2 are left, it's guaranteed to fail, so don't start a match
2552 * that would require us to go beyond the end of the string */
2553 e = HOP3c(strend, -((SSize_t)lnc), s);
2555 /* XXX Note that we could recalculate e to stop the loop earlier,
2556 * as the worst case expansion above will rarely be met, and as we
2557 * go along we would usually find that e moves further to the left.
2558 * This would happen only after we reached the point in the loop
2559 * where if there were no expansion we should fail. Unclear if
2560 * worth the expense */
2563 char *my_strend= (char *)strend;
2564 if ( foldEQ_utf8_flags(s, &my_strend, 0, utf8_target,
2565 pat_string, NULL, ln, is_utf8_pat,
2567 && (reginfo->intuit || regtry(reginfo, &s)) )
2571 s += (utf8_target) ? UTF8_SAFE_SKIP(s, reginfo->strend) : 1;
2578 case BOUND_tb_pb: /* /d without utf8 target is /a */
2580 /* regcomp.c makes sure that these only have the traditional \b
2582 assert(FLAGS(c) == TRADITIONAL_BOUND);
2584 FBC_BOUND_A_NON_UTF8(isWORDCHAR_A);
2587 case BOUNDA_t8_pb: /* What /a matches is same under UTF-8 */
2589 /* regcomp.c makes sure that these only have the traditional \b
2591 assert(FLAGS(c) == TRADITIONAL_BOUND);
2593 FBC_BOUND_A_UTF8(isWORDCHAR_A);
2598 case NBOUND_tb_pb: /* /d without utf8 target is /a */
2600 /* regcomp.c makes sure that these only have the traditional \b
2602 assert(FLAGS(c) == TRADITIONAL_BOUND);
2604 FBC_NBOUND_A_NON_UTF8(isWORDCHAR_A);
2607 case NBOUNDA_t8_pb: /* What /a matches is same under UTF-8 */
2609 /* regcomp.c makes sure that these only have the traditional \b
2611 assert(FLAGS(c) == TRADITIONAL_BOUND);
2613 FBC_NBOUND_A_UTF8(isWORDCHAR_A);
2618 if ((bound_type) FLAGS(c) == TRADITIONAL_BOUND) {
2619 FBC_NBOUND_NON_UTF8(isWORDCHAR_L1);
2624 goto do_boundu_non_utf8;
2628 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2629 if (FLAGS(c) == TRADITIONAL_BOUND) {
2630 FBC_NBOUND_NON_UTF8(isWORDCHAR_LC);
2634 CHECK_AND_WARN_NON_UTF8_CTYPE_LOCALE_IN_BOUND;
2637 goto do_boundu_non_utf8;
2641 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2642 if (FLAGS(c) == TRADITIONAL_BOUND) {
2643 FBC_BOUND_NON_UTF8(isWORDCHAR_LC);
2647 CHECK_AND_WARN_NON_UTF8_CTYPE_LOCALE_IN_BOUND;
2649 goto do_boundu_non_utf8;
2653 if ((bound_type) FLAGS(c) == TRADITIONAL_BOUND) {
2654 FBC_BOUND_NON_UTF8(isWORDCHAR_L1);
2659 if (s == reginfo->strbeg) {
2660 if (reginfo->intuit || regtry(reginfo, &s))
2665 /* Didn't match. Try at the next position (if there is one) */
2667 if (UNLIKELY(s >= reginfo->strend)) {
2672 switch((bound_type) FLAGS(c)) {
2673 case TRADITIONAL_BOUND: /* Should have already been handled */
2678 /* Not utf8. Everything is a GCB except between CR and LF */
2679 while (s < strend) {
2680 if ((to_complement ^ ( UCHARAT(s - 1) != '\r'
2681 || UCHARAT(s) != '\n'))
2682 && (reginfo->intuit || regtry(reginfo, &s)))
2693 LB_enum before = getLB_VAL_CP((U8) *(s -1));
2694 while (s < strend) {
2695 LB_enum after = getLB_VAL_CP((U8) *s);
2696 if (to_complement ^ isLB(before,
2698 (U8*) reginfo->strbeg,
2700 (U8*) reginfo->strend,
2701 0 /* target not utf8 */ )
2702 && (reginfo->intuit || regtry(reginfo, &s)))
2715 SB_enum before = getSB_VAL_CP((U8) *(s -1));
2716 while (s < strend) {
2717 SB_enum after = getSB_VAL_CP((U8) *s);
2718 if ((to_complement ^ isSB(before,
2720 (U8*) reginfo->strbeg,
2722 (U8*) reginfo->strend,
2723 0 /* target not utf8 */ ))
2724 && (reginfo->intuit || regtry(reginfo, &s)))
2737 WB_enum previous = WB_UNKNOWN;
2738 WB_enum before = getWB_VAL_CP((U8) *(s -1));
2739 while (s < strend) {
2740 WB_enum after = getWB_VAL_CP((U8) *s);
2741 if ((to_complement ^ isWB(previous,
2744 (U8*) reginfo->strbeg,
2746 (U8*) reginfo->strend,
2747 0 /* target not utf8 */ ))
2748 && (reginfo->intuit || regtry(reginfo, &s)))
2759 /* Here are at the final position in the target string, which is a
2760 * boundary by definition, so matches, depending on other constraints.
2762 if ( reginfo->intuit
2763 || (s <= reginfo->strend && regtry(reginfo, &s)))
2772 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2773 if (FLAGS(c) == TRADITIONAL_BOUND) {
2774 FBC_BOUND_UTF8(isWORDCHAR_LC, isWORDCHAR_LC_uvchr,
2775 isWORDCHAR_LC_utf8_safe);
2779 CHECK_AND_WARN_NON_UTF8_CTYPE_LOCALE_IN_BOUND;
2782 goto do_boundu_utf8;
2786 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2787 if (FLAGS(c) == TRADITIONAL_BOUND) {
2788 FBC_NBOUND_UTF8(isWORDCHAR_LC, isWORDCHAR_LC_uvchr,
2789 isWORDCHAR_LC_utf8_safe);
2793 CHECK_AND_WARN_NON_UTF8_CTYPE_LOCALE_IN_BOUND;
2796 goto do_boundu_utf8;
2800 /* regcomp.c makes sure that these only have the traditional \b
2802 assert(FLAGS(c) == TRADITIONAL_BOUND);
2808 if ((bound_type) FLAGS(c) == TRADITIONAL_BOUND) {
2809 FBC_NBOUND_UTF8(isWORDCHAR_L1, isWORDCHAR_uni,
2810 isWORDCHAR_utf8_safe);
2815 goto do_boundu_utf8;
2819 /* regcomp.c makes sure that these only have the traditional \b
2821 assert(FLAGS(c) == TRADITIONAL_BOUND);
2827 if ((bound_type) FLAGS(c) == TRADITIONAL_BOUND) {
2828 FBC_BOUND_UTF8(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8_safe);
2833 if (s == reginfo->strbeg) {
2834 if (reginfo->intuit || regtry(reginfo, &s))
2839 /* Didn't match. Try at the next position (if there is one) */
2840 s += UTF8_SAFE_SKIP(s, reginfo->strend);
2841 if (UNLIKELY(s >= reginfo->strend)) {
2846 switch((bound_type) FLAGS(c)) {
2847 case TRADITIONAL_BOUND: /* Should have already been handled */
2853 GCB_enum before = getGCB_VAL_UTF8(
2855 (U8*)(reginfo->strbeg)),
2856 (U8*) reginfo->strend);
2857 while (s < strend) {
2858 GCB_enum after = getGCB_VAL_UTF8((U8*) s,
2859 (U8*) reginfo->strend);
2860 if ( (to_complement ^ isGCB(before,
2862 (U8*) reginfo->strbeg,
2864 1 /* target is utf8 */ ))
2865 && (reginfo->intuit || regtry(reginfo, &s)))
2870 s += UTF8_SAFE_SKIP(s, reginfo->strend);
2877 LB_enum before = getLB_VAL_UTF8(reghop3((U8*)s,
2879 (U8*)(reginfo->strbeg)),
2880 (U8*) reginfo->strend);
2881 while (s < strend) {
2882 LB_enum after = getLB_VAL_UTF8((U8*) s,
2883 (U8*) reginfo->strend);
2884 if (to_complement ^ isLB(before,
2886 (U8*) reginfo->strbeg,
2888 (U8*) reginfo->strend,
2889 1 /* target is utf8 */ )
2890 && (reginfo->intuit || regtry(reginfo, &s)))
2895 s += UTF8_SAFE_SKIP(s, reginfo->strend);
2903 SB_enum before = getSB_VAL_UTF8(reghop3((U8*)s,
2905 (U8*)(reginfo->strbeg)),
2906 (U8*) reginfo->strend);
2907 while (s < strend) {
2908 SB_enum after = getSB_VAL_UTF8((U8*) s,
2909 (U8*) reginfo->strend);
2910 if ((to_complement ^ isSB(before,
2912 (U8*) reginfo->strbeg,
2914 (U8*) reginfo->strend,
2915 1 /* target is utf8 */ ))
2916 && (reginfo->intuit || regtry(reginfo, &s)))
2921 s += UTF8_SAFE_SKIP(s, reginfo->strend);
2929 /* We are at a boundary between char_sub_0 and char_sub_1.
2930 * We also keep track of the value for char_sub_-1 as we
2931 * loop through the line. Context may be needed to make a
2932 * determination, and if so, this can save having to
2934 WB_enum previous = WB_UNKNOWN;
2935 WB_enum before = getWB_VAL_UTF8(
2938 (U8*)(reginfo->strbeg)),
2939 (U8*) reginfo->strend);
2940 while (s < strend) {
2941 WB_enum after = getWB_VAL_UTF8((U8*) s,
2942 (U8*) reginfo->strend);
2943 if ((to_complement ^ isWB(previous,
2946 (U8*) reginfo->strbeg,
2948 (U8*) reginfo->strend,
2949 1 /* target is utf8 */ ))
2950 && (reginfo->intuit || regtry(reginfo, &s)))
2956 s += UTF8_SAFE_SKIP(s, reginfo->strend);
2961 /* Here are at the final position in the target string, which is a
2962 * boundary by definition, so matches, depending on other constraints.
2965 if ( reginfo->intuit
2966 || (s <= reginfo->strend && regtry(reginfo, &s)))
2974 REXEC_FBC_UTF8_CLASS_SCAN(is_LNBREAK_utf8_safe(s, strend));
2979 REXEC_FBC_NON_UTF8_CLASS_SCAN(is_LNBREAK_latin1_safe(s, strend));
2982 /* The argument to all the POSIX node types is the class number to pass
2983 * to _generic_isCC() to build a mask for searching in PL_charclass[] */
2992 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2993 REXEC_FBC_UTF8_CLASS_SCAN(
2994 to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(c), (U8 *) s,
3005 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
3006 REXEC_FBC_NON_UTF8_CLASS_SCAN(
3007 to_complement ^ cBOOL(isFOO_lc(FLAGS(c), *s)));
3012 /* The complement of something that matches only ASCII matches all
3013 * non-ASCII, plus everything in ASCII that isn't in the class. */
3014 REXEC_FBC_UTF8_CLASS_SCAN( ! isASCII_utf8_safe(s, strend)
3015 || ! _generic_isCC_A(*s, FLAGS(c)));
3020 /* Don't need to worry about utf8, as it can match only a single
3021 * byte invariant character. But we do anyway for performance reasons,
3022 * as otherwise we would have to examine all the continuation
3024 REXEC_FBC_UTF8_CLASS_SCAN(_generic_isCC_A(*s, FLAGS(c)));
3038 REXEC_FBC_NON_UTF8_CLASS_SCAN(
3039 to_complement ^ cBOOL(_generic_isCC_A(*s, FLAGS(c))));
3049 REXEC_FBC_NON_UTF8_CLASS_SCAN(
3050 to_complement ^ cBOOL(_generic_isCC(*s,
3065 classnum = (_char_class_number) FLAGS(c);
3068 REXEC_FBC_UTF8_CLASS_SCAN(
3069 to_complement ^ cBOOL(_invlist_contains_cp(
3070 PL_XPosix_ptrs[classnum],
3071 utf8_to_uvchr_buf((U8 *) s,
3076 case _CC_ENUM_SPACE:
3077 REXEC_FBC_UTF8_CLASS_SCAN(
3078 to_complement ^ cBOOL(isSPACE_utf8_safe(s, strend)));
3081 case _CC_ENUM_BLANK:
3082 REXEC_FBC_UTF8_CLASS_SCAN(
3083 to_complement ^ cBOOL(isBLANK_utf8_safe(s, strend)));
3086 case _CC_ENUM_XDIGIT:
3087 REXEC_FBC_UTF8_CLASS_SCAN(
3088 to_complement ^ cBOOL(isXDIGIT_utf8_safe(s, strend)));
3091 case _CC_ENUM_VERTSPACE:
3092 REXEC_FBC_UTF8_CLASS_SCAN(
3093 to_complement ^ cBOOL(isVERTWS_utf8_safe(s, strend)));
3096 case _CC_ENUM_CNTRL:
3097 REXEC_FBC_UTF8_CLASS_SCAN(
3098 to_complement ^ cBOOL(isCNTRL_utf8_safe(s, strend)));
3103 case AHOCORASICKC_tb_pb:
3104 case AHOCORASICKC_tb_p8:
3105 case AHOCORASICKC_t8_pb:
3106 case AHOCORASICKC_t8_p8:
3107 case AHOCORASICK_tb_pb:
3108 case AHOCORASICK_tb_p8:
3109 case AHOCORASICK_t8_pb:
3110 case AHOCORASICK_t8_p8:
3113 /* what trie are we using right now */
3114 reg_ac_data *aho = (reg_ac_data*)progi->data->data[ ARG( c ) ];
3115 reg_trie_data *trie = (reg_trie_data*)progi->data->data[aho->trie];
3116 HV *widecharmap = MUTABLE_HV(progi->data->data[ aho->trie + 1 ]);
3118 const char *last_start = strend - trie->minlen;
3120 const char *real_start = s;
3122 STRLEN maxlen = trie->maxlen;
3124 U8 **points; /* map of where we were in the input string
3125 when reading a given char. For ASCII this
3126 is unnecessary overhead as the relationship
3127 is always 1:1, but for Unicode, especially
3128 case folded Unicode this is not true. */
3129 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
3133 DECLARE_AND_GET_RE_DEBUG_FLAGS;
3135 /* We can't just allocate points here. We need to wrap it in
3136 * an SV so it gets freed properly if there is a croak while
3137 * running the match */
3140 sv_points=newSV(maxlen * sizeof(U8 *));
3141 SvCUR_set(sv_points,
3142 maxlen * sizeof(U8 *));
3143 SvPOK_on(sv_points);
3144 sv_2mortal(sv_points);
3145 points=(U8**)SvPV_nolen(sv_points );
3146 if ( trie_type != trie_utf8_fold
3147 && (trie->bitmap || OP(c)==AHOCORASICKC) )
3150 bitmap=(U8*)trie->bitmap;
3152 bitmap=(U8*)ANYOF_BITMAP(c);
3154 /* this is the Aho-Corasick algorithm modified a touch
3155 to include special handling for long "unknown char" sequences.
3156 The basic idea being that we use AC as long as we are dealing
3157 with a possible matching char, when we encounter an unknown char
3158 (and we have not encountered an accepting state) we scan forward
3159 until we find a legal starting char.
3160 AC matching is basically that of trie matching, except that when
3161 we encounter a failing transition, we fall back to the current
3162 states "fail state", and try the current char again, a process
3163 we repeat until we reach the root state, state 1, or a legal
3164 transition. If we fail on the root state then we can either
3165 terminate if we have reached an accepting state previously, or
3166 restart the entire process from the beginning if we have not.
3169 while (s <= last_start) {
3170 const U32 uniflags = UTF8_ALLOW_DEFAULT;
3178 U8 *uscan = (U8*)NULL;
3179 U8 *leftmost = NULL;
3181 U32 accepted_word= 0;
3185 while ( state && uc <= (U8*)strend ) {
3187 U32 word = aho->states[ state ].wordnum;
3191 DEBUG_TRIE_EXECUTE_r(
3192 if ( uc <= (U8*)last_start
3193 && !BITMAP_TEST(bitmap,*uc) )
3195 dump_exec_pos( (char *)uc, c, strend,
3197 (char *)uc, utf8_target, 0 );
3198 Perl_re_printf( aTHX_
3199 " Scanning for legal start char...\n");
3203 while ( uc <= (U8*)last_start
3204 && !BITMAP_TEST(bitmap,*uc) )
3209 while ( uc <= (U8*)last_start
3210 && ! BITMAP_TEST(bitmap,*uc) )
3217 if (uc >(U8*)last_start) break;
3221 U8 *lpos= points[ (pointpos - trie->wordinfo[word].len)
3223 if (!leftmost || lpos < leftmost) {
3224 DEBUG_r(accepted_word=word);
3230 points[pointpos++ % maxlen]= uc;
3231 if (foldlen || uc < (U8*)strend) {
3232 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
3233 (U8 *) strend, uscan, len, uvc,
3234 charid, foldlen, foldbuf,
3236 DEBUG_TRIE_EXECUTE_r({
3237 dump_exec_pos( (char *)uc, c, strend,
3238 real_start, s, utf8_target, 0);
3239 Perl_re_printf( aTHX_
3240 " Charid:%3u CP:%4" UVxf " ",
3252 word = aho->states[ state ].wordnum;
3254 base = aho->states[ state ].trans.base;
3256 DEBUG_TRIE_EXECUTE_r({
3258 dump_exec_pos((char *)uc, c, strend, real_start,
3259 s, utf8_target, 0 );
3260 Perl_re_printf( aTHX_
3261 "%sState: %4" UVxf ", word=%" UVxf,
3262 failed ? " Fail transition to " : "",
3263 (UV)state, (UV)word);
3269 ( ((offset = base + charid
3270 - 1 - trie->uniquecharcount)) >= 0)
3271 && ((U32)offset < trie->lasttrans)
3272 && trie->trans[offset].check == state
3273 && (tmp=trie->trans[offset].next))
3275 DEBUG_TRIE_EXECUTE_r(
3276 Perl_re_printf( aTHX_ " - legal\n"));
3281 DEBUG_TRIE_EXECUTE_r(
3282 Perl_re_printf( aTHX_ " - fail\n"));
3284 state = aho->fail[state];
3288 /* we must be accepting here */
3289 DEBUG_TRIE_EXECUTE_r(
3290 Perl_re_printf( aTHX_ " - accepting\n"));
3299 if (!state) state = 1;
3302 if ( aho->states[ state ].wordnum ) {
3303 U8 *lpos = points[ (pointpos
3304 - trie->wordinfo[aho->states[ state ]
3305 .wordnum].len) % maxlen ];
3306 if (!leftmost || lpos < leftmost) {
3307 DEBUG_r(accepted_word=aho->states[ state ].wordnum);
3312 s = (char*)leftmost;
3313 DEBUG_TRIE_EXECUTE_r({
3314 Perl_re_printf( aTHX_ "Matches word #%" UVxf
3315 " at position %" IVdf ". Trying full"
3317 (UV)accepted_word, (IV)(s - real_start)
3320 if (reginfo->intuit || regtry(reginfo, &s)) {
3325 if (s < reginfo->strend) {
3328 DEBUG_TRIE_EXECUTE_r({
3329 Perl_re_printf( aTHX_
3330 "Pattern failed. Looking for new start"
3334 DEBUG_TRIE_EXECUTE_r(
3335 Perl_re_printf( aTHX_ "No match.\n"));
3344 case EXACTFU_REQ8_t8_pb:
3345 case EXACTFUP_tb_p8:
3346 case EXACTFUP_t8_p8:
3348 case EXACTF_t8_p8: /* This node only generated for non-utf8 patterns */
3349 case EXACTFAA_NO_TRIE_tb_p8:
3350 case EXACTFAA_NO_TRIE_t8_p8: /* This node only generated for non-utf8
3355 Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
3356 } /* End of switch on node type */
3364 /* set RX_SAVED_COPY, RX_SUBBEG etc.
3365 * flags have same meanings as with regexec_flags() */
3368 S_reg_set_capture_string(pTHX_ REGEXP * const rx,
3375 struct regexp *const prog = ReANY(rx);
3377 if (flags & REXEC_COPY_STR) {
3380 DEBUG_C(Perl_re_printf( aTHX_
3381 "Copy on write: regexp capture, type %d\n",
3383 /* Create a new COW SV to share the match string and store
3384 * in saved_copy, unless the current COW SV in saved_copy
3385 * is valid and suitable for our purpose */
3386 if (( prog->saved_copy
3387 && SvIsCOW(prog->saved_copy)
3388 && SvPOKp(prog->saved_copy)
3391 && SvPVX(sv) == SvPVX(prog->saved_copy)))
3393 /* just reuse saved_copy SV */
3394 if (RXp_MATCH_COPIED(prog)) {
3395 Safefree(prog->subbeg);
3396 RXp_MATCH_COPIED_off(prog);
3400 /* create new COW SV to share string */
3401 RXp_MATCH_COPY_FREE(prog);
3402 prog->saved_copy = sv_setsv_cow(prog->saved_copy, sv);
3404 prog->subbeg = (char *)SvPVX_const(prog->saved_copy);
3405 assert (SvPOKp(prog->saved_copy));
3406 prog->sublen = strend - strbeg;
3407 prog->suboffset = 0;
3408 prog->subcoffset = 0;
3413 SSize_t max = strend - strbeg;
3416 if ( (flags & REXEC_COPY_SKIP_POST)
3417 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
3418 && !(PL_sawampersand & SAWAMPERSAND_RIGHT)
3419 ) { /* don't copy $' part of string */
3422 /* calculate the right-most part of the string covered
3423 * by a capture. Due to lookahead, this may be to
3424 * the right of $&, so we have to scan all captures */
3425 while (n <= prog->lastparen) {
3426 if (prog->offs[n].end > max)
3427 max = prog->offs[n].end;
3431 max = (PL_sawampersand & SAWAMPERSAND_LEFT)
3432 ? prog->offs[0].start
3434 assert(max >= 0 && max <= strend - strbeg);
3437 if ( (flags & REXEC_COPY_SKIP_PRE)
3438 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
3439 && !(PL_sawampersand & SAWAMPERSAND_LEFT)
3440 ) { /* don't copy $` part of string */
3443 /* calculate the left-most part of the string covered
3444 * by a capture. Due to lookbehind, this may be to
3445 * the left of $&, so we have to scan all captures */
3446 while (min && n <= prog->lastparen) {
3447 if ( prog->offs[n].start != -1
3448 && prog->offs[n].start < min)
3450 min = prog->offs[n].start;
3454 if ((PL_sawampersand & SAWAMPERSAND_RIGHT)
3455 && min > prog->offs[0].end
3457 min = prog->offs[0].end;
3461 assert(min >= 0 && min <= max && min <= strend - strbeg);
3464 if (RXp_MATCH_COPIED(prog)) {
3465 if (sublen > prog->sublen)
3467 (char*)saferealloc(prog->subbeg, sublen+1);
3470 prog->subbeg = (char*)safemalloc(sublen+1);
3471 Copy(strbeg + min, prog->subbeg, sublen, char);
3472 prog->subbeg[sublen] = '\0';
3473 prog->suboffset = min;
3474 prog->sublen = sublen;
3475 RXp_MATCH_COPIED_on(prog);
3477 prog->subcoffset = prog->suboffset;
3478 if (prog->suboffset && utf8_target) {
3479 /* Convert byte offset to chars.
3480 * XXX ideally should only compute this if @-/@+
3481 * has been seen, a la PL_sawampersand ??? */
3483 /* If there's a direct correspondence between the
3484 * string which we're matching and the original SV,
3485 * then we can use the utf8 len cache associated with
3486 * the SV. In particular, it means that under //g,
3487 * sv_pos_b2u() will use the previously cached
3488 * position to speed up working out the new length of
3489 * subcoffset, rather than counting from the start of
3490 * the string each time. This stops
3491 * $x = "\x{100}" x 1E6; 1 while $x =~ /(.)/g;
3492 * from going quadratic */
3493 if (SvPOKp(sv) && SvPVX(sv) == strbeg)
3494 prog->subcoffset = sv_pos_b2u_flags(sv, prog->subcoffset,
3495 SV_GMAGIC|SV_CONST_RETURN);
3497 prog->subcoffset = utf8_length((U8*)strbeg,
3498 (U8*)(strbeg+prog->suboffset));
3502 RXp_MATCH_COPY_FREE(prog);
3503 prog->subbeg = strbeg;
3504 prog->suboffset = 0;
3505 prog->subcoffset = 0;
3506 prog->sublen = strend - strbeg;
3514 - regexec_flags - match a regexp against a string
3517 Perl_regexec_flags(pTHX_ REGEXP * const rx, char *stringarg, char *strend,
3518 char *strbeg, SSize_t minend, SV *sv, void *data, U32 flags)
3519 /* stringarg: the point in the string at which to begin matching */
3520 /* strend: pointer to null at end of string */
3521 /* strbeg: real beginning of string */
3522 /* minend: end of match must be >= minend bytes after stringarg. */
3523 /* sv: SV being matched: only used for utf8 flag, pos() etc; string
3524 * itself is accessed via the pointers above */
3525 /* data: May be used for some additional optimizations.
3526 Currently unused. */
3527 /* flags: For optimizations. See REXEC_* in regexp.h */
3530 struct regexp *const prog = ReANY(rx);
3534 SSize_t minlen; /* must match at least this many chars */
3535 SSize_t dontbother = 0; /* how many characters not to try at end */
3536 const bool utf8_target = cBOOL(DO_UTF8(sv));
3538 RXi_GET_DECL(prog,progi);
3539 regmatch_info reginfo_buf; /* create some info to pass to regtry etc */
3540 regmatch_info *const reginfo = ®info_buf;
3541 regexp_paren_pair *swap = NULL;
3543 DECLARE_AND_GET_RE_DEBUG_FLAGS;
3545 PERL_ARGS_ASSERT_REGEXEC_FLAGS;
3546 PERL_UNUSED_ARG(data);
3548 /* Be paranoid... */
3550 Perl_croak(aTHX_ "NULL regexp parameter");
3554 debug_start_match(rx, utf8_target, stringarg, strend,
3558 startpos = stringarg;
3560 /* set these early as they may be used by the HOP macros below */
3561 reginfo->strbeg = strbeg;
3562 reginfo->strend = strend;
3563 reginfo->is_utf8_target = cBOOL(utf8_target);
3565 if (prog->intflags & PREGf_GPOS_SEEN) {
3568 /* set reginfo->ganch, the position where \G can match */
3571 (flags & REXEC_IGNOREPOS)
3572 ? stringarg /* use start pos rather than pos() */
3573 : ((mg = mg_find_mglob(sv)) && mg->mg_len >= 0)
3574 /* Defined pos(): */
3575 ? strbeg + MgBYTEPOS(mg, sv, strbeg, strend-strbeg)
3576 : strbeg; /* pos() not defined; use start of string */
3578 DEBUG_GPOS_r(Perl_re_printf( aTHX_
3579 "GPOS ganch set to strbeg[%" IVdf "]\n", (IV)(reginfo->ganch - strbeg)));
3581 /* in the presence of \G, we may need to start looking earlier in
3582 * the string than the suggested start point of stringarg:
3583 * if prog->gofs is set, then that's a known, fixed minimum
3586 * /ab|c\G/: gofs = 1
3587 * or if the minimum offset isn't known, then we have to go back
3588 * to the start of the string, e.g. /w+\G/
3591 if (prog->intflags & PREGf_ANCH_GPOS) {
3593 startpos = HOPBACKc(reginfo->ganch, prog->gofs);
3595 ((flags & REXEC_FAIL_ON_UNDERFLOW) && startpos < stringarg))
3597 DEBUG_GPOS_r(Perl_re_printf( aTHX_
3598 "fail: ganch-gofs before earliest possible start\n"));
3603 startpos = reginfo->ganch;
3605 else if (prog->gofs) {
3606 startpos = HOPBACKc(startpos, prog->gofs);
3610 else if (prog->intflags & PREGf_GPOS_FLOAT)
3614 minlen = prog->minlen;
3615 if ((startpos + minlen) > strend || startpos < strbeg) {
3616 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
3617 "Regex match can't succeed, so not even tried\n"));
3621 /* at the end of this function, we'll do a LEAVE_SCOPE(oldsave),
3622 * which will call destuctors to reset PL_regmatch_state, free higher
3623 * PL_regmatch_slabs, and clean up regmatch_info_aux and
3624 * regmatch_info_aux_eval */
3626 oldsave = PL_savestack_ix;
3630 if ((prog->extflags & RXf_USE_INTUIT)
3631 && !(flags & REXEC_CHECKED))
3633 s = re_intuit_start(rx, sv, strbeg, startpos, strend,
3638 if (prog->extflags & RXf_CHECK_ALL) {
3639 /* we can match based purely on the result of INTUIT.
3640 * Set up captures etc just for $& and $-[0]
3641 * (an intuit-only match wont have $1,$2,..) */
3642 assert(!prog->nparens);
3644 /* s/// doesn't like it if $& is earlier than where we asked it to
3645 * start searching (which can happen on something like /.\G/) */
3646 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
3649 /* this should only be possible under \G */
3650 assert(prog->intflags & PREGf_GPOS_SEEN);
3651 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
3652 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3656 /* match via INTUIT shouldn't have any captures.
3657 * Let @-, @+, $^N know */
3658 prog->lastparen = prog->lastcloseparen = 0;
3659 RXp_MATCH_UTF8_set(prog, utf8_target);
3660 prog->offs[0].start = s - strbeg;
3661 prog->offs[0].end = utf8_target
3662 ? (char*)utf8_hop_forward((U8*)s, prog->minlenret, (U8 *) strend) - strbeg
3663 : s - strbeg + prog->minlenret;
3664 if ( !(flags & REXEC_NOT_FIRST) )
3665 S_reg_set_capture_string(aTHX_ rx,
3667 sv, flags, utf8_target);
3673 multiline = prog->extflags & RXf_PMf_MULTILINE;
3675 if (strend - s < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
3676 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
3677 "String too short [regexec_flags]...\n"));
3681 /* Check validity of program. */
3682 if (UCHARAT(progi->program) != REG_MAGIC) {
3683 Perl_croak(aTHX_ "corrupted regexp program");
3686 RXp_MATCH_TAINTED_off(prog);
3687 RXp_MATCH_UTF8_set(prog, utf8_target);
3689 reginfo->prog = rx; /* Yes, sorry that this is confusing. */
3690 reginfo->intuit = 0;
3691 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
3692 reginfo->warned = FALSE;
3694 reginfo->poscache_maxiter = 0; /* not yet started a countdown */
3695 /* see how far we have to get to not match where we matched before */
3696 reginfo->till = stringarg + minend;
3698 if (prog->extflags & RXf_EVAL_SEEN && SvPADTMP(sv)) {
3699 /* SAVEFREESV, not sv_mortalcopy, as this SV must last until after
3700 S_cleanup_regmatch_info_aux has executed (registered by
3701 SAVEDESTRUCTOR_X below). S_cleanup_regmatch_info_aux modifies
3702 magic belonging to this SV.
3703 Not newSVsv, either, as it does not COW.
3705 reginfo->sv = newSV(0);
3706 SvSetSV_nosteal(reginfo->sv, sv);
3707 SAVEFREESV(reginfo->sv);
3710 /* reserve next 2 or 3 slots in PL_regmatch_state:
3711 * slot N+0: may currently be in use: skip it
3712 * slot N+1: use for regmatch_info_aux struct
3713 * slot N+2: use for regmatch_info_aux_eval struct if we have (?{})'s
3714 * slot N+3: ready for use by regmatch()
3718 regmatch_state *old_regmatch_state;
3719 regmatch_slab *old_regmatch_slab;
3720 int i, max = (prog->extflags & RXf_EVAL_SEEN) ? 2 : 1;
3722 /* on first ever match, allocate first slab */
3723 if (!PL_regmatch_slab) {
3724 Newx(PL_regmatch_slab, 1, regmatch_slab);
3725 PL_regmatch_slab->prev = NULL;
3726 PL_regmatch_slab->next = NULL;
3727 PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
3730 old_regmatch_state = PL_regmatch_state;
3731 old_regmatch_slab = PL_regmatch_slab;
3733 for (i=0; i <= max; i++) {
3735 reginfo->info_aux = &(PL_regmatch_state->u.info_aux);
3737 reginfo->info_aux_eval =
3738 reginfo->info_aux->info_aux_eval =
3739 &(PL_regmatch_state->u.info_aux_eval);
3741 if (++PL_regmatch_state > SLAB_LAST(PL_regmatch_slab))
3742 PL_regmatch_state = S_push_slab(aTHX);
3745 /* note initial PL_regmatch_state position; at end of match we'll
3746 * pop back to there and free any higher slabs */
3748 reginfo->info_aux->old_regmatch_state = old_regmatch_state;
3749 reginfo->info_aux->old_regmatch_slab = old_regmatch_slab;
3750 reginfo->info_aux->poscache = NULL;
3752 SAVEDESTRUCTOR_X(S_cleanup_regmatch_info_aux, reginfo->info_aux);
3754 if ((prog->extflags & RXf_EVAL_SEEN))
3755 S_setup_eval_state(aTHX_ reginfo);
3757 reginfo->info_aux_eval = reginfo->info_aux->info_aux_eval = NULL;
3760 /* If there is a "must appear" string, look for it. */
3762 if (PL_curpm && (PM_GETRE(PL_curpm) == rx)) {
3763 /* We have to be careful. If the previous successful match
3764 was from this regex we don't want a subsequent partially
3765 successful match to clobber the old results.
3766 So when we detect this possibility we add a swap buffer
3767 to the re, and switch the buffer each match. If we fail,
3768 we switch it back; otherwise we leave it swapped.
3771 /* avoid leak if we die, or clean up anyway if match completes */
3773 Newxz(prog->offs, (prog->nparens + 1), regexp_paren_pair);
3774 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_
3775 "rex=0x%" UVxf " saving offs: orig=0x%" UVxf " new=0x%" UVxf "\n",
3783 if (prog->recurse_locinput)
3784 Zero(prog->recurse_locinput,prog->nparens + 1, char *);
3786 /* Simplest case: anchored match need be tried only once, or with
3787 * MBOL, only at the beginning of each line.
3789 * Note that /.*.../ sets PREGf_IMPLICIT|MBOL, while /.*.../s sets
3790 * PREGf_IMPLICIT|SBOL. The idea is that with /.*.../s, if it doesn't
3791 * match at the start of the string then it won't match anywhere else
3792 * either; while with /.*.../, if it doesn't match at the beginning,
3793 * the earliest it could match is at the start of the next line */
3795 if (prog->intflags & (PREGf_ANCH & ~PREGf_ANCH_GPOS)) {
3798 if (regtry(reginfo, &s))
3801 if (!(prog->intflags & PREGf_ANCH_MBOL))
3804 /* didn't match at start, try at other newline positions */
3807 dontbother = minlen - 1;
3808 end = HOP3c(strend, -dontbother, strbeg) - 1;
3810 /* skip to next newline */
3812 while (s <= end) { /* note it could be possible to match at the end of the string */
3813 /* NB: newlines are the same in unicode as they are in latin */
3816 if (prog->check_substr || prog->check_utf8) {
3817 /* note that with PREGf_IMPLICIT, intuit can only fail
3818 * or return the start position, so it's of limited utility.
3819 * Nevertheless, I made the decision that the potential for
3820 * quick fail was still worth it - DAPM */
3821 s = re_intuit_start(rx, sv, strbeg, s, strend, flags, NULL);
3825 if (regtry(reginfo, &s))
3829 } /* end anchored search */
3831 if (prog->intflags & PREGf_ANCH_GPOS)
3833 /* PREGf_ANCH_GPOS should never be true if PREGf_GPOS_SEEN is not true */
3834 assert(prog->intflags & PREGf_GPOS_SEEN);
3835 /* For anchored \G, the only position it can match from is
3836 * (ganch-gofs); we already set startpos to this above; if intuit
3837 * moved us on from there, we can't possibly succeed */
3838 assert(startpos == HOPBACKc(reginfo->ganch, prog->gofs));
3839 if (s == startpos && regtry(reginfo, &s))
3844 /* Messy cases: unanchored match. */
3845 if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
3846 /* we have /x+whatever/ */
3847 /* it must be a one character string (XXXX Except is_utf8_pat?) */
3853 if (! prog->anchored_utf8) {
3854 to_utf8_substr(prog);
3856 ch = SvPVX_const(prog->anchored_utf8)[0];
3857 REXEC_FBC_UTF8_SCAN(
3859 DEBUG_EXECUTE_r( did_match = 1 );
3860 if (regtry(reginfo, &s)) goto got_it;
3861 s += UTF8_SAFE_SKIP(s, strend);
3862 while (s < strend && *s == ch)
3869 if (! prog->anchored_substr) {
3870 if (! to_byte_substr(prog)) {
3871 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3874 ch = SvPVX_const(prog->anchored_substr)[0];
3875 REXEC_FBC_NON_UTF8_SCAN(
3877 DEBUG_EXECUTE_r( did_match = 1 );
3878 if (regtry(reginfo, &s)) goto got_it;
3880 while (s < strend && *s == ch)
3885 DEBUG_EXECUTE_r(if (!did_match)
3886 Perl_re_printf( aTHX_
3887 "Did not find anchored character...\n")
3890 else if (prog->anchored_substr != NULL
3891 || prog->anchored_utf8 != NULL
3892 || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
3893 && prog->float_max_offset < strend - s)) {
3898 char *last1; /* Last position checked before */
3902 if (prog->anchored_substr || prog->anchored_utf8) {
3904 if (! prog->anchored_utf8) {
3905 to_utf8_substr(prog);
3907 must = prog->anchored_utf8;
3910 if (! prog->anchored_substr) {
3911 if (! to_byte_substr(prog)) {
3912 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3915 must = prog->anchored_substr;
3917 back_max = back_min = prog->anchored_offset;
3920 if (! prog->float_utf8) {
3921 to_utf8_substr(prog);
3923 must = prog->float_utf8;
3926 if (! prog->float_substr) {
3927 if (! to_byte_substr(prog)) {
3928 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3931 must = prog->float_substr;
3933 back_max = prog->float_max_offset;
3934 back_min = prog->float_min_offset;
3940 last = HOP3c(strend, /* Cannot start after this */
3941 -(SSize_t)(CHR_SVLEN(must)
3942 - (SvTAIL(must) != 0) + back_min), strbeg);
3944 if (s > reginfo->strbeg)
3945 last1 = HOPc(s, -1);
3947 last1 = s - 1; /* bogus */
3949 /* XXXX check_substr already used to find "s", can optimize if
3950 check_substr==must. */
3952 strend = HOPc(strend, -dontbother);
3953 while ( (s <= last) &&
3954 (s = fbm_instr((unsigned char*)HOP4c(s, back_min, strbeg, strend),
3955 (unsigned char*)strend, must,
3956 multiline ? FBMrf_MULTILINE : 0)) ) {
3957 DEBUG_EXECUTE_r( did_match = 1 );
3958 if (HOPc(s, -back_max) > last1) {
3959 last1 = HOPc(s, -back_min);
3960 s = HOPc(s, -back_max);
3963 char * const t = (last1 >= reginfo->strbeg)
3964 ? HOPc(last1, 1) : last1 + 1;
3966 last1 = HOPc(s, -back_min);
3970 while (s <= last1) {
3971 if (regtry(reginfo, &s))
3974 s++; /* to break out of outer loop */
3981 while (s <= last1) {
3982 if (regtry(reginfo, &s))
3988 DEBUG_EXECUTE_r(if (!did_match) {
3989 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
3990 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
3991 Perl_re_printf( aTHX_ "Did not find %s substr %s%s...\n",
3992 ((must == prog->anchored_substr || must == prog->anchored_utf8)
3993 ? "anchored" : "floating"),
3994 quoted, RE_SV_TAIL(must));
3998 else if ( (c = progi->regstclass) ) {
4000 const OPCODE op = OP(progi->regstclass);
4001 /* don't bother with what can't match */
4002 if (PL_regkind[op] != EXACT && PL_regkind[op] != TRIE)
4003 strend = HOPc(strend, -(minlen - 1));
4006 SV * const prop = sv_newmortal();
4007 regprop(prog, prop, c, reginfo, NULL);
4009 RE_PV_QUOTED_DECL(quoted,utf8_target,PERL_DEBUG_PAD_ZERO(1),
4010 s,strend-s,PL_dump_re_max_len);
4011 Perl_re_printf( aTHX_
4012 "Matching stclass %.*s against %s (%d bytes)\n",
4013 (int)SvCUR(prop), SvPVX_const(prop),
4014 quoted, (int)(strend - s));
4017 if (find_byclass(prog, c, s, strend, reginfo))
4019 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "Contradicts stclass... [regexec_flags]\n"));
4023 if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
4031 if (! prog->float_utf8) {
4032 to_utf8_substr(prog);
4034 float_real = prog->float_utf8;
4037 if (! prog->float_substr) {
4038 if (! to_byte_substr(prog)) {
4039 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
4042 float_real = prog->float_substr;
4045 little = SvPV_const(float_real, len);
4046 if (SvTAIL(float_real)) {
4047 /* This means that float_real contains an artificial \n on
4048 * the end due to the presence of something like this:
4049 * /foo$/ where we can match both "foo" and "foo\n" at the
4050 * end of the string. So we have to compare the end of the
4051 * string first against the float_real without the \n and
4052 * then against the full float_real with the string. We
4053 * have to watch out for cases where the string might be
4054 * smaller than the float_real or the float_real without
4056 char *checkpos= strend - len;
4058 Perl_re_printf( aTHX_
4059 "%sChecking for float_real.%s\n",
4060 PL_colors[4], PL_colors[5]));
4061 if (checkpos + 1 < strbeg) {
4062 /* can't match, even if we remove the trailing \n
4063 * string is too short to match */
4065 Perl_re_printf( aTHX_
4066 "%sString shorter than required trailing substring, cannot match.%s\n",
4067 PL_colors[4], PL_colors[5]));
4069 } else if (memEQ(checkpos + 1, little, len - 1)) {
4070 /* can match, the end of the string matches without the
4072 last = checkpos + 1;
4073 } else if (checkpos < strbeg) {
4074 /* cant match, string is too short when the "\n" is
4077 Perl_re_printf( aTHX_
4078 "%sString does not contain required trailing substring, cannot match.%s\n",
4079 PL_colors[4], PL_colors[5]));
4081 } else if (!multiline) {
4082 /* non multiline match, so compare with the "\n" at the
4083 * end of the string */
4084 if (memEQ(checkpos, little, len)) {
4088 Perl_re_printf( aTHX_
4089 "%sString does not contain required trailing substring, cannot match.%s\n",
4090 PL_colors[4], PL_colors[5]));
4094 /* multiline match, so we have to search for a place
4095 * where the full string is located */
4101 last = rninstr(s, strend, little, little + len);
4103 last = strend; /* matching "$" */
4106 /* at one point this block contained a comment which was
4107 * probably incorrect, which said that this was a "should not
4108 * happen" case. Even if it was true when it was written I am
4109 * pretty sure it is not anymore, so I have removed the comment
4110 * and replaced it with this one. Yves */
4112 Perl_re_printf( aTHX_
4113 "%sString does not contain required substring, cannot match.%s\n",
4114 PL_colors[4], PL_colors[5]
4118 dontbother = strend - last + prog->float_min_offset;
4120 if (minlen && (dontbother < minlen))
4121 dontbother = minlen - 1;
4122 strend -= dontbother; /* this one's always in bytes! */
4123 /* We don't know much -- general case. */
4126 if (regtry(reginfo, &s))
4135 if (regtry(reginfo, &s))
4137 } while (s++ < strend);
4145 /* s/// doesn't like it if $& is earlier than where we asked it to
4146 * start searching (which can happen on something like /.\G/) */
4147 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
4148 && (prog->offs[0].start < stringarg - strbeg))
4150 /* this should only be possible under \G */
4151 assert(prog->intflags & PREGf_GPOS_SEEN);
4152 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
4153 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
4157 /* clean up; this will trigger destructors that will free all slabs
4158 * above the current one, and cleanup the regmatch_info_aux
4159 * and regmatch_info_aux_eval sructs */
4161 LEAVE_SCOPE(oldsave);
4163 if (RXp_PAREN_NAMES(prog))
4164 (void)hv_iterinit(RXp_PAREN_NAMES(prog));
4166 /* make sure $`, $&, $', and $digit will work later */
4167 if ( !(flags & REXEC_NOT_FIRST) )
4168 S_reg_set_capture_string(aTHX_ rx,
4169 strbeg, reginfo->strend,
4170 sv, flags, utf8_target);
4175 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%sMatch failed%s\n",
4176 PL_colors[4], PL_colors[5]));
4179 /* we failed :-( roll it back.
4180 * Since the swap buffer will be freed on scope exit which follows
4181 * shortly, restore the old captures by copying 'swap's original
4182 * data to the new offs buffer
4184 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_
4185 "rex=0x%" UVxf " rolling back offs: 0x%" UVxf " will be freed; restoring data to =0x%" UVxf "\n",
4192 Copy(swap, prog->offs, prog->nparens + 1, regexp_paren_pair);
4195 /* clean up; this will trigger destructors that will free all slabs
4196 * above the current one, and cleanup the regmatch_info_aux
4197 * and regmatch_info_aux_eval sructs */
4199 LEAVE_SCOPE(oldsave);
4205 /* Set which rex is pointed to by PL_reg_curpm, handling ref counting.
4206 * Do inc before dec, in case old and new rex are the same */
4207 #define SET_reg_curpm(Re2) \
4208 if (reginfo->info_aux_eval) { \
4209 (void)ReREFCNT_inc(Re2); \
4210 ReREFCNT_dec(PM_GETRE(PL_reg_curpm)); \
4211 PM_SETRE((PL_reg_curpm), (Re2)); \
4216 - regtry - try match at specific point
4218 STATIC bool /* 0 failure, 1 success */
4219 S_regtry(pTHX_ regmatch_info *reginfo, char **startposp)
4222 REGEXP *const rx = reginfo->prog;
4223 regexp *const prog = ReANY(rx);
4226 U32 depth = 0; /* used by REGCP_SET */
4228 RXi_GET_DECL(prog,progi);
4229 DECLARE_AND_GET_RE_DEBUG_FLAGS;
4231 PERL_ARGS_ASSERT_REGTRY;
4233 reginfo->cutpoint=NULL;
4235 prog->offs[0].start = *startposp - reginfo->strbeg;
4236 prog->lastparen = 0;
4237 prog->lastcloseparen = 0;
4239 /* XXXX What this code is doing here?!!! There should be no need
4240 to do this again and again, prog->lastparen should take care of
4243 /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
4244 * Actually, the code in regcppop() (which Ilya may be meaning by
4245 * prog->lastparen), is not needed at all by the test suite
4246 * (op/regexp, op/pat, op/split), but that code is needed otherwise
4247 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
4248 * Meanwhile, this code *is* needed for the
4249 * above-mentioned test suite tests to succeed. The common theme
4250 * on those tests seems to be returning null fields from matches.
4251 * --jhi updated by dapm */
4253 /* After encountering a variant of the issue mentioned above I think
4254 * the point Ilya was making is that if we properly unwind whenever
4255 * we set lastparen to a smaller value then we should not need to do
4256 * this every time, only when needed. So if we have tests that fail if
4257 * we remove this, then it suggests somewhere else we are improperly
4258 * unwinding the lastparen/paren buffers. See UNWIND_PARENS() and
4259 * places it is called, and related regcp() routines. - Yves */
4261 if (prog->nparens) {
4262 regexp_paren_pair *pp = prog->offs;
4264 for (i = prog->nparens; i > (I32)prog->lastparen; i--) {
4272 result = regmatch(reginfo, *startposp, progi->program + 1);
4274 prog->offs[0].end = result;
4277 if (reginfo->cutpoint)
4278 *startposp= reginfo->cutpoint;
4279 REGCP_UNWIND(lastcp);
4283 /* this is used to determine how far from the left messages like
4284 'failed...' are printed in regexec.c. It should be set such that
4285 messages are inline with the regop output that created them.
4287 #define REPORT_CODE_OFF 29
4288 #define INDENT_CHARS(depth) ((int)(depth) % 20)
4291 Perl_re_exec_indentf(pTHX_ const char *fmt, U32 depth, ...)
4295 PerlIO *f= Perl_debug_log;
4296 PERL_ARGS_ASSERT_RE_EXEC_INDENTF;
4297 va_start(ap, depth);
4298 PerlIO_printf(f, "%*s|%4" UVuf "| %*s", REPORT_CODE_OFF, "", (UV)depth, INDENT_CHARS(depth), "" );
4299 result = PerlIO_vprintf(f, fmt, ap);
4303 #endif /* DEBUGGING */
4305 /* grab a new slab and return the first slot in it */
4307 STATIC regmatch_state *
4310 regmatch_slab *s = PL_regmatch_slab->next;
4312 Newx(s, 1, regmatch_slab);
4313 s->prev = PL_regmatch_slab;
4315 PL_regmatch_slab->next = s;
4317 PL_regmatch_slab = s;
4318 return SLAB_FIRST(s);
4324 S_debug_start_match(pTHX_ const REGEXP *prog, const bool utf8_target,
4325 const char *start, const char *end, const char *blurb)
4327 const bool utf8_pat = RX_UTF8(prog) ? 1 : 0;
4329 PERL_ARGS_ASSERT_DEBUG_START_MATCH;
4334 RE_PV_QUOTED_DECL(s0, utf8_pat, PERL_DEBUG_PAD_ZERO(0),
4335 RX_PRECOMP_const(prog), RX_PRELEN(prog), PL_dump_re_max_len);
4337 RE_PV_QUOTED_DECL(s1, utf8_target, PERL_DEBUG_PAD_ZERO(1),
4338 start, end - start, PL_dump_re_max_len);
4340 Perl_re_printf( aTHX_
4341 "%s%s REx%s %s against %s\n",
4342 PL_colors[4], blurb, PL_colors[5], s0, s1);
4344 if (utf8_target||utf8_pat)
4345 Perl_re_printf( aTHX_ "UTF-8 %s%s%s...\n",
4346 utf8_pat ? "pattern" : "",
4347 utf8_pat && utf8_target ? " and " : "",
4348 utf8_target ? "string" : ""
4354 S_dump_exec_pos(pTHX_ const char *locinput,
4355 const regnode *scan,
4356 const char *loc_regeol,
4357 const char *loc_bostr,
4358 const char *loc_reg_starttry,
4359 const bool utf8_target,
4363 const int docolor = *PL_colors[0] || *PL_colors[2] || *PL_colors[4];
4364 const int taill = (docolor ? 10 : 7); /* 3 chars for "> <" */
4365 int l = (loc_regeol - locinput) > taill ? taill : (loc_regeol - locinput);
4366 /* The part of the string before starttry has one color
4367 (pref0_len chars), between starttry and current
4368 position another one (pref_len - pref0_len chars),
4369 after the current position the third one.
4370 We assume that pref0_len <= pref_len, otherwise we
4371 decrease pref0_len. */
4372 int pref_len = (locinput - loc_bostr) > (5 + taill) - l
4373 ? (5 + taill) - l : locinput - loc_bostr;
4376 PERL_ARGS_ASSERT_DUMP_EXEC_POS;
4378 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput - pref_len)))
4380 pref0_len = pref_len - (locinput - loc_reg_starttry);
4381 if (l + pref_len < (5 + taill) && l < loc_regeol - locinput)
4382 l = ( loc_regeol - locinput > (5 + taill) - pref_len
4383 ? (5 + taill) - pref_len : loc_regeol - locinput);
4384 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput + l)))
4388 if (pref0_len > pref_len)
4389 pref0_len = pref_len;
4391 const int is_uni = utf8_target ? 1 : 0;
4393 RE_PV_COLOR_DECL(s0,len0,is_uni,PERL_DEBUG_PAD(0),
4394 (locinput - pref_len),pref0_len, PL_dump_re_max_len, 4, 5);
4396 RE_PV_COLOR_DECL(s1,len1,is_uni,PERL_DEBUG_PAD(1),
4397 (locinput - pref_len + pref0_len),
4398 pref_len - pref0_len, PL_dump_re_max_len, 2, 3);
4400 RE_PV_COLOR_DECL(s2,len2,is_uni,PERL_DEBUG_PAD(2),
4401 locinput, loc_regeol - locinput, 10, 0, 1);
4403 const STRLEN tlen=len0+len1+len2;
4404 Perl_re_printf( aTHX_
4405 "%4" IVdf " <%.*s%.*s%s%.*s>%*s|%4u| ",
4406 (IV)(locinput - loc_bostr),
4409 (docolor ? "" : "> <"),
4411 (int)(tlen > 19 ? 0 : 19 - tlen),
4419 /* reg_check_named_buff_matched()
4420 * Checks to see if a named buffer has matched. The data array of
4421 * buffer numbers corresponding to the buffer is expected to reside
4422 * in the regexp->data->data array in the slot stored in the ARG() of
4423 * node involved. Note that this routine doesn't actually care about the
4424 * name, that information is not preserved from compilation to execution.
4425 * Returns the index of the leftmost defined buffer with the given name
4426 * or 0 if non of the buffers matched.
4429 S_reg_check_named_buff_matched(const regexp *rex, const regnode *scan)
4432 RXi_GET_DECL(rex,rexi);
4433 SV *sv_dat= MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
4434 I32 *nums=(I32*)SvPVX(sv_dat);
4436 PERL_ARGS_ASSERT_REG_CHECK_NAMED_BUFF_MATCHED;
4438 for ( n=0; n<SvIVX(sv_dat); n++ ) {
4439 if ((I32)rex->lastparen >= nums[n] &&
4440 rex->offs[nums[n]].end != -1)
4448 #define CHRTEST_UNINIT -1001 /* c1/c2 haven't been calculated yet */
4449 #define CHRTEST_VOID -1000 /* the c1/c2 "next char" test should be skipped */
4450 #define CHRTEST_NOT_A_CP_1 -999
4451 #define CHRTEST_NOT_A_CP_2 -998
4454 S_setup_EXACTISH_ST_c1_c2(pTHX_ const regnode * const text_node, int *c1p,
4455 U8* c1_utf8, int *c2p, U8* c2_utf8, regmatch_info *reginfo)
4457 /* This function determines if there are zero, one, two, or more characters
4458 * that match the first character of the passed-in EXACTish node
4459 * <text_node>, and if there are one or two, it returns them in the
4460 * passed-in pointers.
4462 * If it determines that no possible character in the target string can
4463 * match, it returns FALSE; otherwise TRUE. (The FALSE situation occurs if
4464 * the first character in <text_node> requires UTF-8 to represent, and the
4465 * target string isn't in UTF-8.)
4467 * If there are more than two characters that could match the beginning of
4468 * <text_node>, or if more context is required to determine a match or not,
4469 * it sets both *<c1p> and *<c2p> to CHRTEST_VOID.
4471 * The motiviation behind this function is to allow the caller to set up
4472 * tight loops for matching. If <text_node> is of type EXACT, there is
4473 * only one possible character that can match its first character, and so
4474 * the situation is quite simple. But things get much more complicated if
4475 * folding is involved. It may be that the first character of an EXACTFish
4476 * node doesn't participate in any possible fold, e.g., punctuation, so it
4477 * can be matched only by itself. The vast majority of characters that are
4478 * in folds match just two things, their lower and upper-case equivalents.
4479 * But not all are like that; some have multiple possible matches, or match
4480 * sequences of more than one character. This function sorts all that out.
4482 * Consider the patterns A*B or A*?B where A and B are arbitrary. In a
4483 * loop of trying to match A*, we know we can't exit where the thing
4484 * following it isn't a B. And something can't be a B unless it is the
4485 * beginning of B. By putting a quick test for that beginning in a tight
4486 * loop, we can rule out things that can't possibly be B without having to
4487 * break out of the loop, thus avoiding work. Similarly, if A is a single
4488 * character, we can make a tight loop matching A*, using the outputs of
4491 * If the target string to match isn't in UTF-8, and there aren't
4492 * complications which require CHRTEST_VOID, *<c1p> and *<c2p> are set to
4493 * the one or two possible octets (which are characters in this situation)
4494 * that can match. In all cases, if there is only one character that can
4495 * match, *<c1p> and *<c2p> will be identical.
4497 * If the target string is in UTF-8, the buffers pointed to by <c1_utf8>
4498 * and <c2_utf8> will contain the one or two UTF-8 sequences of bytes that
4499 * can match the beginning of <text_node>. They should be declared with at
4500 * least length UTF8_MAXBYTES+1. (If the target string isn't in UTF-8, it is
4501 * undefined what these contain.) If one or both of the buffers are
4502 * invariant under UTF-8, *<c1p>, and *<c2p> will also be set to the
4503 * corresponding invariant. If variant, the corresponding *<c1p> and/or
4504 * *<c2p> will be set to a negative number(s) that shouldn't match any code
4505 * point (unless inappropriately coerced to unsigned). *<c1p> will equal
4506 * *<c2p> if and only if <c1_utf8> and <c2_utf8> are the same. */
4508 const bool utf8_target = reginfo->is_utf8_target;
4510 UV c1 = (UV)CHRTEST_NOT_A_CP_1;
4511 UV c2 = (UV)CHRTEST_NOT_A_CP_2;
4512 bool use_chrtest_void = FALSE;
4513 const bool utf8_pat = reginfo->is_utf8_pat;
4515 /* Used when we have both utf8 input and utf8 output, to avoid converting
4516 * to/from code points */
4517 bool utf8_has_been_setup = FALSE;
4520 U8 *pat = (U8*)STRING(text_node);
4521 U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' };
4522 const U8 op = OP(text_node);
4524 if (! isEXACTFish(OP(text_node))) {
4526 /* In an exact node, only one thing can be matched, that first
4527 * character. If both the pat and the target are UTF-8, we can just
4528 * copy the input to the output, avoiding finding the code point of
4531 assert(! isEXACT_REQ8(OP(text_node)));
4534 else if (utf8_target) {
4535 Copy(pat, c1_utf8, UTF8SKIP(pat), U8);
4536 Copy(pat, c2_utf8, UTF8SKIP(pat), U8);
4537 utf8_has_been_setup = TRUE;
4539 else if (isEXACT_REQ8(OP(text_node))) {
4540 return FALSE; /* Can only match UTF-8 target */
4543 c2 = c1 = valid_utf8_to_uvchr(pat, NULL);
4546 else { /* an EXACTFish node */
4547 U8 *pat_end = pat + STR_LENs(text_node);
4549 /* An EXACTFL node has at least some characters unfolded, because what
4550 * they match is not known until now. So, now is the time to fold
4551 * the first few of them, as many as are needed to determine 'c1' and
4552 * 'c2' later in the routine. If the pattern isn't UTF-8, we only need
4553 * to fold if in a UTF-8 locale, and then only the Sharp S; everything
4554 * else is 1-1 and isn't assumed to be folded. In a UTF-8 pattern, we
4555 * need to fold as many characters as a single character can fold to,
4556 * so that later we can check if the first ones are such a multi-char
4557 * fold. But, in such a pattern only locale-problematic characters
4558 * aren't folded, so we can skip this completely if the first character
4559 * in the node isn't one of the tricky ones */
4560 if (op == EXACTFL) {
4563 if (IN_UTF8_CTYPE_LOCALE && *pat == LATIN_SMALL_LETTER_SHARP_S)
4565 folded[0] = folded[1] = 's';
4567 pat_end = folded + 2;
4570 else if (is_PROBLEMATIC_LOCALE_FOLDEDS_START_utf8(pat)) {
4575 for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < pat_end; i++) {
4576 if (isASCII(*s) && LIKELY(! PL_in_utf8_turkic_locale)) {
4577 *(d++) = (U8) toFOLD_LC(*s);
4582 _toFOLD_utf8_flags(s,
4586 FOLD_FLAGS_FULL | FOLD_FLAGS_LOCALE);
4597 if ( ( utf8_pat && is_MULTI_CHAR_FOLD_utf8_safe(pat, pat_end))
4598 || (!utf8_pat && is_MULTI_CHAR_FOLD_latin1_safe(pat, pat_end)))
4600 /* Multi-character folds require more context to sort out. Also
4601 * PL_utf8_foldclosures used below doesn't handle them, so have to
4602 * be handled outside this routine */
4603 use_chrtest_void = TRUE;
4605 else { /* an EXACTFish node which doesn't begin with a multi-char fold */
4606 c1 = utf8_pat ? valid_utf8_to_uvchr(pat, NULL) : *pat;
4608 if ( UNLIKELY(PL_in_utf8_turkic_locale)
4610 && UNLIKELY( c1 == 'i' || c1 == 'I'
4611 || c1 == LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE
4612 || c1 == LATIN_SMALL_LETTER_DOTLESS_I))
4613 { /* Hard-coded Turkish locale rules for these 4 characters
4614 override normal rules */
4616 c2 = LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE;
4618 else if (c1 == 'I') {
4619 c2 = LATIN_SMALL_LETTER_DOTLESS_I;
4621 else if (c1 == LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE) {
4624 else if (c1 == LATIN_SMALL_LETTER_DOTLESS_I) {
4628 else if (c1 > 255) {
4629 const U32 * remaining_folds;
4632 /* Look up what code points (besides c1) fold to c1; e.g.,
4633 * [ 'K', KELVIN_SIGN ] both fold to 'k'. */
4634 Size_t folds_count = _inverse_folds(c1, &first_fold,
4636 if (folds_count == 0) {
4637 c2 = c1; /* there is only a single character that could
4640 else if (folds_count != 1) {
4641 /* If there aren't exactly two folds to this (itself and
4642 * another), it is outside the scope of this function */
4643 use_chrtest_void = TRUE;
4645 else { /* There are two. We already have one, get the other */
4648 /* Folds that cross the 255/256 boundary are forbidden if
4649 * EXACTFL (and isnt a UTF8 locale), or EXACTFAA and one is
4650 * ASCIII. The only other match to c1 is c2, and since c1
4651 * is above 255, c2 better be as well under these
4652 * circumstances. If it isn't, it means the only legal
4653 * match of c1 is itself. */
4655 && ( ( op == EXACTFL
4656 && ! IN_UTF8_CTYPE_LOCALE)
4657 || (( op == EXACTFAA
4658 || op == EXACTFAA_NO_TRIE)
4659 && (isASCII(c1) || isASCII(c2)))))
4665 else /* Here, c1 is <= 255 */
4667 && HAS_NONLATIN1_FOLD_CLOSURE(c1)
4668 && ( ! (op == EXACTFL && ! IN_UTF8_CTYPE_LOCALE))
4669 && ( ( op != EXACTFAA
4670 && op != EXACTFAA_NO_TRIE)
4673 /* Here, there could be something above Latin1 in the target
4674 * which folds to this character in the pattern. All such
4675 * cases except LATIN SMALL LETTER Y WITH DIAERESIS have more
4676 * than two characters involved in their folds, so are outside
4677 * the scope of this function */
4678 if (UNLIKELY(c1 == LATIN_SMALL_LETTER_Y_WITH_DIAERESIS)) {
4679 c2 = LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS;
4682 use_chrtest_void = TRUE;
4685 else { /* Here nothing above Latin1 can fold to the pattern
4689 case EXACTFL: /* /l rules */
4690 c2 = PL_fold_locale[c1];
4693 case EXACTF: /* This node only generated for non-utf8
4696 if (! utf8_target) { /* /d rules */
4701 /* /u rules for all these. This happens to work for
4702 * EXACTFAA as nothing in Latin1 folds to ASCII */
4703 case EXACTFAA_NO_TRIE: /* This node only generated for
4704 non-utf8 patterns */
4710 c2 = PL_fold_latin1[c1];
4714 NOT_REACHED; /* NOTREACHED */
4717 Perl_croak(aTHX_ "panic: Unexpected op %u", op);
4718 NOT_REACHED; /* NOTREACHED */
4724 /* Here have figured things out. Set up the returns */
4725 if (use_chrtest_void) {
4726 *c2p = *c1p = CHRTEST_VOID;
4728 else if (utf8_target) {
4729 if (! utf8_has_been_setup) { /* Don't have the utf8; must get it */
4730 uvchr_to_utf8(c1_utf8, c1);
4731 uvchr_to_utf8(c2_utf8, c2);
4734 /* Invariants are stored in both the utf8 and byte outputs; Use
4735 * negative numbers otherwise for the byte ones. Make sure that the
4736 * byte ones are the same iff the utf8 ones are the same */
4737 *c1p = (UTF8_IS_INVARIANT(*c1_utf8)) ? *c1_utf8 : CHRTEST_NOT_A_CP_1;
4738 *c2p = (UTF8_IS_INVARIANT(*c2_utf8))
4741 ? CHRTEST_NOT_A_CP_1
4742 : CHRTEST_NOT_A_CP_2;
4744 else if (c1 > 255) {
4745 if (c2 > 255) { /* both possibilities are above what a non-utf8 string
4750 *c1p = *c2p = c2; /* c2 is the only representable value */
4752 else { /* c1 is representable; see about c2 */
4754 *c2p = (c2 < 256) ? c2 : c1;
4761 S_isGCB(pTHX_ const GCB_enum before, const GCB_enum after, const U8 * const strbeg, const U8 * const curpos, const bool utf8_target)
4763 /* returns a boolean indicating if there is a Grapheme Cluster Boundary
4764 * between the inputs. See https://www.unicode.org/reports/tr29/. */
4766 PERL_ARGS_ASSERT_ISGCB;
4768 switch (GCB_table[before][after]) {
4775 case GCB_RI_then_RI:
4778 U8 * temp_pos = (U8 *) curpos;
4780 /* Do not break within emoji flag sequences. That is, do not
4781 * break between regional indicator (RI) symbols if there is an
4782 * odd number of RI characters before the break point.
4783 * GB12 sot (RI RI)* RI × RI
4784 * GB13 [^RI] (RI RI)* RI × RI */
4786 while (backup_one_GCB(strbeg,
4788 utf8_target) == GCB_Regional_Indicator)
4793 return RI_count % 2 != 1;
4796 case GCB_EX_then_EM:
4798 /* GB10 ( E_Base | E_Base_GAZ ) Extend* × E_Modifier */
4800 U8 * temp_pos = (U8 *) curpos;
4804 prev = backup_one_GCB(strbeg, &temp_pos, utf8_target);
4806 while (prev == GCB_Extend);
4808 return prev != GCB_E_Base && prev != GCB_E_Base_GAZ;
4811 case GCB_Maybe_Emoji_NonBreak:
4815 /* Do not break within emoji modifier sequences or emoji zwj sequences.
4816 GB11 \p{Extended_Pictographic} Extend* ZWJ × \p{Extended_Pictographic}
4818 U8 * temp_pos = (U8 *) curpos;
4822 prev = backup_one_GCB(strbeg, &temp_pos, utf8_target);
4824 while (prev == GCB_Extend);
4826 return prev != GCB_ExtPict_XX;
4834 Perl_re_printf( aTHX_ "Unhandled GCB pair: GCB_table[%d, %d] = %d\n",
4835 before, after, GCB_table[before][after]);
4842 S_backup_one_GCB(pTHX_ const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
4846 PERL_ARGS_ASSERT_BACKUP_ONE_GCB;
4848 if (*curpos < strbeg) {
4853 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
4854 U8 * prev_prev_char_pos;
4856 if (! prev_char_pos) {
4860 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos, -1, strbeg))) {
4861 gcb = getGCB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
4862 *curpos = prev_char_pos;
4863 prev_char_pos = prev_prev_char_pos;
4866 *curpos = (U8 *) strbeg;
4871 if (*curpos - 2 < strbeg) {
4872 *curpos = (U8 *) strbeg;
4876 gcb = getGCB_VAL_CP(*(*curpos - 1));
4882 /* Combining marks attach to most classes that precede them, but this defines
4883 * the exceptions (from TR14) */
4884 #define LB_CM_ATTACHES_TO(prev) ( ! ( prev == LB_EDGE \
4885 || prev == LB_Mandatory_Break \
4886 || prev == LB_Carriage_Return \
4887 || prev == LB_Line_Feed \
4888 || prev == LB_Next_Line \
4889 || prev == LB_Space \
4890 || prev == LB_ZWSpace))
4893 S_isLB(pTHX_ LB_enum before,
4895 const U8 * const strbeg,
4896 const U8 * const curpos,
4897 const U8 * const strend,
4898 const bool utf8_target)
4900 U8 * temp_pos = (U8 *) curpos;
4901 LB_enum prev = before;
4903 /* Is the boundary between 'before' and 'after' line-breakable?
4904 * Most of this is just a table lookup of a generated table from Unicode
4905 * rules. But some rules require context to decide, and so have to be
4906 * implemented in code */
4908 PERL_ARGS_ASSERT_ISLB;
4910 /* Rule numbers in the comments below are as of Unicode 9.0 */
4914 switch (LB_table[before][after]) {
4919 case LB_NOBREAK_EVEN_WITH_SP_BETWEEN:
4922 case LB_SP_foo + LB_BREAKABLE:
4923 case LB_SP_foo + LB_NOBREAK:
4924 case LB_SP_foo + LB_NOBREAK_EVEN_WITH_SP_BETWEEN:
4926 /* When we have something following a SP, we have to look at the
4927 * context in order to know what to do.
4929 * SP SP should not reach here because LB7: Do not break before
4930 * spaces. (For two spaces in a row there is nothing that
4931 * overrides that) */
4932 assert(after != LB_Space);
4934 /* Here we have a space followed by a non-space. Mostly this is a
4935 * case of LB18: "Break after spaces". But there are complications
4936 * as the handling of spaces is somewhat tricky. They are in a
4937 * number of rules, which have to be applied in priority order, but
4938 * something earlier in the string can cause a rule to be skipped
4939 * and a lower priority rule invoked. A prime example is LB7 which
4940 * says don't break before a space. But rule LB8 (lower priority)
4941 * says that the first break opportunity after a ZW is after any
4942 * span of spaces immediately after it. If a ZW comes before a SP
4943 * in the input, rule LB8 applies, and not LB7. Other such rules
4944 * involve combining marks which are rules 9 and 10, but they may
4945 * override higher priority rules if they come earlier in the
4946 * string. Since we're doing random access into the middle of the
4947 * string, we have to look for rules that should get applied based
4948 * on both string position and priority. Combining marks do not
4949 * attach to either ZW nor SP, so we don't have to consider them
4952 * To check for LB8, we have to find the first non-space character
4953 * before this span of spaces */
4955 prev = backup_one_LB(strbeg, &temp_pos, utf8_target);
4957 while (prev == LB_Space);
4959 /* LB8 Break before any character following a zero-width space,
4960 * even if one or more spaces intervene.
4962 * So if we have a ZW just before this span, and to get here this
4963 * is the final space in the span. */
4964 if (prev == LB_ZWSpace) {
4968 /* Here, not ZW SP+. There are several rules that have higher
4969 * priority than LB18 and can be resolved now, as they don't depend
4970 * on anything earlier in the string (except ZW, which we have
4971 * already handled). One of these rules is LB11 Do not break
4972 * before Word joiner, but we have specially encoded that in the
4973 * lookup table so it is caught by the single test below which
4974 * catches the other ones. */
4975 if (LB_table[LB_Space][after] - LB_SP_foo
4976 == LB_NOBREAK_EVEN_WITH_SP_BETWEEN)
4981 /* If we get here, we have to XXX consider combining marks. */
4982 if (prev == LB_Combining_Mark) {
4984 /* What happens with these depends on the character they
4987 prev = backup_one_LB(strbeg, &temp_pos, utf8_target);
4989 while (prev == LB_Combining_Mark);
4991 /* Most times these attach to and inherit the characteristics
4992 * of that character, but not always, and when not, they are to
4993 * be treated as AL by rule LB10. */
4994 if (! LB_CM_ATTACHES_TO(prev)) {
4995 prev = LB_Alphabetic;
4999 /* Here, we have the character preceding the span of spaces all set
5000 * up. We follow LB18: "Break after spaces" unless the table shows
5001 * that is overriden */
5002 return LB_table[prev][after] != LB_NOBREAK_EVEN_WITH_SP_BETWEEN;
5006 /* We don't know how to treat the CM except by looking at the first
5007 * non-CM character preceding it. ZWJ is treated as CM */
5009 prev = backup_one_LB(strbeg, &temp_pos, utf8_target);
5011 while (prev == LB_Combining_Mark || prev == LB_ZWJ);
5013 /* Here, 'prev' is that first earlier non-CM character. If the CM
5014 * attatches to it, then it inherits the behavior of 'prev'. If it
5015 * doesn't attach, it is to be treated as an AL */
5016 if (! LB_CM_ATTACHES_TO(prev)) {
5017 prev = LB_Alphabetic;
5022 case LB_HY_or_BA_then_foo + LB_BREAKABLE:
5023 case LB_HY_or_BA_then_foo + LB_NOBREAK:
5025 /* LB21a Don't break after Hebrew + Hyphen.
5026 * HL (HY | BA) × */
5028 if (backup_one_LB(strbeg, &temp_pos, utf8_target)
5029 == LB_Hebrew_Letter)
5034 return LB_table[prev][after] - LB_HY_or_BA_then_foo == LB_BREAKABLE;
5036 case LB_PR_or_PO_then_OP_or_HY + LB_BREAKABLE:
5037 case LB_PR_or_PO_then_OP_or_HY + LB_NOBREAK:
5039 /* LB25a (PR | PO) × ( OP | HY )? NU */
5040 if (advance_one_LB(&temp_pos, strend, utf8_target) == LB_Numeric) {
5044 return LB_table[prev][after] - LB_PR_or_PO_then_OP_or_HY
5047 case LB_SY_or_IS_then_various + LB_BREAKABLE:
5048 case LB_SY_or_IS_then_various + LB_NOBREAK:
5050 /* LB25d NU (SY | IS)* × (NU | SY | IS | CL | CP ) */
5052 LB_enum temp = prev;
5054 temp = backup_one_LB(strbeg, &temp_pos, utf8_target);
5056 while (temp == LB_Break_Symbols || temp == LB_Infix_Numeric);
5057 if (temp == LB_Numeric) {
5061 return LB_table[prev][after] - LB_SY_or_IS_then_various
5065 case LB_various_then_PO_or_PR + LB_BREAKABLE:
5066 case LB_various_then_PO_or_PR + LB_NOBREAK:
5068 /* LB25e NU (SY | IS)* (CL | CP)? × (PO | PR) */
5070 LB_enum temp = prev;
5071 if (temp == LB_Close_Punctuation || temp == LB_Close_Parenthesis)
5073 temp = backup_one_LB(strbeg, &temp_pos, utf8_target);
5075 while (temp == LB_Break_Symbols || temp == LB_Infix_Numeric) {
5076 temp = backup_one_LB(strbeg, &temp_pos, utf8_target);
5078 if (temp == LB_Numeric) {
5081 return LB_various_then_PO_or_PR;
5084 case LB_RI_then_RI + LB_NOBREAK:
5085 case LB_RI_then_RI + LB_BREAKABLE:
5089 /* LB30a Break between two regional indicator symbols if and
5090 * only if there are an even number of regional indicators
5091 * preceding the position of the break.
5093 * sot (RI RI)* RI × RI
5094 * [^RI] (RI RI)* RI × RI */
5096 while (backup_one_LB(strbeg,
5098 utf8_target) == LB_Regional_Indicator)
5103 return RI_count % 2 == 0;
5111 Perl_re_printf( aTHX_ "Unhandled LB pair: LB_table[%d, %d] = %d\n",
5112 before, after, LB_table[before][after]);
5119 S_advance_one_LB(pTHX_ U8 ** curpos, const U8 * const strend, const bool utf8_target)
5124 PERL_ARGS_ASSERT_ADVANCE_ONE_LB;
5126 if (*curpos >= strend) {
5131 *curpos += UTF8SKIP(*curpos);
5132 if (*curpos >= strend) {
5135 lb = getLB_VAL_UTF8(*curpos, strend);
5139 if (*curpos >= strend) {
5142 lb = getLB_VAL_CP(**curpos);
5149 S_backup_one_LB(pTHX_ const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
5153 PERL_ARGS_ASSERT_BACKUP_ONE_LB;
5155 if (*curpos < strbeg) {
5160 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
5161 U8 * prev_prev_char_pos;
5163 if (! prev_char_pos) {
5167 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos, -1, strbeg))) {
5168 lb = getLB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
5169 *curpos = prev_char_pos;
5170 prev_char_pos = prev_prev_char_pos;
5173 *curpos = (U8 *) strbeg;
5178 if (*curpos - 2 < strbeg) {
5179 *curpos = (U8 *) strbeg;
5183 lb = getLB_VAL_CP(*(*curpos - 1));
5190 S_isSB(pTHX_ SB_enum before,
5192 const U8 * const strbeg,
5193 const U8 * const curpos,
5194 const U8 * const strend,
5195 const bool utf8_target)
5197 /* returns a boolean indicating if there is a Sentence Boundary Break
5198 * between the inputs. See https://www.unicode.org/reports/tr29/ */
5200 U8 * lpos = (U8 *) curpos;
5201 bool has_para_sep = FALSE;
5202 bool has_sp = FALSE;
5204 PERL_ARGS_ASSERT_ISSB;
5206 /* Break at the start and end of text.
5209 But unstated in Unicode is don't break if the text is empty */
5210 if (before == SB_EDGE || after == SB_EDGE) {
5211 return before != after;
5214 /* SB 3: Do not break within CRLF. */
5215 if (before == SB_CR && after == SB_LF) {
5219 /* Break after paragraph separators. CR and LF are considered
5220 * so because Unicode views text as like word processing text where there
5221 * are no newlines except between paragraphs, and the word processor takes
5222 * care of wrapping without there being hard line-breaks in the text *./
5223 SB4. Sep | CR | LF ÷ */
5224 if (before == SB_Sep || before == SB_CR || before == SB_LF) {
5228 /* Ignore Format and Extend characters, except after sot, Sep, CR, or LF.
5229 * (See Section 6.2, Replacing Ignore Rules.)
5230 SB5. X (Extend | Format)* → X */
5231 if (after == SB_Extend || after == SB_Format) {
5233 /* Implied is that the these characters attach to everything
5234 * immediately prior to them except for those separator-type
5235 * characters. And the rules earlier have already handled the case
5236 * when one of those immediately precedes the extend char */
5240 if (before == SB_Extend || before == SB_Format) {
5241 U8 * temp_pos = lpos;
5242 const SB_enum backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
5243 if ( backup != SB_EDGE
5252 /* Here, both 'before' and 'backup' are these types; implied is that we
5253 * don't break between them */
5254 if (backup == SB_Extend || backup == SB_Format) {
5259 /* Do not break after ambiguous terminators like period, if they are
5260 * immediately followed by a number or lowercase letter, if they are
5261 * between uppercase letters, if the first following letter (optionally
5262 * after certain punctuation) is lowercase, or if they are followed by
5263 * "continuation" punctuation such as comma, colon, or semicolon. For
5264 * example, a period may be an abbreviation or numeric period, and thus may
5265 * not mark the end of a sentence.
5267 * SB6. ATerm × Numeric */
5268 if (before == SB_ATerm && after == SB_Numeric) {
5272 /* SB7. (Upper | Lower) ATerm × Upper */
5273 if (before == SB_ATerm && after == SB_Upper) {
5274 U8 * temp_pos = lpos;
5275 SB_enum backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
5276 if (backup == SB_Upper || backup == SB_Lower) {
5281 /* The remaining rules that aren't the final one, all require an STerm or
5282 * an ATerm after having backed up over some Close* Sp*, and in one case an
5283 * optional Paragraph separator, although one rule doesn't have any Sp's in it.
5284 * So do that backup now, setting flags if either Sp or a paragraph
5285 * separator are found */
5287 if (before == SB_Sep || before == SB_CR || before == SB_LF) {
5288 has_para_sep = TRUE;
5289 before = backup_one_SB(strbeg, &lpos, utf8_target);
5292 if (before == SB_Sp) {
5295 before = backup_one_SB(strbeg, &lpos, utf8_target);
5297 while (before == SB_Sp);
5300 while (before == SB_Close) {
5301 before = backup_one_SB(strbeg, &lpos, utf8_target);
5304 /* The next few rules apply only when the backed-up-to is an ATerm, and in
5305 * most cases an STerm */
5306 if (before == SB_STerm || before == SB_ATerm) {
5308 /* So, here the lhs matches
5309 * (STerm | ATerm) Close* Sp* (Sep | CR | LF)?
5310 * and we have set flags if we found an Sp, or the optional Sep,CR,LF.
5311 * The rules that apply here are:
5313 * SB8 ATerm Close* Sp* × ( ¬(OLetter | Upper | Lower | Sep | CR
5314 | LF | STerm | ATerm) )* Lower
5315 SB8a (STerm | ATerm) Close* Sp* × (SContinue | STerm | ATerm)
5316 SB9 (STerm | ATerm) Close* × (Close | Sp | Sep | CR | LF)
5317 SB10 (STerm | ATerm) Close* Sp* × (Sp | Sep | CR | LF)
5318 SB11 (STerm | ATerm) Close* Sp* (Sep | CR | LF)? ÷
5321 /* And all but SB11 forbid having seen a paragraph separator */
5322 if (! has_para_sep) {
5323 if (before == SB_ATerm) { /* SB8 */
5324 U8 * rpos = (U8 *) curpos;
5325 SB_enum later = after;
5327 while ( later != SB_OLetter
5328 && later != SB_Upper
5329 && later != SB_Lower
5333 && later != SB_STerm
5334 && later != SB_ATerm
5335 && later != SB_EDGE)
5337 later = advance_one_SB(&rpos, strend, utf8_target);
5339 if (later == SB_Lower) {
5344 if ( after == SB_SContinue /* SB8a */
5345 || after == SB_STerm
5346 || after == SB_ATerm)
5351 if (! has_sp) { /* SB9 applies only if there was no Sp* */
5352 if ( after == SB_Close
5362 /* SB10. This and SB9 could probably be combined some way, but khw
5363 * has decided to follow the Unicode rule book precisely for
5364 * simplified maintenance */
5378 /* Otherwise, do not break.
5385 S_advance_one_SB(pTHX_ U8 ** curpos, const U8 * const strend, const bool utf8_target)
5389 PERL_ARGS_ASSERT_ADVANCE_ONE_SB;
5391 if (*curpos >= strend) {
5397 *curpos += UTF8SKIP(*curpos);
5398 if (*curpos >= strend) {
5401 sb = getSB_VAL_UTF8(*curpos, strend);
5402 } while (sb == SB_Extend || sb == SB_Format);
5407 if (*curpos >= strend) {
5410 sb = getSB_VAL_CP(**curpos);
5411 } while (sb == SB_Extend || sb == SB_Format);
5418 S_backup_one_SB(pTHX_ const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
5422 PERL_ARGS_ASSERT_BACKUP_ONE_SB;
5424 if (*curpos < strbeg) {
5429 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
5430 if (! prev_char_pos) {
5434 /* Back up over Extend and Format. curpos is always just to the right
5435 * of the characater whose value we are getting */
5437 U8 * prev_prev_char_pos;
5438 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos, -1,
5441 sb = getSB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
5442 *curpos = prev_char_pos;
5443 prev_char_pos = prev_prev_char_pos;
5446 *curpos = (U8 *) strbeg;
5449 } while (sb == SB_Extend || sb == SB_Format);
5453 if (*curpos - 2 < strbeg) {
5454 *curpos = (U8 *) strbeg;
5458 sb = getSB_VAL_CP(*(*curpos - 1));
5459 } while (sb == SB_Extend || sb == SB_Format);
5466 S_isWB(pTHX_ WB_enum previous,
5469 const U8 * const strbeg,
5470 const U8 * const curpos,
5471 const U8 * const strend,
5472 const bool utf8_target)
5474 /* Return a boolean as to if the boundary between 'before' and 'after' is
5475 * a Unicode word break, using their published algorithm, but tailored for
5476 * Perl by treating spans of white space as one unit. Context may be
5477 * needed to make this determination. If the value for the character
5478 * before 'before' is known, it is passed as 'previous'; otherwise that
5479 * should be set to WB_UNKNOWN. The other input parameters give the
5480 * boundaries and current position in the matching of the string. That
5481 * is, 'curpos' marks the position where the character whose wb value is
5482 * 'after' begins. See http://www.unicode.org/reports/tr29/ */
5484 U8 * before_pos = (U8 *) curpos;
5485 U8 * after_pos = (U8 *) curpos;
5486 WB_enum prev = before;
5489 PERL_ARGS_ASSERT_ISWB;
5491 /* Rule numbers in the comments below are as of Unicode 9.0 */
5495 switch (WB_table[before][after]) {
5502 case WB_hs_then_hs: /* 2 horizontal spaces in a row */
5503 next = advance_one_WB(&after_pos, strend, utf8_target,
5504 FALSE /* Don't skip Extend nor Format */ );
5505 /* A space immediately preceeding an Extend or Format is attached
5506 * to by them, and hence gets separated from previous spaces.
5507 * Otherwise don't break between horizontal white space */
5508 return next == WB_Extend || next == WB_Format;
5510 /* WB4 Ignore Format and Extend characters, except when they appear at
5511 * the beginning of a region of text. This code currently isn't
5512 * general purpose, but it works as the rules are currently and likely
5513 * to be laid out. The reason it works is that when 'they appear at
5514 * the beginning of a region of text', the rule is to break before
5515 * them, just like any other character. Therefore, the default rule
5516 * applies and we don't have to look in more depth. Should this ever
5517 * change, we would have to have 2 'case' statements, like in the rules
5518 * below, and backup a single character (not spacing over the extend
5519 * ones) and then see if that is one of the region-end characters and
5521 case WB_Ex_or_FO_or_ZWJ_then_foo:
5522 prev = backup_one_WB(&previous, strbeg, &before_pos, utf8_target);
5525 case WB_DQ_then_HL + WB_BREAKABLE:
5526 case WB_DQ_then_HL + WB_NOBREAK:
5528 /* WB7c Hebrew_Letter Double_Quote × Hebrew_Letter */
5530 if (backup_one_WB(&previous, strbeg, &before_pos, utf8_target)
5531 == WB_Hebrew_Letter)
5536 return WB_table[before][after] - WB_DQ_then_HL == WB_BREAKABLE;
5538 case WB_HL_then_DQ + WB_BREAKABLE:
5539 case WB_HL_then_DQ + WB_NOBREAK:
5541 /* WB7b Hebrew_Letter × Double_Quote Hebrew_Letter */
5543 if (advance_one_WB(&after_pos, strend, utf8_target,
5544 TRUE /* Do skip Extend and Format */ )
5545 == WB_Hebrew_Letter)
5550 return WB_table[before][after] - WB_HL_then_DQ == WB_BREAKABLE;
5552 case WB_LE_or_HL_then_MB_or_ML_or_SQ + WB_NOBREAK:
5553 case WB_LE_or_HL_then_MB_or_ML_or_SQ + WB_BREAKABLE:
5555 /* WB6 (ALetter | Hebrew_Letter) × (MidLetter | MidNumLet
5556 * | Single_Quote) (ALetter | Hebrew_Letter) */
5558 next = advance_one_WB(&after_pos, strend, utf8_target,
5559 TRUE /* Do skip Extend and Format */ );
5561 if (next == WB_ALetter || next == WB_Hebrew_Letter)
5566 return WB_table[before][after]
5567 - WB_LE_or_HL_then_MB_or_ML_or_SQ == WB_BREAKABLE;
5569 case WB_MB_or_ML_or_SQ_then_LE_or_HL + WB_NOBREAK:
5570 case WB_MB_or_ML_or_SQ_then_LE_or_HL + WB_BREAKABLE:
5572 /* WB7 (ALetter | Hebrew_Letter) (MidLetter | MidNumLet
5573 * | Single_Quote) × (ALetter | Hebrew_Letter) */
5575 prev = backup_one_WB(&previous, strbeg, &before_pos, utf8_target);
5576 if (prev == WB_ALetter || prev == WB_Hebrew_Letter)
5581 return WB_table[before][after]
5582 - WB_MB_or_ML_or_SQ_then_LE_or_HL == WB_BREAKABLE;
5584 case WB_MB_or_MN_or_SQ_then_NU + WB_NOBREAK:
5585 case WB_MB_or_MN_or_SQ_then_NU + WB_BREAKABLE:
5587 /* WB11 Numeric (MidNum | (MidNumLet | Single_Quote)) × Numeric
5590 if (backup_one_WB(&previous, strbeg, &before_pos, utf8_target)
5596 return WB_table[before][after]
5597 - WB_MB_or_MN_or_SQ_then_NU == WB_BREAKABLE;
5599 case WB_NU_then_MB_or_MN_or_SQ + WB_NOBREAK:
5600 case WB_NU_then_MB_or_MN_or_SQ + WB_BREAKABLE:
5602 /* WB12 Numeric × (MidNum | MidNumLet | Single_Quote) Numeric */
5604 if (advance_one_WB(&after_pos, strend, utf8_target,
5605 TRUE /* Do skip Extend and Format */ )
5611 return WB_table[before][after]
5612 - WB_NU_then_MB_or_MN_or_SQ == WB_BREAKABLE;
5614 case WB_RI_then_RI + WB_NOBREAK:
5615 case WB_RI_then_RI + WB_BREAKABLE:
5619 /* Do not break within emoji flag sequences. That is, do not
5620 * break between regional indicator (RI) symbols if there is an
5621 * odd number of RI characters before the potential break
5624 * WB15 sot (RI RI)* RI × RI
5625 * WB16 [^RI] (RI RI)* RI × RI */
5627 while (backup_one_WB(&previous,
5630 utf8_target) == WB_Regional_Indicator)
5635 return RI_count % 2 != 1;
5643 Perl_re_printf( aTHX_ "Unhandled WB pair: WB_table[%d, %d] = %d\n",
5644 before, after, WB_table[before][after]);
5651 S_advance_one_WB(pTHX_ U8 ** curpos,
5652 const U8 * const strend,
5653 const bool utf8_target,
5654 const bool skip_Extend_Format)
5658 PERL_ARGS_ASSERT_ADVANCE_ONE_WB;
5660 if (*curpos >= strend) {
5666 /* Advance over Extend and Format */
5668 *curpos += UTF8SKIP(*curpos);
5669 if (*curpos >= strend) {
5672 wb = getWB_VAL_UTF8(*curpos, strend);
5673 } while ( skip_Extend_Format
5674 && (wb == WB_Extend || wb == WB_Format));
5679 if (*curpos >= strend) {
5682 wb = getWB_VAL_CP(**curpos);
5683 } while ( skip_Extend_Format
5684 && (wb == WB_Extend || wb == WB_Format));
5691 S_backup_one_WB(pTHX_ WB_enum * previous, const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
5695 PERL_ARGS_ASSERT_BACKUP_ONE_WB;
5697 /* If we know what the previous character's break value is, don't have
5699 if (*previous != WB_UNKNOWN) {
5702 /* But we need to move backwards by one */
5704 *curpos = reghopmaybe3(*curpos, -1, strbeg);
5706 *previous = WB_EDGE;
5707 *curpos = (U8 *) strbeg;
5710 *previous = WB_UNKNOWN;
5715 *previous = (*curpos <= strbeg) ? WB_EDGE : WB_UNKNOWN;
5718 /* And we always back up over these three types */
5719 if (wb != WB_Extend && wb != WB_Format && wb != WB_ZWJ) {
5724 if (*curpos < strbeg) {
5729 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
5730 if (! prev_char_pos) {
5734 /* Back up over Extend and Format. curpos is always just to the right
5735 * of the characater whose value we are getting */
5737 U8 * prev_prev_char_pos;
5738 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos,
5742 wb = getWB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
5743 *curpos = prev_char_pos;
5744 prev_char_pos = prev_prev_char_pos;
5747 *curpos = (U8 *) strbeg;
5750 } while (wb == WB_Extend || wb == WB_Format || wb == WB_ZWJ);
5754 if (*curpos - 2 < strbeg) {
5755 *curpos = (U8 *) strbeg;
5759 wb = getWB_VAL_CP(*(*curpos - 1));
5760 } while (wb == WB_Extend || wb == WB_Format);
5766 /* Macros for regmatch(), using its internal variables */
5767 #define NEXTCHR_EOS -10 /* nextchr has fallen off the end */
5768 #define NEXTCHR_IS_EOS (nextbyte < 0)
5770 #define SET_nextchr \
5771 nextbyte = ((locinput < reginfo->strend) ? UCHARAT(locinput) : NEXTCHR_EOS)
5773 #define SET_locinput(p) \
5777 #define sayYES goto yes
5778 #define sayNO goto no
5779 #define sayNO_SILENT goto no_silent
5781 /* we dont use STMT_START/END here because it leads to
5782 "unreachable code" warnings, which are bogus, but distracting. */
5783 #define CACHEsayNO \
5784 if (ST.cache_mask) \
5785 reginfo->info_aux->poscache[ST.cache_offset] |= ST.cache_mask; \
5788 #define EVAL_CLOSE_PAREN_IS(st,expr) \
5791 ( ( st )->u.eval.close_paren ) && \
5792 ( ( ( st )->u.eval.close_paren ) == ( (expr) + 1 ) ) \
5795 #define EVAL_CLOSE_PAREN_IS_TRUE(st,expr) \
5798 ( ( st )->u.eval.close_paren ) && \
5800 ( ( ( st )->u.eval.close_paren ) == ( (expr) + 1 ) ) \
5804 #define EVAL_CLOSE_PAREN_SET(st,expr) \
5805 (st)->u.eval.close_paren = ( (expr) + 1 )
5807 #define EVAL_CLOSE_PAREN_CLEAR(st) \
5808 (st)->u.eval.close_paren = 0
5810 /* push a new state then goto it */
5812 #define PUSH_STATE_GOTO(state, node, input, eol, sr0) \
5813 pushinput = input; \
5817 st->resume_state = state; \
5820 /* push a new state with success backtracking, then goto it */
5822 #define PUSH_YES_STATE_GOTO(state, node, input, eol, sr0) \
5823 pushinput = input; \
5827 st->resume_state = state; \
5828 goto push_yes_state;
5830 #define DEBUG_STATE_pp(pp) \
5832 DUMP_EXEC_POS(locinput, scan, utf8_target,depth); \
5833 Perl_re_printf( aTHX_ \
5834 "%*s" pp " %s%s%s%s%s\n", \
5835 INDENT_CHARS(depth), "", \
5836 PL_reg_name[st->resume_state], \
5837 ((st==yes_state||st==mark_state) ? "[" : ""), \
5838 ((st==yes_state) ? "Y" : ""), \
5839 ((st==mark_state) ? "M" : ""), \
5840 ((st==yes_state||st==mark_state) ? "]" : "") \
5846 regmatch() - main matching routine
5848 This is basically one big switch statement in a loop. We execute an op,
5849 set 'next' to point the next op, and continue. If we come to a point which
5850 we may need to backtrack to on failure such as (A|B|C), we push a
5851 backtrack state onto the backtrack stack. On failure, we pop the top
5852 state, and re-enter the loop at the state indicated. If there are no more
5853 states to pop, we return failure.
5855 Sometimes we also need to backtrack on success; for example /A+/, where
5856 after successfully matching one A, we need to go back and try to
5857 match another one; similarly for lookahead assertions: if the assertion
5858 completes successfully, we backtrack to the state just before the assertion
5859 and then carry on. In these cases, the pushed state is marked as
5860 'backtrack on success too'. This marking is in fact done by a chain of
5861 pointers, each pointing to the previous 'yes' state. On success, we pop to
5862 the nearest yes state, discarding any intermediate failure-only states.
5863 Sometimes a yes state is pushed just to force some cleanup code to be
5864 called at the end of a successful match or submatch; e.g. (??{$re}) uses
5865 it to free the inner regex.
5867 Note that failure backtracking rewinds the cursor position, while
5868 success backtracking leaves it alone.
5870 A pattern is complete when the END op is executed, while a subpattern
5871 such as (?=foo) is complete when the SUCCESS op is executed. Both of these
5872 ops trigger the "pop to last yes state if any, otherwise return true"
5875 A common convention in this function is to use A and B to refer to the two
5876 subpatterns (or to the first nodes thereof) in patterns like /A*B/: so A is
5877 the subpattern to be matched possibly multiple times, while B is the entire
5878 rest of the pattern. Variable and state names reflect this convention.
5880 The states in the main switch are the union of ops and failure/success of
5881 substates associated with that op. For example, IFMATCH is the op
5882 that does lookahead assertions /(?=A)B/ and so the IFMATCH state means
5883 'execute IFMATCH'; while IFMATCH_A is a state saying that we have just
5884 successfully matched A and IFMATCH_A_fail is a state saying that we have
5885 just failed to match A. Resume states always come in pairs. The backtrack
5886 state we push is marked as 'IFMATCH_A', but when that is popped, we resume
5887 at IFMATCH_A or IFMATCH_A_fail, depending on whether we are backtracking
5888 on success or failure.
5890 The struct that holds a backtracking state is actually a big union, with
5891 one variant for each major type of op. The variable st points to the
5892 top-most backtrack struct. To make the code clearer, within each
5893 block of code we #define ST to alias the relevant union.
5895 Here's a concrete example of a (vastly oversimplified) IFMATCH
5901 #define ST st->u.ifmatch
5903 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
5904 ST.foo = ...; // some state we wish to save
5906 // push a yes backtrack state with a resume value of
5907 // IFMATCH_A/IFMATCH_A_fail, then continue execution at the
5909 PUSH_YES_STATE_GOTO(IFMATCH_A, A, newinput);
5912 case IFMATCH_A: // we have successfully executed A; now continue with B
5914 bar = ST.foo; // do something with the preserved value
5917 case IFMATCH_A_fail: // A failed, so the assertion failed
5918 ...; // do some housekeeping, then ...
5919 sayNO; // propagate the failure
5926 For any old-timers reading this who are familiar with the old recursive
5927 approach, the code above is equivalent to:
5929 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
5938 ...; // do some housekeeping, then ...
5939 sayNO; // propagate the failure
5942 The topmost backtrack state, pointed to by st, is usually free. If you
5943 want to claim it, populate any ST.foo fields in it with values you wish to
5944 save, then do one of
5946 PUSH_STATE_GOTO(resume_state, node, newinput, new_eol);
5947 PUSH_YES_STATE_GOTO(resume_state, node, newinput, new_eol);
5949 which sets that backtrack state's resume value to 'resume_state', pushes a
5950 new free entry to the top of the backtrack stack, then goes to 'node'.
5951 On backtracking, the free slot is popped, and the saved state becomes the
5952 new free state. An ST.foo field in this new top state can be temporarily
5953 accessed to retrieve values, but once the main loop is re-entered, it
5954 becomes available for reuse.
5956 Note that the depth of the backtrack stack constantly increases during the
5957 left-to-right execution of the pattern, rather than going up and down with
5958 the pattern nesting. For example the stack is at its maximum at Z at the
5959 end of the pattern, rather than at X in the following:
5961 /(((X)+)+)+....(Y)+....Z/
5963 The only exceptions to this are lookahead/behind assertions and the cut,
5964 (?>A), which pop all the backtrack states associated with A before
5967 Backtrack state structs are allocated in slabs of about 4K in size.
5968 PL_regmatch_state and st always point to the currently active state,
5969 and PL_regmatch_slab points to the slab currently containing
5970 PL_regmatch_state. The first time regmatch() is called, the first slab is
5971 allocated, and is never freed until interpreter destruction. When the slab
5972 is full, a new one is allocated and chained to the end. At exit from
5973 regmatch(), slabs allocated since entry are freed.
5975 In order to work with variable length lookbehinds, an upper limit is placed on
5976 lookbehinds which is set to where the match position is at the end of where the
5977 lookbehind would get to. Nothing in the lookbehind should match above that,
5978 except we should be able to look beyond if for things like \b, which need the
5979 next character in the string to be able to determine if this is a boundary or
5980 not. We also can't match the end of string/line unless we are also at the end
5981 of the entire string, so NEXTCHR_IS_EOS remains the same, and for those OPs
5982 that match a width, we have to add a condition that they are within the legal
5983 bounds of our window into the string.
5987 /* returns -1 on failure, $+[0] on success */
5989 S_regmatch(pTHX_ regmatch_info *reginfo, char *startpos, regnode *prog)
5991 const bool utf8_target = reginfo->is_utf8_target;
5992 const U32 uniflags = UTF8_ALLOW_DEFAULT;
5993 REGEXP *rex_sv = reginfo->prog;
5994 regexp *rex = ReANY(rex_sv);
5995 RXi_GET_DECL(rex,rexi);
5996 /* the current state. This is a cached copy of PL_regmatch_state */
5998 /* cache heavy used fields of st in registers */
6001 U32 n = 0; /* general value; init to avoid compiler warning */
6002 SSize_t ln = 0; /* len or last; init to avoid compiler warning */
6003 SSize_t endref = 0; /* offset of end of backref when ln is start */
6004 char *locinput = startpos;
6005 char *loceol = reginfo->strend;
6006 char *pushinput; /* where to continue after a PUSH */
6007 char *pusheol; /* where to stop matching (loceol) after a PUSH */
6008 U8 *pushsr0; /* save starting pos of script run */
6009 PERL_INT_FAST16_T nextbyte; /* is always set to UCHARAT(locinput), or -1
6012 bool result = 0; /* return value of S_regmatch */
6013 U32 depth = 0; /* depth of backtrack stack */
6014 U32 nochange_depth = 0; /* depth of GOSUB recursion with nochange */
6015 const U32 max_nochange_depth =
6016 (3 * rex->nparens > MAX_RECURSE_EVAL_NOCHANGE_DEPTH) ?
6017 3 * rex->nparens : MAX_RECURSE_EVAL_NOCHANGE_DEPTH;
6018 regmatch_state *yes_state = NULL; /* state to pop to on success of
6020 /* mark_state piggy backs on the yes_state logic so that when we unwind
6021 the stack on success we can update the mark_state as we go */
6022 regmatch_state *mark_state = NULL; /* last mark state we have seen */
6023 regmatch_state *cur_eval = NULL; /* most recent EVAL_AB state */
6024 struct regmatch_state *cur_curlyx = NULL; /* most recent curlyx */
6026 bool no_final = 0; /* prevent failure from backtracking? */
6027 bool do_cutgroup = 0; /* no_final only until next branch/trie entry */
6028 char *startpoint = locinput;
6029 SV *popmark = NULL; /* are we looking for a mark? */
6030 SV *sv_commit = NULL; /* last mark name seen in failure */
6031 SV *sv_yes_mark = NULL; /* last mark name we have seen
6032 during a successful match */
6033 U32 lastopen = 0; /* last open we saw */
6034 bool has_cutgroup = RXp_HAS_CUTGROUP(rex) ? 1 : 0;
6035 SV* const oreplsv = GvSVn(PL_replgv);
6036 /* these three flags are set by various ops to signal information to
6037 * the very next op. They have a useful lifetime of exactly one loop
6038 * iteration, and are not preserved or restored by state pushes/pops
6040 bool sw = 0; /* the condition value in (?(cond)a|b) */
6041 bool minmod = 0; /* the next "{n,m}" is a "{n,m}?" */
6042 int logical = 0; /* the following EVAL is:
6046 or the following IFMATCH/UNLESSM is:
6047 false: plain (?=foo)
6048 true: used as a condition: (?(?=foo))
6050 PAD* last_pad = NULL;
6052 U8 gimme = G_SCALAR;
6053 CV *caller_cv = NULL; /* who called us */
6054 CV *last_pushed_cv = NULL; /* most recently called (?{}) CV */
6055 U32 maxopenparen = 0; /* max '(' index seen so far */
6056 int to_complement; /* Invert the result? */
6057 _char_class_number classnum;
6058 bool is_utf8_pat = reginfo->is_utf8_pat;
6060 I32 orig_savestack_ix = PL_savestack_ix;
6061 U8 * script_run_begin = NULL;
6063 /* Solaris Studio 12.3 messes up fetching PL_charclass['\n'] */
6064 #if (defined(__SUNPRO_C) && (__SUNPRO_C == 0x5120) && defined(__x86_64) && defined(USE_64_BIT_ALL))
6065 # define SOLARIS_BAD_OPTIMIZER
6066 const U32 *pl_charclass_dup = PL_charclass;
6067 # define PL_charclass pl_charclass_dup
6071 DECLARE_AND_GET_RE_DEBUG_FLAGS;
6074 /* protect against undef(*^R) */
6075 SAVEFREESV(SvREFCNT_inc_simple_NN(oreplsv));
6077 /* shut up 'may be used uninitialized' compiler warnings for dMULTICALL */
6078 multicall_oldcatch = 0;
6079 PERL_UNUSED_VAR(multicall_cop);
6081 PERL_ARGS_ASSERT_REGMATCH;
6083 st = PL_regmatch_state;
6085 /* Note that nextbyte is a byte even in UTF */
6089 DEBUG_OPTIMISE_r( DEBUG_EXECUTE_r({
6090 DUMP_EXEC_POS( locinput, scan, utf8_target, depth );
6091 Perl_re_printf( aTHX_ "regmatch start\n" );
6094 while (scan != NULL) {
6095 next = scan + NEXT_OFF(scan);
6098 state_num = OP(scan);
6102 if (state_num <= REGNODE_MAX) {
6103 SV * const prop = sv_newmortal();
6104 regnode *rnext = regnext(scan);
6106 DUMP_EXEC_POS( locinput, scan, utf8_target, depth );
6107 regprop(rex, prop, scan, reginfo, NULL);
6108 Perl_re_printf( aTHX_
6109 "%*s%" IVdf ":%s(%" IVdf ")\n",
6110 INDENT_CHARS(depth), "",
6111 (IV)(scan - rexi->program),
6113 (PL_regkind[OP(scan)] == END || !rnext) ?
6114 0 : (IV)(rnext - rexi->program));
6121 assert(nextbyte < 256 && (nextbyte >= 0 || nextbyte == NEXTCHR_EOS));
6123 switch (state_num) {
6124 case SBOL: /* /^../ and /\A../ */
6125 if (locinput == reginfo->strbeg)
6129 case MBOL: /* /^../m */
6130 if (locinput == reginfo->strbeg ||
6131 (!NEXTCHR_IS_EOS && locinput[-1] == '\n'))
6138 if (locinput == reginfo->ganch)
6142 case KEEPS: /* \K */
6143 /* update the startpoint */
6144 st->u.keeper.val = rex->offs[0].start;
6145 rex->offs[0].start = locinput - reginfo->strbeg;
6146 PUSH_STATE_GOTO(KEEPS_next, next, locinput, loceol,
6148 NOT_REACHED; /* NOTREACHED */
6150 case KEEPS_next_fail:
6151 /* rollback the start point change */
6152 rex->offs[0].start = st->u.keeper.val;
6154 NOT_REACHED; /* NOTREACHED */
6156 case MEOL: /* /..$/m */
6157 if (!NEXTCHR_IS_EOS && nextbyte != '\n')
6161 case SEOL: /* /..$/ */
6162 if (!NEXTCHR_IS_EOS && nextbyte != '\n')
6164 if (reginfo->strend - locinput > 1)
6169 if (!NEXTCHR_IS_EOS)
6173 case SANY: /* /./s */
6174 if (NEXTCHR_IS_EOS || locinput >= loceol)
6176 goto increment_locinput;
6178 case REG_ANY: /* /./ */
6180 || locinput >= loceol
6181 || nextbyte == '\n')
6185 goto increment_locinput;
6189 #define ST st->u.trie
6190 case TRIEC: /* (ab|cd) with known charclass */
6191 /* In this case the charclass data is available inline so
6192 we can fail fast without a lot of extra overhead.
6194 if ( ! NEXTCHR_IS_EOS
6195 && locinput < loceol
6196 && ! ANYOF_BITMAP_TEST(scan, nextbyte))
6199 Perl_re_exec_indentf( aTHX_ "%sTRIE: failed to match trie start class...%s\n",
6200 depth, PL_colors[4], PL_colors[5])
6203 NOT_REACHED; /* NOTREACHED */
6206 case TRIE: /* (ab|cd) */
6207 /* the basic plan of execution of the trie is:
6208 * At the beginning, run though all the states, and
6209 * find the longest-matching word. Also remember the position
6210 * of the shortest matching word. For example, this pattern:
6213 * when matched against the string "abcde", will generate
6214 * accept states for all words except 3, with the longest
6215 * matching word being 4, and the shortest being 2 (with
6216 * the position being after char 1 of the string).
6218 * Then for each matching word, in word order (i.e. 1,2,4,5),
6219 * we run the remainder of the pattern; on each try setting
6220 * the current position to the character following the word,
6221 * returning to try the next word on failure.
6223 * We avoid having to build a list of words at runtime by
6224 * using a compile-time structure, wordinfo[].prev, which
6225 * gives, for each word, the previous accepting word (if any).
6226 * In the case above it would contain the mappings 1->2, 2->0,
6227 * 3->0, 4->5, 5->1. We can use this table to generate, from
6228 * the longest word (4 above), a list of all words, by
6229 * following the list of prev pointers; this gives us the
6230 * unordered list 4,5,1,2. Then given the current word we have
6231 * just tried, we can go through the list and find the
6232 * next-biggest word to try (so if we just failed on word 2,
6233 * the next in the list is 4).
6235 * Since at runtime we don't record the matching position in
6236 * the string for each word, we have to work that out for
6237 * each word we're about to process. The wordinfo table holds
6238 * the character length of each word; given that we recorded
6239 * at the start: the position of the shortest word and its
6240 * length in chars, we just need to move the pointer the
6241 * difference between the two char lengths. Depending on
6242 * Unicode status and folding, that's cheap or expensive.
6244 * This algorithm is optimised for the case where are only a
6245 * small number of accept states, i.e. 0,1, or maybe 2.
6246 * With lots of accepts states, and having to try all of them,
6247 * it becomes quadratic on number of accept states to find all
6252 /* what type of TRIE am I? (utf8 makes this contextual) */
6253 DECL_TRIE_TYPE(scan);
6255 /* what trie are we using right now */
6256 reg_trie_data * const trie
6257 = (reg_trie_data*)rexi->data->data[ ARG( scan ) ];
6258 HV * widecharmap = MUTABLE_HV(rexi->data->data[ ARG( scan ) + 1 ]);
6259 U32 state = trie->startstate;
6261 if (scan->flags == EXACTL || scan->flags == EXACTFLU8) {
6262 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6265 && UTF8_IS_ABOVE_LATIN1(nextbyte)
6266 && scan->flags == EXACTL)
6268 /* We only output for EXACTL, as we let the folder
6269 * output this message for EXACTFLU8 to avoid
6271 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput,
6277 || locinput >= loceol
6278 || ! TRIE_BITMAP_TEST(trie, nextbyte)))
6280 if (trie->states[ state ].wordnum) {
6282 Perl_re_exec_indentf( aTHX_ "%sTRIE: matched empty string...%s\n",
6283 depth, PL_colors[4], PL_colors[5])
6289 Perl_re_exec_indentf( aTHX_ "%sTRIE: failed to match trie start class...%s\n",
6290 depth, PL_colors[4], PL_colors[5])
6297 U8 *uc = ( U8* )locinput;
6301 U8 *uscan = (U8*)NULL;
6302 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
6303 U32 charcount = 0; /* how many input chars we have matched */
6304 U32 accepted = 0; /* have we seen any accepting states? */
6306 ST.jump = trie->jump;
6309 ST.longfold = FALSE; /* char longer if folded => it's harder */
6312 /* fully traverse the TRIE; note the position of the
6313 shortest accept state and the wordnum of the longest
6316 while ( state && uc <= (U8*)(loceol) ) {
6317 U32 base = trie->states[ state ].trans.base;
6321 wordnum = trie->states[ state ].wordnum;
6323 if (wordnum) { /* it's an accept state */
6326 /* record first match position */
6328 ST.firstpos = (U8*)locinput;
6333 ST.firstchars = charcount;
6336 if (!ST.nextword || wordnum < ST.nextword)
6337 ST.nextword = wordnum;
6338 ST.topword = wordnum;
6341 DEBUG_TRIE_EXECUTE_r({
6342 DUMP_EXEC_POS( (char *)uc, scan, utf8_target, depth );
6344 PerlIO_printf( Perl_debug_log,
6345 "%*s%sTRIE: State: %4" UVxf " Accepted: %c ",
6346 INDENT_CHARS(depth), "", PL_colors[4],
6347 (UV)state, (accepted ? 'Y' : 'N'));
6350 /* read a char and goto next state */
6351 if ( base && (foldlen || uc < (U8*)(loceol))) {
6353 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
6354 (U8 *) loceol, uscan,
6355 len, uvc, charid, foldlen,
6362 base + charid - 1 - trie->uniquecharcount)) >= 0)
6364 && ((U32)offset < trie->lasttrans)
6365 && trie->trans[offset].check == state)
6367 state = trie->trans[offset].next;
6378 DEBUG_TRIE_EXECUTE_r(
6379 Perl_re_printf( aTHX_
6380 "TRIE: Charid:%3x CP:%4" UVxf " After State: %4" UVxf "%s\n",
6381 charid, uvc, (UV)state, PL_colors[5] );
6387 /* calculate total number of accept states */
6392 w = trie->wordinfo[w].prev;
6395 ST.accepted = accepted;
6399 Perl_re_exec_indentf( aTHX_ "%sTRIE: got %" IVdf " possible matches%s\n",
6401 PL_colors[4], (IV)ST.accepted, PL_colors[5] );
6403 goto trie_first_try; /* jump into the fail handler */
6405 NOT_REACHED; /* NOTREACHED */
6407 case TRIE_next_fail: /* we failed - try next alternative */
6411 /* undo any captures done in the tail part of a branch,
6413 * /(?:X(.)(.)|Y(.)).../
6414 * where the trie just matches X then calls out to do the
6415 * rest of the branch */
6416 REGCP_UNWIND(ST.cp);
6417 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
6419 if (!--ST.accepted) {
6421 Perl_re_exec_indentf( aTHX_ "%sTRIE failed...%s\n",
6429 /* Find next-highest word to process. Note that this code
6430 * is O(N^2) per trie run (O(N) per branch), so keep tight */
6433 U16 const nextword = ST.nextword;
6434 reg_trie_wordinfo * const wordinfo
6435 = ((reg_trie_data*)rexi->data->data[ARG(ST.me)])->wordinfo;
6436 for (word=ST.topword; word; word=wordinfo[word].prev) {
6437 if (word > nextword && (!min || word < min))
6450 ST.lastparen = rex->lastparen;
6451 ST.lastcloseparen = rex->lastcloseparen;
6455 /* find start char of end of current word */
6457 U32 chars; /* how many chars to skip */
6458 reg_trie_data * const trie
6459 = (reg_trie_data*)rexi->data->data[ARG(ST.me)];
6461 assert((trie->wordinfo[ST.nextword].len - trie->prefixlen)
6463 chars = (trie->wordinfo[ST.nextword].len - trie->prefixlen)
6468 /* the hard option - fold each char in turn and find
6469 * its folded length (which may be different */
6470 U8 foldbuf[UTF8_MAXBYTES_CASE + 1];
6478 /* XXX This assumes the length is well-formed, as
6479 * does the UTF8SKIP below */
6480 uvc = utf8n_to_uvchr((U8*)uc, UTF8_MAXLEN, &len,
6488 uvc = to_uni_fold(uvc, foldbuf, &foldlen);
6493 uvc = utf8n_to_uvchr(uscan, foldlen, &len,
6509 scan = ST.me + ((ST.jump && ST.jump[ST.nextword])
6510 ? ST.jump[ST.nextword]
6514 Perl_re_exec_indentf( aTHX_ "%sTRIE matched word #%d, continuing%s\n",
6522 if ( ST.accepted > 1 || has_cutgroup || ST.jump ) {
6523 PUSH_STATE_GOTO(TRIE_next, scan, (char*)uc, loceol,
6525 NOT_REACHED; /* NOTREACHED */
6527 /* only one choice left - just continue */
6529 AV *const trie_words
6530 = MUTABLE_AV(rexi->data->data[ARG(ST.me)+TRIE_WORDS_OFFSET]);
6531 SV ** const tmp = trie_words
6532 ? av_fetch(trie_words, ST.nextword - 1, 0) : NULL;
6533 SV *sv= tmp ? sv_newmortal() : NULL;
6535 Perl_re_exec_indentf( aTHX_ "%sTRIE: only one match left, short-circuiting: #%d <%s>%s\n",
6536 depth, PL_colors[4],
6538 tmp ? pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 0,
6539 PL_colors[0], PL_colors[1],
6540 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)|PERL_PV_ESCAPE_NONASCII
6542 : "not compiled under -Dr",
6546 locinput = (char*)uc;
6547 continue; /* execute rest of RE */
6553 if (! utf8_target) {
6563 ln = STR_LENl(scan);
6564 goto join_short_long_exact;
6566 case EXACTL: /* /abc/l */
6567 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6569 /* Complete checking would involve going through every character
6570 * matched by the string to see if any is above latin1. But the
6571 * comparision otherwise might very well be a fast assembly
6572 * language routine, and I (khw) don't think slowing things down
6573 * just to check for this warning is worth it. So this just checks
6574 * the first character */
6575 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*locinput)) {
6576 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput, reginfo->strend);
6580 if (! utf8_target) {
6585 case EXACT: /* /abc/ */
6588 ln = STR_LENs(scan);
6590 join_short_long_exact:
6591 if (utf8_target != is_utf8_pat) {
6592 /* The target and the pattern have differing utf8ness. */
6594 const char * const e = s + ln;
6597 /* The target is utf8, the pattern is not utf8.
6598 * Above-Latin1 code points can't match the pattern;
6599 * invariants match exactly, and the other Latin1 ones need
6600 * to be downgraded to a single byte in order to do the
6601 * comparison. (If we could be confident that the target
6602 * is not malformed, this could be refactored to have fewer
6603 * tests by just assuming that if the first bytes match, it
6604 * is an invariant, but there are tests in the test suite
6605 * dealing with (??{...}) which violate this) */
6608 || UTF8_IS_ABOVE_LATIN1(* (U8*) l))
6612 if (UTF8_IS_INVARIANT(*(U8*)l)) {
6619 if (EIGHT_BIT_UTF8_TO_NATIVE(*l, *(l+1)) != * (U8*) s)
6629 /* The target is not utf8, the pattern is utf8. */
6632 || UTF8_IS_ABOVE_LATIN1(* (U8*) s))
6636 if (UTF8_IS_INVARIANT(*(U8*)s)) {
6643 if (EIGHT_BIT_UTF8_TO_NATIVE(*s, *(s+1)) != * (U8*) l)
6655 /* The target and the pattern have the same utf8ness. */
6656 /* Inline the first character, for speed. */
6657 if ( loceol - locinput < ln
6658 || UCHARAT(s) != nextbyte
6659 || (ln > 1 && memNE(s, locinput, ln)))
6668 case EXACTFL: /* /abc/il */
6671 const U8 * fold_array;
6673 U32 fold_utf8_flags;
6675 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6676 folder = foldEQ_locale;
6677 fold_array = PL_fold_locale;
6678 fold_utf8_flags = FOLDEQ_LOCALE;
6681 case EXACTFLU8: /* /abc/il; but all 'abc' are above 255, so
6682 is effectively /u; hence to match, target
6684 if (! utf8_target) {
6687 fold_utf8_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
6688 | FOLDEQ_S2_FOLDS_SANE;
6689 folder = foldEQ_latin1_s2_folded;
6690 fold_array = PL_fold_latin1;
6693 case EXACTFU_REQ8: /* /abc/iu with something in /abc/ > 255 */
6694 if (! utf8_target) {
6697 assert(is_utf8_pat);
6698 fold_utf8_flags = FOLDEQ_S2_ALREADY_FOLDED;
6701 case EXACTFUP: /* /foo/iu, and something is problematic in
6702 'foo' so can't take shortcuts. */
6703 assert(! is_utf8_pat);
6704 folder = foldEQ_latin1;
6705 fold_array = PL_fold_latin1;
6706 fold_utf8_flags = 0;
6709 case EXACTFU: /* /abc/iu */
6710 folder = foldEQ_latin1_s2_folded;
6711 fold_array = PL_fold_latin1;
6712 fold_utf8_flags = FOLDEQ_S2_ALREADY_FOLDED;
6715 case EXACTFAA_NO_TRIE: /* This node only generated for non-utf8
6717 assert(! is_utf8_pat);
6719 case EXACTFAA: /* /abc/iaa */
6720 folder = foldEQ_latin1_s2_folded;
6721 fold_array = PL_fold_latin1;
6722 fold_utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
6723 if (is_utf8_pat || ! utf8_target) {
6725 /* The possible presence of a MICRO SIGN in the pattern forbids
6726 * us to view a non-UTF-8 pattern as folded when there is a
6728 fold_utf8_flags |= FOLDEQ_S2_ALREADY_FOLDED
6729 |FOLDEQ_S2_FOLDS_SANE;
6734 case EXACTF: /* /abc/i This node only generated for
6735 non-utf8 patterns */
6736 assert(! is_utf8_pat);
6738 fold_array = PL_fold;
6739 fold_utf8_flags = 0;
6743 ln = STR_LENs(scan);
6747 || state_num == EXACTFUP
6748 || (state_num == EXACTFL && IN_UTF8_CTYPE_LOCALE))
6750 /* Either target or the pattern are utf8, or has the issue where
6751 * the fold lengths may differ. */
6752 const char * const l = locinput;
6755 if (! foldEQ_utf8_flags(l, &e, 0, utf8_target,
6756 s, 0, ln, is_utf8_pat,fold_utf8_flags))
6764 /* Neither the target nor the pattern are utf8 */
6765 if (UCHARAT(s) != nextbyte
6767 && UCHARAT(s) != fold_array[nextbyte])
6771 if (loceol - locinput < ln)
6773 if (ln > 1 && ! folder(locinput, s, ln))
6779 case NBOUNDL: /* /\B/l */
6783 case BOUNDL: /* /\b/l */
6786 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6788 if (FLAGS(scan) != TRADITIONAL_BOUND) {
6789 CHECK_AND_WARN_NON_UTF8_CTYPE_LOCALE_IN_BOUND;
6794 if (locinput == reginfo->strbeg)
6795 b1 = isWORDCHAR_LC('\n');
6797 U8 *p = reghop3((U8*)locinput, -1,
6798 (U8*)(reginfo->strbeg));
6799 b1 = isWORDCHAR_LC_utf8_safe(p, (U8*)(reginfo->strend));
6801 b2 = (NEXTCHR_IS_EOS)
6802 ? isWORDCHAR_LC('\n')
6803 : isWORDCHAR_LC_utf8_safe((U8*) locinput,
6804 (U8*) reginfo->strend);
6806 else { /* Here the string isn't utf8 */
6807 b1 = (locinput == reginfo->strbeg)
6808 ? isWORDCHAR_LC('\n')
6809 : isWORDCHAR_LC(UCHARAT(locinput - 1));
6810 b2 = (NEXTCHR_IS_EOS)
6811 ? isWORDCHAR_LC('\n')
6812 : isWORDCHAR_LC(nextbyte);
6814 if (to_complement ^ (b1 == b2)) {
6820 case NBOUND: /* /\B/ */
6824 case BOUND: /* /\b/ */
6828 goto bound_ascii_match_only;
6830 case NBOUNDA: /* /\B/a */
6834 case BOUNDA: /* /\b/a */
6838 bound_ascii_match_only:
6839 /* Here the string isn't utf8, or is utf8 and only ascii characters
6840 * are to match \w. In the latter case looking at the byte just
6841 * prior to the current one may be just the final byte of a
6842 * multi-byte character. This is ok. There are two cases:
6843 * 1) it is a single byte character, and then the test is doing
6844 * just what it's supposed to.
6845 * 2) it is a multi-byte character, in which case the final byte is
6846 * never mistakable for ASCII, and so the test will say it is
6847 * not a word character, which is the correct answer. */
6848 b1 = (locinput == reginfo->strbeg)
6849 ? isWORDCHAR_A('\n')
6850 : isWORDCHAR_A(UCHARAT(locinput - 1));
6851 b2 = (NEXTCHR_IS_EOS)
6852 ? isWORDCHAR_A('\n')
6853 : isWORDCHAR_A(nextbyte);
6854 if (to_complement ^ (b1 == b2)) {
6860 case NBOUNDU: /* /\B/u */
6864 case BOUNDU: /* /\b/u */
6867 if (UNLIKELY(reginfo->strbeg >= reginfo->strend)) {
6870 else if (utf8_target) {
6872 switch((bound_type) FLAGS(scan)) {
6873 case TRADITIONAL_BOUND:
6876 if (locinput == reginfo->strbeg) {
6877 b1 = 0 /* isWORDCHAR_L1('\n') */;
6880 U8 *p = reghop3((U8*)locinput, -1,
6881 (U8*)(reginfo->strbeg));
6883 b1 = isWORDCHAR_utf8_safe(p, (U8*) reginfo->strend);
6885 b2 = (NEXTCHR_IS_EOS)
6886 ? 0 /* isWORDCHAR_L1('\n') */
6887 : isWORDCHAR_utf8_safe((U8*)locinput,
6888 (U8*) reginfo->strend);
6889 match = cBOOL(b1 != b2);
6893 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6894 match = TRUE; /* GCB always matches at begin and
6898 /* Find the gcb values of previous and current
6899 * chars, then see if is a break point */
6900 match = isGCB(getGCB_VAL_UTF8(
6901 reghop3((U8*)locinput,
6903 (U8*)(reginfo->strbeg)),
6904 (U8*) reginfo->strend),
6905 getGCB_VAL_UTF8((U8*) locinput,
6906 (U8*) reginfo->strend),
6907 (U8*) reginfo->strbeg,
6914 if (locinput == reginfo->strbeg) {
6917 else if (NEXTCHR_IS_EOS) {
6921 match = isLB(getLB_VAL_UTF8(
6922 reghop3((U8*)locinput,
6924 (U8*)(reginfo->strbeg)),
6925 (U8*) reginfo->strend),
6926 getLB_VAL_UTF8((U8*) locinput,
6927 (U8*) reginfo->strend),
6928 (U8*) reginfo->strbeg,
6930 (U8*) reginfo->strend,
6935 case SB_BOUND: /* Always matches at begin and end */
6936 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6940 match = isSB(getSB_VAL_UTF8(
6941 reghop3((U8*)locinput,
6943 (U8*)(reginfo->strbeg)),
6944 (U8*) reginfo->strend),
6945 getSB_VAL_UTF8((U8*) locinput,
6946 (U8*) reginfo->strend),
6947 (U8*) reginfo->strbeg,
6949 (U8*) reginfo->strend,
6955 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6959 match = isWB(WB_UNKNOWN,
6961 reghop3((U8*)locinput,
6963 (U8*)(reginfo->strbeg)),
6964 (U8*) reginfo->strend),
6965 getWB_VAL_UTF8((U8*) locinput,
6966 (U8*) reginfo->strend),
6967 (U8*) reginfo->strbeg,
6969 (U8*) reginfo->strend,
6975 else { /* Not utf8 target */
6976 switch((bound_type) FLAGS(scan)) {
6977 case TRADITIONAL_BOUND:
6980 b1 = (locinput == reginfo->strbeg)
6981 ? 0 /* isWORDCHAR_L1('\n') */
6982 : isWORDCHAR_L1(UCHARAT(locinput - 1));
6983 b2 = (NEXTCHR_IS_EOS)
6984 ? 0 /* isWORDCHAR_L1('\n') */
6985 : isWORDCHAR_L1(nextbyte);
6986 match = cBOOL(b1 != b2);
6991 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6992 match = TRUE; /* GCB always matches at begin and
6995 else { /* Only CR-LF combo isn't a GCB in 0-255
6997 match = UCHARAT(locinput - 1) != '\r'
6998 || UCHARAT(locinput) != '\n';
7003 if (locinput == reginfo->strbeg) {
7006 else if (NEXTCHR_IS_EOS) {
7010 match = isLB(getLB_VAL_CP(UCHARAT(locinput -1)),
7011 getLB_VAL_CP(UCHARAT(locinput)),
7012 (U8*) reginfo->strbeg,
7014 (U8*) reginfo->strend,
7019 case SB_BOUND: /* Always matches at begin and end */
7020 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
7024 match = isSB(getSB_VAL_CP(UCHARAT(locinput -1)),
7025 getSB_VAL_CP(UCHARAT(locinput)),
7026 (U8*) reginfo->strbeg,
7028 (U8*) reginfo->strend,
7034 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
7038 match = isWB(WB_UNKNOWN,
7039 getWB_VAL_CP(UCHARAT(locinput -1)),
7040 getWB_VAL_CP(UCHARAT(locinput)),
7041 (U8*) reginfo->strbeg,
7043 (U8*) reginfo->strend,
7050 if (to_complement ^ ! match) {
7056 case ANYOFL: /* /[abc]/l */
7057 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
7058 CHECK_AND_WARN_NON_UTF8_CTYPE_LOCALE_IN_SETS(scan);
7061 case ANYOFD: /* /[abc]/d */
7062 case ANYOF: /* /[abc]/ */
7063 if (NEXTCHR_IS_EOS || locinput >= loceol)
7065 if ( (! utf8_target || UTF8_IS_INVARIANT(*locinput))
7066 && ! (ANYOF_FLAGS(scan) & ~ ANYOF_MATCHES_ALL_ABOVE_BITMAP))
7068 if (! ANYOF_BITMAP_TEST(scan, * (U8 *) (locinput))) {
7074 if (!reginclass(rex, scan, (U8*)locinput, (U8*) loceol,
7079 goto increment_locinput;
7085 || (UCHARAT(locinput) & FLAGS(scan)) != ARG(scan)
7086 || locinput >= loceol)
7090 locinput++; /* ANYOFM is always single byte */
7095 || (UCHARAT(locinput) & FLAGS(scan)) == ARG(scan)
7096 || locinput >= loceol)
7100 goto increment_locinput;
7106 || ANYOF_FLAGS(scan) > NATIVE_UTF8_TO_I8(*locinput)
7107 || ! reginclass(rex, scan, (U8*)locinput, (U8*) loceol,
7112 goto increment_locinput;
7118 || ANYOF_FLAGS(scan) != (U8) *locinput
7119 || ! reginclass(rex, scan, (U8*)locinput, (U8*) loceol,
7124 goto increment_locinput;
7130 || ! inRANGE((U8) NATIVE_UTF8_TO_I8(*locinput),
7131 LOWEST_ANYOF_HRx_BYTE(ANYOF_FLAGS(scan)),
7132 HIGHEST_ANYOF_HRx_BYTE(ANYOF_FLAGS(scan)))
7133 || ! reginclass(rex, scan, (U8*)locinput, (U8*) loceol,
7138 goto increment_locinput;
7144 || loceol - locinput < FLAGS(scan)
7145 || memNE(locinput, ((struct regnode_anyofhs *) scan)->string, FLAGS(scan))
7146 || ! reginclass(rex, scan, (U8*)locinput, (U8*) loceol,
7151 goto increment_locinput;
7155 if (NEXTCHR_IS_EOS) {
7160 if ( ANYOF_FLAGS(scan) > NATIVE_UTF8_TO_I8(*locinput)
7161 || ! withinCOUNT(utf8_to_uvchr_buf((U8 *) locinput,
7162 (U8 *) reginfo->strend,
7164 ANYOFRbase(scan), ANYOFRdelta(scan)))
7170 if (! withinCOUNT((U8) *locinput,
7171 ANYOFRbase(scan), ANYOFRdelta(scan)))
7176 goto increment_locinput;
7180 if (NEXTCHR_IS_EOS) {
7185 if ( ANYOF_FLAGS(scan) != (U8) *locinput
7186 || ! withinCOUNT(utf8_to_uvchr_buf((U8 *) locinput,
7187 (U8 *) reginfo->strend,
7189 ANYOFRbase(scan), ANYOFRdelta(scan)))
7195 if (! withinCOUNT((U8) *locinput,
7196 ANYOFRbase(scan), ANYOFRdelta(scan)))
7201 goto increment_locinput;
7204 /* The argument (FLAGS) to all the POSIX node types is the class number
7207 case NPOSIXL: /* \W or [:^punct:] etc. under /l */
7211 case POSIXL: /* \w or [:punct:] etc. under /l */
7212 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
7213 if (NEXTCHR_IS_EOS || locinput >= loceol)
7216 /* Use isFOO_lc() for characters within Latin1. (Note that
7217 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
7218 * wouldn't be invariant) */
7219 if (UTF8_IS_INVARIANT(nextbyte) || ! utf8_target) {
7220 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan), (U8) nextbyte)))) {
7228 if (! UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(locinput, reginfo->strend)) {
7229 /* An above Latin-1 code point, or malformed */
7230 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput,
7232 goto utf8_posix_above_latin1;
7235 /* Here is a UTF-8 variant code point below 256 and the target is
7237 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan),
7238 EIGHT_BIT_UTF8_TO_NATIVE(nextbyte,
7239 *(locinput + 1))))))
7244 goto increment_locinput;
7246 case NPOSIXD: /* \W or [:^punct:] etc. under /d */
7250 case POSIXD: /* \w or [:punct:] etc. under /d */
7256 case NPOSIXA: /* \W or [:^punct:] etc. under /a */
7258 if (NEXTCHR_IS_EOS || locinput >= loceol) {
7262 /* All UTF-8 variants match */
7263 if (! UTF8_IS_INVARIANT(nextbyte)) {
7264 goto increment_locinput;
7270 case POSIXA: /* \w or [:punct:] etc. under /a */
7273 /* We get here through POSIXD, NPOSIXD, and NPOSIXA when not in
7274 * UTF-8, and also from NPOSIXA even in UTF-8 when the current
7275 * character is a single byte */
7277 if (NEXTCHR_IS_EOS || locinput >= loceol) {
7283 if (! (to_complement ^ cBOOL(_generic_isCC_A(nextbyte,
7289 /* Here we are either not in utf8, or we matched a utf8-invariant,
7290 * so the next char is the next byte */
7294 case NPOSIXU: /* \W or [:^punct:] etc. under /u */
7298 case POSIXU: /* \w or [:punct:] etc. under /u */
7300 if (NEXTCHR_IS_EOS || locinput >= loceol) {
7304 /* Use _generic_isCC() for characters within Latin1. (Note that
7305 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
7306 * wouldn't be invariant) */
7307 if (UTF8_IS_INVARIANT(nextbyte) || ! utf8_target) {
7308 if (! (to_complement ^ cBOOL(_generic_isCC(nextbyte,
7315 else if (UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(locinput, reginfo->strend)) {
7316 if (! (to_complement
7317 ^ cBOOL(_generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(nextbyte,
7325 else { /* Handle above Latin-1 code points */
7326 utf8_posix_above_latin1:
7327 classnum = (_char_class_number) FLAGS(scan);
7330 if (! (to_complement
7331 ^ cBOOL(_invlist_contains_cp(
7332 PL_XPosix_ptrs[classnum],
7333 utf8_to_uvchr_buf((U8 *) locinput,
7334 (U8 *) reginfo->strend,
7340 case _CC_ENUM_SPACE:
7341 if (! (to_complement
7342 ^ cBOOL(is_XPERLSPACE_high(locinput))))
7347 case _CC_ENUM_BLANK:
7348 if (! (to_complement
7349 ^ cBOOL(is_HORIZWS_high(locinput))))
7354 case _CC_ENUM_XDIGIT:
7355 if (! (to_complement
7356 ^ cBOOL(is_XDIGIT_high(locinput))))
7361 case _CC_ENUM_VERTSPACE:
7362 if (! (to_complement
7363 ^ cBOOL(is_VERTWS_high(locinput))))
7368 case _CC_ENUM_CNTRL: /* These can't match above Latin1 */
7369 case _CC_ENUM_ASCII:
7370 if (! to_complement) {
7375 locinput += UTF8_SAFE_SKIP(locinput, reginfo->strend);
7379 case CLUMP: /* Match \X: logical Unicode character. This is defined as
7380 a Unicode extended Grapheme Cluster */
7381 if (NEXTCHR_IS_EOS || locinput >= loceol)
7383 if (! utf8_target) {
7385 /* Match either CR LF or '.', as all the other possibilities
7387 locinput++; /* Match the . or CR */
7388 if (nextbyte == '\r' /* And if it was CR, and the next is LF,
7390 && locinput < loceol
7391 && UCHARAT(locinput) == '\n')
7398 /* Get the gcb type for the current character */
7399 GCB_enum prev_gcb = getGCB_VAL_UTF8((U8*) locinput,
7400 (U8*) reginfo->strend);
7402 /* Then scan through the input until we get to the first
7403 * character whose type is supposed to be a gcb with the
7404 * current character. (There is always a break at the
7406 locinput += UTF8SKIP(locinput);
7407 while (locinput < loceol) {
7408 GCB_enum cur_gcb = getGCB_VAL_UTF8((U8*) locinput,
7409 (U8*) reginfo->strend);
7410 if (isGCB(prev_gcb, cur_gcb,
7411 (U8*) reginfo->strbeg, (U8*) locinput,
7418 locinput += UTF8SKIP(locinput);
7425 case REFFLN: /* /\g{name}/il */
7426 { /* The capture buffer cases. The ones beginning with N for the
7427 named buffers just convert to the equivalent numbered and
7428 pretend they were called as the corresponding numbered buffer
7430 /* don't initialize these in the declaration, it makes C++
7435 const U8 *fold_array;
7438 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
7439 folder = foldEQ_locale;
7440 fold_array = PL_fold_locale;
7442 utf8_fold_flags = FOLDEQ_LOCALE;
7445 case REFFAN: /* /\g{name}/iaa */
7446 folder = foldEQ_latin1;
7447 fold_array = PL_fold_latin1;
7449 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
7452 case REFFUN: /* /\g{name}/iu */
7453 folder = foldEQ_latin1;
7454 fold_array = PL_fold_latin1;
7456 utf8_fold_flags = 0;
7459 case REFFN: /* /\g{name}/i */
7461 fold_array = PL_fold;
7463 utf8_fold_flags = 0;
7466 case REFN: /* /\g{name}/ */
7470 utf8_fold_flags = 0;
7473 /* For the named back references, find the corresponding buffer
7475 n = reg_check_named_buff_matched(rex,scan);
7480 goto do_nref_ref_common;
7482 case REFFL: /* /\1/il */
7483 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
7484 folder = foldEQ_locale;
7485 fold_array = PL_fold_locale;
7486 utf8_fold_flags = FOLDEQ_LOCALE;
7489 case REFFA: /* /\1/iaa */
7490 folder = foldEQ_latin1;
7491 fold_array = PL_fold_latin1;
7492 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
7495 case REFFU: /* /\1/iu */
7496 folder = foldEQ_latin1;
7497 fold_array = PL_fold_latin1;
7498 utf8_fold_flags = 0;
7501 case REFF: /* /\1/i */
7503 fold_array = PL_fold;
7504 utf8_fold_flags = 0;
7507 case REF: /* /\1/ */
7510 utf8_fold_flags = 0;
7514 n = ARG(scan); /* which paren pair */
7517 ln = rex->offs[n].start;
7518 endref = rex->offs[n].end;
7519 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
7520 if (rex->lastparen < n || ln == -1 || endref == -1)
7521 sayNO; /* Do not match unless seen CLOSEn. */
7525 s = reginfo->strbeg + ln;
7526 if (type != REF /* REF can do byte comparison */
7527 && (utf8_target || type == REFFU || type == REFFL))
7529 char * limit = loceol;
7531 /* This call case insensitively compares the entire buffer
7532 * at s, with the current input starting at locinput, but
7533 * not going off the end given by loceol, and
7534 * returns in <limit> upon success, how much of the
7535 * current input was matched */
7536 if (! foldEQ_utf8_flags(s, NULL, endref - ln, utf8_target,
7537 locinput, &limit, 0, utf8_target, utf8_fold_flags))
7545 /* Not utf8: Inline the first character, for speed. */
7546 if ( ! NEXTCHR_IS_EOS
7547 && locinput < loceol
7548 && UCHARAT(s) != nextbyte
7550 || UCHARAT(s) != fold_array[nextbyte]))
7555 if (locinput + ln > loceol)
7557 if (ln > 1 && (type == REF
7558 ? memNE(s, locinput, ln)
7559 : ! folder(locinput, s, ln)))
7565 case NOTHING: /* null op; e.g. the 'nothing' following
7566 * the '*' in m{(a+|b)*}' */
7568 case TAIL: /* placeholder while compiling (A|B|C) */
7572 #define ST st->u.eval
7573 #define CUR_EVAL cur_eval->u.eval
7579 regexp_internal *rei;
7580 regnode *startpoint;
7583 case GOSUB: /* /(...(?1))/ /(...(?&foo))/ */
7584 arg= (U32)ARG(scan);
7585 if (cur_eval && cur_eval->locinput == locinput) {
7586 if ( ++nochange_depth > max_nochange_depth )
7588 "Pattern subroutine nesting without pos change"
7589 " exceeded limit in regex");
7596 startpoint = scan + ARG2L(scan);
7597 EVAL_CLOSE_PAREN_SET( st, arg );
7598 /* Detect infinite recursion
7600 * A pattern like /(?R)foo/ or /(?<x>(?&y)foo)(?<y>(?&x)bar)/
7601 * or "a"=~/(.(?2))((?<=(?=(?1)).))/ could recurse forever.
7602 * So we track the position in the string we are at each time
7603 * we recurse and if we try to enter the same routine twice from
7604 * the same position we throw an error.
7606 if ( rex->recurse_locinput[arg] == locinput ) {
7607 /* FIXME: we should show the regop that is failing as part
7608 * of the error message. */
7609 Perl_croak(aTHX_ "Infinite recursion in regex");
7611 ST.prev_recurse_locinput= rex->recurse_locinput[arg];
7612 rex->recurse_locinput[arg]= locinput;
7615 DECLARE_AND_GET_RE_DEBUG_FLAGS;
7617 Perl_re_exec_indentf( aTHX_
7618 "entering GOSUB, prev_recurse_locinput=%p recurse_locinput[%d]=%p\n",
7619 depth, ST.prev_recurse_locinput, arg, rex->recurse_locinput[arg]
7625 /* Save all the positions seen so far. */
7626 ST.cp = regcppush(rex, 0, maxopenparen);
7627 REGCP_SET(ST.lastcp);
7629 /* and then jump to the code we share with EVAL */
7630 goto eval_recurse_doit;
7633 case EVAL: /* /(?{...})B/ /(??{A})B/ and /(?(?{...})X|Y)B/ */
7634 if (logical == 2 && cur_eval && cur_eval->locinput==locinput) {
7635 if ( ++nochange_depth > max_nochange_depth )
7636 Perl_croak(aTHX_ "EVAL without pos change exceeded limit in regex");
7641 /* execute the code in the {...} */
7645 OP * const oop = PL_op;
7646 COP * const ocurcop = PL_curcop;
7650 /* save *all* paren positions */
7651 regcppush(rex, 0, maxopenparen);
7652 REGCP_SET(ST.lastcp);
7655 caller_cv = find_runcv(NULL);
7659 if (rexi->data->what[n] == 'r') { /* code from an external qr */
7661 (REGEXP*)(rexi->data->data[n])
7663 nop = (OP*)rexi->data->data[n+1];
7665 else if (rexi->data->what[n] == 'l') { /* literal code */
7667 nop = (OP*)rexi->data->data[n];
7668 assert(CvDEPTH(newcv));
7671 /* literal with own CV */
7672 assert(rexi->data->what[n] == 'L');
7673 newcv = rex->qr_anoncv;
7674 nop = (OP*)rexi->data->data[n];
7677 /* Some notes about MULTICALL and the context and save stacks.
7680 * /...(?{ my $x)}...(?{ my $y)}...(?{ my $z)}.../
7681 * since codeblocks don't introduce a new scope (so that
7682 * local() etc accumulate), at the end of a successful
7683 * match there will be a SAVEt_CLEARSV on the savestack
7684 * for each of $x, $y, $z. If the three code blocks above
7685 * happen to have come from different CVs (e.g. via
7686 * embedded qr//s), then we must ensure that during any
7687 * savestack unwinding, PL_comppad always points to the
7688 * right pad at each moment. We achieve this by
7689 * interleaving SAVEt_COMPPAD's on the savestack whenever
7690 * there is a change of pad.
7691 * In theory whenever we call a code block, we should
7692 * push a CXt_SUB context, then pop it on return from
7693 * that code block. This causes a bit of an issue in that
7694 * normally popping a context also clears the savestack
7695 * back to cx->blk_oldsaveix, but here we specifically
7696 * don't want to clear the save stack on exit from the
7698 * Also for efficiency we don't want to keep pushing and
7699 * popping the single SUB context as we backtrack etc.
7700 * So instead, we push a single context the first time
7701 * we need, it, then hang onto it until the end of this
7702 * function. Whenever we encounter a new code block, we
7703 * update the CV etc if that's changed. During the times
7704 * in this function where we're not executing a code
7705 * block, having the SUB context still there is a bit
7706 * naughty - but we hope that no-one notices.
7707 * When the SUB context is initially pushed, we fake up
7708 * cx->blk_oldsaveix to be as if we'd pushed this context
7709 * on first entry to S_regmatch rather than at some random
7710 * point during the regexe execution. That way if we
7711 * croak, popping the context stack will ensure that
7712 * *everything* SAVEd by this function is undone and then
7713 * the context popped, rather than e.g., popping the
7714 * context (and restoring the original PL_comppad) then
7715 * popping more of the savestack and restoring a bad
7719 /* If this is the first EVAL, push a MULTICALL. On
7720 * subsequent calls, if we're executing a different CV, or
7721 * if PL_comppad has got messed up from backtracking
7722 * through SAVECOMPPADs, then refresh the context.
7724 if (newcv != last_pushed_cv || PL_comppad != last_pad)
7726 U8 flags = (CXp_SUB_RE |
7727 ((newcv == caller_cv) ? CXp_SUB_RE_FAKE : 0));
7729 if (last_pushed_cv) {
7730 CHANGE_MULTICALL_FLAGS(newcv, flags);
7733 PUSH_MULTICALL_FLAGS(newcv, flags);
7735 /* see notes above */
7736 CX_CUR()->blk_oldsaveix = orig_savestack_ix;
7738 last_pushed_cv = newcv;
7741 /* these assignments are just to silence compiler
7743 multicall_cop = NULL;
7745 last_pad = PL_comppad;
7747 /* the initial nextstate you would normally execute
7748 * at the start of an eval (which would cause error
7749 * messages to come from the eval), may be optimised
7750 * away from the execution path in the regex code blocks;
7751 * so manually set PL_curcop to it initially */
7753 OP *o = cUNOPx(nop)->op_first;
7754 assert(o->op_type == OP_NULL);
7755 if (o->op_targ == OP_SCOPE) {
7756 o = cUNOPo->op_first;
7759 assert(o->op_targ == OP_LEAVE);
7760 o = cUNOPo->op_first;
7761 assert(o->op_type == OP_ENTER);
7765 if (o->op_type != OP_STUB) {
7766 assert( o->op_type == OP_NEXTSTATE
7767 || o->op_type == OP_DBSTATE
7768 || (o->op_type == OP_NULL
7769 && ( o->op_targ == OP_NEXTSTATE
7770 || o->op_targ == OP_DBSTATE
7774 PL_curcop = (COP*)o;
7779 DEBUG_STATE_r( Perl_re_printf( aTHX_
7780 " re EVAL PL_op=0x%" UVxf "\n", PTR2UV(nop)) );
7782 rex->offs[0].end = locinput - reginfo->strbeg;
7783 if (reginfo->info_aux_eval->pos_magic)
7784 MgBYTEPOS_set(reginfo->info_aux_eval->pos_magic,
7785 reginfo->sv, reginfo->strbeg,
7786 locinput - reginfo->strbeg);
7789 SV *sv_mrk = get_sv("REGMARK", 1);
7790 sv_setsv(sv_mrk, sv_yes_mark);
7793 /* we don't use MULTICALL here as we want to call the
7794 * first op of the block of interest, rather than the
7795 * first op of the sub. Also, we don't want to free
7796 * the savestack frame */
7797 before = (IV)(SP-PL_stack_base);
7799 CALLRUNOPS(aTHX); /* Scalar context. */
7801 if ((IV)(SP-PL_stack_base) == before)
7802 ret = &PL_sv_undef; /* protect against empty (?{}) blocks. */
7808 /* before restoring everything, evaluate the returned
7809 * value, so that 'uninit' warnings don't use the wrong
7810 * PL_op or pad. Also need to process any magic vars
7811 * (e.g. $1) *before* parentheses are restored */
7816 if (logical == 0) { /* (?{})/ */
7817 SV *replsv = save_scalar(PL_replgv);
7818 sv_setsv(replsv, ret); /* $^R */
7821 else if (logical == 1) { /* /(?(?{...})X|Y)/ */
7822 sw = cBOOL(SvTRUE_NN(ret));
7825 else { /* /(??{}) */
7826 /* if its overloaded, let the regex compiler handle
7827 * it; otherwise extract regex, or stringify */
7828 if (SvGMAGICAL(ret))
7829 ret = sv_mortalcopy(ret);
7830 if (!SvAMAGIC(ret)) {
7834 if (SvTYPE(sv) == SVt_REGEXP)
7835 re_sv = (REGEXP*) sv;
7836 else if (SvSMAGICAL(ret)) {
7837 MAGIC *mg = mg_find(ret, PERL_MAGIC_qr);
7839 re_sv = (REGEXP *) mg->mg_obj;
7842 /* force any undef warnings here */
7843 if (!re_sv && !SvPOK(ret) && !SvNIOK(ret)) {
7844 ret = sv_mortalcopy(ret);
7845 (void) SvPV_force_nolen(ret);
7851 /* *** Note that at this point we don't restore
7852 * PL_comppad, (or pop the CxSUB) on the assumption it may
7853 * be used again soon. This is safe as long as nothing
7854 * in the regexp code uses the pad ! */
7856 PL_curcop = ocurcop;
7857 regcp_restore(rex, ST.lastcp, &maxopenparen);
7858 PL_curpm_under = PL_curpm;
7859 PL_curpm = PL_reg_curpm;
7862 PUSH_STATE_GOTO(EVAL_B, next, locinput, loceol,
7868 /* only /(??{})/ from now on */
7871 /* extract RE object from returned value; compiling if
7875 re_sv = reg_temp_copy(NULL, re_sv);
7880 if (SvUTF8(ret) && IN_BYTES) {
7881 /* In use 'bytes': make a copy of the octet
7882 * sequence, but without the flag on */
7884 const char *const p = SvPV(ret, len);
7885 ret = newSVpvn_flags(p, len, SVs_TEMP);
7887 if (rex->intflags & PREGf_USE_RE_EVAL)
7888 pm_flags |= PMf_USE_RE_EVAL;
7890 /* if we got here, it should be an engine which
7891 * supports compiling code blocks and stuff */
7892 assert(rex->engine && rex->engine->op_comp);
7893 assert(!(scan->flags & ~RXf_PMf_COMPILETIME));
7894 re_sv = rex->engine->op_comp(aTHX_ &ret, 1, NULL,
7895 rex->engine, NULL, NULL,
7896 /* copy /msixn etc to inner pattern */
7901 & (SVs_TEMP | SVs_GMG | SVf_ROK))
7902 && (!SvPADTMP(ret) || SvREADONLY(ret))) {
7903 /* This isn't a first class regexp. Instead, it's
7904 caching a regexp onto an existing, Perl visible
7906 sv_magic(ret, MUTABLE_SV(re_sv), PERL_MAGIC_qr, 0, 0);
7912 RXp_MATCH_COPIED_off(re);
7913 re->subbeg = rex->subbeg;
7914 re->sublen = rex->sublen;
7915 re->suboffset = rex->suboffset;
7916 re->subcoffset = rex->subcoffset;
7918 re->lastcloseparen = 0;
7921 debug_start_match(re_sv, utf8_target, locinput,
7922 reginfo->strend, "EVAL/GOSUB: Matching embedded");
7924 startpoint = rei->program + 1;
7925 EVAL_CLOSE_PAREN_CLEAR(st); /* ST.close_paren = 0;
7926 * close_paren only for GOSUB */
7927 ST.prev_recurse_locinput= NULL; /* only used for GOSUB */
7928 /* Save all the seen positions so far. */
7929 ST.cp = regcppush(rex, 0, maxopenparen);
7930 REGCP_SET(ST.lastcp);
7931 /* and set maxopenparen to 0, since we are starting a "fresh" match */
7933 /* run the pattern returned from (??{...}) */
7935 eval_recurse_doit: /* Share code with GOSUB below this line
7936 * At this point we expect the stack context to be
7937 * set up correctly */
7939 /* invalidate the S-L poscache. We're now executing a
7940 * different set of WHILEM ops (and their associated
7941 * indexes) against the same string, so the bits in the
7942 * cache are meaningless. Setting maxiter to zero forces
7943 * the cache to be invalidated and zeroed before reuse.
7944 * XXX This is too dramatic a measure. Ideally we should
7945 * save the old cache and restore when running the outer
7947 reginfo->poscache_maxiter = 0;
7949 /* the new regexp might have a different is_utf8_pat than we do */
7950 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(re_sv));
7952 ST.prev_rex = rex_sv;
7953 ST.prev_curlyx = cur_curlyx;
7955 SET_reg_curpm(rex_sv);
7960 ST.prev_eval = cur_eval;
7962 /* now continue from first node in postoned RE */
7963 PUSH_YES_STATE_GOTO(EVAL_postponed_AB, startpoint, locinput,
7964 loceol, script_run_begin);
7965 NOT_REACHED; /* NOTREACHED */
7968 case EVAL_postponed_AB: /* cleanup after a successful (??{A})B */
7969 /* note: this is called twice; first after popping B, then A */
7971 Perl_re_exec_indentf( aTHX_ "EVAL_AB cur_eval=%p prev_eval=%p\n",
7972 depth, cur_eval, ST.prev_eval);
7975 #define SET_RECURSE_LOCINPUT(STR,VAL)\
7976 if ( cur_eval && CUR_EVAL.close_paren ) {\
7978 Perl_re_exec_indentf( aTHX_ STR " GOSUB%d ce=%p recurse_locinput=%p\n",\
7980 CUR_EVAL.close_paren - 1,\
7984 rex->recurse_locinput[CUR_EVAL.close_paren - 1] = VAL;\
7987 SET_RECURSE_LOCINPUT("EVAL_AB[before]", CUR_EVAL.prev_recurse_locinput);
7989 rex_sv = ST.prev_rex;
7990 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
7991 SET_reg_curpm(rex_sv);
7992 rex = ReANY(rex_sv);
7993 rexi = RXi_GET(rex);
7995 /* preserve $^R across LEAVE's. See Bug 121070. */
7996 SV *save_sv= GvSV(PL_replgv);
7998 SvREFCNT_inc(save_sv);
7999 regcpblow(ST.cp); /* LEAVE in disguise */
8000 /* don't move this initialization up */
8001 replsv = GvSV(PL_replgv);
8002 sv_setsv(replsv, save_sv);
8004 SvREFCNT_dec(save_sv);
8006 cur_eval = ST.prev_eval;
8007 cur_curlyx = ST.prev_curlyx;
8009 /* Invalidate cache. See "invalidate" comment above. */
8010 reginfo->poscache_maxiter = 0;
8011 if ( nochange_depth )
8014 SET_RECURSE_LOCINPUT("EVAL_AB[after]", cur_eval->locinput);
8018 case EVAL_B_fail: /* unsuccessful B in (?{...})B */
8019 REGCP_UNWIND(ST.lastcp);
8022 case EVAL_postponed_AB_fail: /* unsuccessfully ran A or B in (??{A})B */
8023 /* note: this is called twice; first after popping B, then A */
8025 Perl_re_exec_indentf( aTHX_ "EVAL_AB_fail cur_eval=%p prev_eval=%p\n",
8026 depth, cur_eval, ST.prev_eval);
8029 SET_RECURSE_LOCINPUT("EVAL_AB_fail[before]", CUR_EVAL.prev_recurse_locinput);
8031 rex_sv = ST.prev_rex;
8032 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
8033 SET_reg_curpm(rex_sv);
8034 rex = ReANY(rex_sv);
8035 rexi = RXi_GET(rex);
8037 REGCP_UNWIND(ST.lastcp);
8038 regcppop(rex, &maxopenparen);
8039 cur_eval = ST.prev_eval;
8040 cur_curlyx = ST.prev_curlyx;
8042 /* Invalidate cache. See "invalidate" comment above. */
8043 reginfo->poscache_maxiter = 0;
8044 if ( nochange_depth )
8047 SET_RECURSE_LOCINPUT("EVAL_AB_fail[after]", cur_eval->locinput);
8052 n = ARG(scan); /* which paren pair */
8053 rex->offs[n].start_tmp = locinput - reginfo->strbeg;
8054 if (n > maxopenparen)
8056 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_
8057 "OPEN: rex=0x%" UVxf " offs=0x%" UVxf ": \\%" UVuf ": set %" IVdf " tmp; maxopenparen=%" UVuf "\n",
8062 (IV)rex->offs[n].start_tmp,
8068 case SROPEN: /* (*SCRIPT_RUN: */
8069 script_run_begin = (U8 *) locinput;
8074 n = ARG(scan); /* which paren pair */
8075 CLOSE_CAPTURE(n, rex->offs[n].start_tmp,
8076 locinput - reginfo->strbeg);
8077 if ( EVAL_CLOSE_PAREN_IS( cur_eval, n ) )
8082 case SRCLOSE: /* (*SCRIPT_RUN: ... ) */
8084 if (! isSCRIPT_RUN(script_run_begin, (U8 *) locinput, utf8_target))
8092 case ACCEPT: /* (*ACCEPT) */
8094 sv_yes_mark = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8098 cursor && OP(cursor)!=END;
8099 cursor=regnext(cursor))
8101 if ( OP(cursor)==CLOSE ){
8103 if ( n <= lastopen ) {
8104 CLOSE_CAPTURE(n, rex->offs[n].start_tmp,
8105 locinput - reginfo->strbeg);
8106 if ( n == ARG(scan) || EVAL_CLOSE_PAREN_IS(cur_eval, n) )
8115 case GROUPP: /* (?(1)) */
8116 n = ARG(scan); /* which paren pair */
8117 sw = cBOOL(rex->lastparen >= n && rex->offs[n].end != -1);
8120 case GROUPPN: /* (?(<name>)) */
8121 /* reg_check_named_buff_matched returns 0 for no match */
8122 sw = cBOOL(0 < reg_check_named_buff_matched(rex,scan));
8125 case INSUBP: /* (?(R)) */
8127 /* this does not need to use EVAL_CLOSE_PAREN macros, as the arg
8128 * of SCAN is already set up as matches a eval.close_paren */
8129 sw = cur_eval && (n == 0 || CUR_EVAL.close_paren == n);
8132 case DEFINEP: /* (?(DEFINE)) */
8136 case IFTHEN: /* (?(cond)A|B) */
8137 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
8139 next = NEXTOPER(NEXTOPER(scan));
8141 next = scan + ARG(scan);
8142 if (OP(next) == IFTHEN) /* Fake one. */
8143 next = NEXTOPER(NEXTOPER(next));
8147 case LOGICAL: /* modifier for EVAL and IFMATCH */
8148 logical = scan->flags;
8151 /*******************************************************************
8153 The CURLYX/WHILEM pair of ops handle the most generic case of the /A*B/
8154 pattern, where A and B are subpatterns. (For simple A, CURLYM or
8155 STAR/PLUS/CURLY/CURLYN are used instead.)
8157 A*B is compiled as <CURLYX><A><WHILEM><B>
8159 On entry to the subpattern, CURLYX is called. This pushes a CURLYX
8160 state, which contains the current count, initialised to -1. It also sets
8161 cur_curlyx to point to this state, with any previous value saved in the
8164 CURLYX then jumps straight to the WHILEM op, rather than executing A,
8165 since the pattern may possibly match zero times (i.e. it's a while {} loop
8166 rather than a do {} while loop).
8168 Each entry to WHILEM represents a successful match of A. The count in the
8169 CURLYX block is incremented, another WHILEM state is pushed, and execution
8170 passes to A or B depending on greediness and the current count.
8172 For example, if matching against the string a1a2a3b (where the aN are
8173 substrings that match /A/), then the match progresses as follows: (the
8174 pushed states are interspersed with the bits of strings matched so far):
8177 <CURLYX cnt=0><WHILEM>
8178 <CURLYX cnt=1><WHILEM> a1 <WHILEM>
8179 <CURLYX cnt=2><WHILEM> a1 <WHILEM> a2 <WHILEM>
8180 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM>
8181 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM> b
8183 (Contrast this with something like CURLYM, which maintains only a single
8187 a1 <CURLYM cnt=1> a2
8188 a1 a2 <CURLYM cnt=2> a3
8189 a1 a2 a3 <CURLYM cnt=3> b
8192 Each WHILEM state block marks a point to backtrack to upon partial failure
8193 of A or B, and also contains some minor state data related to that
8194 iteration. The CURLYX block, pointed to by cur_curlyx, contains the
8195 overall state, such as the count, and pointers to the A and B ops.
8197 This is complicated slightly by nested CURLYX/WHILEM's. Since cur_curlyx
8198 must always point to the *current* CURLYX block, the rules are:
8200 When executing CURLYX, save the old cur_curlyx in the CURLYX state block,
8201 and set cur_curlyx to point the new block.
8203 When popping the CURLYX block after a successful or unsuccessful match,
8204 restore the previous cur_curlyx.
8206 When WHILEM is about to execute B, save the current cur_curlyx, and set it
8207 to the outer one saved in the CURLYX block.
8209 When popping the WHILEM block after a successful or unsuccessful B match,
8210 restore the previous cur_curlyx.
8212 Here's an example for the pattern (AI* BI)*BO
8213 I and O refer to inner and outer, C and W refer to CURLYX and WHILEM:
8216 curlyx backtrack stack
8217 ------ ---------------
8219 CO <CO prev=NULL> <WO>
8220 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
8221 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
8222 NULL <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi <WO prev=CO> bo
8224 At this point the pattern succeeds, and we work back down the stack to
8225 clean up, restoring as we go:
8227 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
8228 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
8229 CO <CO prev=NULL> <WO>
8232 *******************************************************************/
8234 #define ST st->u.curlyx
8236 case CURLYX: /* start of /A*B/ (for complex A) */
8238 /* No need to save/restore up to this paren */
8239 I32 parenfloor = scan->flags;
8241 assert(next); /* keep Coverity happy */
8242 if (OP(PREVOPER(next)) == NOTHING) /* LONGJMP */
8245 /* XXXX Probably it is better to teach regpush to support
8246 parenfloor > maxopenparen ... */
8247 if (parenfloor > (I32)rex->lastparen)
8248 parenfloor = rex->lastparen; /* Pessimization... */
8250 ST.prev_curlyx= cur_curlyx;
8252 ST.cp = PL_savestack_ix;
8254 /* these fields contain the state of the current curly.
8255 * they are accessed by subsequent WHILEMs */
8256 ST.parenfloor = parenfloor;
8261 ST.count = -1; /* this will be updated by WHILEM */
8262 ST.lastloc = NULL; /* this will be updated by WHILEM */
8264 PUSH_YES_STATE_GOTO(CURLYX_end, PREVOPER(next), locinput, loceol,
8266 NOT_REACHED; /* NOTREACHED */
8269 case CURLYX_end: /* just finished matching all of A*B */
8270 cur_curlyx = ST.prev_curlyx;
8272 NOT_REACHED; /* NOTREACHED */
8274 case CURLYX_end_fail: /* just failed to match all of A*B */
8276 cur_curlyx = ST.prev_curlyx;
8278 NOT_REACHED; /* NOTREACHED */
8282 #define ST st->u.whilem
8284 case WHILEM: /* just matched an A in /A*B/ (for complex A) */
8286 /* see the discussion above about CURLYX/WHILEM */
8291 assert(cur_curlyx); /* keep Coverity happy */
8293 min = ARG1(cur_curlyx->u.curlyx.me);
8294 max = ARG2(cur_curlyx->u.curlyx.me);
8295 A = NEXTOPER(cur_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS;
8296 n = ++cur_curlyx->u.curlyx.count; /* how many A's matched */
8297 ST.save_lastloc = cur_curlyx->u.curlyx.lastloc;
8298 ST.cache_offset = 0;
8302 DEBUG_EXECUTE_r( Perl_re_exec_indentf( aTHX_ "WHILEM: matched %ld out of %d..%d\n",
8303 depth, (long)n, min, max)
8306 /* First just match a string of min A's. */
8309 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor, maxopenparen);
8310 cur_curlyx->u.curlyx.lastloc = locinput;
8311 REGCP_SET(ST.lastcp);
8313 PUSH_STATE_GOTO(WHILEM_A_pre, A, locinput, loceol,
8315 NOT_REACHED; /* NOTREACHED */
8318 /* If degenerate A matches "", assume A done. */
8320 if (locinput == cur_curlyx->u.curlyx.lastloc) {
8321 DEBUG_EXECUTE_r( Perl_re_exec_indentf( aTHX_ "WHILEM: empty match detected, trying continuation...\n",
8324 goto do_whilem_B_max;
8327 /* super-linear cache processing.
8329 * The idea here is that for certain types of CURLYX/WHILEM -
8330 * principally those whose upper bound is infinity (and
8331 * excluding regexes that have things like \1 and other very
8332 * non-regular expresssiony things), then if a pattern like
8333 * /....A*.../ fails and we backtrack to the WHILEM, then we
8334 * make a note that this particular WHILEM op was at string
8335 * position 47 (say) when the rest of pattern failed. Then, if
8336 * we ever find ourselves back at that WHILEM, and at string
8337 * position 47 again, we can just fail immediately rather than
8338 * running the rest of the pattern again.
8340 * This is very handy when patterns start to go
8341 * 'super-linear', like in (a+)*(a+)*(a+)*, where you end up
8342 * with a combinatorial explosion of backtracking.
8344 * The cache is implemented as a bit array, with one bit per
8345 * string byte position per WHILEM op (up to 16) - so its
8346 * between 0.25 and 2x the string size.
8348 * To avoid allocating a poscache buffer every time, we do an
8349 * initially countdown; only after we have executed a WHILEM
8350 * op (string-length x #WHILEMs) times do we allocate the
8353 * The top 4 bits of scan->flags byte say how many different
8354 * relevant CURLLYX/WHILEM op pairs there are, while the
8355 * bottom 4-bits is the identifying index number of this
8361 if (!reginfo->poscache_maxiter) {
8362 /* start the countdown: Postpone detection until we
8363 * know the match is not *that* much linear. */
8364 reginfo->poscache_maxiter
8365 = (reginfo->strend - reginfo->strbeg + 1)
8367 /* possible overflow for long strings and many CURLYX's */
8368 if (reginfo->poscache_maxiter < 0)
8369 reginfo->poscache_maxiter = I32_MAX;
8370 reginfo->poscache_iter = reginfo->poscache_maxiter;
8373 if (reginfo->poscache_iter-- == 0) {
8374 /* initialise cache */
8375 const SSize_t size = (reginfo->poscache_maxiter + 7)/8;
8376 regmatch_info_aux *const aux = reginfo->info_aux;
8377 if (aux->poscache) {
8378 if ((SSize_t)reginfo->poscache_size < size) {
8379 Renew(aux->poscache, size, char);
8380 reginfo->poscache_size = size;
8382 Zero(aux->poscache, size, char);
8385 reginfo->poscache_size = size;
8386 Newxz(aux->poscache, size, char);
8388 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
8389 "%sWHILEM: Detected a super-linear match, switching on caching%s...\n",
8390 PL_colors[4], PL_colors[5])
8394 if (reginfo->poscache_iter < 0) {
8395 /* have we already failed at this position? */
8396 SSize_t offset, mask;
8398 reginfo->poscache_iter = -1; /* stop eventual underflow */
8399 offset = (scan->flags & 0xf) - 1
8400 + (locinput - reginfo->strbeg)
8402 mask = 1 << (offset % 8);
8404 if (reginfo->info_aux->poscache[offset] & mask) {
8405 DEBUG_EXECUTE_r( Perl_re_exec_indentf( aTHX_ "WHILEM: (cache) already tried at this position...\n",
8408 cur_curlyx->u.curlyx.count--;
8409 sayNO; /* cache records failure */
8411 ST.cache_offset = offset;
8412 ST.cache_mask = mask;
8416 /* Prefer B over A for minimal matching. */
8418 if (cur_curlyx->u.curlyx.minmod) {
8419 ST.save_curlyx = cur_curlyx;
8420 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
8421 PUSH_YES_STATE_GOTO(WHILEM_B_min, ST.save_curlyx->u.curlyx.B,
8422 locinput, loceol, script_run_begin);
8423 NOT_REACHED; /* NOTREACHED */
8426 /* Prefer A over B for maximal matching. */
8428 if (n < max) { /* More greed allowed? */
8429 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
8431 cur_curlyx->u.curlyx.lastloc = locinput;
8432 REGCP_SET(ST.lastcp);
8433 PUSH_STATE_GOTO(WHILEM_A_max, A, locinput, loceol,
8435 NOT_REACHED; /* NOTREACHED */
8437 goto do_whilem_B_max;
8439 NOT_REACHED; /* NOTREACHED */
8441 case WHILEM_B_min: /* just matched B in a minimal match */
8442 case WHILEM_B_max: /* just matched B in a maximal match */
8443 cur_curlyx = ST.save_curlyx;
8445 NOT_REACHED; /* NOTREACHED */
8447 case WHILEM_B_max_fail: /* just failed to match B in a maximal match */
8448 cur_curlyx = ST.save_curlyx;
8449 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
8450 cur_curlyx->u.curlyx.count--;
8452 NOT_REACHED; /* NOTREACHED */
8454 case WHILEM_A_min_fail: /* just failed to match A in a minimal match */
8456 case WHILEM_A_pre_fail: /* just failed to match even minimal A */
8457 REGCP_UNWIND(ST.lastcp);
8458 regcppop(rex, &maxopenparen);
8459 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
8460 cur_curlyx->u.curlyx.count--;
8462 NOT_REACHED; /* NOTREACHED */
8464 case WHILEM_A_max_fail: /* just failed to match A in a maximal match */
8465 REGCP_UNWIND(ST.lastcp);
8466 regcppop(rex, &maxopenparen); /* Restore some previous $<digit>s? */
8467 DEBUG_EXECUTE_r(Perl_re_exec_indentf( aTHX_ "WHILEM: failed, trying continuation...\n",
8471 if (cur_curlyx->u.curlyx.count >= REG_INFTY
8472 && ckWARN(WARN_REGEXP)
8473 && !reginfo->warned)
8475 reginfo->warned = TRUE;
8476 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
8477 "Complex regular subexpression recursion limit (%d) "
8483 ST.save_curlyx = cur_curlyx;
8484 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
8485 PUSH_YES_STATE_GOTO(WHILEM_B_max, ST.save_curlyx->u.curlyx.B,
8486 locinput, loceol, script_run_begin);
8487 NOT_REACHED; /* NOTREACHED */
8489 case WHILEM_B_min_fail: /* just failed to match B in a minimal match */
8490 cur_curlyx = ST.save_curlyx;
8492 if (cur_curlyx->u.curlyx.count >= /*max*/ARG2(cur_curlyx->u.curlyx.me)) {
8493 /* Maximum greed exceeded */
8494 if (cur_curlyx->u.curlyx.count >= REG_INFTY
8495 && ckWARN(WARN_REGEXP)
8496 && !reginfo->warned)
8498 reginfo->warned = TRUE;
8499 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
8500 "Complex regular subexpression recursion "
8501 "limit (%d) exceeded",
8504 cur_curlyx->u.curlyx.count--;
8508 DEBUG_EXECUTE_r(Perl_re_exec_indentf( aTHX_ "WHILEM: B min fail: trying longer...\n", depth)
8510 /* Try grabbing another A and see if it helps. */
8511 cur_curlyx->u.curlyx.lastloc = locinput;
8512 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
8514 REGCP_SET(ST.lastcp);
8515 PUSH_STATE_GOTO(WHILEM_A_min,
8516 /*A*/ NEXTOPER(ST.save_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS,
8517 locinput, loceol, script_run_begin);
8518 NOT_REACHED; /* NOTREACHED */
8521 #define ST st->u.branch
8523 case BRANCHJ: /* /(...|A|...)/ with long next pointer */
8524 next = scan + ARG(scan);
8527 scan = NEXTOPER(scan);
8530 case BRANCH: /* /(...|A|...)/ */
8531 scan = NEXTOPER(scan); /* scan now points to inner node */
8532 ST.lastparen = rex->lastparen;
8533 ST.lastcloseparen = rex->lastcloseparen;
8534 ST.next_branch = next;
8537 /* Now go into the branch */
8539 PUSH_YES_STATE_GOTO(BRANCH_next, scan, locinput, loceol,
8542 PUSH_STATE_GOTO(BRANCH_next, scan, locinput, loceol,
8545 NOT_REACHED; /* NOTREACHED */
8547 case CUTGROUP: /* /(*THEN)/ */
8548 sv_yes_mark = st->u.mark.mark_name = scan->flags
8549 ? MUTABLE_SV(rexi->data->data[ ARG( scan ) ])
8551 PUSH_STATE_GOTO(CUTGROUP_next, next, locinput, loceol,
8553 NOT_REACHED; /* NOTREACHED */
8555 case CUTGROUP_next_fail:
8558 if (st->u.mark.mark_name)
8559 sv_commit = st->u.mark.mark_name;
8561 NOT_REACHED; /* NOTREACHED */
8565 NOT_REACHED; /* NOTREACHED */
8567 case BRANCH_next_fail: /* that branch failed; try the next, if any */
8572 REGCP_UNWIND(ST.cp);
8573 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
8574 scan = ST.next_branch;
8575 /* no more branches? */
8576 if (!scan || (OP(scan) != BRANCH && OP(scan) != BRANCHJ)) {
8578 Perl_re_exec_indentf( aTHX_ "%sBRANCH failed...%s\n",
8585 continue; /* execute next BRANCH[J] op */
8588 case MINMOD: /* next op will be non-greedy, e.g. A*? */
8593 #define ST st->u.curlym
8595 case CURLYM: /* /A{m,n}B/ where A is fixed-length */
8597 /* This is an optimisation of CURLYX that enables us to push
8598 * only a single backtracking state, no matter how many matches
8599 * there are in {m,n}. It relies on the pattern being constant
8600 * length, with no parens to influence future backrefs
8604 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
8606 ST.lastparen = rex->lastparen;
8607 ST.lastcloseparen = rex->lastcloseparen;
8609 /* if paren positive, emulate an OPEN/CLOSE around A */
8611 U32 paren = ST.me->flags;
8612 if (paren > maxopenparen)
8613 maxopenparen = paren;
8614 scan += NEXT_OFF(scan); /* Skip former OPEN. */
8622 ST.c1 = CHRTEST_UNINIT;
8625 if (!(ST.minmod ? ARG1(ST.me) : ARG2(ST.me))) /* min/max */
8628 curlym_do_A: /* execute the A in /A{m,n}B/ */
8629 PUSH_YES_STATE_GOTO(CURLYM_A, ST.A, locinput, loceol, /* match A */
8631 NOT_REACHED; /* NOTREACHED */
8633 case CURLYM_A: /* we've just matched an A */
8635 /* after first match, determine A's length: u.curlym.alen */
8636 if (ST.count == 1) {
8637 if (reginfo->is_utf8_target) {
8638 char *s = st->locinput;
8639 while (s < locinput) {
8645 ST.alen = locinput - st->locinput;
8648 ST.count = ST.minmod ? ARG1(ST.me) : ARG2(ST.me);
8651 Perl_re_exec_indentf( aTHX_ "CURLYM now matched %" IVdf " times, len=%" IVdf "...\n",
8652 depth, (IV) ST.count, (IV)ST.alen)
8655 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.me->flags))
8659 I32 max = (ST.minmod ? ARG1(ST.me) : ARG2(ST.me));
8660 if ( max == REG_INFTY || ST.count < max )
8661 goto curlym_do_A; /* try to match another A */
8663 goto curlym_do_B; /* try to match B */
8665 case CURLYM_A_fail: /* just failed to match an A */
8666 REGCP_UNWIND(ST.cp);
8669 if (ST.minmod || ST.count < ARG1(ST.me) /* min*/
8670 || EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.me->flags))
8673 curlym_do_B: /* execute the B in /A{m,n}B/ */
8674 if (ST.c1 == CHRTEST_UNINIT) {
8675 /* calculate c1 and c2 for possible match of 1st char
8676 * following curly */
8677 ST.c1 = ST.c2 = CHRTEST_VOID;
8679 if (HAS_TEXT(ST.B) || JUMPABLE(ST.B)) {
8680 regnode *text_node = ST.B;
8681 if (! HAS_TEXT(text_node))
8682 FIND_NEXT_IMPT(text_node);
8683 if (PL_regkind[OP(text_node)] == EXACT) {
8684 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
8685 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
8695 Perl_re_exec_indentf( aTHX_ "CURLYM trying tail with matches=%" IVdf "...\n",
8696 depth, (IV)ST.count)
8698 if (! NEXTCHR_IS_EOS && ST.c1 != CHRTEST_VOID) {
8699 if (! UTF8_IS_INVARIANT(nextbyte) && utf8_target) {
8701 /* (We can use memEQ and memNE in this file without
8702 * having to worry about one being shorter than the
8703 * other, since the first byte of each gives the
8704 * length of the character) */
8705 if ( memNE(locinput, ST.c1_utf8, UTF8_SAFE_SKIP(locinput,
8707 && memNE(locinput, ST.c2_utf8, UTF8_SAFE_SKIP(locinput,
8710 /* simulate B failing */
8712 Perl_re_exec_indentf( aTHX_ "CURLYM Fast bail next target=0x%" UVXf " c1=0x%" UVXf " c2=0x%" UVXf "\n",
8714 valid_utf8_to_uvchr((U8 *) locinput, NULL),
8715 valid_utf8_to_uvchr(ST.c1_utf8, NULL),
8716 valid_utf8_to_uvchr(ST.c2_utf8, NULL))
8718 state_num = CURLYM_B_fail;
8719 goto reenter_switch;
8722 else if (nextbyte != ST.c1 && nextbyte != ST.c2) {
8723 /* simulate B failing */
8725 Perl_re_exec_indentf( aTHX_ "CURLYM Fast bail next target=0x%X c1=0x%X c2=0x%X\n",
8727 (int) nextbyte, ST.c1, ST.c2)
8729 state_num = CURLYM_B_fail;
8730 goto reenter_switch;
8735 /* emulate CLOSE: mark current A as captured */
8736 U32 paren = (U32)ST.me->flags;
8738 CLOSE_CAPTURE(paren,
8739 HOPc(locinput, -ST.alen) - reginfo->strbeg,
8740 locinput - reginfo->strbeg);
8743 rex->offs[paren].end = -1;
8745 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.me->flags))
8754 PUSH_STATE_GOTO(CURLYM_B, ST.B, locinput, loceol, /* match B */
8756 NOT_REACHED; /* NOTREACHED */
8758 case CURLYM_B_fail: /* just failed to match a B */
8759 REGCP_UNWIND(ST.cp);
8760 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
8762 I32 max = ARG2(ST.me);
8763 if (max != REG_INFTY && ST.count == max)
8765 goto curlym_do_A; /* try to match a further A */
8767 /* backtrack one A */
8768 if (ST.count == ARG1(ST.me) /* min */)
8771 SET_locinput(HOPc(locinput, -ST.alen));
8772 goto curlym_do_B; /* try to match B */
8775 #define ST st->u.curly
8777 #define CURLY_SETPAREN(paren, success) \
8780 CLOSE_CAPTURE(paren, HOPc(locinput, -1) - reginfo->strbeg, \
8781 locinput - reginfo->strbeg); \
8784 rex->offs[paren].end = -1; \
8785 rex->lastparen = ST.lastparen; \
8786 rex->lastcloseparen = ST.lastcloseparen; \
8790 case STAR: /* /A*B/ where A is width 1 char */
8794 scan = NEXTOPER(scan);
8797 case PLUS: /* /A+B/ where A is width 1 char */
8801 scan = NEXTOPER(scan);
8804 case CURLYN: /* /(A){m,n}B/ where A is width 1 char */
8805 ST.paren = scan->flags; /* Which paren to set */
8806 ST.lastparen = rex->lastparen;
8807 ST.lastcloseparen = rex->lastcloseparen;
8808 if (ST.paren > maxopenparen)
8809 maxopenparen = ST.paren;
8810 ST.min = ARG1(scan); /* min to match */
8811 ST.max = ARG2(scan); /* max to match */
8812 scan = regnext(NEXTOPER(scan) + NODE_STEP_REGNODE);
8814 /* handle the single-char capture called as a GOSUB etc */
8815 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.paren))
8817 char *li = locinput;
8818 if (!regrepeat(rex, &li, scan, loceol, reginfo, 1))
8826 case CURLY: /* /A{m,n}B/ where A is width 1 char */
8828 ST.min = ARG1(scan); /* min to match */
8829 ST.max = ARG2(scan); /* max to match */
8830 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
8833 * Lookahead to avoid useless match attempts
8834 * when we know what character comes next.
8836 * Used to only do .*x and .*?x, but now it allows
8837 * for )'s, ('s and (?{ ... })'s to be in the way
8838 * of the quantifier and the EXACT-like node. -- japhy
8841 assert(ST.min <= ST.max);
8842 if (! HAS_TEXT(next) && ! JUMPABLE(next)) {
8843 ST.c1 = ST.c2 = CHRTEST_VOID;
8846 regnode *text_node = next;
8848 if (! HAS_TEXT(text_node))
8849 FIND_NEXT_IMPT(text_node);
8851 if (! HAS_TEXT(text_node))
8852 ST.c1 = ST.c2 = CHRTEST_VOID;
8854 if ( PL_regkind[OP(text_node)] != EXACT ) {
8855 ST.c1 = ST.c2 = CHRTEST_VOID;
8858 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
8859 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
8871 char *li = locinput;
8874 regrepeat(rex, &li, ST.A, loceol, reginfo, ST.min)
8880 if (ST.c1 == CHRTEST_VOID)
8881 goto curly_try_B_min;
8883 ST.oldloc = locinput;
8885 /* set ST.maxpos to the furthest point along the
8886 * string that could possibly match */
8887 if (ST.max == REG_INFTY) {
8888 ST.maxpos = loceol - 1;
8890 while (UTF8_IS_CONTINUATION(*(U8*)ST.maxpos))
8893 else if (utf8_target) {
8894 int m = ST.max - ST.min;
8895 for (ST.maxpos = locinput;
8896 m >0 && ST.maxpos < loceol; m--)
8897 ST.maxpos += UTF8SKIP(ST.maxpos);
8900 ST.maxpos = locinput + ST.max - ST.min;
8901 if (ST.maxpos >= loceol)
8902 ST.maxpos = loceol - 1;
8904 goto curly_try_B_min_known;
8908 /* avoid taking address of locinput, so it can remain
8910 char *li = locinput;
8911 ST.count = regrepeat(rex, &li, ST.A, loceol, reginfo, ST.max);
8912 if (ST.count < ST.min)
8915 if ((ST.count > ST.min)
8916 && (PL_regkind[OP(ST.B)] == EOL) && (OP(ST.B) != MEOL))
8918 /* A{m,n} must come at the end of the string, there's
8919 * no point in backing off ... */
8921 /* ...except that $ and \Z can match before *and* after
8922 newline at the end. Consider "\n\n" =~ /\n+\Z\n/.
8923 We may back off by one in this case. */
8924 if (UCHARAT(locinput - 1) == '\n' && OP(ST.B) != EOS)
8928 goto curly_try_B_max;
8930 NOT_REACHED; /* NOTREACHED */
8932 case CURLY_B_min_fail:
8933 /* failed to find B in a non-greedy match.
8934 * Handles both cases where c1,c2 valid or not */
8936 REGCP_UNWIND(ST.cp);
8938 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
8941 if (ST.c1 == CHRTEST_VOID) {
8942 /* failed -- move forward one */
8943 char *li = locinput;
8944 if (!regrepeat(rex, &li, ST.A, loceol, reginfo, 1)) {
8949 if (!( ST.count <= ST.max
8950 /* count overflow ? */
8951 || (ST.max == REG_INFTY && ST.count > 0))
8957 /* Couldn't or didn't -- move forward. */
8958 ST.oldloc = locinput;
8960 locinput += UTF8SKIP(locinput);
8965 curly_try_B_min_known:
8966 /* find the next place where 'B' could work, then call B */
8968 n = (ST.oldloc == locinput) ? 0 : 1;
8969 if (ST.c1 == ST.c2) {
8970 /* set n to utf8_distance(oldloc, locinput) */
8971 while ( locinput <= ST.maxpos
8972 && locinput < loceol
8973 && memNE(locinput, ST.c1_utf8,
8974 UTF8_SAFE_SKIP(locinput, reginfo->strend)))
8976 locinput += UTF8_SAFE_SKIP(locinput,
8982 /* set n to utf8_distance(oldloc, locinput) */
8983 while ( locinput <= ST.maxpos
8984 && locinput < loceol
8985 && memNE(locinput, ST.c1_utf8,
8986 UTF8_SAFE_SKIP(locinput, reginfo->strend))
8987 && memNE(locinput, ST.c2_utf8,
8988 UTF8_SAFE_SKIP(locinput, reginfo->strend)))
8990 locinput += UTF8_SAFE_SKIP(locinput, reginfo->strend);
8995 else { /* Not utf8_target */
8996 if (ST.c1 == ST.c2) {
8997 locinput = (char *) memchr(locinput,
8999 ST.maxpos + 1 - locinput);
9001 locinput = ST.maxpos + 1;
9005 U8 c1_c2_bits_differing = ST.c1 ^ ST.c2;
9007 if (! isPOWER_OF_2(c1_c2_bits_differing)) {
9008 while ( locinput <= ST.maxpos
9009 && UCHARAT(locinput) != ST.c1
9010 && UCHARAT(locinput) != ST.c2)
9016 /* If c1 and c2 only differ by a single bit, we can
9017 * avoid a conditional each time through the loop,
9018 * at the expense of a little preliminary setup and
9019 * an extra mask each iteration. By masking out
9020 * that bit, we match exactly two characters, c1
9021 * and c2, and so we don't have to test for both.
9022 * On both ASCII and EBCDIC platforms, most of the
9023 * ASCII-range and Latin1-range folded equivalents
9024 * differ only in a single bit, so this is actually
9025 * the most common case. (e.g. 'A' 0x41 vs 'a'
9027 U8 c1_masked = ST.c1 &~ c1_c2_bits_differing;
9028 U8 c1_c2_mask = ~ c1_c2_bits_differing;
9029 while ( locinput <= ST.maxpos
9030 && (UCHARAT(locinput) & c1_c2_mask)
9037 n = locinput - ST.oldloc;
9039 if (locinput > ST.maxpos)
9042 /* In /a{m,n}b/, ST.oldloc is at "a" x m, locinput is
9043 * at b; check that everything between oldloc and
9044 * locinput matches */
9045 char *li = ST.oldloc;
9047 if (regrepeat(rex, &li, ST.A, loceol, reginfo, n) < n)
9049 assert(n == REG_INFTY || locinput == li);
9054 CURLY_SETPAREN(ST.paren, ST.count);
9055 PUSH_STATE_GOTO(CURLY_B_min, ST.B, locinput, loceol,
9057 NOT_REACHED; /* NOTREACHED */
9061 /* a successful greedy match: now try to match B */
9063 bool could_match = locinput < loceol;
9065 /* If it could work, try it. */
9066 if (ST.c1 != CHRTEST_VOID && could_match) {
9067 if (! UTF8_IS_INVARIANT(UCHARAT(locinput)) && utf8_target)
9069 could_match = memEQ(locinput, ST.c1_utf8,
9070 UTF8_SAFE_SKIP(locinput,
9072 || memEQ(locinput, ST.c2_utf8,
9073 UTF8_SAFE_SKIP(locinput,
9077 could_match = UCHARAT(locinput) == ST.c1
9078 || UCHARAT(locinput) == ST.c2;
9081 if (ST.c1 == CHRTEST_VOID || could_match) {
9082 CURLY_SETPAREN(ST.paren, ST.count);
9083 PUSH_STATE_GOTO(CURLY_B_max, ST.B, locinput, loceol,
9085 NOT_REACHED; /* NOTREACHED */
9090 case CURLY_B_max_fail:
9091 /* failed to find B in a greedy match */
9093 REGCP_UNWIND(ST.cp);
9095 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
9098 if (--ST.count < ST.min)
9100 locinput = HOPc(locinput, -1);
9101 goto curly_try_B_max;
9105 case END: /* last op of main pattern */
9108 /* we've just finished A in /(??{A})B/; now continue with B */
9109 SET_RECURSE_LOCINPUT("FAKE-END[before]", CUR_EVAL.prev_recurse_locinput);
9110 st->u.eval.prev_rex = rex_sv; /* inner */
9112 /* Save *all* the positions. */
9113 st->u.eval.cp = regcppush(rex, 0, maxopenparen);
9114 rex_sv = CUR_EVAL.prev_rex;
9115 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
9116 SET_reg_curpm(rex_sv);
9117 rex = ReANY(rex_sv);
9118 rexi = RXi_GET(rex);
9120 st->u.eval.prev_curlyx = cur_curlyx;
9121 cur_curlyx = CUR_EVAL.prev_curlyx;
9123 REGCP_SET(st->u.eval.lastcp);
9125 /* Restore parens of the outer rex without popping the
9127 regcp_restore(rex, CUR_EVAL.lastcp, &maxopenparen);
9129 st->u.eval.prev_eval = cur_eval;
9130 cur_eval = CUR_EVAL.prev_eval;
9132 Perl_re_exec_indentf( aTHX_ "END: EVAL trying tail ... (cur_eval=%p)\n",
9134 if ( nochange_depth )
9137 SET_RECURSE_LOCINPUT("FAKE-END[after]", cur_eval->locinput);
9139 PUSH_YES_STATE_GOTO(EVAL_postponed_AB, /* match B */
9140 st->u.eval.prev_eval->u.eval.B,
9141 locinput, loceol, script_run_begin);
9144 if (locinput < reginfo->till) {
9145 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
9146 "%sEND: Match possible, but length=%ld is smaller than requested=%ld, failing!%s\n",
9148 (long)(locinput - startpos),
9149 (long)(reginfo->till - startpos),
9152 sayNO_SILENT; /* Cannot match: too short. */
9154 sayYES; /* Success! */
9156 case SUCCEED: /* successful SUSPEND/UNLESSM/IFMATCH/CURLYM */
9158 Perl_re_exec_indentf( aTHX_ "%sSUCCEED: subpattern success...%s\n",
9159 depth, PL_colors[4], PL_colors[5]));
9160 sayYES; /* Success! */
9163 #define ST st->u.ifmatch
9165 case SUSPEND: /* (?>A) */
9167 ST.start = locinput;
9172 case UNLESSM: /* -ve lookaround: (?!A), or with 'flags', (?<!A) */
9174 goto ifmatch_trivial_fail_test;
9176 case IFMATCH: /* +ve lookaround: (?=A), or with 'flags', (?<=A) */
9178 ifmatch_trivial_fail_test:
9179 ST.count = scan->next_off + 1; /* next_off repurposed to be
9180 lookbehind count, requires
9182 if (! scan->flags) { /* 'flags' zero means lookahed */
9184 /* Lookahead starts here and ends at the normal place */
9185 ST.start = locinput;
9189 PERL_UINT_FAST8_T back_count = scan->flags;
9192 /* Lookbehind can look beyond the current position */
9195 /* ... and starts at the first place in the input that is in
9196 * the range of the possible start positions */
9197 for (; ST.count > 0; ST.count--, back_count--) {
9198 s = HOPBACKc(locinput, back_count);
9205 /* If the lookbehind doesn't start in the actual string, is a
9206 * trivial match failure */
9209 sw = 1 - cBOOL(ST.wanted);
9214 /* Here, we didn't want it to match, so is actually success */
9215 next = scan + ARG(scan);
9223 ST.logical = logical;
9224 logical = 0; /* XXX: reset state of logical once it has been saved into ST */
9226 /* execute body of (?...A) */
9227 PUSH_YES_STATE_GOTO(IFMATCH_A, NEXTOPER(NEXTOPER(scan)), ST.start,
9228 ST.end, script_run_begin);
9229 NOT_REACHED; /* NOTREACHED */
9234 case IFMATCH_A_fail: /* body of (?...A) failed */
9235 if (! ST.logical && ST.count > 1) {
9237 /* It isn't a real failure until we've tried all starting
9238 * positions. Move to the next starting position and retry */
9240 ST.start = HOPc(ST.start, 1);
9242 logical = ST.logical;
9246 /* Here, all starting positions have been tried. */
9250 case IFMATCH_A: /* body of (?...A) succeeded */
9253 sw = matched == ST.wanted;
9254 if (! ST.logical && !sw) {
9258 if (OP(ST.me) != SUSPEND) {
9259 /* restore old position except for (?>...) */
9260 locinput = st->locinput;
9261 loceol = st->loceol;
9262 script_run_begin = st->sr0;
9264 scan = ST.me + ARG(ST.me);
9267 continue; /* execute B */
9272 case LONGJMP: /* alternative with many branches compiles to
9273 * (BRANCHJ; EXACT ...; LONGJMP ) x N */
9274 next = scan + ARG(scan);
9279 case COMMIT: /* (*COMMIT) */
9280 reginfo->cutpoint = loceol;
9283 case PRUNE: /* (*PRUNE) */
9285 sv_yes_mark = sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
9286 PUSH_STATE_GOTO(COMMIT_next, next, locinput, loceol,
9288 NOT_REACHED; /* NOTREACHED */
9290 case COMMIT_next_fail:
9294 NOT_REACHED; /* NOTREACHED */
9296 case OPFAIL: /* (*FAIL) */
9298 sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
9300 /* deal with (?(?!)X|Y) properly,
9301 * make sure we trigger the no branch
9302 * of the trailing IFTHEN structure*/
9308 NOT_REACHED; /* NOTREACHED */
9310 #define ST st->u.mark
9311 case MARKPOINT: /* (*MARK:foo) */
9312 ST.prev_mark = mark_state;
9313 ST.mark_name = sv_commit = sv_yes_mark
9314 = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
9316 ST.mark_loc = locinput;
9317 PUSH_YES_STATE_GOTO(MARKPOINT_next, next, locinput, loceol,
9319 NOT_REACHED; /* NOTREACHED */
9321 case MARKPOINT_next:
9322 mark_state = ST.prev_mark;
9324 NOT_REACHED; /* NOTREACHED */
9326 case MARKPOINT_next_fail:
9327 if (popmark && sv_eq(ST.mark_name,popmark))
9329 if (ST.mark_loc > startpoint)
9330 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
9331 popmark = NULL; /* we found our mark */
9332 sv_commit = ST.mark_name;
9335 Perl_re_exec_indentf( aTHX_ "%sMARKPOINT: next fail: setting cutpoint to mark:%" SVf "...%s\n",
9337 PL_colors[4], SVfARG(sv_commit), PL_colors[5]);
9340 mark_state = ST.prev_mark;
9341 sv_yes_mark = mark_state ?
9342 mark_state->u.mark.mark_name : NULL;
9344 NOT_REACHED; /* NOTREACHED */
9346 case SKIP: /* (*SKIP) */
9348 /* (*SKIP) : if we fail we cut here*/
9349 ST.mark_name = NULL;
9350 ST.mark_loc = locinput;
9351 PUSH_STATE_GOTO(SKIP_next,next, locinput, loceol,
9354 /* (*SKIP:NAME) : if there is a (*MARK:NAME) fail where it was,
9355 otherwise do nothing. Meaning we need to scan
9357 regmatch_state *cur = mark_state;
9358 SV *find = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
9361 if ( sv_eq( cur->u.mark.mark_name,
9364 ST.mark_name = find;
9365 PUSH_STATE_GOTO( SKIP_next, next, locinput, loceol,
9368 cur = cur->u.mark.prev_mark;
9371 /* Didn't find our (*MARK:NAME) so ignore this (*SKIP:NAME) */
9374 case SKIP_next_fail:
9376 /* (*CUT:NAME) - Set up to search for the name as we
9377 collapse the stack*/
9378 popmark = ST.mark_name;
9380 /* (*CUT) - No name, we cut here.*/
9381 if (ST.mark_loc > startpoint)
9382 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
9383 /* but we set sv_commit to latest mark_name if there
9384 is one so they can test to see how things lead to this
9387 sv_commit=mark_state->u.mark.mark_name;
9391 NOT_REACHED; /* NOTREACHED */
9394 case LNBREAK: /* \R */
9395 if ((n=is_LNBREAK_safe(locinput, loceol, utf8_target))) {
9402 PerlIO_printf(Perl_error_log, "%" UVxf " %d\n",
9403 PTR2UV(scan), OP(scan));
9404 Perl_croak(aTHX_ "regexp memory corruption");
9406 /* this is a point to jump to in order to increment
9407 * locinput by one character */
9409 assert(!NEXTCHR_IS_EOS);
9411 locinput += PL_utf8skip[nextbyte];
9412 /* locinput is allowed to go 1 char off the end (signifying
9413 * EOS), but not 2+ */
9414 if (locinput > loceol)
9423 /* switch break jumps here */
9424 scan = next; /* prepare to execute the next op and ... */
9425 continue; /* ... jump back to the top, reusing st */
9429 /* push a state that backtracks on success */
9430 st->u.yes.prev_yes_state = yes_state;
9434 /* push a new regex state, then continue at scan */
9436 regmatch_state *newst;
9437 DECLARE_AND_GET_RE_DEBUG_FLAGS;
9439 DEBUG_r( /* DEBUG_STACK_r */
9440 if (DEBUG_v_TEST || RE_DEBUG_FLAG(RE_DEBUG_EXTRA_STACK)) {
9441 regmatch_state *cur = st;
9442 regmatch_state *curyes = yes_state;
9444 regmatch_slab *slab = PL_regmatch_slab;
9445 for (i = 0; i < 3 && i <= depth; cur--,i++) {
9446 if (cur < SLAB_FIRST(slab)) {
9448 cur = SLAB_LAST(slab);
9450 Perl_re_exec_indentf( aTHX_ "%4s #%-3d %-10s %s\n",
9453 depth - i, PL_reg_name[cur->resume_state],
9454 (curyes == cur) ? "yes" : ""
9457 curyes = cur->u.yes.prev_yes_state;
9460 DEBUG_STATE_pp("push")
9463 st->locinput = locinput;
9464 st->loceol = loceol;
9465 st->sr0 = script_run_begin;
9467 if (newst > SLAB_LAST(PL_regmatch_slab))
9468 newst = S_push_slab(aTHX);
9469 PL_regmatch_state = newst;
9471 locinput = pushinput;
9473 script_run_begin = pushsr0;
9479 #ifdef SOLARIS_BAD_OPTIMIZER
9480 # undef PL_charclass
9484 * We get here only if there's trouble -- normally "case END" is
9485 * the terminating point.
9487 Perl_croak(aTHX_ "corrupted regexp pointers");
9488 NOT_REACHED; /* NOTREACHED */
9492 /* we have successfully completed a subexpression, but we must now
9493 * pop to the state marked by yes_state and continue from there */
9494 assert(st != yes_state);
9496 while (st != yes_state) {
9498 if (st < SLAB_FIRST(PL_regmatch_slab)) {
9499 PL_regmatch_slab = PL_regmatch_slab->prev;
9500 st = SLAB_LAST(PL_regmatch_slab);
9504 DEBUG_STATE_pp("pop (no final)");
9506 DEBUG_STATE_pp("pop (yes)");
9512 while (yes_state < SLAB_FIRST(PL_regmatch_slab)
9513 || yes_state > SLAB_LAST(PL_regmatch_slab))
9515 /* not in this slab, pop slab */
9516 depth -= (st - SLAB_FIRST(PL_regmatch_slab) + 1);
9517 PL_regmatch_slab = PL_regmatch_slab->prev;
9518 st = SLAB_LAST(PL_regmatch_slab);
9520 depth -= (st - yes_state);
9523 yes_state = st->u.yes.prev_yes_state;
9524 PL_regmatch_state = st;
9527 locinput= st->locinput;
9529 script_run_begin = st->sr0;
9531 state_num = st->resume_state + no_final;
9532 goto reenter_switch;
9535 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%sMatch successful!%s\n",
9536 PL_colors[4], PL_colors[5]));
9538 if (reginfo->info_aux_eval) {
9539 /* each successfully executed (?{...}) block does the equivalent of
9540 * local $^R = do {...}
9541 * When popping the save stack, all these locals would be undone;
9542 * bypass this by setting the outermost saved $^R to the latest
9544 /* I dont know if this is needed or works properly now.
9545 * see code related to PL_replgv elsewhere in this file.
9548 if (oreplsv != GvSV(PL_replgv)) {
9549 sv_setsv(oreplsv, GvSV(PL_replgv));
9550 SvSETMAGIC(oreplsv);
9558 Perl_re_exec_indentf( aTHX_ "%sfailed...%s\n",
9560 PL_colors[4], PL_colors[5])
9572 /* there's a previous state to backtrack to */
9574 if (st < SLAB_FIRST(PL_regmatch_slab)) {
9575 PL_regmatch_slab = PL_regmatch_slab->prev;
9576 st = SLAB_LAST(PL_regmatch_slab);
9578 PL_regmatch_state = st;
9579 locinput= st->locinput;
9581 script_run_begin = st->sr0;
9583 DEBUG_STATE_pp("pop");
9585 if (yes_state == st)
9586 yes_state = st->u.yes.prev_yes_state;
9588 state_num = st->resume_state + 1; /* failure = success + 1 */
9590 goto reenter_switch;
9595 if (rex->intflags & PREGf_VERBARG_SEEN) {
9596 SV *sv_err = get_sv("REGERROR", 1);
9597 SV *sv_mrk = get_sv("REGMARK", 1);
9599 sv_commit = &PL_sv_no;
9601 sv_yes_mark = &PL_sv_yes;
9604 sv_commit = &PL_sv_yes;
9605 sv_yes_mark = &PL_sv_no;
9609 sv_setsv(sv_err, sv_commit);
9610 sv_setsv(sv_mrk, sv_yes_mark);
9614 if (last_pushed_cv) {
9616 /* see "Some notes about MULTICALL" above */
9618 PERL_UNUSED_VAR(SP);
9621 LEAVE_SCOPE(orig_savestack_ix);
9623 assert(!result || locinput - reginfo->strbeg >= 0);
9624 return result ? locinput - reginfo->strbeg : -1;
9628 - regrepeat - repeatedly match something simple, report how many
9630 * What 'simple' means is a node which can be the operand of a quantifier like
9633 * startposp - pointer to a pointer to the start position. This is updated
9634 * to point to the byte following the highest successful
9636 * p - the regnode to be repeatedly matched against.
9637 * loceol - pointer to the end position beyond which we aren't supposed to
9639 * reginfo - struct holding match state, such as utf8_target
9640 * max - maximum number of things to match.
9641 * depth - (for debugging) backtracking depth.
9644 S_regrepeat(pTHX_ regexp *prog, char **startposp, const regnode *p,
9645 char * loceol, regmatch_info *const reginfo, I32 max _pDEPTH)
9647 char *scan; /* Pointer to current position in target string */
9649 char *this_eol = loceol; /* potentially adjusted version. */
9650 I32 hardcount = 0; /* How many matches so far */
9651 bool utf8_target = reginfo->is_utf8_target;
9652 unsigned int to_complement = 0; /* Invert the result? */
9654 _char_class_number classnum;
9656 PERL_ARGS_ASSERT_REGREPEAT;
9658 /* This routine is structured so that we switch on the input OP. Each OP
9659 * case: statement contains a loop to repeatedly apply the OP, advancing
9660 * the input until it fails, or reaches the end of the input, or until it
9661 * reaches the upper limit of matches. */
9664 if (max == REG_INFTY) /* This is a special marker to go to the platform's
9667 else if (! utf8_target && this_eol - scan > max)
9668 this_eol = scan + max;
9670 /* Here, for the case of a non-UTF-8 target we have adjusted <this_eol> down
9671 * to the maximum of how far we should go in it (leaving it set to the real
9672 * end, if the maximum permissible would take us beyond that). This allows
9673 * us to make the loop exit condition that we haven't gone past <this_eol> to
9674 * also mean that we haven't exceeded the max permissible count, saving a
9675 * test each time through the loops. But it assumes that the OP matches a
9676 * single byte, which is true for most of the OPs below when applied to a
9677 * non-UTF-8 target. Those relatively few OPs that don't have this
9678 * characteristic will have to compensate.
9680 * There is no adjustment for UTF-8 targets, as the number of bytes per
9681 * character varies. OPs will have to test both that the count is less
9682 * than the max permissible (using <hardcount> to keep track), and that we
9683 * are still within the bounds of the string (using <this_eol>. A few OPs
9684 * match a single byte no matter what the encoding. They can omit the max
9685 * test if, for the UTF-8 case, they do the adjustment that was skipped
9688 * Thus, the code above sets things up for the common case; and exceptional
9689 * cases need extra work; the common case is to make sure <scan> doesn't
9690 * go past <this_eol>, and for UTF-8 to also use <hardcount> to make sure the
9691 * count doesn't exceed the maximum permissible */
9696 while (scan < this_eol && hardcount < max && *scan != '\n') {
9697 scan += UTF8SKIP(scan);
9701 scan = (char *) memchr(scan, '\n', this_eol - scan);
9709 while (scan < this_eol && hardcount < max) {
9710 scan += UTF8SKIP(scan);
9719 if (! utf8_target) {
9729 string = (U8 *) STRINGl(p);
9730 str_len = STR_LENl(p);
9731 goto join_short_long_exact;
9734 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
9735 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*scan)) {
9736 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(scan, loceol);
9741 if (! utf8_target) {
9747 string = (U8 *) STRINGs(p);
9748 str_len = STR_LENs(p);
9750 join_short_long_exact:
9751 assert(str_len == reginfo->is_utf8_pat ? UTF8SKIP(string) : 1);
9755 /* Can use a simple find if the pattern char to match on is invariant
9756 * under UTF-8, or both target and pattern aren't UTF-8. Note that we
9757 * can use UTF8_IS_INVARIANT() even if the pattern isn't UTF-8, as it's
9758 * true iff it doesn't matter if the argument is in UTF-8 or not */
9759 if (UTF8_IS_INVARIANT(c) || (! utf8_target && ! reginfo->is_utf8_pat)) {
9760 if (utf8_target && this_eol - scan > max) {
9761 /* We didn't adjust <this_eol> because is UTF-8, but ok to do so,
9762 * since here, to match at all, 1 char == 1 byte */
9763 this_eol = scan + max;
9765 scan = (char *) find_span_end((U8 *) scan, (U8 *) this_eol, (U8) c);
9767 else if (reginfo->is_utf8_pat) {
9769 STRLEN scan_char_len;
9771 /* When both target and pattern are UTF-8, we have to do
9773 while (hardcount < max
9775 && (scan_char_len = UTF8SKIP(scan)) <= str_len
9776 && memEQ(scan, string, scan_char_len))
9778 scan += scan_char_len;
9782 else if (! UTF8_IS_ABOVE_LATIN1(c)) {
9784 /* Target isn't utf8; convert the character in the UTF-8
9785 * pattern to non-UTF8, and do a simple find */
9786 c = EIGHT_BIT_UTF8_TO_NATIVE(c, *(string + 1));
9787 scan = (char *) find_span_end((U8 *) scan, (U8 *) this_eol, (U8) c);
9788 } /* else pattern char is above Latin1, can't possibly match the
9793 /* Here, the string must be utf8; pattern isn't, and <c> is
9794 * different in utf8 than not, so can't compare them directly.
9795 * Outside the loop, find the two utf8 bytes that represent c, and
9796 * then look for those in sequence in the utf8 string */
9797 U8 high = UTF8_TWO_BYTE_HI(c);
9798 U8 low = UTF8_TWO_BYTE_LO(c);
9800 while (hardcount < max
9801 && scan + 1 < this_eol
9802 && UCHARAT(scan) == high
9803 && UCHARAT(scan + 1) == low)
9812 case EXACTFAA_NO_TRIE: /* This node only generated for non-utf8 patterns */
9813 assert(! reginfo->is_utf8_pat);
9816 utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
9817 if (reginfo->is_utf8_pat || ! utf8_target) {
9819 /* The possible presence of a MICRO SIGN in the pattern forbids us
9820 * to view a non-UTF-8 pattern as folded when there is a UTF-8
9822 utf8_flags |= FOLDEQ_S2_ALREADY_FOLDED|FOLDEQ_S2_FOLDS_SANE;
9827 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
9828 utf8_flags = FOLDEQ_LOCALE;
9831 case EXACTF: /* This node only generated for non-utf8 patterns */
9832 assert(! reginfo->is_utf8_pat);
9836 if (! utf8_target) {
9839 utf8_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
9840 | FOLDEQ_S2_FOLDS_SANE;
9844 if (! utf8_target) {
9847 assert(reginfo->is_utf8_pat);
9848 utf8_flags = FOLDEQ_S2_ALREADY_FOLDED;
9852 utf8_flags = FOLDEQ_S2_ALREADY_FOLDED;
9859 U8 c1_utf8[UTF8_MAXBYTES+1], c2_utf8[UTF8_MAXBYTES+1];
9861 assert(STR_LENs(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRINGs(p)) : 1);
9863 if (S_setup_EXACTISH_ST_c1_c2(aTHX_ p, &c1, c1_utf8, &c2, c2_utf8,
9866 if (c1 == CHRTEST_VOID) {
9867 /* Use full Unicode fold matching */
9868 char *tmpeol = loceol;
9869 STRLEN pat_len = reginfo->is_utf8_pat ? UTF8SKIP(STRINGs(p)) : 1;
9870 while (hardcount < max
9871 && foldEQ_utf8_flags(scan, &tmpeol, 0, utf8_target,
9872 STRINGs(p), NULL, pat_len,
9873 reginfo->is_utf8_pat, utf8_flags))
9880 else if (utf8_target) {
9882 while (scan < this_eol
9884 && memEQ(scan, c1_utf8, UTF8_SAFE_SKIP(scan,
9887 scan += UTF8SKIP(c1_utf8);
9892 while (scan < this_eol
9894 && ( memEQ(scan, c1_utf8, UTF8_SAFE_SKIP(scan,
9896 || memEQ(scan, c2_utf8, UTF8_SAFE_SKIP(scan,
9899 scan += UTF8_SAFE_SKIP(scan, loceol);
9904 else if (c1 == c2) {
9905 scan = (char *) find_span_end((U8 *) scan, (U8 *) this_eol, (U8) c1);
9908 /* See comments in regmatch() CURLY_B_min_known_fail. We avoid
9909 * a conditional each time through the loop if the characters
9910 * differ only in a single bit, as is the usual situation */
9911 U8 c1_c2_bits_differing = c1 ^ c2;
9913 if (isPOWER_OF_2(c1_c2_bits_differing)) {
9914 U8 c1_c2_mask = ~ c1_c2_bits_differing;
9916 scan = (char *) find_span_end_mask((U8 *) scan,
9922 while ( scan < this_eol
9923 && (UCHARAT(scan) == c1 || UCHARAT(scan) == c2))
9934 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
9935 CHECK_AND_WARN_NON_UTF8_CTYPE_LOCALE_IN_SETS(p);
9941 while (hardcount < max
9943 && reginclass(prog, p, (U8*)scan, (U8*) this_eol, utf8_target))
9945 scan += UTF8SKIP(scan);
9949 else if (ANYOF_FLAGS(p) & ~ ANYOF_MATCHES_ALL_ABOVE_BITMAP) {
9950 while (scan < this_eol
9951 && reginclass(prog, p, (U8*)scan, (U8*)scan+1, 0))
9955 while (scan < this_eol && ANYOF_BITMAP_TEST(p, *((U8*)scan)))
9961 if (utf8_target && this_eol - scan > max) {
9963 /* We didn't adjust <this_eol> at the beginning of this routine
9964 * because is UTF-8, but it is actually ok to do so, since here, to
9965 * match, 1 char == 1 byte. */
9966 this_eol = scan + max;
9969 scan = (char *) find_span_end_mask((U8 *) scan, (U8 *) this_eol, (U8) ARG(p), FLAGS(p));
9974 while ( hardcount < max
9976 && (*scan & FLAGS(p)) != ARG(p))
9978 scan += UTF8SKIP(scan);
9983 scan = (char *) find_next_masked((U8 *) scan, (U8 *) this_eol, (U8) ARG(p), FLAGS(p));
9988 if (utf8_target) { /* ANYOFH only can match UTF-8 targets */
9989 while ( hardcount < max
9991 && NATIVE_UTF8_TO_I8(*scan) >= ANYOF_FLAGS(p)
9992 && reginclass(prog, p, (U8*)scan, (U8*) this_eol, TRUE))
9994 scan += UTF8SKIP(scan);
10001 if (utf8_target) { /* ANYOFHb only can match UTF-8 targets */
10003 /* we know the first byte must be the FLAGS field */
10004 while ( hardcount < max
10006 && (U8) *scan == ANYOF_FLAGS(p)
10007 && reginclass(prog, p, (U8*)scan, (U8*) this_eol,
10010 scan += UTF8SKIP(scan);
10017 if (utf8_target) { /* ANYOFH only can match UTF-8 targets */
10018 while ( hardcount < max
10020 && inRANGE(NATIVE_UTF8_TO_I8(*scan),
10021 LOWEST_ANYOF_HRx_BYTE(ANYOF_FLAGS(p)),
10022 HIGHEST_ANYOF_HRx_BYTE(ANYOF_FLAGS(p)))
10023 && NATIVE_UTF8_TO_I8(*scan) >= ANYOF_FLAGS(p)
10024 && reginclass(prog, p, (U8*)scan, (U8*) this_eol, TRUE))
10026 scan += UTF8SKIP(scan);
10033 if (utf8_target) { /* ANYOFH only can match UTF-8 targets */
10034 while ( hardcount < max
10035 && scan + FLAGS(p) < this_eol
10036 && memEQ(scan, ((struct regnode_anyofhs *) p)->string, FLAGS(p))
10037 && reginclass(prog, p, (U8*)scan, (U8*) this_eol, TRUE))
10039 scan += UTF8SKIP(scan);
10047 while ( hardcount < max
10049 && NATIVE_UTF8_TO_I8(*scan) >= ANYOF_FLAGS(p)
10050 && withinCOUNT(utf8_to_uvchr_buf((U8 *) scan,
10053 ANYOFRbase(p), ANYOFRdelta(p)))
10055 scan += UTF8SKIP(scan);
10060 while ( hardcount < max
10062 && withinCOUNT((U8) *scan, ANYOFRbase(p), ANYOFRdelta(p)))
10072 while ( hardcount < max
10074 && (U8) *scan == ANYOF_FLAGS(p)
10075 && withinCOUNT(utf8_to_uvchr_buf((U8 *) scan,
10078 ANYOFRbase(p), ANYOFRdelta(p)))
10080 scan += UTF8SKIP(scan);
10085 while ( hardcount < max
10087 && withinCOUNT((U8) *scan, ANYOFRbase(p), ANYOFRdelta(p)))
10095 /* The argument (FLAGS) to all the POSIX node types is the class number */
10102 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
10103 if (! utf8_target) {
10104 while (scan < this_eol && to_complement ^ cBOOL(isFOO_lc(FLAGS(p),
10110 while (hardcount < max && scan < this_eol
10111 && to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(p),
10115 scan += UTF8SKIP(scan);
10128 if (utf8_target && this_eol - scan > max) {
10130 /* We didn't adjust <this_eol> at the beginning of this routine
10131 * because is UTF-8, but it is actually ok to do so, since here, to
10132 * match, 1 char == 1 byte. */
10133 this_eol = scan + max;
10135 while (scan < this_eol && _generic_isCC_A((U8) *scan, FLAGS(p))) {
10148 if (! utf8_target) {
10149 while (scan < this_eol && ! _generic_isCC_A((U8) *scan, FLAGS(p))) {
10155 /* The complement of something that matches only ASCII matches all
10156 * non-ASCII, plus everything in ASCII that isn't in the class. */
10157 while (hardcount < max && scan < this_eol
10158 && ( ! isASCII_utf8_safe(scan, loceol)
10159 || ! _generic_isCC_A((U8) *scan, FLAGS(p))))
10161 scan += UTF8SKIP(scan);
10172 if (! utf8_target) {
10173 while (scan < this_eol && to_complement
10174 ^ cBOOL(_generic_isCC((U8) *scan, FLAGS(p))))
10181 classnum = (_char_class_number) FLAGS(p);
10182 switch (classnum) {
10184 while ( hardcount < max && scan < this_eol
10185 && to_complement ^ cBOOL(_invlist_contains_cp(
10186 PL_XPosix_ptrs[classnum],
10187 utf8_to_uvchr_buf((U8 *) scan,
10191 scan += UTF8SKIP(scan);
10196 /* For the classes below, the knowledge of how to handle
10197 * every code point is compiled in to Perl via a macro.
10198 * This code is written for making the loops as tight as
10199 * possible. It could be refactored to save space instead.
10202 case _CC_ENUM_SPACE:
10203 while (hardcount < max
10206 ^ cBOOL(isSPACE_utf8_safe(scan, this_eol))))
10208 scan += UTF8SKIP(scan);
10212 case _CC_ENUM_BLANK:
10213 while (hardcount < max
10216 ^ cBOOL(isBLANK_utf8_safe(scan, this_eol))))
10218 scan += UTF8SKIP(scan);
10222 case _CC_ENUM_XDIGIT:
10223 while (hardcount < max
10226 ^ cBOOL(isXDIGIT_utf8_safe(scan, this_eol))))
10228 scan += UTF8SKIP(scan);
10232 case _CC_ENUM_VERTSPACE:
10233 while (hardcount < max
10236 ^ cBOOL(isVERTWS_utf8_safe(scan, this_eol))))
10238 scan += UTF8SKIP(scan);
10242 case _CC_ENUM_CNTRL:
10243 while (hardcount < max
10246 ^ cBOOL(isCNTRL_utf8_safe(scan, this_eol))))
10248 scan += UTF8SKIP(scan);
10258 while (hardcount < max && scan < this_eol &&
10259 (c=is_LNBREAK_utf8_safe(scan, this_eol))) {
10264 /* LNBREAK can match one or two latin chars, which is ok, but we
10265 * have to use hardcount in this situation, and throw away the
10266 * adjustment to <this_eol> done before the switch statement */
10267 while (scan < loceol && (c=is_LNBREAK_latin1_safe(scan, loceol))) {
10275 Perl_croak(aTHX_ "panic: regrepeat() called with unrecognized node type %d='%s'", OP(p), PL_reg_name[OP(p)]);
10276 NOT_REACHED; /* NOTREACHED */
10283 c = scan - *startposp;
10287 DECLARE_AND_GET_RE_DEBUG_FLAGS;
10289 SV * const prop = sv_newmortal();
10290 regprop(prog, prop, p, reginfo, NULL);
10291 Perl_re_exec_indentf( aTHX_ "%s can match %" IVdf " times out of %" IVdf "...\n",
10292 depth, SvPVX_const(prop),(IV)c,(IV)max);
10300 - reginclass - determine if a character falls into a character class
10302 n is the ANYOF-type regnode
10303 p is the target string
10304 p_end points to one byte beyond the end of the target string
10305 utf8_target tells whether p is in UTF-8.
10307 Returns true if matched; false otherwise.
10309 Note that this can be a synthetic start class, a combination of various
10310 nodes, so things you think might be mutually exclusive, such as locale,
10311 aren't. It can match both locale and non-locale
10316 S_reginclass(pTHX_ regexp * const prog, const regnode * const n, const U8* const p, const U8* const p_end, const bool utf8_target)
10318 const char flags = (inRANGE(OP(n), ANYOFH, ANYOFHs))
10321 bool match = FALSE;
10324 PERL_ARGS_ASSERT_REGINCLASS;
10326 /* If c is not already the code point, get it. Note that
10327 * UTF8_IS_INVARIANT() works even if not in UTF-8 */
10328 if (! UTF8_IS_INVARIANT(c) && utf8_target) {
10330 const U32 utf8n_flags = UTF8_ALLOW_DEFAULT;
10331 c = utf8n_to_uvchr(p, p_end - p, &c_len, utf8n_flags | UTF8_CHECK_ONLY);
10332 if (c_len == (STRLEN)-1) {
10333 _force_out_malformed_utf8_message(p, p_end,
10335 1 /* 1 means die */ );
10336 NOT_REACHED; /* NOTREACHED */
10339 && (OP(n) == ANYOFL || OP(n) == ANYOFPOSIXL)
10340 && ! ANYOFL_UTF8_LOCALE_REQD(flags))
10342 _CHECK_AND_OUTPUT_WIDE_LOCALE_CP_MSG(c);
10346 /* If this character is potentially in the bitmap, check it */
10347 if (c < NUM_ANYOF_CODE_POINTS && ! inRANGE(OP(n), ANYOFH, ANYOFHb)) {
10348 if (ANYOF_BITMAP_TEST(n, c))
10351 & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
10358 else if (flags & ANYOF_LOCALE_FLAGS) {
10359 if ( (flags & ANYOFL_FOLD)
10361 && ANYOF_BITMAP_TEST(n, PL_fold_locale[c]))
10365 else if ( ANYOF_POSIXL_TEST_ANY_SET(n)
10366 && c <= U8_MAX /* param to isFOO_lc() */
10369 /* The data structure is arranged so bits 0, 2, 4, ... are set
10370 * if the class includes the Posix character class given by
10371 * bit/2; and 1, 3, 5, ... are set if the class includes the
10372 * complemented Posix class given by int(bit/2). So we loop
10373 * through the bits, each time changing whether we complement
10374 * the result or not. Suppose for the sake of illustration
10375 * that bits 0-3 mean respectively, \w, \W, \s, \S. If bit 0
10376 * is set, it means there is a match for this ANYOF node if the
10377 * character is in the class given by the expression (0 / 2 = 0
10378 * = \w). If it is in that class, isFOO_lc() will return 1,
10379 * and since 'to_complement' is 0, the result will stay TRUE,
10380 * and we exit the loop. Suppose instead that bit 0 is 0, but
10381 * bit 1 is 1. That means there is a match if the character
10382 * matches \W. We won't bother to call isFOO_lc() on bit 0,
10383 * but will on bit 1. On the second iteration 'to_complement'
10384 * will be 1, so the exclusive or will reverse things, so we
10385 * are testing for \W. On the third iteration, 'to_complement'
10386 * will be 0, and we would be testing for \s; the fourth
10387 * iteration would test for \S, etc.
10389 * Note that this code assumes that all the classes are closed
10390 * under folding. For example, if a character matches \w, then
10391 * its fold does too; and vice versa. This should be true for
10392 * any well-behaved locale for all the currently defined Posix
10393 * classes, except for :lower: and :upper:, which are handled
10394 * by the pseudo-class :cased: which matches if either of the
10395 * other two does. To get rid of this assumption, an outer
10396 * loop could be used below to iterate over both the source
10397 * character, and its fold (if different) */
10400 int to_complement = 0;
10402 while (count < ANYOF_MAX) {
10403 if (ANYOF_POSIXL_TEST(n, count)
10404 && to_complement ^ cBOOL(isFOO_lc(count/2, (U8) c)))
10410 to_complement ^= 1;
10417 /* If the bitmap didn't (or couldn't) match, and something outside the
10418 * bitmap could match, try that. */
10420 if (c >= NUM_ANYOF_CODE_POINTS
10421 && (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP))
10423 match = TRUE; /* Everything above the bitmap matches */
10425 /* Here doesn't match everything above the bitmap. If there is
10426 * some information available beyond the bitmap, we may find a
10427 * match in it. If so, this is most likely because the code point
10428 * is outside the bitmap range. But rarely, it could be because of
10429 * some other reason. If so, various flags are set to indicate
10430 * this possibility. On ANYOFD nodes, there may be matches that
10431 * happen only when the target string is UTF-8; or for other node
10432 * types, because runtime lookup is needed, regardless of the
10433 * UTF-8ness of the target string. Finally, under /il, there may
10434 * be some matches only possible if the locale is a UTF-8 one. */
10435 else if ( ARG(n) != ANYOF_ONLY_HAS_BITMAP
10436 && ( c >= NUM_ANYOF_CODE_POINTS
10437 || ( (flags & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)
10438 && ( UNLIKELY(OP(n) != ANYOFD)
10439 || (utf8_target && ! isASCII_uni(c)
10440 # if NUM_ANYOF_CODE_POINTS > 256
10444 || ( ANYOFL_SOME_FOLDS_ONLY_IN_UTF8_LOCALE(flags)
10445 && IN_UTF8_CTYPE_LOCALE)))
10447 SV* only_utf8_locale = NULL;
10448 SV * const definition =
10449 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
10450 get_regclass_nonbitmap_data(prog, n, TRUE, 0,
10451 &only_utf8_locale, NULL);
10453 get_re_gclass_nonbitmap_data(prog, n, TRUE, 0,
10454 &only_utf8_locale, NULL);
10461 } else { /* Convert to utf8 */
10462 utf8_p = utf8_buffer;
10463 append_utf8_from_native_byte(*p, &utf8_p);
10464 utf8_p = utf8_buffer;
10467 /* Turkish locales have these hard-coded rules overriding
10469 if ( UNLIKELY(PL_in_utf8_turkic_locale)
10470 && isALPHA_FOLD_EQ(*p, 'i'))
10473 if (_invlist_contains_cp(definition,
10474 LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE))
10479 else if (*p == 'I') {
10480 if (_invlist_contains_cp(definition,
10481 LATIN_SMALL_LETTER_DOTLESS_I))
10487 else if (_invlist_contains_cp(definition, c)) {
10491 if (! match && only_utf8_locale && IN_UTF8_CTYPE_LOCALE) {
10492 match = _invlist_contains_cp(only_utf8_locale, c);
10496 /* In a Turkic locale under folding, hard-code the I i case pair
10498 if ( UNLIKELY(PL_in_utf8_turkic_locale)
10500 && (flags & ANYOFL_FOLD)
10503 if (c == LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE) {
10504 if (ANYOF_BITMAP_TEST(n, 'i')) {
10508 else if (c == LATIN_SMALL_LETTER_DOTLESS_I) {
10509 if (ANYOF_BITMAP_TEST(n, 'I')) {
10515 if (UNICODE_IS_SUPER(c)
10517 & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
10519 && ckWARN_d(WARN_NON_UNICODE))
10521 Perl_warner(aTHX_ packWARN(WARN_NON_UNICODE),
10522 "Matched non-Unicode code point 0x%04" UVXf " against Unicode property; may not be portable", c);
10526 #if ANYOF_INVERT != 1
10527 /* Depending on compiler optimization cBOOL takes time, so if don't have to
10529 # error ANYOF_INVERT needs to be set to 1, or guarded with cBOOL below,
10532 /* The xor complements the return if to invert: 1^1 = 0, 1^0 = 1 */
10533 return (flags & ANYOF_INVERT) ^ match;
10537 S_reghop3(U8 *s, SSize_t off, const U8* lim)
10539 /* return the position 'off' UTF-8 characters away from 's', forward if
10540 * 'off' >= 0, backwards if negative. But don't go outside of position
10541 * 'lim', which better be < s if off < 0 */
10543 PERL_ARGS_ASSERT_REGHOP3;
10546 while (off-- && s < lim) {
10547 /* XXX could check well-formedness here */
10548 U8 *new_s = s + UTF8SKIP(s);
10549 if (new_s > lim) /* lim may be in the middle of a long character */
10555 while (off++ && s > lim) {
10557 if (UTF8_IS_CONTINUED(*s)) {
10558 while (s > lim && UTF8_IS_CONTINUATION(*s))
10560 if (! UTF8_IS_START(*s)) {
10561 Perl_croak_nocontext("Malformed UTF-8 character (fatal)");
10564 /* XXX could check well-formedness here */
10571 S_reghop4(U8 *s, SSize_t off, const U8* llim, const U8* rlim)
10573 PERL_ARGS_ASSERT_REGHOP4;
10576 while (off-- && s < rlim) {
10577 /* XXX could check well-formedness here */
10582 while (off++ && s > llim) {
10584 if (UTF8_IS_CONTINUED(*s)) {
10585 while (s > llim && UTF8_IS_CONTINUATION(*s))
10587 if (! UTF8_IS_START(*s)) {
10588 Perl_croak_nocontext("Malformed UTF-8 character (fatal)");
10591 /* XXX could check well-formedness here */
10597 /* like reghop3, but returns NULL on overrun, rather than returning last
10601 S_reghopmaybe3(U8* s, SSize_t off, const U8* const lim)
10603 PERL_ARGS_ASSERT_REGHOPMAYBE3;
10606 while (off-- && s < lim) {
10607 /* XXX could check well-formedness here */
10614 while (off++ && s > lim) {
10616 if (UTF8_IS_CONTINUED(*s)) {
10617 while (s > lim && UTF8_IS_CONTINUATION(*s))
10619 if (! UTF8_IS_START(*s)) {
10620 Perl_croak_nocontext("Malformed UTF-8 character (fatal)");
10623 /* XXX could check well-formedness here */
10632 /* when executing a regex that may have (?{}), extra stuff needs setting
10633 up that will be visible to the called code, even before the current
10634 match has finished. In particular:
10636 * $_ is localised to the SV currently being matched;
10637 * pos($_) is created if necessary, ready to be updated on each call-out
10639 * a fake PMOP is created that can be set to PL_curpm (normally PL_curpm
10640 isn't set until the current pattern is successfully finished), so that
10641 $1 etc of the match-so-far can be seen;
10642 * save the old values of subbeg etc of the current regex, and set then
10643 to the current string (again, this is normally only done at the end
10648 S_setup_eval_state(pTHX_ regmatch_info *const reginfo)
10651 regexp *const rex = ReANY(reginfo->prog);
10652 regmatch_info_aux_eval *eval_state = reginfo->info_aux_eval;
10654 eval_state->rex = rex;
10655 eval_state->sv = reginfo->sv;
10658 /* Make $_ available to executed code. */
10659 if (reginfo->sv != DEFSV) {
10661 DEFSV_set(reginfo->sv);
10663 /* will be dec'd by S_cleanup_regmatch_info_aux */
10664 SvREFCNT_inc_NN(reginfo->sv);
10666 if (!(mg = mg_find_mglob(reginfo->sv))) {
10667 /* prepare for quick setting of pos */
10668 mg = sv_magicext_mglob(reginfo->sv);
10671 eval_state->pos_magic = mg;
10672 eval_state->pos = mg->mg_len;
10673 eval_state->pos_flags = mg->mg_flags;
10676 eval_state->pos_magic = NULL;
10678 if (!PL_reg_curpm) {
10679 /* PL_reg_curpm is a fake PMOP that we can attach the current
10680 * regex to and point PL_curpm at, so that $1 et al are visible
10681 * within a /(?{})/. It's just allocated once per interpreter the
10682 * first time its needed */
10683 Newxz(PL_reg_curpm, 1, PMOP);
10684 #ifdef USE_ITHREADS
10686 SV* const repointer = &PL_sv_undef;
10687 /* this regexp is also owned by the new PL_reg_curpm, which
10688 will try to free it. */
10689 av_push(PL_regex_padav, repointer);
10690 PL_reg_curpm->op_pmoffset = av_top_index(PL_regex_padav);
10691 PL_regex_pad = AvARRAY(PL_regex_padav);
10695 SET_reg_curpm(reginfo->prog);
10696 eval_state->curpm = PL_curpm;
10697 PL_curpm_under = PL_curpm;
10698 PL_curpm = PL_reg_curpm;
10699 if (RXp_MATCH_COPIED(rex)) {
10700 /* Here is a serious problem: we cannot rewrite subbeg,
10701 since it may be needed if this match fails. Thus
10702 $` inside (?{}) could fail... */
10703 eval_state->subbeg = rex->subbeg;
10704 eval_state->sublen = rex->sublen;
10705 eval_state->suboffset = rex->suboffset;
10706 eval_state->subcoffset = rex->subcoffset;
10707 #ifdef PERL_ANY_COW
10708 eval_state->saved_copy = rex->saved_copy;
10710 RXp_MATCH_COPIED_off(rex);
10713 eval_state->subbeg = NULL;
10714 rex->subbeg = (char *)reginfo->strbeg;
10715 rex->suboffset = 0;
10716 rex->subcoffset = 0;
10717 rex->sublen = reginfo->strend - reginfo->strbeg;
10721 /* destructor to clear up regmatch_info_aux and regmatch_info_aux_eval */
10724 S_cleanup_regmatch_info_aux(pTHX_ void *arg)
10726 regmatch_info_aux *aux = (regmatch_info_aux *) arg;
10727 regmatch_info_aux_eval *eval_state = aux->info_aux_eval;
10730 Safefree(aux->poscache);
10734 /* undo the effects of S_setup_eval_state() */
10736 if (eval_state->subbeg) {
10737 regexp * const rex = eval_state->rex;
10738 rex->subbeg = eval_state->subbeg;
10739 rex->sublen = eval_state->sublen;
10740 rex->suboffset = eval_state->suboffset;
10741 rex->subcoffset = eval_state->subcoffset;
10742 #ifdef PERL_ANY_COW
10743 rex->saved_copy = eval_state->saved_copy;
10745 RXp_MATCH_COPIED_on(rex);
10747 if (eval_state->pos_magic)
10749 eval_state->pos_magic->mg_len = eval_state->pos;
10750 eval_state->pos_magic->mg_flags =
10751 (eval_state->pos_magic->mg_flags & ~MGf_BYTES)
10752 | (eval_state->pos_flags & MGf_BYTES);
10755 PL_curpm = eval_state->curpm;
10756 SvREFCNT_dec(eval_state->sv);
10759 PL_regmatch_state = aux->old_regmatch_state;
10760 PL_regmatch_slab = aux->old_regmatch_slab;
10762 /* free all slabs above current one - this must be the last action
10763 * of this function, as aux and eval_state are allocated within
10764 * slabs and may be freed here */
10766 s = PL_regmatch_slab->next;
10768 PL_regmatch_slab->next = NULL;
10770 regmatch_slab * const osl = s;
10779 S_to_utf8_substr(pTHX_ regexp *prog)
10781 /* Converts substr fields in prog from bytes to UTF-8, calling fbm_compile
10782 * on the converted value */
10786 PERL_ARGS_ASSERT_TO_UTF8_SUBSTR;
10789 if (prog->substrs->data[i].substr
10790 && !prog->substrs->data[i].utf8_substr) {
10791 SV* const sv = newSVsv(prog->substrs->data[i].substr);
10792 prog->substrs->data[i].utf8_substr = sv;
10793 sv_utf8_upgrade(sv);
10794 if (SvVALID(prog->substrs->data[i].substr)) {
10795 if (SvTAIL(prog->substrs->data[i].substr)) {
10796 /* Trim the trailing \n that fbm_compile added last
10798 SvCUR_set(sv, SvCUR(sv) - 1);
10799 /* Whilst this makes the SV technically "invalid" (as its
10800 buffer is no longer followed by "\0") when fbm_compile()
10801 adds the "\n" back, a "\0" is restored. */
10802 fbm_compile(sv, FBMcf_TAIL);
10804 fbm_compile(sv, 0);
10806 if (prog->substrs->data[i].substr == prog->check_substr)
10807 prog->check_utf8 = sv;
10813 S_to_byte_substr(pTHX_ regexp *prog)
10815 /* Converts substr fields in prog from UTF-8 to bytes, calling fbm_compile
10816 * on the converted value; returns FALSE if can't be converted. */
10820 PERL_ARGS_ASSERT_TO_BYTE_SUBSTR;
10823 if (prog->substrs->data[i].utf8_substr
10824 && !prog->substrs->data[i].substr) {
10825 SV* sv = newSVsv(prog->substrs->data[i].utf8_substr);
10826 if (! sv_utf8_downgrade(sv, TRUE)) {
10827 SvREFCNT_dec_NN(sv);
10830 if (SvVALID(prog->substrs->data[i].utf8_substr)) {
10831 if (SvTAIL(prog->substrs->data[i].utf8_substr)) {
10832 /* Trim the trailing \n that fbm_compile added last
10834 SvCUR_set(sv, SvCUR(sv) - 1);
10835 fbm_compile(sv, FBMcf_TAIL);
10837 fbm_compile(sv, 0);
10839 prog->substrs->data[i].substr = sv;
10840 if (prog->substrs->data[i].utf8_substr == prog->check_utf8)
10841 prog->check_substr = sv;
10848 #ifndef PERL_IN_XSUB_RE
10851 Perl_is_grapheme(pTHX_ const U8 * strbeg, const U8 * s, const U8 * strend, const UV cp)
10853 /* Temporary helper function for toke.c. Verify that the code point 'cp'
10854 * is a stand-alone grapheme. The UTF-8 for 'cp' begins at position 's' in
10855 * the larger string bounded by 'strbeg' and 'strend'.
10857 * 'cp' needs to be assigned (if not, a future version of the Unicode
10858 * Standard could make it something that combines with adjacent characters,
10859 * so code using it would then break), and there has to be a GCB break
10860 * before and after the character. */
10863 GCB_enum cp_gcb_val, prev_cp_gcb_val, next_cp_gcb_val;
10864 const U8 * prev_cp_start;
10866 PERL_ARGS_ASSERT_IS_GRAPHEME;
10868 if ( UNLIKELY(UNICODE_IS_SUPER(cp))
10869 || UNLIKELY(UNICODE_IS_NONCHAR(cp)))
10871 /* These are considered graphemes */
10875 /* Otherwise, unassigned code points are forbidden */
10876 if (UNLIKELY(! ELEMENT_RANGE_MATCHES_INVLIST(
10877 _invlist_search(PL_Assigned_invlist, cp))))
10882 cp_gcb_val = getGCB_VAL_CP(cp);
10884 /* Find the GCB value of the previous code point in the input */
10885 prev_cp_start = utf8_hop_back(s, -1, strbeg);
10886 if (UNLIKELY(prev_cp_start == s)) {
10887 prev_cp_gcb_val = GCB_EDGE;
10890 prev_cp_gcb_val = getGCB_VAL_UTF8(prev_cp_start, strend);
10893 /* And check that is a grapheme boundary */
10894 if (! isGCB(prev_cp_gcb_val, cp_gcb_val, strbeg, s,
10895 TRUE /* is UTF-8 encoded */ ))
10900 /* Similarly verify there is a break between the current character and the
10904 next_cp_gcb_val = GCB_EDGE;
10907 next_cp_gcb_val = getGCB_VAL_UTF8(s, strend);
10910 return isGCB(cp_gcb_val, next_cp_gcb_val, strbeg, s, TRUE);
10914 =for apidoc_section $unicode
10916 =for apidoc isSCRIPT_RUN
10918 Returns a bool as to whether or not the sequence of bytes from C<s> up to but
10919 not including C<send> form a "script run". C<utf8_target> is TRUE iff the
10920 sequence starting at C<s> is to be treated as UTF-8. To be precise, except for
10921 two degenerate cases given below, this function returns TRUE iff all code
10922 points in it come from any combination of three "scripts" given by the Unicode
10923 "Script Extensions" property: Common, Inherited, and possibly one other.
10924 Additionally all decimal digits must come from the same consecutive sequence of
10927 For example, if all the characters in the sequence are Greek, or Common, or
10928 Inherited, this function will return TRUE, provided any decimal digits in it
10929 are from the same block of digits in Common. (These are the ASCII digits
10930 "0".."9" and additionally a block for full width forms of these, and several
10931 others used in mathematical notation.) For scripts (unlike Greek) that have
10932 their own digits defined this will accept either digits from that set or from
10933 one of the Common digit sets, but not a combination of the two. Some scripts,
10934 such as Arabic, have more than one set of digits. All digits must come from
10935 the same set for this function to return TRUE.
10937 C<*ret_script>, if C<ret_script> is not NULL, will on return of TRUE
10938 contain the script found, using the C<SCX_enum> typedef. Its value will be
10939 C<SCX_INVALID> if the function returns FALSE.
10941 If the sequence is empty, TRUE is returned, but C<*ret_script> (if asked for)
10942 will be C<SCX_INVALID>.
10944 If the sequence contains a single code point which is unassigned to a character
10945 in the version of Unicode being used, the function will return TRUE, and the
10946 script will be C<SCX_Unknown>. Any other combination of unassigned code points
10947 in the input sequence will result in the function treating the input as not
10948 being a script run.
10950 The returned script will be C<SCX_Inherited> iff all the code points in it are
10951 from the Inherited script.
10953 Otherwise, the returned script will be C<SCX_Common> iff all the code points in
10954 it are from the Inherited or Common scripts.
10961 Perl_isSCRIPT_RUN(pTHX_ const U8 * s, const U8 * send, const bool utf8_target)
10963 /* Basically, it looks at each character in the sequence to see if the
10964 * above conditions are met; if not it fails. It uses an inversion map to
10965 * find the enum corresponding to the script of each character. But this
10966 * is complicated by the fact that a few code points can be in any of
10967 * several scripts. The data has been constructed so that there are
10968 * additional enum values (all negative) for these situations. The
10969 * absolute value of those is an index into another table which contains
10970 * pointers to auxiliary tables for each such situation. Each aux array
10971 * lists all the scripts for the given situation. There is another,
10972 * parallel, table that gives the number of entries in each aux table.
10973 * These are all defined in charclass_invlists.h */
10975 /* XXX Here are the additional things UTS 39 says could be done:
10977 * Forbid sequences of the same nonspacing mark
10979 * Check to see that all the characters are in the sets of exemplar
10980 * characters for at least one language in the Unicode Common Locale Data
10981 * Repository [CLDR]. */
10984 /* Things that match /\d/u */
10985 SV * decimals_invlist = PL_XPosix_ptrs[_CC_DIGIT];
10986 UV * decimals_array = invlist_array(decimals_invlist);
10988 /* What code point is the digit '0' of the script run? (0 meaning FALSE if
10989 * not currently known) */
10990 UV zero_of_run = 0;
10992 SCX_enum script_of_run = SCX_INVALID; /* Illegal value */
10993 SCX_enum script_of_char = SCX_INVALID;
10995 /* If the script remains not fully determined from iteration to iteration,
10996 * this is the current intersection of the possiblities. */
10997 SCX_enum * intersection = NULL;
10998 PERL_UINT_FAST8_T intersection_len = 0;
11000 bool retval = TRUE;
11001 SCX_enum * ret_script = NULL;
11005 PERL_ARGS_ASSERT_ISSCRIPT_RUN;
11007 /* All code points in 0..255 are either Common or Latin, so must be a
11008 * script run. We can return immediately unless we need to know which
11010 if (! utf8_target && LIKELY(send > s)) {
11011 if (ret_script == NULL) {
11015 /* If any character is Latin, the run is Latin */
11017 if (isALPHA_L1(*s) && LIKELY(*s != MICRO_SIGN_NATIVE)) {
11018 *ret_script = SCX_Latin;
11023 /* Here, all are Common */
11024 *ret_script = SCX_Common;
11028 /* Look at each character in the sequence */
11030 /* If the current character being examined is a digit, this is the code
11031 * point of the zero for its sequence of 10 */
11036 /* The code allows all scripts to use the ASCII digits. This is
11037 * because they are in the Common script. Hence any ASCII ones found
11038 * are ok, unless and until a digit from another set has already been
11039 * encountered. digit ranges in Common are not similarly blessed) */
11040 if (UNLIKELY(isDIGIT(*s))) {
11041 if (UNLIKELY(script_of_run == SCX_Unknown)) {
11046 if (zero_of_run != '0') {
11058 /* Here, isn't an ASCII digit. Find the code point of the character */
11059 if (! UTF8_IS_INVARIANT(*s)) {
11061 cp = valid_utf8_to_uvchr((U8 *) s, &len);
11068 /* If is within the range [+0 .. +9] of the script's zero, it also is a
11069 * digit in that script. We can skip the rest of this code for this
11071 if (UNLIKELY(zero_of_run && withinCOUNT(cp, zero_of_run, 9))) {
11075 /* Find the character's script. The correct values are hard-coded here
11076 * for small-enough code points. */
11077 if (cp < 0x2B9) { /* From inspection of Unicode db; extremely
11078 unlikely to change */
11080 || ( isALPHA_L1(cp)
11081 && LIKELY(cp != MICRO_SIGN_NATIVE)))
11083 script_of_char = SCX_Latin;
11086 script_of_char = SCX_Common;
11090 script_of_char = _Perl_SCX_invmap[
11091 _invlist_search(PL_SCX_invlist, cp)];
11094 /* We arbitrarily accept a single unassigned character, but not in
11095 * combination with anything else, and not a run of them. */
11096 if ( UNLIKELY(script_of_run == SCX_Unknown)
11097 || UNLIKELY( script_of_run != SCX_INVALID
11098 && script_of_char == SCX_Unknown))
11104 /* For the first character, or the run is inherited, the run's script
11105 * is set to the char's */
11106 if ( UNLIKELY(script_of_run == SCX_INVALID)
11107 || UNLIKELY(script_of_run == SCX_Inherited))
11109 script_of_run = script_of_char;
11112 /* For the character's script to be Unknown, it must be the first
11113 * character in the sequence (for otherwise a test above would have
11114 * prevented us from reaching here), and we have set the run's script
11115 * to it. Nothing further to be done for this character */
11116 if (UNLIKELY(script_of_char == SCX_Unknown)) {
11120 /* We accept 'inherited' script characters currently even at the
11121 * beginning. (We know that no characters in Inherited are digits, or
11122 * we'd have to check for that) */
11123 if (UNLIKELY(script_of_char == SCX_Inherited)) {
11127 /* If the run so far is Common, and the new character isn't, change the
11128 * run's script to that of this character */
11129 if (script_of_run == SCX_Common && script_of_char != SCX_Common) {
11130 script_of_run = script_of_char;
11133 /* Now we can see if the script of the new character is the same as
11134 * that of the run */
11135 if (LIKELY(script_of_char == script_of_run)) {
11136 /* By far the most common case */
11137 goto scripts_match;
11140 /* Here, the script of the run isn't Common. But characters in Common
11141 * match any script */
11142 if (script_of_char == SCX_Common) {
11143 goto scripts_match;
11146 #ifndef HAS_SCX_AUX_TABLES
11148 /* Too early a Unicode version to have a code point belonging to more
11149 * than one script, so, if the scripts don't exactly match, fail */
11150 PERL_UNUSED_VAR(intersection_len);
11156 /* Here there is no exact match between the character's script and the
11157 * run's. And we've handled the special cases of scripts Unknown,
11158 * Inherited, and Common.
11160 * Negative script numbers signify that the value may be any of several
11161 * scripts, and we need to look at auxiliary information to make our
11162 * deterimination. But if both are non-negative, we can fail now */
11163 if (LIKELY(script_of_char >= 0)) {
11164 const SCX_enum * search_in;
11165 PERL_UINT_FAST8_T search_in_len;
11166 PERL_UINT_FAST8_T i;
11168 if (LIKELY(script_of_run >= 0)) {
11173 /* Use the previously constructed set of possible scripts, if any.
11175 if (intersection) {
11176 search_in = intersection;
11177 search_in_len = intersection_len;
11180 search_in = SCX_AUX_TABLE_ptrs[-script_of_run];
11181 search_in_len = SCX_AUX_TABLE_lengths[-script_of_run];
11184 for (i = 0; i < search_in_len; i++) {
11185 if (search_in[i] == script_of_char) {
11186 script_of_run = script_of_char;
11187 goto scripts_match;
11194 else if (LIKELY(script_of_run >= 0)) {
11195 /* script of character could be one of several, but run is a single
11197 const SCX_enum * search_in = SCX_AUX_TABLE_ptrs[-script_of_char];
11198 const PERL_UINT_FAST8_T search_in_len
11199 = SCX_AUX_TABLE_lengths[-script_of_char];
11200 PERL_UINT_FAST8_T i;
11202 for (i = 0; i < search_in_len; i++) {
11203 if (search_in[i] == script_of_run) {
11204 script_of_char = script_of_run;
11205 goto scripts_match;
11213 /* Both run and char could be in one of several scripts. If the
11214 * intersection is empty, then this character isn't in this script
11215 * run. Otherwise, we need to calculate the intersection to use
11216 * for future iterations of the loop, unless we are already at the
11217 * final character */
11218 const SCX_enum * search_char = SCX_AUX_TABLE_ptrs[-script_of_char];
11219 const PERL_UINT_FAST8_T char_len
11220 = SCX_AUX_TABLE_lengths[-script_of_char];
11221 const SCX_enum * search_run;
11222 PERL_UINT_FAST8_T run_len;
11224 SCX_enum * new_overlap = NULL;
11225 PERL_UINT_FAST8_T i, j;
11227 if (intersection) {
11228 search_run = intersection;
11229 run_len = intersection_len;
11232 search_run = SCX_AUX_TABLE_ptrs[-script_of_run];
11233 run_len = SCX_AUX_TABLE_lengths[-script_of_run];
11236 intersection_len = 0;
11238 for (i = 0; i < run_len; i++) {
11239 for (j = 0; j < char_len; j++) {
11240 if (search_run[i] == search_char[j]) {
11242 /* Here, the script at i,j matches. That means this
11243 * character is in the run. But continue on to find
11244 * the complete intersection, for the next loop
11245 * iteration, and for the digit check after it.
11247 * On the first found common script, we malloc space
11248 * for the intersection list for the worst case of the
11249 * intersection, which is the minimum of the number of
11250 * scripts remaining in each set. */
11251 if (intersection_len == 0) {
11253 MIN(run_len - i, char_len - j),
11256 new_overlap[intersection_len++] = search_run[i];
11261 /* Here we've looked through everything. If they have no scripts
11262 * in common, not a run */
11263 if (intersection_len == 0) {
11268 /* If there is only a single script in common, set to that.
11269 * Otherwise, use the intersection going forward */
11270 Safefree(intersection);
11271 intersection = NULL;
11272 if (intersection_len == 1) {
11273 script_of_run = script_of_char = new_overlap[0];
11274 Safefree(new_overlap);
11275 new_overlap = NULL;
11278 intersection = new_overlap;
11286 /* Here, the script of the character is compatible with that of the
11287 * run. That means that in most cases, it continues the script run.
11288 * Either it and the run match exactly, or one or both can be in any of
11289 * several scripts, and the intersection is not empty. However, if the
11290 * character is a decimal digit, it could still mean failure if it is
11291 * from the wrong sequence of 10. So, we need to look at if it's a
11292 * digit. We've already handled the 10 digits [0-9], and the next
11293 * lowest one is this one: */
11294 if (cp < FIRST_NON_ASCII_DECIMAL_DIGIT) {
11295 continue; /* Not a digit; this character is part of the run */
11298 /* If we have a definitive '0' for the script of this character, we
11299 * know that for this to be a digit, it must be in the range of +0..+9
11301 if ( script_of_char >= 0
11302 && (zero_of_char = script_zeros[script_of_char]))
11304 if (! withinCOUNT(cp, zero_of_char, 9)) {
11305 continue; /* Not a digit; this character is part of the run
11310 else { /* Need to look up if this character is a digit or not */
11311 SSize_t index_of_zero_of_char;
11312 index_of_zero_of_char = _invlist_search(decimals_invlist, cp);
11313 if ( UNLIKELY(index_of_zero_of_char < 0)
11314 || ! ELEMENT_RANGE_MATCHES_INVLIST(index_of_zero_of_char))
11316 continue; /* Not a digit; this character is part of the run.
11320 zero_of_char = decimals_array[index_of_zero_of_char];
11323 /* Here, the character is a decimal digit, and the zero of its sequence
11324 * of 10 is in 'zero_of_char'. If we already have a zero for this run,
11325 * they better be the same. */
11327 if (zero_of_run != zero_of_char) {
11332 else { /* Otherwise we now have a zero for this run */
11333 zero_of_run = zero_of_char;
11335 } /* end of looping through CLOSESR text */
11337 Safefree(intersection);
11339 if (ret_script != NULL) {
11341 *ret_script = script_of_run;
11344 *ret_script = SCX_INVALID;
11351 #endif /* ifndef PERL_IN_XSUB_RE */
11354 * ex: set ts=8 sts=4 sw=4 et: