5 * One Ring to rule them all, One Ring to find them
7 * [p.v of _The Lord of the Rings_, opening poem]
8 * [p.50 of _The Lord of the Rings_, I/iii: "The Shadow of the Past"]
9 * [p.254 of _The Lord of the Rings_, II/ii: "The Council of Elrond"]
12 /* This file contains functions for executing a regular expression. See
13 * also regcomp.c which funnily enough, contains functions for compiling
14 * a regular expression.
16 * This file is also copied at build time to ext/re/re_exec.c, where
17 * it's built with -DPERL_EXT_RE_BUILD -DPERL_EXT_RE_DEBUG -DPERL_EXT.
18 * This causes the main functions to be compiled under new names and with
19 * debugging support added, which makes "use re 'debug'" work.
22 /* NOTE: this is derived from Henry Spencer's regexp code, and should not
23 * confused with the original package (see point 3 below). Thanks, Henry!
26 /* Additional note: this code is very heavily munged from Henry's version
27 * in places. In some spots I've traded clarity for efficiency, so don't
28 * blame Henry for some of the lack of readability.
31 /* The names of the functions have been changed from regcomp and
32 * regexec to pregcomp and pregexec in order to avoid conflicts
33 * with the POSIX routines of the same names.
36 #ifdef PERL_EXT_RE_BUILD
41 * pregcomp and pregexec -- regsub and regerror are not used in perl
43 * Copyright (c) 1986 by University of Toronto.
44 * Written by Henry Spencer. Not derived from licensed software.
46 * Permission is granted to anyone to use this software for any
47 * purpose on any computer system, and to redistribute it freely,
48 * subject to the following restrictions:
50 * 1. The author is not responsible for the consequences of use of
51 * this software, no matter how awful, even if they arise
54 * 2. The origin of this software must not be misrepresented, either
55 * by explicit claim or by omission.
57 * 3. Altered versions must be plainly marked as such, and must not
58 * be misrepresented as being the original software.
60 **** Alterations to Henry's code are...
62 **** Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
63 **** 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
64 **** by Larry Wall and others
66 **** You may distribute under the terms of either the GNU General Public
67 **** License or the Artistic License, as specified in the README file.
69 * Beware that some of this code is subtly aware of the way operator
70 * precedence is structured in regular expressions. Serious changes in
71 * regular-expression syntax might require a total rethink.
74 #define PERL_IN_REGEXEC_C
77 #ifdef PERL_IN_XSUB_RE
83 #include "invlist_inline.h"
84 #include "unicode_constants.h"
86 #define B_ON_NON_UTF8_LOCALE_IS_WRONG \
87 "Use of \\b{} or \\B{} for non-UTF-8 locale is wrong. Assuming a UTF-8 locale"
89 static const char utf8_locale_required[] =
90 "Use of (?[ ]) for non-UTF-8 locale is wrong. Assuming a UTF-8 locale";
93 /* At least one required character in the target string is expressible only in
95 static const char* const non_utf8_target_but_utf8_required
96 = "Can't match, because target string needs to be in UTF-8\n";
99 #define NON_UTF8_TARGET_BUT_UTF8_REQUIRED(target) STMT_START { \
100 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%s", non_utf8_target_but_utf8_required));\
104 #define HAS_NONLATIN1_FOLD_CLOSURE(i) _HAS_NONLATIN1_FOLD_CLOSURE_ONLY_FOR_USE_BY_REGCOMP_DOT_C_AND_REGEXEC_DOT_C(i)
107 #define STATIC static
110 /* Valid only if 'c', the character being looke-up, is an invariant under
111 * UTF-8: it avoids the reginclass call if there are no complications: i.e., if
112 * everything matchable is straight forward in the bitmap */
113 #define REGINCLASS(prog,p,c,u) (ANYOF_FLAGS(p) \
114 ? reginclass(prog,p,c,c+1,u) \
115 : ANYOF_BITMAP_TEST(p,*(c)))
121 #define CHR_SVLEN(sv) (utf8_target ? sv_len_utf8(sv) : SvCUR(sv))
123 #define HOPc(pos,off) \
124 (char *)(reginfo->is_utf8_target \
125 ? reghop3((U8*)pos, off, \
126 (U8*)(off >= 0 ? reginfo->strend : reginfo->strbeg)) \
129 /* like HOPMAYBE3 but backwards. lim must be +ve. Returns NULL on overshoot */
130 #define HOPBACK3(pos, off, lim) \
131 (reginfo->is_utf8_target \
132 ? reghopmaybe3((U8*)pos, (SSize_t)0-off, (U8*)(lim)) \
133 : (pos - off >= lim) \
137 #define HOPBACKc(pos, off) ((char*)HOPBACK3(pos, off, reginfo->strbeg))
139 #define HOP3(pos,off,lim) (reginfo->is_utf8_target ? reghop3((U8*)(pos), off, (U8*)(lim)) : (U8*)(pos + off))
140 #define HOP3c(pos,off,lim) ((char*)HOP3(pos,off,lim))
142 /* lim must be +ve. Returns NULL on overshoot */
143 #define HOPMAYBE3(pos,off,lim) \
144 (reginfo->is_utf8_target \
145 ? reghopmaybe3((U8*)pos, off, (U8*)(lim)) \
146 : ((U8*)pos + off <= lim) \
150 /* like HOP3, but limits the result to <= lim even for the non-utf8 case.
151 * off must be >=0; args should be vars rather than expressions */
152 #define HOP3lim(pos,off,lim) (reginfo->is_utf8_target \
153 ? reghop3((U8*)(pos), off, (U8*)(lim)) \
154 : (U8*)((pos + off) > lim ? lim : (pos + off)))
155 #define HOP3clim(pos,off,lim) ((char*)HOP3lim(pos,off,lim))
157 #define HOP4(pos,off,llim, rlim) (reginfo->is_utf8_target \
158 ? reghop4((U8*)(pos), off, (U8*)(llim), (U8*)(rlim)) \
160 #define HOP4c(pos,off,llim, rlim) ((char*)HOP4(pos,off,llim, rlim))
162 #define NEXTCHR_EOS -10 /* nextchr has fallen off the end */
163 #define NEXTCHR_IS_EOS (nextchr < 0)
165 #define SET_nextchr \
166 nextchr = ((locinput < reginfo->strend) ? UCHARAT(locinput) : NEXTCHR_EOS)
168 #define SET_locinput(p) \
173 #define LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist) STMT_START { \
175 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST; \
176 swash_ptr = _core_swash_init("utf8", property_name, &PL_sv_undef, \
177 1, 0, invlist, &flags); \
182 /* If in debug mode, we test that a known character properly matches */
184 # define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
187 utf8_char_in_property) \
188 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist); \
189 assert(swash_fetch(swash_ptr, (U8 *) utf8_char_in_property, TRUE));
191 # define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
194 utf8_char_in_property) \
195 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist)
198 #define LOAD_UTF8_CHARCLASS_ALNUM() LOAD_UTF8_CHARCLASS_DEBUG_TEST( \
199 PL_utf8_swash_ptrs[_CC_WORDCHAR], \
201 PL_XPosix_ptrs[_CC_WORDCHAR], \
202 LATIN_SMALL_LIGATURE_LONG_S_T_UTF8);
204 #define PLACEHOLDER /* Something for the preprocessor to grab onto */
205 /* TODO: Combine JUMPABLE and HAS_TEXT to cache OP(rn) */
207 /* for use after a quantifier and before an EXACT-like node -- japhy */
208 /* it would be nice to rework regcomp.sym to generate this stuff. sigh
210 * NOTE that *nothing* that affects backtracking should be in here, specifically
211 * VERBS must NOT be included. JUMPABLE is used to determine if we can ignore a
212 * node that is in between two EXACT like nodes when ascertaining what the required
213 * "follow" character is. This should probably be moved to regex compile time
214 * although it may be done at run time beause of the REF possibility - more
215 * investigation required. -- demerphq
217 #define JUMPABLE(rn) ( \
219 (OP(rn) == CLOSE && \
220 !EVAL_CLOSE_PAREN_IS(cur_eval,ARG(rn)) ) || \
222 OP(rn) == SUSPEND || OP(rn) == IFMATCH || \
223 OP(rn) == PLUS || OP(rn) == MINMOD || \
225 (PL_regkind[OP(rn)] == CURLY && ARG1(rn) > 0) \
227 #define IS_EXACT(rn) (PL_regkind[OP(rn)] == EXACT)
229 #define HAS_TEXT(rn) ( IS_EXACT(rn) || PL_regkind[OP(rn)] == REF )
232 /* Currently these are only used when PL_regkind[OP(rn)] == EXACT so
233 we don't need this definition. XXX These are now out-of-sync*/
234 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==REF || OP(rn)==NREF )
235 #define IS_TEXTF(rn) ( OP(rn)==EXACTFU || OP(rn)==EXACTFU_SS || OP(rn)==EXACTFA || OP(rn)==EXACTFA_NO_TRIE || OP(rn)==EXACTF || OP(rn)==REFF || OP(rn)==NREFF )
236 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL || OP(rn)==REFFL || OP(rn)==NREFFL )
239 /* ... so we use this as its faster. */
240 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==EXACTL )
241 #define IS_TEXTFU(rn) ( OP(rn)==EXACTFU || OP(rn)==EXACTFLU8 || OP(rn)==EXACTFU_SS || OP(rn) == EXACTFA || OP(rn) == EXACTFA_NO_TRIE)
242 #define IS_TEXTF(rn) ( OP(rn)==EXACTF )
243 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL )
248 Search for mandatory following text node; for lookahead, the text must
249 follow but for lookbehind (rn->flags != 0) we skip to the next step.
251 #define FIND_NEXT_IMPT(rn) STMT_START { \
252 while (JUMPABLE(rn)) { \
253 const OPCODE type = OP(rn); \
254 if (type == SUSPEND || PL_regkind[type] == CURLY) \
255 rn = NEXTOPER(NEXTOPER(rn)); \
256 else if (type == PLUS) \
258 else if (type == IFMATCH) \
259 rn = (rn->flags == 0) ? NEXTOPER(NEXTOPER(rn)) : rn + ARG(rn); \
260 else rn += NEXT_OFF(rn); \
264 #define SLAB_FIRST(s) (&(s)->states[0])
265 #define SLAB_LAST(s) (&(s)->states[PERL_REGMATCH_SLAB_SLOTS-1])
267 static void S_setup_eval_state(pTHX_ regmatch_info *const reginfo);
268 static void S_cleanup_regmatch_info_aux(pTHX_ void *arg);
269 static regmatch_state * S_push_slab(pTHX);
271 #define REGCP_PAREN_ELEMS 3
272 #define REGCP_OTHER_ELEMS 3
273 #define REGCP_FRAME_ELEMS 1
274 /* REGCP_FRAME_ELEMS are not part of the REGCP_OTHER_ELEMS and
275 * are needed for the regexp context stack bookkeeping. */
278 S_regcppush(pTHX_ const regexp *rex, I32 parenfloor, U32 maxopenparen _pDEPTH)
280 const int retval = PL_savestack_ix;
281 const int paren_elems_to_push =
282 (maxopenparen - parenfloor) * REGCP_PAREN_ELEMS;
283 const UV total_elems = paren_elems_to_push + REGCP_OTHER_ELEMS;
284 const UV elems_shifted = total_elems << SAVE_TIGHT_SHIFT;
286 GET_RE_DEBUG_FLAGS_DECL;
288 PERL_ARGS_ASSERT_REGCPPUSH;
290 if (paren_elems_to_push < 0)
291 Perl_croak(aTHX_ "panic: paren_elems_to_push, %i < 0, maxopenparen: %i parenfloor: %i REGCP_PAREN_ELEMS: %u",
292 (int)paren_elems_to_push, (int)maxopenparen,
293 (int)parenfloor, (unsigned)REGCP_PAREN_ELEMS);
295 if ((elems_shifted >> SAVE_TIGHT_SHIFT) != total_elems)
296 Perl_croak(aTHX_ "panic: paren_elems_to_push offset %" UVuf
297 " out of range (%lu-%ld)",
299 (unsigned long)maxopenparen,
302 SSGROW(total_elems + REGCP_FRAME_ELEMS);
305 if ((int)maxopenparen > (int)parenfloor)
306 Perl_re_exec_indentf( aTHX_
307 "rex=0x%" UVxf " offs=0x%" UVxf ": saving capture indices:\n",
313 for (p = parenfloor+1; p <= (I32)maxopenparen; p++) {
314 /* REGCP_PARENS_ELEMS are pushed per pairs of parentheses. */
315 SSPUSHIV(rex->offs[p].end);
316 SSPUSHIV(rex->offs[p].start);
317 SSPUSHINT(rex->offs[p].start_tmp);
318 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_
319 " \\%" UVuf ": %" IVdf "(%" IVdf ")..%" IVdf "\n",
322 (IV)rex->offs[p].start,
323 (IV)rex->offs[p].start_tmp,
327 /* REGCP_OTHER_ELEMS are pushed in any case, parentheses or no. */
328 SSPUSHINT(maxopenparen);
329 SSPUSHINT(rex->lastparen);
330 SSPUSHINT(rex->lastcloseparen);
331 SSPUSHUV(SAVEt_REGCONTEXT | elems_shifted); /* Magic cookie. */
336 /* These are needed since we do not localize EVAL nodes: */
337 #define REGCP_SET(cp) \
339 Perl_re_exec_indentf( aTHX_ \
340 "Setting an EVAL scope, savestack=%" IVdf ",\n", \
341 depth, (IV)PL_savestack_ix \
346 #define REGCP_UNWIND(cp) \
348 if (cp != PL_savestack_ix) \
349 Perl_re_exec_indentf( aTHX_ \
350 "Clearing an EVAL scope, savestack=%" \
351 IVdf "..%" IVdf "\n", \
352 depth, (IV)(cp), (IV)PL_savestack_ix \
357 #define UNWIND_PAREN(lp, lcp) \
358 for (n = rex->lastparen; n > lp; n--) \
359 rex->offs[n].end = -1; \
360 rex->lastparen = n; \
361 rex->lastcloseparen = lcp;
365 S_regcppop(pTHX_ regexp *rex, U32 *maxopenparen_p _pDEPTH)
369 GET_RE_DEBUG_FLAGS_DECL;
371 PERL_ARGS_ASSERT_REGCPPOP;
373 /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
375 assert((i & SAVE_MASK) == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
376 i >>= SAVE_TIGHT_SHIFT; /* Parentheses elements to pop. */
377 rex->lastcloseparen = SSPOPINT;
378 rex->lastparen = SSPOPINT;
379 *maxopenparen_p = SSPOPINT;
381 i -= REGCP_OTHER_ELEMS;
382 /* Now restore the parentheses context. */
384 if (i || rex->lastparen + 1 <= rex->nparens)
385 Perl_re_exec_indentf( aTHX_
386 "rex=0x%" UVxf " offs=0x%" UVxf ": restoring capture indices to:\n",
392 paren = *maxopenparen_p;
393 for ( ; i > 0; i -= REGCP_PAREN_ELEMS) {
395 rex->offs[paren].start_tmp = SSPOPINT;
396 rex->offs[paren].start = SSPOPIV;
398 if (paren <= rex->lastparen)
399 rex->offs[paren].end = tmps;
400 DEBUG_BUFFERS_r( Perl_re_exec_indentf( aTHX_
401 " \\%" UVuf ": %" IVdf "(%" IVdf ")..%" IVdf "%s\n",
404 (IV)rex->offs[paren].start,
405 (IV)rex->offs[paren].start_tmp,
406 (IV)rex->offs[paren].end,
407 (paren > rex->lastparen ? "(skipped)" : ""));
412 /* It would seem that the similar code in regtry()
413 * already takes care of this, and in fact it is in
414 * a better location to since this code can #if 0-ed out
415 * but the code in regtry() is needed or otherwise tests
416 * requiring null fields (pat.t#187 and split.t#{13,14}
417 * (as of patchlevel 7877) will fail. Then again,
418 * this code seems to be necessary or otherwise
419 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
420 * --jhi updated by dapm */
421 for (i = rex->lastparen + 1; i <= rex->nparens; i++) {
422 if (i > *maxopenparen_p)
423 rex->offs[i].start = -1;
424 rex->offs[i].end = -1;
425 DEBUG_BUFFERS_r( Perl_re_exec_indentf( aTHX_
426 " \\%" UVuf ": %s ..-1 undeffing\n",
429 (i > *maxopenparen_p) ? "-1" : " "
435 /* restore the parens and associated vars at savestack position ix,
436 * but without popping the stack */
439 S_regcp_restore(pTHX_ regexp *rex, I32 ix, U32 *maxopenparen_p _pDEPTH)
441 I32 tmpix = PL_savestack_ix;
442 PERL_ARGS_ASSERT_REGCP_RESTORE;
444 PL_savestack_ix = ix;
445 regcppop(rex, maxopenparen_p);
446 PL_savestack_ix = tmpix;
449 #define regcpblow(cp) LEAVE_SCOPE(cp) /* Ignores regcppush()ed data. */
451 #ifndef PERL_IN_XSUB_RE
454 Perl_isFOO_lc(pTHX_ const U8 classnum, const U8 character)
456 /* Returns a boolean as to whether or not 'character' is a member of the
457 * Posix character class given by 'classnum' that should be equivalent to a
458 * value in the typedef '_char_class_number'.
460 * Ideally this could be replaced by a just an array of function pointers
461 * to the C library functions that implement the macros this calls.
462 * However, to compile, the precise function signatures are required, and
463 * these may vary from platform to to platform. To avoid having to figure
464 * out what those all are on each platform, I (khw) am using this method,
465 * which adds an extra layer of function call overhead (unless the C
466 * optimizer strips it away). But we don't particularly care about
467 * performance with locales anyway. */
469 switch ((_char_class_number) classnum) {
470 case _CC_ENUM_ALPHANUMERIC: return isALPHANUMERIC_LC(character);
471 case _CC_ENUM_ALPHA: return isALPHA_LC(character);
472 case _CC_ENUM_ASCII: return isASCII_LC(character);
473 case _CC_ENUM_BLANK: return isBLANK_LC(character);
474 case _CC_ENUM_CASED: return isLOWER_LC(character)
475 || isUPPER_LC(character);
476 case _CC_ENUM_CNTRL: return isCNTRL_LC(character);
477 case _CC_ENUM_DIGIT: return isDIGIT_LC(character);
478 case _CC_ENUM_GRAPH: return isGRAPH_LC(character);
479 case _CC_ENUM_LOWER: return isLOWER_LC(character);
480 case _CC_ENUM_PRINT: return isPRINT_LC(character);
481 case _CC_ENUM_PUNCT: return isPUNCT_LC(character);
482 case _CC_ENUM_SPACE: return isSPACE_LC(character);
483 case _CC_ENUM_UPPER: return isUPPER_LC(character);
484 case _CC_ENUM_WORDCHAR: return isWORDCHAR_LC(character);
485 case _CC_ENUM_XDIGIT: return isXDIGIT_LC(character);
486 default: /* VERTSPACE should never occur in locales */
487 Perl_croak(aTHX_ "panic: isFOO_lc() has an unexpected character class '%d'", classnum);
490 NOT_REACHED; /* NOTREACHED */
497 S_isFOO_utf8_lc(pTHX_ const U8 classnum, const U8* character)
499 /* Returns a boolean as to whether or not the (well-formed) UTF-8-encoded
500 * 'character' is a member of the Posix character class given by 'classnum'
501 * that should be equivalent to a value in the typedef
502 * '_char_class_number'.
504 * This just calls isFOO_lc on the code point for the character if it is in
505 * the range 0-255. Outside that range, all characters use Unicode
506 * rules, ignoring any locale. So use the Unicode function if this class
507 * requires a swash, and use the Unicode macro otherwise. */
509 PERL_ARGS_ASSERT_ISFOO_UTF8_LC;
511 if (UTF8_IS_INVARIANT(*character)) {
512 return isFOO_lc(classnum, *character);
514 else if (UTF8_IS_DOWNGRADEABLE_START(*character)) {
515 return isFOO_lc(classnum,
516 EIGHT_BIT_UTF8_TO_NATIVE(*character, *(character + 1)));
519 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(character, character + UTF8SKIP(character));
521 if (classnum < _FIRST_NON_SWASH_CC) {
523 /* Initialize the swash unless done already */
524 if (! PL_utf8_swash_ptrs[classnum]) {
525 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
526 PL_utf8_swash_ptrs[classnum] =
527 _core_swash_init("utf8",
530 PL_XPosix_ptrs[classnum], &flags);
533 return cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum], (U8 *)
535 TRUE /* is UTF */ ));
538 switch ((_char_class_number) classnum) {
539 case _CC_ENUM_SPACE: return is_XPERLSPACE_high(character);
540 case _CC_ENUM_BLANK: return is_HORIZWS_high(character);
541 case _CC_ENUM_XDIGIT: return is_XDIGIT_high(character);
542 case _CC_ENUM_VERTSPACE: return is_VERTWS_high(character);
546 return FALSE; /* Things like CNTRL are always below 256 */
550 * pregexec and friends
553 #ifndef PERL_IN_XSUB_RE
555 - pregexec - match a regexp against a string
558 Perl_pregexec(pTHX_ REGEXP * const prog, char* stringarg, char *strend,
559 char *strbeg, SSize_t minend, SV *screamer, U32 nosave)
560 /* stringarg: the point in the string at which to begin matching */
561 /* strend: pointer to null at end of string */
562 /* strbeg: real beginning of string */
563 /* minend: end of match must be >= minend bytes after stringarg. */
564 /* screamer: SV being matched: only used for utf8 flag, pos() etc; string
565 * itself is accessed via the pointers above */
566 /* nosave: For optimizations. */
568 PERL_ARGS_ASSERT_PREGEXEC;
571 regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
572 nosave ? 0 : REXEC_COPY_STR);
578 /* re_intuit_start():
580 * Based on some optimiser hints, try to find the earliest position in the
581 * string where the regex could match.
583 * rx: the regex to match against
584 * sv: the SV being matched: only used for utf8 flag; the string
585 * itself is accessed via the pointers below. Note that on
586 * something like an overloaded SV, SvPOK(sv) may be false
587 * and the string pointers may point to something unrelated to
589 * strbeg: real beginning of string
590 * strpos: the point in the string at which to begin matching
591 * strend: pointer to the byte following the last char of the string
592 * flags currently unused; set to 0
593 * data: currently unused; set to NULL
595 * The basic idea of re_intuit_start() is to use some known information
596 * about the pattern, namely:
598 * a) the longest known anchored substring (i.e. one that's at a
599 * constant offset from the beginning of the pattern; but not
600 * necessarily at a fixed offset from the beginning of the
602 * b) the longest floating substring (i.e. one that's not at a constant
603 * offset from the beginning of the pattern);
604 * c) Whether the pattern is anchored to the string; either
605 * an absolute anchor: /^../, or anchored to \n: /^.../m,
606 * or anchored to pos(): /\G/;
607 * d) A start class: a real or synthetic character class which
608 * represents which characters are legal at the start of the pattern;
610 * to either quickly reject the match, or to find the earliest position
611 * within the string at which the pattern might match, thus avoiding
612 * running the full NFA engine at those earlier locations, only to
613 * eventually fail and retry further along.
615 * Returns NULL if the pattern can't match, or returns the address within
616 * the string which is the earliest place the match could occur.
618 * The longest of the anchored and floating substrings is called 'check'
619 * and is checked first. The other is called 'other' and is checked
620 * second. The 'other' substring may not be present. For example,
622 * /(abc|xyz)ABC\d{0,3}DEFG/
626 * check substr (float) = "DEFG", offset 6..9 chars
627 * other substr (anchored) = "ABC", offset 3..3 chars
630 * Be aware that during the course of this function, sometimes 'anchored'
631 * refers to a substring being anchored relative to the start of the
632 * pattern, and sometimes to the pattern itself being anchored relative to
633 * the string. For example:
635 * /\dabc/: "abc" is anchored to the pattern;
636 * /^\dabc/: "abc" is anchored to the pattern and the string;
637 * /\d+abc/: "abc" is anchored to neither the pattern nor the string;
638 * /^\d+abc/: "abc" is anchored to neither the pattern nor the string,
639 * but the pattern is anchored to the string.
643 Perl_re_intuit_start(pTHX_
646 const char * const strbeg,
650 re_scream_pos_data *data)
652 struct regexp *const prog = ReANY(rx);
653 SSize_t start_shift = prog->check_offset_min;
654 /* Should be nonnegative! */
655 SSize_t end_shift = 0;
656 /* current lowest pos in string where the regex can start matching */
657 char *rx_origin = strpos;
659 const bool utf8_target = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
660 U8 other_ix = 1 - prog->substrs->check_ix;
662 char *other_last = strpos;/* latest pos 'other' substr already checked to */
663 char *check_at = NULL; /* check substr found at this pos */
664 const I32 multiline = prog->extflags & RXf_PMf_MULTILINE;
665 RXi_GET_DECL(prog,progi);
666 regmatch_info reginfo_buf; /* create some info to pass to find_byclass */
667 regmatch_info *const reginfo = ®info_buf;
668 GET_RE_DEBUG_FLAGS_DECL;
670 PERL_ARGS_ASSERT_RE_INTUIT_START;
671 PERL_UNUSED_ARG(flags);
672 PERL_UNUSED_ARG(data);
674 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
675 "Intuit: trying to determine minimum start position...\n"));
677 /* for now, assume that all substr offsets are positive. If at some point
678 * in the future someone wants to do clever things with lookbehind and
679 * -ve offsets, they'll need to fix up any code in this function
680 * which uses these offsets. See the thread beginning
681 * <20140113145929.GF27210@iabyn.com>
683 assert(prog->substrs->data[0].min_offset >= 0);
684 assert(prog->substrs->data[0].max_offset >= 0);
685 assert(prog->substrs->data[1].min_offset >= 0);
686 assert(prog->substrs->data[1].max_offset >= 0);
687 assert(prog->substrs->data[2].min_offset >= 0);
688 assert(prog->substrs->data[2].max_offset >= 0);
690 /* for now, assume that if both present, that the floating substring
691 * doesn't start before the anchored substring.
692 * If you break this assumption (e.g. doing better optimisations
693 * with lookahead/behind), then you'll need to audit the code in this
694 * function carefully first
697 ! ( (prog->anchored_utf8 || prog->anchored_substr)
698 && (prog->float_utf8 || prog->float_substr))
699 || (prog->float_min_offset >= prog->anchored_offset));
701 /* byte rather than char calculation for efficiency. It fails
702 * to quickly reject some cases that can't match, but will reject
703 * them later after doing full char arithmetic */
704 if (prog->minlen > strend - strpos) {
705 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
706 " String too short...\n"));
710 RXp_MATCH_UTF8_set(prog, utf8_target);
711 reginfo->is_utf8_target = cBOOL(utf8_target);
712 reginfo->info_aux = NULL;
713 reginfo->strbeg = strbeg;
714 reginfo->strend = strend;
715 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
717 /* not actually used within intuit, but zero for safety anyway */
718 reginfo->poscache_maxiter = 0;
721 if ((!prog->anchored_utf8 && prog->anchored_substr)
722 || (!prog->float_utf8 && prog->float_substr))
723 to_utf8_substr(prog);
724 check = prog->check_utf8;
726 if (!prog->check_substr && prog->check_utf8) {
727 if (! to_byte_substr(prog)) {
728 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(fail);
731 check = prog->check_substr;
734 /* dump the various substring data */
735 DEBUG_OPTIMISE_MORE_r({
737 for (i=0; i<=2; i++) {
738 SV *sv = (utf8_target ? prog->substrs->data[i].utf8_substr
739 : prog->substrs->data[i].substr);
743 Perl_re_printf( aTHX_
744 " substrs[%d]: min=%" IVdf " max=%" IVdf " end shift=%" IVdf
745 " useful=%" IVdf " utf8=%d [%s]\n",
747 (IV)prog->substrs->data[i].min_offset,
748 (IV)prog->substrs->data[i].max_offset,
749 (IV)prog->substrs->data[i].end_shift,
756 if (prog->intflags & PREGf_ANCH) { /* Match at \G, beg-of-str or after \n */
758 /* ml_anch: check after \n?
760 * A note about PREGf_IMPLICIT: on an un-anchored pattern beginning
761 * with /.*.../, these flags will have been added by the
763 * /.*abc/, /.*abc/m: PREGf_IMPLICIT | PREGf_ANCH_MBOL
764 * /.*abc/s: PREGf_IMPLICIT | PREGf_ANCH_SBOL
766 ml_anch = (prog->intflags & PREGf_ANCH_MBOL)
767 && !(prog->intflags & PREGf_IMPLICIT);
769 if (!ml_anch && !(prog->intflags & PREGf_IMPLICIT)) {
770 /* we are only allowed to match at BOS or \G */
772 /* trivially reject if there's a BOS anchor and we're not at BOS.
774 * Note that we don't try to do a similar quick reject for
775 * \G, since generally the caller will have calculated strpos
776 * based on pos() and gofs, so the string is already correctly
777 * anchored by definition; and handling the exceptions would
778 * be too fiddly (e.g. REXEC_IGNOREPOS).
780 if ( strpos != strbeg
781 && (prog->intflags & PREGf_ANCH_SBOL))
783 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
784 " Not at start...\n"));
788 /* in the presence of an anchor, the anchored (relative to the
789 * start of the regex) substr must also be anchored relative
790 * to strpos. So quickly reject if substr isn't found there.
791 * This works for \G too, because the caller will already have
792 * subtracted gofs from pos, and gofs is the offset from the
793 * \G to the start of the regex. For example, in /.abc\Gdef/,
794 * where substr="abcdef", pos()=3, gofs=4, offset_min=1:
795 * caller will have set strpos=pos()-4; we look for the substr
796 * at position pos()-4+1, which lines up with the "a" */
798 if (prog->check_offset_min == prog->check_offset_max) {
799 /* Substring at constant offset from beg-of-str... */
800 SSize_t slen = SvCUR(check);
801 char *s = HOP3c(strpos, prog->check_offset_min, strend);
803 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
804 " Looking for check substr at fixed offset %" IVdf "...\n",
805 (IV)prog->check_offset_min));
808 /* In this case, the regex is anchored at the end too.
809 * Unless it's a multiline match, the lengths must match
810 * exactly, give or take a \n. NB: slen >= 1 since
811 * the last char of check is \n */
813 && ( strend - s > slen
814 || strend - s < slen - 1
815 || (strend - s == slen && strend[-1] != '\n')))
817 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
818 " String too long...\n"));
821 /* Now should match s[0..slen-2] */
824 if (slen && (strend - s < slen
825 || *SvPVX_const(check) != *s
826 || (slen > 1 && (memNE(SvPVX_const(check), s, slen)))))
828 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
829 " String not equal...\n"));
834 goto success_at_start;
839 end_shift = prog->check_end_shift;
841 #ifdef DEBUGGING /* 7/99: reports of failure (with the older version) */
843 Perl_croak(aTHX_ "panic: end_shift: %" IVdf " pattern:\n%s\n ",
844 (IV)end_shift, RX_PRECOMP(rx));
849 /* This is the (re)entry point of the main loop in this function.
850 * The goal of this loop is to:
851 * 1) find the "check" substring in the region rx_origin..strend
852 * (adjusted by start_shift / end_shift). If not found, reject
854 * 2) If it exists, look for the "other" substr too if defined; for
855 * example, if the check substr maps to the anchored substr, then
856 * check the floating substr, and vice-versa. If not found, go
857 * back to (1) with rx_origin suitably incremented.
858 * 3) If we find an rx_origin position that doesn't contradict
859 * either of the substrings, then check the possible additional
860 * constraints on rx_origin of /^.../m or a known start class.
861 * If these fail, then depending on which constraints fail, jump
862 * back to here, or to various other re-entry points further along
863 * that skip some of the first steps.
864 * 4) If we pass all those tests, update the BmUSEFUL() count on the
865 * substring. If the start position was determined to be at the
866 * beginning of the string - so, not rejected, but not optimised,
867 * since we have to run regmatch from position 0 - decrement the
868 * BmUSEFUL() count. Otherwise increment it.
872 /* first, look for the 'check' substring */
878 DEBUG_OPTIMISE_MORE_r({
879 Perl_re_printf( aTHX_
880 " At restart: rx_origin=%" IVdf " Check offset min: %" IVdf
881 " Start shift: %" IVdf " End shift %" IVdf
882 " Real end Shift: %" IVdf "\n",
883 (IV)(rx_origin - strbeg),
884 (IV)prog->check_offset_min,
887 (IV)prog->check_end_shift);
890 end_point = HOPBACK3(strend, end_shift, rx_origin);
893 start_point = HOPMAYBE3(rx_origin, start_shift, end_point);
898 /* If the regex is absolutely anchored to either the start of the
899 * string (SBOL) or to pos() (ANCH_GPOS), then
900 * check_offset_max represents an upper bound on the string where
901 * the substr could start. For the ANCH_GPOS case, we assume that
902 * the caller of intuit will have already set strpos to
903 * pos()-gofs, so in this case strpos + offset_max will still be
904 * an upper bound on the substr.
907 && prog->intflags & PREGf_ANCH
908 && prog->check_offset_max != SSize_t_MAX)
910 SSize_t check_len = SvCUR(check) - !!SvTAIL(check);
911 const char * const anchor =
912 (prog->intflags & PREGf_ANCH_GPOS ? strpos : strbeg);
913 SSize_t targ_len = (char*)end_point - anchor;
915 if (check_len > targ_len) {
916 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
917 "Anchored string too short...\n"));
921 /* do a bytes rather than chars comparison. It's conservative;
922 * so it skips doing the HOP if the result can't possibly end
923 * up earlier than the old value of end_point.
925 assert(anchor + check_len <= (char *)end_point);
926 if (prog->check_offset_max + check_len < targ_len) {
927 end_point = HOP3lim((U8*)anchor,
928 prog->check_offset_max,
929 end_point - check_len
935 check_at = fbm_instr( start_point, end_point,
936 check, multiline ? FBMrf_MULTILINE : 0);
938 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
939 " doing 'check' fbm scan, [%" IVdf "..%" IVdf "] gave %" IVdf "\n",
940 (IV)((char*)start_point - strbeg),
941 (IV)((char*)end_point - strbeg),
942 (IV)(check_at ? check_at - strbeg : -1)
945 /* Update the count-of-usability, remove useless subpatterns,
949 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
950 SvPVX_const(check), RE_SV_DUMPLEN(check), 30);
951 Perl_re_printf( aTHX_ " %s %s substr %s%s%s",
952 (check_at ? "Found" : "Did not find"),
953 (check == (utf8_target ? prog->anchored_utf8 : prog->anchored_substr)
954 ? "anchored" : "floating"),
957 (check_at ? " at offset " : "...\n") );
962 /* set rx_origin to the minimum position where the regex could start
963 * matching, given the constraint of the just-matched check substring.
964 * But don't set it lower than previously.
967 if (check_at - rx_origin > prog->check_offset_max)
968 rx_origin = HOP3c(check_at, -prog->check_offset_max, rx_origin);
969 /* Finish the diagnostic message */
970 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
971 "%ld (rx_origin now %" IVdf ")...\n",
972 (long)(check_at - strbeg),
973 (IV)(rx_origin - strbeg)
978 /* now look for the 'other' substring if defined */
980 if (utf8_target ? prog->substrs->data[other_ix].utf8_substr
981 : prog->substrs->data[other_ix].substr)
983 /* Take into account the "other" substring. */
987 struct reg_substr_datum *other;
990 other = &prog->substrs->data[other_ix];
992 /* if "other" is anchored:
993 * we've previously found a floating substr starting at check_at.
994 * This means that the regex origin must lie somewhere
995 * between min (rx_origin): HOP3(check_at, -check_offset_max)
996 * and max: HOP3(check_at, -check_offset_min)
997 * (except that min will be >= strpos)
998 * So the fixed substr must lie somewhere between
999 * HOP3(min, anchored_offset)
1000 * HOP3(max, anchored_offset) + SvCUR(substr)
1003 /* if "other" is floating
1004 * Calculate last1, the absolute latest point where the
1005 * floating substr could start in the string, ignoring any
1006 * constraints from the earlier fixed match. It is calculated
1009 * strend - prog->minlen (in chars) is the absolute latest
1010 * position within the string where the origin of the regex
1011 * could appear. The latest start point for the floating
1012 * substr is float_min_offset(*) on from the start of the
1013 * regex. last1 simply combines thee two offsets.
1015 * (*) You might think the latest start point should be
1016 * float_max_offset from the regex origin, and technically
1017 * you'd be correct. However, consider
1019 * Here, float min, max are 3,5 and minlen is 7.
1020 * This can match either
1024 * In the first case, the regex matches minlen chars; in the
1025 * second, minlen+1, in the third, minlen+2.
1026 * In the first case, the floating offset is 3 (which equals
1027 * float_min), in the second, 4, and in the third, 5 (which
1028 * equals float_max). In all cases, the floating string bcd
1029 * can never start more than 4 chars from the end of the
1030 * string, which equals minlen - float_min. As the substring
1031 * starts to match more than float_min from the start of the
1032 * regex, it makes the regex match more than minlen chars,
1033 * and the two cancel each other out. So we can always use
1034 * float_min - minlen, rather than float_max - minlen for the
1035 * latest position in the string.
1037 * Note that -minlen + float_min_offset is equivalent (AFAIKT)
1038 * to CHR_SVLEN(must) - !!SvTAIL(must) + prog->float_end_shift
1041 assert(prog->minlen >= other->min_offset);
1042 last1 = HOP3c(strend,
1043 other->min_offset - prog->minlen, strbeg);
1045 if (other_ix) {/* i.e. if (other-is-float) */
1046 /* last is the latest point where the floating substr could
1047 * start, *given* any constraints from the earlier fixed
1048 * match. This constraint is that the floating string starts
1049 * <= float_max_offset chars from the regex origin (rx_origin).
1050 * If this value is less than last1, use it instead.
1052 assert(rx_origin <= last1);
1054 /* this condition handles the offset==infinity case, and
1055 * is a short-cut otherwise. Although it's comparing a
1056 * byte offset to a char length, it does so in a safe way,
1057 * since 1 char always occupies 1 or more bytes,
1058 * so if a string range is (last1 - rx_origin) bytes,
1059 * it will be less than or equal to (last1 - rx_origin)
1060 * chars; meaning it errs towards doing the accurate HOP3
1061 * rather than just using last1 as a short-cut */
1062 (last1 - rx_origin) < other->max_offset
1064 : (char*)HOP3lim(rx_origin, other->max_offset, last1);
1067 assert(strpos + start_shift <= check_at);
1068 last = HOP4c(check_at, other->min_offset - start_shift,
1072 s = HOP3c(rx_origin, other->min_offset, strend);
1073 if (s < other_last) /* These positions already checked */
1076 must = utf8_target ? other->utf8_substr : other->substr;
1077 assert(SvPOK(must));
1080 char *to = last + SvCUR(must) - (SvTAIL(must)!=0);
1086 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1087 " skipping 'other' fbm scan: %" IVdf " > %" IVdf "\n",
1088 (IV)(from - strbeg),
1094 (unsigned char*)from,
1097 multiline ? FBMrf_MULTILINE : 0
1099 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1100 " doing 'other' fbm scan, [%" IVdf "..%" IVdf "] gave %" IVdf "\n",
1101 (IV)(from - strbeg),
1103 (IV)(s ? s - strbeg : -1)
1109 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
1110 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
1111 Perl_re_printf( aTHX_ " %s %s substr %s%s",
1112 s ? "Found" : "Contradicts",
1113 other_ix ? "floating" : "anchored",
1114 quoted, RE_SV_TAIL(must));
1119 /* last1 is latest possible substr location. If we didn't
1120 * find it before there, we never will */
1121 if (last >= last1) {
1122 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1123 "; giving up...\n"));
1127 /* try to find the check substr again at a later
1128 * position. Maybe next time we'll find the "other" substr
1130 other_last = HOP3c(last, 1, strend) /* highest failure */;
1132 other_ix /* i.e. if other-is-float */
1133 ? HOP3c(rx_origin, 1, strend)
1134 : HOP4c(last, 1 - other->min_offset, strbeg, strend);
1135 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1136 "; about to retry %s at offset %ld (rx_origin now %" IVdf ")...\n",
1137 (other_ix ? "floating" : "anchored"),
1138 (long)(HOP3c(check_at, 1, strend) - strbeg),
1139 (IV)(rx_origin - strbeg)
1144 if (other_ix) { /* if (other-is-float) */
1145 /* other_last is set to s, not s+1, since its possible for
1146 * a floating substr to fail first time, then succeed
1147 * second time at the same floating position; e.g.:
1148 * "-AB--AABZ" =~ /\wAB\d*Z/
1149 * The first time round, anchored and float match at
1150 * "-(AB)--AAB(Z)" then fail on the initial \w character
1151 * class. Second time round, they match at "-AB--A(AB)(Z)".
1156 rx_origin = HOP3c(s, -other->min_offset, strbeg);
1157 other_last = HOP3c(s, 1, strend);
1159 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1160 " at offset %ld (rx_origin now %" IVdf ")...\n",
1162 (IV)(rx_origin - strbeg)
1168 DEBUG_OPTIMISE_MORE_r(
1169 Perl_re_printf( aTHX_
1170 " Check-only match: offset min:%" IVdf " max:%" IVdf
1171 " check_at:%" IVdf " rx_origin:%" IVdf " rx_origin-check_at:%" IVdf
1172 " strend:%" IVdf "\n",
1173 (IV)prog->check_offset_min,
1174 (IV)prog->check_offset_max,
1175 (IV)(check_at-strbeg),
1176 (IV)(rx_origin-strbeg),
1177 (IV)(rx_origin-check_at),
1183 postprocess_substr_matches:
1185 /* handle the extra constraint of /^.../m if present */
1187 if (ml_anch && rx_origin != strbeg && rx_origin[-1] != '\n') {
1190 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1191 " looking for /^/m anchor"));
1193 /* we have failed the constraint of a \n before rx_origin.
1194 * Find the next \n, if any, even if it's beyond the current
1195 * anchored and/or floating substrings. Whether we should be
1196 * scanning ahead for the next \n or the next substr is debatable.
1197 * On the one hand you'd expect rare substrings to appear less
1198 * often than \n's. On the other hand, searching for \n means
1199 * we're effectively flipping between check_substr and "\n" on each
1200 * iteration as the current "rarest" string candidate, which
1201 * means for example that we'll quickly reject the whole string if
1202 * hasn't got a \n, rather than trying every substr position
1206 s = HOP3c(strend, - prog->minlen, strpos);
1207 if (s <= rx_origin ||
1208 ! ( rx_origin = (char *)memchr(rx_origin, '\n', s - rx_origin)))
1210 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1211 " Did not find /%s^%s/m...\n",
1212 PL_colors[0], PL_colors[1]));
1216 /* earliest possible origin is 1 char after the \n.
1217 * (since *rx_origin == '\n', it's safe to ++ here rather than
1218 * HOP(rx_origin, 1)) */
1221 if (prog->substrs->check_ix == 0 /* check is anchored */
1222 || rx_origin >= HOP3c(check_at, - prog->check_offset_min, strpos))
1224 /* Position contradicts check-string; either because
1225 * check was anchored (and thus has no wiggle room),
1226 * or check was float and rx_origin is above the float range */
1227 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1228 " Found /%s^%s/m, about to restart lookup for check-string with rx_origin %ld...\n",
1229 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1233 /* if we get here, the check substr must have been float,
1234 * is in range, and we may or may not have had an anchored
1235 * "other" substr which still contradicts */
1236 assert(prog->substrs->check_ix); /* check is float */
1238 if (utf8_target ? prog->anchored_utf8 : prog->anchored_substr) {
1239 /* whoops, the anchored "other" substr exists, so we still
1240 * contradict. On the other hand, the float "check" substr
1241 * didn't contradict, so just retry the anchored "other"
1243 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1244 " Found /%s^%s/m, rescanning for anchored from offset %" IVdf " (rx_origin now %" IVdf ")...\n",
1245 PL_colors[0], PL_colors[1],
1246 (IV)(rx_origin - strbeg + prog->anchored_offset),
1247 (IV)(rx_origin - strbeg)
1249 goto do_other_substr;
1252 /* success: we don't contradict the found floating substring
1253 * (and there's no anchored substr). */
1254 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1255 " Found /%s^%s/m with rx_origin %ld...\n",
1256 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1259 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1260 " (multiline anchor test skipped)\n"));
1266 /* if we have a starting character class, then test that extra constraint.
1267 * (trie stclasses are too expensive to use here, we are better off to
1268 * leave it to regmatch itself) */
1270 if (progi->regstclass && PL_regkind[OP(progi->regstclass)]!=TRIE) {
1271 const U8* const str = (U8*)STRING(progi->regstclass);
1273 /* XXX this value could be pre-computed */
1274 const int cl_l = (PL_regkind[OP(progi->regstclass)] == EXACT
1275 ? (reginfo->is_utf8_pat
1276 ? utf8_distance(str + STR_LEN(progi->regstclass), str)
1277 : STR_LEN(progi->regstclass))
1281 /* latest pos that a matching float substr constrains rx start to */
1282 char *rx_max_float = NULL;
1284 /* if the current rx_origin is anchored, either by satisfying an
1285 * anchored substring constraint, or a /^.../m constraint, then we
1286 * can reject the current origin if the start class isn't found
1287 * at the current position. If we have a float-only match, then
1288 * rx_origin is constrained to a range; so look for the start class
1289 * in that range. if neither, then look for the start class in the
1290 * whole rest of the string */
1292 /* XXX DAPM it's not clear what the minlen test is for, and why
1293 * it's not used in the floating case. Nothing in the test suite
1294 * causes minlen == 0 here. See <20140313134639.GS12844@iabyn.com>.
1295 * Here are some old comments, which may or may not be correct:
1297 * minlen == 0 is possible if regstclass is \b or \B,
1298 * and the fixed substr is ''$.
1299 * Since minlen is already taken into account, rx_origin+1 is
1300 * before strend; accidentally, minlen >= 1 guaranties no false
1301 * positives at rx_origin + 1 even for \b or \B. But (minlen? 1 :
1302 * 0) below assumes that regstclass does not come from lookahead...
1303 * If regstclass takes bytelength more than 1: If charlength==1, OK.
1304 * This leaves EXACTF-ish only, which are dealt with in
1308 if (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
1309 endpos = HOP3clim(rx_origin, (prog->minlen ? cl_l : 0), strend);
1310 else if (prog->float_substr || prog->float_utf8) {
1311 rx_max_float = HOP3c(check_at, -start_shift, strbeg);
1312 endpos = HOP3clim(rx_max_float, cl_l, strend);
1317 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1318 " looking for class: start_shift: %" IVdf " check_at: %" IVdf
1319 " rx_origin: %" IVdf " endpos: %" IVdf "\n",
1320 (IV)start_shift, (IV)(check_at - strbeg),
1321 (IV)(rx_origin - strbeg), (IV)(endpos - strbeg)));
1323 s = find_byclass(prog, progi->regstclass, rx_origin, endpos,
1326 if (endpos == strend) {
1327 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1328 " Could not match STCLASS...\n") );
1331 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1332 " This position contradicts STCLASS...\n") );
1333 if ((prog->intflags & PREGf_ANCH) && !ml_anch
1334 && !(prog->intflags & PREGf_IMPLICIT))
1337 /* Contradict one of substrings */
1338 if (prog->anchored_substr || prog->anchored_utf8) {
1339 if (prog->substrs->check_ix == 1) { /* check is float */
1340 /* Have both, check_string is floating */
1341 assert(rx_origin + start_shift <= check_at);
1342 if (rx_origin + start_shift != check_at) {
1343 /* not at latest position float substr could match:
1344 * Recheck anchored substring, but not floating.
1345 * The condition above is in bytes rather than
1346 * chars for efficiency. It's conservative, in
1347 * that it errs on the side of doing 'goto
1348 * do_other_substr'. In this case, at worst,
1349 * an extra anchored search may get done, but in
1350 * practice the extra fbm_instr() is likely to
1351 * get skipped anyway. */
1352 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1353 " about to retry anchored at offset %ld (rx_origin now %" IVdf ")...\n",
1354 (long)(other_last - strbeg),
1355 (IV)(rx_origin - strbeg)
1357 goto do_other_substr;
1365 /* In the presence of ml_anch, we might be able to
1366 * find another \n without breaking the current float
1369 /* strictly speaking this should be HOP3c(..., 1, ...),
1370 * but since we goto a block of code that's going to
1371 * search for the next \n if any, its safe here */
1373 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1374 " about to look for /%s^%s/m starting at rx_origin %ld...\n",
1375 PL_colors[0], PL_colors[1],
1376 (long)(rx_origin - strbeg)) );
1377 goto postprocess_substr_matches;
1380 /* strictly speaking this can never be true; but might
1381 * be if we ever allow intuit without substrings */
1382 if (!(utf8_target ? prog->float_utf8 : prog->float_substr))
1385 rx_origin = rx_max_float;
1388 /* at this point, any matching substrings have been
1389 * contradicted. Start again... */
1391 rx_origin = HOP3c(rx_origin, 1, strend);
1393 /* uses bytes rather than char calculations for efficiency.
1394 * It's conservative: it errs on the side of doing 'goto restart',
1395 * where there is code that does a proper char-based test */
1396 if (rx_origin + start_shift + end_shift > strend) {
1397 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1398 " Could not match STCLASS...\n") );
1401 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1402 " about to look for %s substr starting at offset %ld (rx_origin now %" IVdf ")...\n",
1403 (prog->substrs->check_ix ? "floating" : "anchored"),
1404 (long)(rx_origin + start_shift - strbeg),
1405 (IV)(rx_origin - strbeg)
1412 if (rx_origin != s) {
1413 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1414 " By STCLASS: moving %ld --> %ld\n",
1415 (long)(rx_origin - strbeg), (long)(s - strbeg))
1419 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1420 " Does not contradict STCLASS...\n");
1425 /* Decide whether using the substrings helped */
1427 if (rx_origin != strpos) {
1428 /* Fixed substring is found far enough so that the match
1429 cannot start at strpos. */
1431 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ " try at offset...\n"));
1432 ++BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr); /* hooray/5 */
1435 /* The found rx_origin position does not prohibit matching at
1436 * strpos, so calling intuit didn't gain us anything. Decrement
1437 * the BmUSEFUL() count on the check substring, and if we reach
1439 if (!(prog->intflags & PREGf_NAUGHTY)
1441 prog->check_utf8 /* Could be deleted already */
1442 && --BmUSEFUL(prog->check_utf8) < 0
1443 && (prog->check_utf8 == prog->float_utf8)
1445 prog->check_substr /* Could be deleted already */
1446 && --BmUSEFUL(prog->check_substr) < 0
1447 && (prog->check_substr == prog->float_substr)
1450 /* If flags & SOMETHING - do not do it many times on the same match */
1451 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ " ... Disabling check substring...\n"));
1452 /* XXX Does the destruction order has to change with utf8_target? */
1453 SvREFCNT_dec(utf8_target ? prog->check_utf8 : prog->check_substr);
1454 SvREFCNT_dec(utf8_target ? prog->check_substr : prog->check_utf8);
1455 prog->check_substr = prog->check_utf8 = NULL; /* disable */
1456 prog->float_substr = prog->float_utf8 = NULL; /* clear */
1457 check = NULL; /* abort */
1458 /* XXXX This is a remnant of the old implementation. It
1459 looks wasteful, since now INTUIT can use many
1460 other heuristics. */
1461 prog->extflags &= ~RXf_USE_INTUIT;
1465 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1466 "Intuit: %sSuccessfully guessed:%s match at offset %ld\n",
1467 PL_colors[4], PL_colors[5], (long)(rx_origin - strbeg)) );
1471 fail_finish: /* Substring not found */
1472 if (prog->check_substr || prog->check_utf8) /* could be removed already */
1473 BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
1475 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%sMatch rejected by optimizer%s\n",
1476 PL_colors[4], PL_colors[5]));
1481 #define DECL_TRIE_TYPE(scan) \
1482 const enum { trie_plain, trie_utf8, trie_utf8_fold, trie_latin_utf8_fold, \
1483 trie_utf8_exactfa_fold, trie_latin_utf8_exactfa_fold, \
1484 trie_utf8l, trie_flu8 } \
1485 trie_type = ((scan->flags == EXACT) \
1486 ? (utf8_target ? trie_utf8 : trie_plain) \
1487 : (scan->flags == EXACTL) \
1488 ? (utf8_target ? trie_utf8l : trie_plain) \
1489 : (scan->flags == EXACTFA) \
1491 ? trie_utf8_exactfa_fold \
1492 : trie_latin_utf8_exactfa_fold) \
1493 : (scan->flags == EXACTFLU8 \
1497 : trie_latin_utf8_fold)))
1499 #define REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc, uscan, len, uvc, charid, foldlen, foldbuf, uniflags) \
1502 U8 flags = FOLD_FLAGS_FULL; \
1503 switch (trie_type) { \
1505 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1506 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1507 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1509 goto do_trie_utf8_fold; \
1510 case trie_utf8_exactfa_fold: \
1511 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1513 case trie_utf8_fold: \
1514 do_trie_utf8_fold: \
1515 if ( foldlen>0 ) { \
1516 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1521 len = UTF8SKIP(uc); \
1522 uvc = _toFOLD_utf8_flags( (const U8*) uc, uc + len, foldbuf, &foldlen, \
1524 skiplen = UVCHR_SKIP( uvc ); \
1525 foldlen -= skiplen; \
1526 uscan = foldbuf + skiplen; \
1529 case trie_latin_utf8_exactfa_fold: \
1530 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1532 case trie_latin_utf8_fold: \
1533 if ( foldlen>0 ) { \
1534 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1540 uvc = _to_fold_latin1( (U8) *uc, foldbuf, &foldlen, flags); \
1541 skiplen = UVCHR_SKIP( uvc ); \
1542 foldlen -= skiplen; \
1543 uscan = foldbuf + skiplen; \
1547 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1548 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1549 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1553 uvc = utf8n_to_uvchr( (const U8*) uc, UTF8_MAXLEN, &len, uniflags ); \
1560 charid = trie->charmap[ uvc ]; \
1564 if (widecharmap) { \
1565 SV** const svpp = hv_fetch(widecharmap, \
1566 (char*)&uvc, sizeof(UV), 0); \
1568 charid = (U16)SvIV(*svpp); \
1573 #define DUMP_EXEC_POS(li,s,doutf8,depth) \
1574 dump_exec_pos(li,s,(reginfo->strend),(reginfo->strbeg), \
1575 startpos, doutf8, depth)
1577 #define REXEC_FBC_EXACTISH_SCAN(COND) \
1581 && (ln == 1 || folder(s, pat_string, ln)) \
1582 && (reginfo->intuit || regtry(reginfo, &s)) )\
1588 #define REXEC_FBC_UTF8_SCAN(CODE) \
1590 while (s < strend) { \
1596 #define REXEC_FBC_SCAN(CODE) \
1598 while (s < strend) { \
1604 #define REXEC_FBC_UTF8_CLASS_SCAN(COND) \
1605 REXEC_FBC_UTF8_SCAN( /* Loops while (s < strend) */ \
1607 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1616 #define REXEC_FBC_CLASS_SCAN(COND) \
1617 REXEC_FBC_SCAN( /* Loops while (s < strend) */ \
1619 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1628 #define REXEC_FBC_CSCAN(CONDUTF8,COND) \
1629 if (utf8_target) { \
1630 REXEC_FBC_UTF8_CLASS_SCAN(CONDUTF8); \
1633 REXEC_FBC_CLASS_SCAN(COND); \
1636 /* The three macros below are slightly different versions of the same logic.
1638 * The first is for /a and /aa when the target string is UTF-8. This can only
1639 * match ascii, but it must advance based on UTF-8. The other two handle the
1640 * non-UTF-8 and the more generic UTF-8 cases. In all three, we are looking
1641 * for the boundary (or non-boundary) between a word and non-word character.
1642 * The utf8 and non-utf8 cases have the same logic, but the details must be
1643 * different. Find the "wordness" of the character just prior to this one, and
1644 * compare it with the wordness of this one. If they differ, we have a
1645 * boundary. At the beginning of the string, pretend that the previous
1646 * character was a new-line.
1648 * All these macros uncleanly have side-effects with each other and outside
1649 * variables. So far it's been too much trouble to clean-up
1651 * TEST_NON_UTF8 is the macro or function to call to test if its byte input is
1652 * a word character or not.
1653 * IF_SUCCESS is code to do if it finds that we are at a boundary between
1655 * IF_FAIL is code to do if we aren't at a boundary between word/non-word
1657 * Exactly one of the two IF_FOO parameters is a no-op, depending on whether we
1658 * are looking for a boundary or for a non-boundary. If we are looking for a
1659 * boundary, we want IF_FAIL to be the no-op, and for IF_SUCCESS to go out and
1660 * see if this tentative match actually works, and if so, to quit the loop
1661 * here. And vice-versa if we are looking for a non-boundary.
1663 * 'tmp' below in the next three macros in the REXEC_FBC_SCAN and
1664 * REXEC_FBC_UTF8_SCAN loops is a loop invariant, a bool giving the return of
1665 * TEST_NON_UTF8(s-1). To see this, note that that's what it is defined to be
1666 * at entry to the loop, and to get to the IF_FAIL branch, tmp must equal
1667 * TEST_NON_UTF8(s), and in the opposite branch, IF_SUCCESS, tmp is that
1668 * complement. But in that branch we complement tmp, meaning that at the
1669 * bottom of the loop tmp is always going to be equal to TEST_NON_UTF8(s),
1670 * which means at the top of the loop in the next iteration, it is
1671 * TEST_NON_UTF8(s-1) */
1672 #define FBC_UTF8_A(TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1673 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1674 tmp = TEST_NON_UTF8(tmp); \
1675 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1676 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1678 IF_SUCCESS; /* Is a boundary if values for s-1 and s differ */ \
1685 /* Like FBC_UTF8_A, but TEST_UV is a macro which takes a UV as its input, and
1686 * TEST_UTF8 is a macro that for the same input code points returns identically
1687 * to TEST_UV, but takes a pointer to a UTF-8 encoded string instead */
1688 #define FBC_UTF8(TEST_UV, TEST_UTF8, IF_SUCCESS, IF_FAIL) \
1689 if (s == reginfo->strbeg) { \
1692 else { /* Back-up to the start of the previous character */ \
1693 U8 * const r = reghop3((U8*)s, -1, (U8*)reginfo->strbeg); \
1694 tmp = utf8n_to_uvchr(r, (U8*) reginfo->strend - r, \
1695 0, UTF8_ALLOW_DEFAULT); \
1697 tmp = TEST_UV(tmp); \
1698 LOAD_UTF8_CHARCLASS_ALNUM(); \
1699 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1700 if (tmp == ! (TEST_UTF8((U8 *) s, (U8 *) reginfo->strend))) { \
1709 /* Like the above two macros. UTF8_CODE is the complete code for handling
1710 * UTF-8. Common to the BOUND and NBOUND cases, set-up by the FBC_BOUND, etc
1712 #define FBC_BOUND_COMMON(UTF8_CODE, TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1713 if (utf8_target) { \
1716 else { /* Not utf8 */ \
1717 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1718 tmp = TEST_NON_UTF8(tmp); \
1719 REXEC_FBC_SCAN( /* advances s while s < strend */ \
1720 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1729 /* Here, things have been set up by the previous code so that tmp is the \
1730 * return of TEST_NON_UTF(s-1) or TEST_UTF8(s-1) (depending on the \
1731 * utf8ness of the target). We also have to check if this matches against \
1732 * the EOS, which we treat as a \n (which is the same value in both UTF-8 \
1733 * or non-UTF8, so can use the non-utf8 test condition even for a UTF-8 \
1735 if (tmp == ! TEST_NON_UTF8('\n')) { \
1742 /* This is the macro to use when we want to see if something that looks like it
1743 * could match, actually does, and if so exits the loop */
1744 #define REXEC_FBC_TRYIT \
1745 if ((reginfo->intuit || regtry(reginfo, &s))) \
1748 /* The only difference between the BOUND and NBOUND cases is that
1749 * REXEC_FBC_TRYIT is called when matched in BOUND, and when non-matched in
1750 * NBOUND. This is accomplished by passing it as either the if or else clause,
1751 * with the other one being empty (PLACEHOLDER is defined as empty).
1753 * The TEST_FOO parameters are for operating on different forms of input, but
1754 * all should be ones that return identically for the same underlying code
1756 #define FBC_BOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1758 FBC_UTF8(TEST_UV, TEST_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1759 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1761 #define FBC_BOUND_A(TEST_NON_UTF8) \
1763 FBC_UTF8_A(TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1764 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1766 #define FBC_NBOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1768 FBC_UTF8(TEST_UV, TEST_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1769 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1771 #define FBC_NBOUND_A(TEST_NON_UTF8) \
1773 FBC_UTF8_A(TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1774 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1778 S_get_break_val_cp_checked(SV* const invlist, const UV cp_in) {
1779 IV cp_out = Perl__invlist_search(invlist, cp_in);
1780 assert(cp_out >= 0);
1783 # define _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp) \
1784 invmap[S_get_break_val_cp_checked(invlist, cp)]
1786 # define _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp) \
1787 invmap[_invlist_search(invlist, cp)]
1790 /* Takes a pointer to an inversion list, a pointer to its corresponding
1791 * inversion map, and a code point, and returns the code point's value
1792 * according to the two arrays. It assumes that all code points have a value.
1793 * This is used as the base macro for macros for particular properties */
1794 #define _generic_GET_BREAK_VAL_CP(invlist, invmap, cp) \
1795 _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp)
1797 /* Same as above, but takes begin, end ptrs to a UTF-8 encoded string instead
1798 * of a code point, returning the value for the first code point in the string.
1799 * And it takes the particular macro name that finds the desired value given a
1800 * code point. Merely convert the UTF-8 to code point and call the cp macro */
1801 #define _generic_GET_BREAK_VAL_UTF8(cp_macro, pos, strend) \
1802 (__ASSERT_(pos < strend) \
1803 /* Note assumes is valid UTF-8 */ \
1804 (cp_macro(utf8_to_uvchr_buf((pos), (strend), NULL))))
1806 /* Returns the GCB value for the input code point */
1807 #define getGCB_VAL_CP(cp) \
1808 _generic_GET_BREAK_VAL_CP( \
1813 /* Returns the GCB value for the first code point in the UTF-8 encoded string
1814 * bounded by pos and strend */
1815 #define getGCB_VAL_UTF8(pos, strend) \
1816 _generic_GET_BREAK_VAL_UTF8(getGCB_VAL_CP, pos, strend)
1818 /* Returns the LB value for the input code point */
1819 #define getLB_VAL_CP(cp) \
1820 _generic_GET_BREAK_VAL_CP( \
1825 /* Returns the LB value for the first code point in the UTF-8 encoded string
1826 * bounded by pos and strend */
1827 #define getLB_VAL_UTF8(pos, strend) \
1828 _generic_GET_BREAK_VAL_UTF8(getLB_VAL_CP, pos, strend)
1831 /* Returns the SB value for the input code point */
1832 #define getSB_VAL_CP(cp) \
1833 _generic_GET_BREAK_VAL_CP( \
1838 /* Returns the SB value for the first code point in the UTF-8 encoded string
1839 * bounded by pos and strend */
1840 #define getSB_VAL_UTF8(pos, strend) \
1841 _generic_GET_BREAK_VAL_UTF8(getSB_VAL_CP, pos, strend)
1843 /* Returns the WB value for the input code point */
1844 #define getWB_VAL_CP(cp) \
1845 _generic_GET_BREAK_VAL_CP( \
1850 /* Returns the WB value for the first code point in the UTF-8 encoded string
1851 * bounded by pos and strend */
1852 #define getWB_VAL_UTF8(pos, strend) \
1853 _generic_GET_BREAK_VAL_UTF8(getWB_VAL_CP, pos, strend)
1855 /* We know what class REx starts with. Try to find this position... */
1856 /* if reginfo->intuit, its a dryrun */
1857 /* annoyingly all the vars in this routine have different names from their counterparts
1858 in regmatch. /grrr */
1860 S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
1861 const char *strend, regmatch_info *reginfo)
1864 const I32 doevery = (prog->intflags & PREGf_SKIP) == 0;
1865 char *pat_string; /* The pattern's exactish string */
1866 char *pat_end; /* ptr to end char of pat_string */
1867 re_fold_t folder; /* Function for computing non-utf8 folds */
1868 const U8 *fold_array; /* array for folding ords < 256 */
1874 I32 tmp = 1; /* Scratch variable? */
1875 const bool utf8_target = reginfo->is_utf8_target;
1876 UV utf8_fold_flags = 0;
1877 const bool is_utf8_pat = reginfo->is_utf8_pat;
1878 bool to_complement = FALSE; /* Invert the result? Taking the xor of this
1879 with a result inverts that result, as 0^1 =
1881 _char_class_number classnum;
1883 RXi_GET_DECL(prog,progi);
1885 PERL_ARGS_ASSERT_FIND_BYCLASS;
1887 /* We know what class it must start with. */
1890 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1892 if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(c)) && ! IN_UTF8_CTYPE_LOCALE) {
1893 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
1900 REXEC_FBC_UTF8_CLASS_SCAN(
1901 reginclass(prog, c, (U8*)s, (U8*) strend, utf8_target));
1903 else if (ANYOF_FLAGS(c)) {
1904 REXEC_FBC_CLASS_SCAN(reginclass(prog,c, (U8*)s, (U8*)s+1, 0));
1907 REXEC_FBC_CLASS_SCAN(ANYOF_BITMAP_TEST(c, *((U8*)s)));
1911 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
1912 assert(! is_utf8_pat);
1915 if (is_utf8_pat || utf8_target) {
1916 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
1917 goto do_exactf_utf8;
1919 fold_array = PL_fold_latin1; /* Latin1 folds are not affected by */
1920 folder = foldEQ_latin1; /* /a, except the sharp s one which */
1921 goto do_exactf_non_utf8; /* isn't dealt with by these */
1923 case EXACTF: /* This node only generated for non-utf8 patterns */
1924 assert(! is_utf8_pat);
1926 utf8_fold_flags = 0;
1927 goto do_exactf_utf8;
1929 fold_array = PL_fold;
1931 goto do_exactf_non_utf8;
1934 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1935 if (is_utf8_pat || utf8_target || IN_UTF8_CTYPE_LOCALE) {
1936 utf8_fold_flags = FOLDEQ_LOCALE;
1937 goto do_exactf_utf8;
1939 fold_array = PL_fold_locale;
1940 folder = foldEQ_locale;
1941 goto do_exactf_non_utf8;
1945 utf8_fold_flags = FOLDEQ_S2_ALREADY_FOLDED;
1947 goto do_exactf_utf8;
1950 if (! utf8_target) { /* All code points in this node require
1951 UTF-8 to express. */
1954 utf8_fold_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
1955 | FOLDEQ_S2_FOLDS_SANE;
1956 goto do_exactf_utf8;
1959 if (is_utf8_pat || utf8_target) {
1960 utf8_fold_flags = is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
1961 goto do_exactf_utf8;
1964 /* Any 'ss' in the pattern should have been replaced by regcomp,
1965 * so we don't have to worry here about this single special case
1966 * in the Latin1 range */
1967 fold_array = PL_fold_latin1;
1968 folder = foldEQ_latin1;
1972 do_exactf_non_utf8: /* Neither pattern nor string are UTF8, and there
1973 are no glitches with fold-length differences
1974 between the target string and pattern */
1976 /* The idea in the non-utf8 EXACTF* cases is to first find the
1977 * first character of the EXACTF* node and then, if necessary,
1978 * case-insensitively compare the full text of the node. c1 is the
1979 * first character. c2 is its fold. This logic will not work for
1980 * Unicode semantics and the german sharp ss, which hence should
1981 * not be compiled into a node that gets here. */
1982 pat_string = STRING(c);
1983 ln = STR_LEN(c); /* length to match in octets/bytes */
1985 /* We know that we have to match at least 'ln' bytes (which is the
1986 * same as characters, since not utf8). If we have to match 3
1987 * characters, and there are only 2 availabe, we know without
1988 * trying that it will fail; so don't start a match past the
1989 * required minimum number from the far end */
1990 e = HOP3c(strend, -((SSize_t)ln), s);
1995 c2 = fold_array[c1];
1996 if (c1 == c2) { /* If char and fold are the same */
1997 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1);
2000 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1 || *(U8*)s == c2);
2008 /* If one of the operands is in utf8, we can't use the simpler folding
2009 * above, due to the fact that many different characters can have the
2010 * same fold, or portion of a fold, or different- length fold */
2011 pat_string = STRING(c);
2012 ln = STR_LEN(c); /* length to match in octets/bytes */
2013 pat_end = pat_string + ln;
2014 lnc = is_utf8_pat /* length to match in characters */
2015 ? utf8_length((U8 *) pat_string, (U8 *) pat_end)
2018 /* We have 'lnc' characters to match in the pattern, but because of
2019 * multi-character folding, each character in the target can match
2020 * up to 3 characters (Unicode guarantees it will never exceed
2021 * this) if it is utf8-encoded; and up to 2 if not (based on the
2022 * fact that the Latin 1 folds are already determined, and the
2023 * only multi-char fold in that range is the sharp-s folding to
2024 * 'ss'. Thus, a pattern character can match as little as 1/3 of a
2025 * string character. Adjust lnc accordingly, rounding up, so that
2026 * if we need to match at least 4+1/3 chars, that really is 5. */
2027 expansion = (utf8_target) ? UTF8_MAX_FOLD_CHAR_EXPAND : 2;
2028 lnc = (lnc + expansion - 1) / expansion;
2030 /* As in the non-UTF8 case, if we have to match 3 characters, and
2031 * only 2 are left, it's guaranteed to fail, so don't start a
2032 * match that would require us to go beyond the end of the string
2034 e = HOP3c(strend, -((SSize_t)lnc), s);
2036 /* XXX Note that we could recalculate e to stop the loop earlier,
2037 * as the worst case expansion above will rarely be met, and as we
2038 * go along we would usually find that e moves further to the left.
2039 * This would happen only after we reached the point in the loop
2040 * where if there were no expansion we should fail. Unclear if
2041 * worth the expense */
2044 char *my_strend= (char *)strend;
2045 if (foldEQ_utf8_flags(s, &my_strend, 0, utf8_target,
2046 pat_string, NULL, ln, is_utf8_pat, utf8_fold_flags)
2047 && (reginfo->intuit || regtry(reginfo, &s)) )
2051 s += (utf8_target) ? UTF8SKIP(s) : 1;
2057 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2058 if (FLAGS(c) != TRADITIONAL_BOUND) {
2059 if (! IN_UTF8_CTYPE_LOCALE) {
2060 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2061 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2066 FBC_BOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8_safe);
2070 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2071 if (FLAGS(c) != TRADITIONAL_BOUND) {
2072 if (! IN_UTF8_CTYPE_LOCALE) {
2073 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2074 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2079 FBC_NBOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8_safe);
2082 case BOUND: /* regcomp.c makes sure that this only has the traditional \b
2084 assert(FLAGS(c) == TRADITIONAL_BOUND);
2086 FBC_BOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8_safe);
2089 case BOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2091 assert(FLAGS(c) == TRADITIONAL_BOUND);
2093 FBC_BOUND_A(isWORDCHAR_A);
2096 case NBOUND: /* regcomp.c makes sure that this only has the traditional \b
2098 assert(FLAGS(c) == TRADITIONAL_BOUND);
2100 FBC_NBOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8_safe);
2103 case NBOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2105 assert(FLAGS(c) == TRADITIONAL_BOUND);
2107 FBC_NBOUND_A(isWORDCHAR_A);
2111 if ((bound_type) FLAGS(c) == TRADITIONAL_BOUND) {
2112 FBC_NBOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8_safe);
2123 switch((bound_type) FLAGS(c)) {
2124 case TRADITIONAL_BOUND:
2125 FBC_BOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8_safe);
2128 if (s == reginfo->strbeg) {
2129 if (reginfo->intuit || regtry(reginfo, &s))
2134 /* Didn't match. Try at the next position (if there is one) */
2135 s += (utf8_target) ? UTF8SKIP(s) : 1;
2136 if (UNLIKELY(s >= reginfo->strend)) {
2142 GCB_enum before = getGCB_VAL_UTF8(
2144 (U8*)(reginfo->strbeg)),
2145 (U8*) reginfo->strend);
2146 while (s < strend) {
2147 GCB_enum after = getGCB_VAL_UTF8((U8*) s,
2148 (U8*) reginfo->strend);
2149 if ( (to_complement ^ isGCB(before,
2151 (U8*) reginfo->strbeg,
2154 && (reginfo->intuit || regtry(reginfo, &s)))
2162 else { /* Not utf8. Everything is a GCB except between CR and
2164 while (s < strend) {
2165 if ((to_complement ^ ( UCHARAT(s - 1) != '\r'
2166 || UCHARAT(s) != '\n'))
2167 && (reginfo->intuit || regtry(reginfo, &s)))
2175 /* And, since this is a bound, it can match after the final
2176 * character in the string */
2177 if ((reginfo->intuit || regtry(reginfo, &s))) {
2183 if (s == reginfo->strbeg) {
2184 if (reginfo->intuit || regtry(reginfo, &s)) {
2187 s += (utf8_target) ? UTF8SKIP(s) : 1;
2188 if (UNLIKELY(s >= reginfo->strend)) {
2194 LB_enum before = getLB_VAL_UTF8(reghop3((U8*)s,
2196 (U8*)(reginfo->strbeg)),
2197 (U8*) reginfo->strend);
2198 while (s < strend) {
2199 LB_enum after = getLB_VAL_UTF8((U8*) s, (U8*) reginfo->strend);
2200 if (to_complement ^ isLB(before,
2202 (U8*) reginfo->strbeg,
2204 (U8*) reginfo->strend,
2206 && (reginfo->intuit || regtry(reginfo, &s)))
2214 else { /* Not utf8. */
2215 LB_enum before = getLB_VAL_CP((U8) *(s -1));
2216 while (s < strend) {
2217 LB_enum after = getLB_VAL_CP((U8) *s);
2218 if (to_complement ^ isLB(before,
2220 (U8*) reginfo->strbeg,
2222 (U8*) reginfo->strend,
2224 && (reginfo->intuit || regtry(reginfo, &s)))
2233 if (reginfo->intuit || regtry(reginfo, &s)) {
2240 if (s == reginfo->strbeg) {
2241 if (reginfo->intuit || regtry(reginfo, &s)) {
2244 s += (utf8_target) ? UTF8SKIP(s) : 1;
2245 if (UNLIKELY(s >= reginfo->strend)) {
2251 SB_enum before = getSB_VAL_UTF8(reghop3((U8*)s,
2253 (U8*)(reginfo->strbeg)),
2254 (U8*) reginfo->strend);
2255 while (s < strend) {
2256 SB_enum after = getSB_VAL_UTF8((U8*) s,
2257 (U8*) reginfo->strend);
2258 if ((to_complement ^ isSB(before,
2260 (U8*) reginfo->strbeg,
2262 (U8*) reginfo->strend,
2264 && (reginfo->intuit || regtry(reginfo, &s)))
2272 else { /* Not utf8. */
2273 SB_enum before = getSB_VAL_CP((U8) *(s -1));
2274 while (s < strend) {
2275 SB_enum after = getSB_VAL_CP((U8) *s);
2276 if ((to_complement ^ isSB(before,
2278 (U8*) reginfo->strbeg,
2280 (U8*) reginfo->strend,
2282 && (reginfo->intuit || regtry(reginfo, &s)))
2291 /* Here are at the final position in the target string. The SB
2292 * value is always true here, so matches, depending on other
2294 if (reginfo->intuit || regtry(reginfo, &s)) {
2301 if (s == reginfo->strbeg) {
2302 if (reginfo->intuit || regtry(reginfo, &s)) {
2305 s += (utf8_target) ? UTF8SKIP(s) : 1;
2306 if (UNLIKELY(s >= reginfo->strend)) {
2312 /* We are at a boundary between char_sub_0 and char_sub_1.
2313 * We also keep track of the value for char_sub_-1 as we
2314 * loop through the line. Context may be needed to make a
2315 * determination, and if so, this can save having to
2317 WB_enum previous = WB_UNKNOWN;
2318 WB_enum before = getWB_VAL_UTF8(
2321 (U8*)(reginfo->strbeg)),
2322 (U8*) reginfo->strend);
2323 while (s < strend) {
2324 WB_enum after = getWB_VAL_UTF8((U8*) s,
2325 (U8*) reginfo->strend);
2326 if ((to_complement ^ isWB(previous,
2329 (U8*) reginfo->strbeg,
2331 (U8*) reginfo->strend,
2333 && (reginfo->intuit || regtry(reginfo, &s)))
2342 else { /* Not utf8. */
2343 WB_enum previous = WB_UNKNOWN;
2344 WB_enum before = getWB_VAL_CP((U8) *(s -1));
2345 while (s < strend) {
2346 WB_enum after = getWB_VAL_CP((U8) *s);
2347 if ((to_complement ^ isWB(previous,
2350 (U8*) reginfo->strbeg,
2352 (U8*) reginfo->strend,
2354 && (reginfo->intuit || regtry(reginfo, &s)))
2364 if (reginfo->intuit || regtry(reginfo, &s)) {
2371 REXEC_FBC_CSCAN(is_LNBREAK_utf8_safe(s, strend),
2372 is_LNBREAK_latin1_safe(s, strend)
2376 /* The argument to all the POSIX node types is the class number to pass to
2377 * _generic_isCC() to build a mask for searching in PL_charclass[] */
2384 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2385 REXEC_FBC_CSCAN(to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(c), (U8 *) s)),
2386 to_complement ^ cBOOL(isFOO_lc(FLAGS(c), *s)));
2401 /* The complement of something that matches only ASCII matches all
2402 * non-ASCII, plus everything in ASCII that isn't in the class. */
2403 REXEC_FBC_UTF8_CLASS_SCAN( ! isASCII_utf8_safe(s, strend)
2404 || ! _generic_isCC_A(*s, FLAGS(c)));
2413 /* Don't need to worry about utf8, as it can match only a single
2414 * byte invariant character. */
2415 REXEC_FBC_CLASS_SCAN(
2416 to_complement ^ cBOOL(_generic_isCC_A(*s, FLAGS(c))));
2424 if (! utf8_target) {
2425 REXEC_FBC_CLASS_SCAN(to_complement ^ cBOOL(_generic_isCC(*s,
2431 classnum = (_char_class_number) FLAGS(c);
2432 if (classnum < _FIRST_NON_SWASH_CC) {
2433 while (s < strend) {
2435 /* We avoid loading in the swash as long as possible, but
2436 * should we have to, we jump to a separate loop. This
2437 * extra 'if' statement is what keeps this code from being
2438 * just a call to REXEC_FBC_UTF8_CLASS_SCAN() */
2439 if (UTF8_IS_ABOVE_LATIN1(*s)) {
2440 goto found_above_latin1;
2442 if ((UTF8_IS_INVARIANT(*s)
2443 && to_complement ^ cBOOL(_generic_isCC((U8) *s,
2445 || ( UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(s, strend)
2446 && to_complement ^ cBOOL(
2447 _generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(*s,
2451 if (tmp && (reginfo->intuit || regtry(reginfo, &s)))
2463 else switch (classnum) { /* These classes are implemented as
2465 case _CC_ENUM_SPACE:
2466 REXEC_FBC_UTF8_CLASS_SCAN(
2467 to_complement ^ cBOOL(isSPACE_utf8_safe(s, strend)));
2470 case _CC_ENUM_BLANK:
2471 REXEC_FBC_UTF8_CLASS_SCAN(
2472 to_complement ^ cBOOL(isBLANK_utf8_safe(s, strend)));
2475 case _CC_ENUM_XDIGIT:
2476 REXEC_FBC_UTF8_CLASS_SCAN(
2477 to_complement ^ cBOOL(isXDIGIT_utf8_safe(s, strend)));
2480 case _CC_ENUM_VERTSPACE:
2481 REXEC_FBC_UTF8_CLASS_SCAN(
2482 to_complement ^ cBOOL(isVERTWS_utf8_safe(s, strend)));
2485 case _CC_ENUM_CNTRL:
2486 REXEC_FBC_UTF8_CLASS_SCAN(
2487 to_complement ^ cBOOL(isCNTRL_utf8_safe(s, strend)));
2491 Perl_croak(aTHX_ "panic: find_byclass() node %d='%s' has an unexpected character class '%d'", OP(c), PL_reg_name[OP(c)], classnum);
2492 NOT_REACHED; /* NOTREACHED */
2497 found_above_latin1: /* Here we have to load a swash to get the result
2498 for the current code point */
2499 if (! PL_utf8_swash_ptrs[classnum]) {
2500 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
2501 PL_utf8_swash_ptrs[classnum] =
2502 _core_swash_init("utf8",
2505 PL_XPosix_ptrs[classnum], &flags);
2508 /* This is a copy of the loop above for swash classes, though using the
2509 * FBC macro instead of being expanded out. Since we've loaded the
2510 * swash, we don't have to check for that each time through the loop */
2511 REXEC_FBC_UTF8_CLASS_SCAN(
2512 to_complement ^ cBOOL(_generic_utf8_safe(
2516 swash_fetch(PL_utf8_swash_ptrs[classnum],
2524 /* what trie are we using right now */
2525 reg_ac_data *aho = (reg_ac_data*)progi->data->data[ ARG( c ) ];
2526 reg_trie_data *trie = (reg_trie_data*)progi->data->data[ aho->trie ];
2527 HV *widecharmap = MUTABLE_HV(progi->data->data[ aho->trie + 1 ]);
2529 const char *last_start = strend - trie->minlen;
2531 const char *real_start = s;
2533 STRLEN maxlen = trie->maxlen;
2535 U8 **points; /* map of where we were in the input string
2536 when reading a given char. For ASCII this
2537 is unnecessary overhead as the relationship
2538 is always 1:1, but for Unicode, especially
2539 case folded Unicode this is not true. */
2540 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
2544 GET_RE_DEBUG_FLAGS_DECL;
2546 /* We can't just allocate points here. We need to wrap it in
2547 * an SV so it gets freed properly if there is a croak while
2548 * running the match */
2551 sv_points=newSV(maxlen * sizeof(U8 *));
2552 SvCUR_set(sv_points,
2553 maxlen * sizeof(U8 *));
2554 SvPOK_on(sv_points);
2555 sv_2mortal(sv_points);
2556 points=(U8**)SvPV_nolen(sv_points );
2557 if ( trie_type != trie_utf8_fold
2558 && (trie->bitmap || OP(c)==AHOCORASICKC) )
2561 bitmap=(U8*)trie->bitmap;
2563 bitmap=(U8*)ANYOF_BITMAP(c);
2565 /* this is the Aho-Corasick algorithm modified a touch
2566 to include special handling for long "unknown char" sequences.
2567 The basic idea being that we use AC as long as we are dealing
2568 with a possible matching char, when we encounter an unknown char
2569 (and we have not encountered an accepting state) we scan forward
2570 until we find a legal starting char.
2571 AC matching is basically that of trie matching, except that when
2572 we encounter a failing transition, we fall back to the current
2573 states "fail state", and try the current char again, a process
2574 we repeat until we reach the root state, state 1, or a legal
2575 transition. If we fail on the root state then we can either
2576 terminate if we have reached an accepting state previously, or
2577 restart the entire process from the beginning if we have not.
2580 while (s <= last_start) {
2581 const U32 uniflags = UTF8_ALLOW_DEFAULT;
2589 U8 *uscan = (U8*)NULL;
2590 U8 *leftmost = NULL;
2592 U32 accepted_word= 0;
2596 while ( state && uc <= (U8*)strend ) {
2598 U32 word = aho->states[ state ].wordnum;
2602 DEBUG_TRIE_EXECUTE_r(
2603 if ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2604 dump_exec_pos( (char *)uc, c, strend, real_start,
2605 (char *)uc, utf8_target, 0 );
2606 Perl_re_printf( aTHX_
2607 " Scanning for legal start char...\n");
2611 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2615 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2621 if (uc >(U8*)last_start) break;
2625 U8 *lpos= points[ (pointpos - trie->wordinfo[word].len) % maxlen ];
2626 if (!leftmost || lpos < leftmost) {
2627 DEBUG_r(accepted_word=word);
2633 points[pointpos++ % maxlen]= uc;
2634 if (foldlen || uc < (U8*)strend) {
2635 REXEC_TRIE_READ_CHAR(trie_type, trie,
2637 uscan, len, uvc, charid, foldlen,
2639 DEBUG_TRIE_EXECUTE_r({
2640 dump_exec_pos( (char *)uc, c, strend,
2641 real_start, s, utf8_target, 0);
2642 Perl_re_printf( aTHX_
2643 " Charid:%3u CP:%4" UVxf " ",
2655 word = aho->states[ state ].wordnum;
2657 base = aho->states[ state ].trans.base;
2659 DEBUG_TRIE_EXECUTE_r({
2661 dump_exec_pos( (char *)uc, c, strend, real_start,
2662 s, utf8_target, 0 );
2663 Perl_re_printf( aTHX_
2664 "%sState: %4" UVxf ", word=%" UVxf,
2665 failed ? " Fail transition to " : "",
2666 (UV)state, (UV)word);
2672 ( ((offset = base + charid
2673 - 1 - trie->uniquecharcount)) >= 0)
2674 && ((U32)offset < trie->lasttrans)
2675 && trie->trans[offset].check == state
2676 && (tmp=trie->trans[offset].next))
2678 DEBUG_TRIE_EXECUTE_r(
2679 Perl_re_printf( aTHX_ " - legal\n"));
2684 DEBUG_TRIE_EXECUTE_r(
2685 Perl_re_printf( aTHX_ " - fail\n"));
2687 state = aho->fail[state];
2691 /* we must be accepting here */
2692 DEBUG_TRIE_EXECUTE_r(
2693 Perl_re_printf( aTHX_ " - accepting\n"));
2702 if (!state) state = 1;
2705 if ( aho->states[ state ].wordnum ) {
2706 U8 *lpos = points[ (pointpos - trie->wordinfo[aho->states[ state ].wordnum].len) % maxlen ];
2707 if (!leftmost || lpos < leftmost) {
2708 DEBUG_r(accepted_word=aho->states[ state ].wordnum);
2713 s = (char*)leftmost;
2714 DEBUG_TRIE_EXECUTE_r({
2715 Perl_re_printf( aTHX_ "Matches word #%" UVxf " at position %" IVdf ". Trying full pattern...\n",
2716 (UV)accepted_word, (IV)(s - real_start)
2719 if (reginfo->intuit || regtry(reginfo, &s)) {
2725 DEBUG_TRIE_EXECUTE_r({
2726 Perl_re_printf( aTHX_ "Pattern failed. Looking for new start point...\n");
2729 DEBUG_TRIE_EXECUTE_r(
2730 Perl_re_printf( aTHX_ "No match.\n"));
2739 Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
2746 /* set RX_SAVED_COPY, RX_SUBBEG etc.
2747 * flags have same meanings as with regexec_flags() */
2750 S_reg_set_capture_string(pTHX_ REGEXP * const rx,
2757 struct regexp *const prog = ReANY(rx);
2759 if (flags & REXEC_COPY_STR) {
2762 DEBUG_C(Perl_re_printf( aTHX_
2763 "Copy on write: regexp capture, type %d\n",
2765 /* Create a new COW SV to share the match string and store
2766 * in saved_copy, unless the current COW SV in saved_copy
2767 * is valid and suitable for our purpose */
2768 if (( prog->saved_copy
2769 && SvIsCOW(prog->saved_copy)
2770 && SvPOKp(prog->saved_copy)
2773 && SvPVX(sv) == SvPVX(prog->saved_copy)))
2775 /* just reuse saved_copy SV */
2776 if (RXp_MATCH_COPIED(prog)) {
2777 Safefree(prog->subbeg);
2778 RXp_MATCH_COPIED_off(prog);
2782 /* create new COW SV to share string */
2783 RXp_MATCH_COPY_FREE(prog);
2784 prog->saved_copy = sv_setsv_cow(prog->saved_copy, sv);
2786 prog->subbeg = (char *)SvPVX_const(prog->saved_copy);
2787 assert (SvPOKp(prog->saved_copy));
2788 prog->sublen = strend - strbeg;
2789 prog->suboffset = 0;
2790 prog->subcoffset = 0;
2795 SSize_t max = strend - strbeg;
2798 if ( (flags & REXEC_COPY_SKIP_POST)
2799 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2800 && !(PL_sawampersand & SAWAMPERSAND_RIGHT)
2801 ) { /* don't copy $' part of string */
2804 /* calculate the right-most part of the string covered
2805 * by a capture. Due to lookahead, this may be to
2806 * the right of $&, so we have to scan all captures */
2807 while (n <= prog->lastparen) {
2808 if (prog->offs[n].end > max)
2809 max = prog->offs[n].end;
2813 max = (PL_sawampersand & SAWAMPERSAND_LEFT)
2814 ? prog->offs[0].start
2816 assert(max >= 0 && max <= strend - strbeg);
2819 if ( (flags & REXEC_COPY_SKIP_PRE)
2820 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2821 && !(PL_sawampersand & SAWAMPERSAND_LEFT)
2822 ) { /* don't copy $` part of string */
2825 /* calculate the left-most part of the string covered
2826 * by a capture. Due to lookbehind, this may be to
2827 * the left of $&, so we have to scan all captures */
2828 while (min && n <= prog->lastparen) {
2829 if ( prog->offs[n].start != -1
2830 && prog->offs[n].start < min)
2832 min = prog->offs[n].start;
2836 if ((PL_sawampersand & SAWAMPERSAND_RIGHT)
2837 && min > prog->offs[0].end
2839 min = prog->offs[0].end;
2843 assert(min >= 0 && min <= max && min <= strend - strbeg);
2846 if (RXp_MATCH_COPIED(prog)) {
2847 if (sublen > prog->sublen)
2849 (char*)saferealloc(prog->subbeg, sublen+1);
2852 prog->subbeg = (char*)safemalloc(sublen+1);
2853 Copy(strbeg + min, prog->subbeg, sublen, char);
2854 prog->subbeg[sublen] = '\0';
2855 prog->suboffset = min;
2856 prog->sublen = sublen;
2857 RXp_MATCH_COPIED_on(prog);
2859 prog->subcoffset = prog->suboffset;
2860 if (prog->suboffset && utf8_target) {
2861 /* Convert byte offset to chars.
2862 * XXX ideally should only compute this if @-/@+
2863 * has been seen, a la PL_sawampersand ??? */
2865 /* If there's a direct correspondence between the
2866 * string which we're matching and the original SV,
2867 * then we can use the utf8 len cache associated with
2868 * the SV. In particular, it means that under //g,
2869 * sv_pos_b2u() will use the previously cached
2870 * position to speed up working out the new length of
2871 * subcoffset, rather than counting from the start of
2872 * the string each time. This stops
2873 * $x = "\x{100}" x 1E6; 1 while $x =~ /(.)/g;
2874 * from going quadratic */
2875 if (SvPOKp(sv) && SvPVX(sv) == strbeg)
2876 prog->subcoffset = sv_pos_b2u_flags(sv, prog->subcoffset,
2877 SV_GMAGIC|SV_CONST_RETURN);
2879 prog->subcoffset = utf8_length((U8*)strbeg,
2880 (U8*)(strbeg+prog->suboffset));
2884 RXp_MATCH_COPY_FREE(prog);
2885 prog->subbeg = strbeg;
2886 prog->suboffset = 0;
2887 prog->subcoffset = 0;
2888 prog->sublen = strend - strbeg;
2896 - regexec_flags - match a regexp against a string
2899 Perl_regexec_flags(pTHX_ REGEXP * const rx, char *stringarg, char *strend,
2900 char *strbeg, SSize_t minend, SV *sv, void *data, U32 flags)
2901 /* stringarg: the point in the string at which to begin matching */
2902 /* strend: pointer to null at end of string */
2903 /* strbeg: real beginning of string */
2904 /* minend: end of match must be >= minend bytes after stringarg. */
2905 /* sv: SV being matched: only used for utf8 flag, pos() etc; string
2906 * itself is accessed via the pointers above */
2907 /* data: May be used for some additional optimizations.
2908 Currently unused. */
2909 /* flags: For optimizations. See REXEC_* in regexp.h */
2912 struct regexp *const prog = ReANY(rx);
2916 SSize_t minlen; /* must match at least this many chars */
2917 SSize_t dontbother = 0; /* how many characters not to try at end */
2918 const bool utf8_target = cBOOL(DO_UTF8(sv));
2920 RXi_GET_DECL(prog,progi);
2921 regmatch_info reginfo_buf; /* create some info to pass to regtry etc */
2922 regmatch_info *const reginfo = ®info_buf;
2923 regexp_paren_pair *swap = NULL;
2925 GET_RE_DEBUG_FLAGS_DECL;
2927 PERL_ARGS_ASSERT_REGEXEC_FLAGS;
2928 PERL_UNUSED_ARG(data);
2930 /* Be paranoid... */
2932 Perl_croak(aTHX_ "NULL regexp parameter");
2936 debug_start_match(rx, utf8_target, stringarg, strend,
2940 startpos = stringarg;
2942 /* set these early as they may be used by the HOP macros below */
2943 reginfo->strbeg = strbeg;
2944 reginfo->strend = strend;
2945 reginfo->is_utf8_target = cBOOL(utf8_target);
2947 if (prog->intflags & PREGf_GPOS_SEEN) {
2950 /* set reginfo->ganch, the position where \G can match */
2953 (flags & REXEC_IGNOREPOS)
2954 ? stringarg /* use start pos rather than pos() */
2955 : ((mg = mg_find_mglob(sv)) && mg->mg_len >= 0)
2956 /* Defined pos(): */
2957 ? strbeg + MgBYTEPOS(mg, sv, strbeg, strend-strbeg)
2958 : strbeg; /* pos() not defined; use start of string */
2960 DEBUG_GPOS_r(Perl_re_printf( aTHX_
2961 "GPOS ganch set to strbeg[%" IVdf "]\n", (IV)(reginfo->ganch - strbeg)));
2963 /* in the presence of \G, we may need to start looking earlier in
2964 * the string than the suggested start point of stringarg:
2965 * if prog->gofs is set, then that's a known, fixed minimum
2968 * /ab|c\G/: gofs = 1
2969 * or if the minimum offset isn't known, then we have to go back
2970 * to the start of the string, e.g. /w+\G/
2973 if (prog->intflags & PREGf_ANCH_GPOS) {
2975 startpos = HOPBACKc(reginfo->ganch, prog->gofs);
2977 ((flags & REXEC_FAIL_ON_UNDERFLOW) && startpos < stringarg))
2979 DEBUG_r(Perl_re_printf( aTHX_
2980 "fail: ganch-gofs before earliest possible start\n"));
2985 startpos = reginfo->ganch;
2987 else if (prog->gofs) {
2988 startpos = HOPBACKc(startpos, prog->gofs);
2992 else if (prog->intflags & PREGf_GPOS_FLOAT)
2996 minlen = prog->minlen;
2997 if ((startpos + minlen) > strend || startpos < strbeg) {
2998 DEBUG_r(Perl_re_printf( aTHX_
2999 "Regex match can't succeed, so not even tried\n"));
3003 /* at the end of this function, we'll do a LEAVE_SCOPE(oldsave),
3004 * which will call destuctors to reset PL_regmatch_state, free higher
3005 * PL_regmatch_slabs, and clean up regmatch_info_aux and
3006 * regmatch_info_aux_eval */
3008 oldsave = PL_savestack_ix;
3012 if ((prog->extflags & RXf_USE_INTUIT)
3013 && !(flags & REXEC_CHECKED))
3015 s = re_intuit_start(rx, sv, strbeg, startpos, strend,
3020 if (prog->extflags & RXf_CHECK_ALL) {
3021 /* we can match based purely on the result of INTUIT.
3022 * Set up captures etc just for $& and $-[0]
3023 * (an intuit-only match wont have $1,$2,..) */
3024 assert(!prog->nparens);
3026 /* s/// doesn't like it if $& is earlier than where we asked it to
3027 * start searching (which can happen on something like /.\G/) */
3028 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
3031 /* this should only be possible under \G */
3032 assert(prog->intflags & PREGf_GPOS_SEEN);
3033 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
3034 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3038 /* match via INTUIT shouldn't have any captures.
3039 * Let @-, @+, $^N know */
3040 prog->lastparen = prog->lastcloseparen = 0;
3041 RXp_MATCH_UTF8_set(prog, utf8_target);
3042 prog->offs[0].start = s - strbeg;
3043 prog->offs[0].end = utf8_target
3044 ? (char*)utf8_hop((U8*)s, prog->minlenret) - strbeg
3045 : s - strbeg + prog->minlenret;
3046 if ( !(flags & REXEC_NOT_FIRST) )
3047 S_reg_set_capture_string(aTHX_ rx,
3049 sv, flags, utf8_target);
3055 multiline = prog->extflags & RXf_PMf_MULTILINE;
3057 if (strend - s < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
3058 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
3059 "String too short [regexec_flags]...\n"));
3063 /* Check validity of program. */
3064 if (UCHARAT(progi->program) != REG_MAGIC) {
3065 Perl_croak(aTHX_ "corrupted regexp program");
3068 RXp_MATCH_TAINTED_off(prog);
3069 RXp_MATCH_UTF8_set(prog, utf8_target);
3071 reginfo->prog = rx; /* Yes, sorry that this is confusing. */
3072 reginfo->intuit = 0;
3073 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
3074 reginfo->warned = FALSE;
3076 reginfo->poscache_maxiter = 0; /* not yet started a countdown */
3077 /* see how far we have to get to not match where we matched before */
3078 reginfo->till = stringarg + minend;
3080 if (prog->extflags & RXf_EVAL_SEEN && SvPADTMP(sv)) {
3081 /* SAVEFREESV, not sv_mortalcopy, as this SV must last until after
3082 S_cleanup_regmatch_info_aux has executed (registered by
3083 SAVEDESTRUCTOR_X below). S_cleanup_regmatch_info_aux modifies
3084 magic belonging to this SV.
3085 Not newSVsv, either, as it does not COW.
3087 reginfo->sv = newSV(0);
3088 SvSetSV_nosteal(reginfo->sv, sv);
3089 SAVEFREESV(reginfo->sv);
3092 /* reserve next 2 or 3 slots in PL_regmatch_state:
3093 * slot N+0: may currently be in use: skip it
3094 * slot N+1: use for regmatch_info_aux struct
3095 * slot N+2: use for regmatch_info_aux_eval struct if we have (?{})'s
3096 * slot N+3: ready for use by regmatch()
3100 regmatch_state *old_regmatch_state;
3101 regmatch_slab *old_regmatch_slab;
3102 int i, max = (prog->extflags & RXf_EVAL_SEEN) ? 2 : 1;
3104 /* on first ever match, allocate first slab */
3105 if (!PL_regmatch_slab) {
3106 Newx(PL_regmatch_slab, 1, regmatch_slab);
3107 PL_regmatch_slab->prev = NULL;
3108 PL_regmatch_slab->next = NULL;
3109 PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
3112 old_regmatch_state = PL_regmatch_state;
3113 old_regmatch_slab = PL_regmatch_slab;
3115 for (i=0; i <= max; i++) {
3117 reginfo->info_aux = &(PL_regmatch_state->u.info_aux);
3119 reginfo->info_aux_eval =
3120 reginfo->info_aux->info_aux_eval =
3121 &(PL_regmatch_state->u.info_aux_eval);
3123 if (++PL_regmatch_state > SLAB_LAST(PL_regmatch_slab))
3124 PL_regmatch_state = S_push_slab(aTHX);
3127 /* note initial PL_regmatch_state position; at end of match we'll
3128 * pop back to there and free any higher slabs */
3130 reginfo->info_aux->old_regmatch_state = old_regmatch_state;
3131 reginfo->info_aux->old_regmatch_slab = old_regmatch_slab;
3132 reginfo->info_aux->poscache = NULL;
3134 SAVEDESTRUCTOR_X(S_cleanup_regmatch_info_aux, reginfo->info_aux);
3136 if ((prog->extflags & RXf_EVAL_SEEN))
3137 S_setup_eval_state(aTHX_ reginfo);
3139 reginfo->info_aux_eval = reginfo->info_aux->info_aux_eval = NULL;
3142 /* If there is a "must appear" string, look for it. */
3144 if (PL_curpm && (PM_GETRE(PL_curpm) == rx)) {
3145 /* We have to be careful. If the previous successful match
3146 was from this regex we don't want a subsequent partially
3147 successful match to clobber the old results.
3148 So when we detect this possibility we add a swap buffer
3149 to the re, and switch the buffer each match. If we fail,
3150 we switch it back; otherwise we leave it swapped.
3153 /* do we need a save destructor here for eval dies? */
3154 Newxz(prog->offs, (prog->nparens + 1), regexp_paren_pair);
3155 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_
3156 "rex=0x%" UVxf " saving offs: orig=0x%" UVxf " new=0x%" UVxf "\n",
3164 if (prog->recurse_locinput)
3165 Zero(prog->recurse_locinput,prog->nparens + 1, char *);
3167 /* Simplest case: anchored match need be tried only once, or with
3168 * MBOL, only at the beginning of each line.
3170 * Note that /.*.../ sets PREGf_IMPLICIT|MBOL, while /.*.../s sets
3171 * PREGf_IMPLICIT|SBOL. The idea is that with /.*.../s, if it doesn't
3172 * match at the start of the string then it won't match anywhere else
3173 * either; while with /.*.../, if it doesn't match at the beginning,
3174 * the earliest it could match is at the start of the next line */
3176 if (prog->intflags & (PREGf_ANCH & ~PREGf_ANCH_GPOS)) {
3179 if (regtry(reginfo, &s))
3182 if (!(prog->intflags & PREGf_ANCH_MBOL))
3185 /* didn't match at start, try at other newline positions */
3188 dontbother = minlen - 1;
3189 end = HOP3c(strend, -dontbother, strbeg) - 1;
3191 /* skip to next newline */
3193 while (s <= end) { /* note it could be possible to match at the end of the string */
3194 /* NB: newlines are the same in unicode as they are in latin */
3197 if (prog->check_substr || prog->check_utf8) {
3198 /* note that with PREGf_IMPLICIT, intuit can only fail
3199 * or return the start position, so it's of limited utility.
3200 * Nevertheless, I made the decision that the potential for
3201 * quick fail was still worth it - DAPM */
3202 s = re_intuit_start(rx, sv, strbeg, s, strend, flags, NULL);
3206 if (regtry(reginfo, &s))
3210 } /* end anchored search */
3212 if (prog->intflags & PREGf_ANCH_GPOS)
3214 /* PREGf_ANCH_GPOS should never be true if PREGf_GPOS_SEEN is not true */
3215 assert(prog->intflags & PREGf_GPOS_SEEN);
3216 /* For anchored \G, the only position it can match from is
3217 * (ganch-gofs); we already set startpos to this above; if intuit
3218 * moved us on from there, we can't possibly succeed */
3219 assert(startpos == HOPBACKc(reginfo->ganch, prog->gofs));
3220 if (s == startpos && regtry(reginfo, &s))
3225 /* Messy cases: unanchored match. */
3226 if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
3227 /* we have /x+whatever/ */
3228 /* it must be a one character string (XXXX Except is_utf8_pat?) */
3234 if (! prog->anchored_utf8) {
3235 to_utf8_substr(prog);
3237 ch = SvPVX_const(prog->anchored_utf8)[0];
3240 DEBUG_EXECUTE_r( did_match = 1 );
3241 if (regtry(reginfo, &s)) goto got_it;
3243 while (s < strend && *s == ch)
3250 if (! prog->anchored_substr) {
3251 if (! to_byte_substr(prog)) {
3252 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3255 ch = SvPVX_const(prog->anchored_substr)[0];
3258 DEBUG_EXECUTE_r( did_match = 1 );
3259 if (regtry(reginfo, &s)) goto got_it;
3261 while (s < strend && *s == ch)
3266 DEBUG_EXECUTE_r(if (!did_match)
3267 Perl_re_printf( aTHX_
3268 "Did not find anchored character...\n")
3271 else if (prog->anchored_substr != NULL
3272 || prog->anchored_utf8 != NULL
3273 || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
3274 && prog->float_max_offset < strend - s)) {
3279 char *last1; /* Last position checked before */
3283 if (prog->anchored_substr || prog->anchored_utf8) {
3285 if (! prog->anchored_utf8) {
3286 to_utf8_substr(prog);
3288 must = prog->anchored_utf8;
3291 if (! prog->anchored_substr) {
3292 if (! to_byte_substr(prog)) {
3293 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3296 must = prog->anchored_substr;
3298 back_max = back_min = prog->anchored_offset;
3301 if (! prog->float_utf8) {
3302 to_utf8_substr(prog);
3304 must = prog->float_utf8;
3307 if (! prog->float_substr) {
3308 if (! to_byte_substr(prog)) {
3309 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3312 must = prog->float_substr;
3314 back_max = prog->float_max_offset;
3315 back_min = prog->float_min_offset;
3321 last = HOP3c(strend, /* Cannot start after this */
3322 -(SSize_t)(CHR_SVLEN(must)
3323 - (SvTAIL(must) != 0) + back_min), strbeg);
3325 if (s > reginfo->strbeg)
3326 last1 = HOPc(s, -1);
3328 last1 = s - 1; /* bogus */
3330 /* XXXX check_substr already used to find "s", can optimize if
3331 check_substr==must. */
3333 strend = HOPc(strend, -dontbother);
3334 while ( (s <= last) &&
3335 (s = fbm_instr((unsigned char*)HOP4c(s, back_min, strbeg, strend),
3336 (unsigned char*)strend, must,
3337 multiline ? FBMrf_MULTILINE : 0)) ) {
3338 DEBUG_EXECUTE_r( did_match = 1 );
3339 if (HOPc(s, -back_max) > last1) {
3340 last1 = HOPc(s, -back_min);
3341 s = HOPc(s, -back_max);
3344 char * const t = (last1 >= reginfo->strbeg)
3345 ? HOPc(last1, 1) : last1 + 1;
3347 last1 = HOPc(s, -back_min);
3351 while (s <= last1) {
3352 if (regtry(reginfo, &s))
3355 s++; /* to break out of outer loop */
3362 while (s <= last1) {
3363 if (regtry(reginfo, &s))
3369 DEBUG_EXECUTE_r(if (!did_match) {
3370 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
3371 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
3372 Perl_re_printf( aTHX_ "Did not find %s substr %s%s...\n",
3373 ((must == prog->anchored_substr || must == prog->anchored_utf8)
3374 ? "anchored" : "floating"),
3375 quoted, RE_SV_TAIL(must));
3379 else if ( (c = progi->regstclass) ) {
3381 const OPCODE op = OP(progi->regstclass);
3382 /* don't bother with what can't match */
3383 if (PL_regkind[op] != EXACT && PL_regkind[op] != TRIE)
3384 strend = HOPc(strend, -(minlen - 1));
3387 SV * const prop = sv_newmortal();
3388 regprop(prog, prop, c, reginfo, NULL);
3390 RE_PV_QUOTED_DECL(quoted,utf8_target,PERL_DEBUG_PAD_ZERO(1),
3391 s,strend-s,PL_dump_re_max_len);
3392 Perl_re_printf( aTHX_
3393 "Matching stclass %.*s against %s (%d bytes)\n",
3394 (int)SvCUR(prop), SvPVX_const(prop),
3395 quoted, (int)(strend - s));
3398 if (find_byclass(prog, c, s, strend, reginfo))
3400 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "Contradicts stclass... [regexec_flags]\n"));
3404 if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
3412 if (! prog->float_utf8) {
3413 to_utf8_substr(prog);
3415 float_real = prog->float_utf8;
3418 if (! prog->float_substr) {
3419 if (! to_byte_substr(prog)) {
3420 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3423 float_real = prog->float_substr;
3426 little = SvPV_const(float_real, len);
3427 if (SvTAIL(float_real)) {
3428 /* This means that float_real contains an artificial \n on
3429 * the end due to the presence of something like this:
3430 * /foo$/ where we can match both "foo" and "foo\n" at the
3431 * end of the string. So we have to compare the end of the
3432 * string first against the float_real without the \n and
3433 * then against the full float_real with the string. We
3434 * have to watch out for cases where the string might be
3435 * smaller than the float_real or the float_real without
3437 char *checkpos= strend - len;
3439 Perl_re_printf( aTHX_
3440 "%sChecking for float_real.%s\n",
3441 PL_colors[4], PL_colors[5]));
3442 if (checkpos + 1 < strbeg) {
3443 /* can't match, even if we remove the trailing \n
3444 * string is too short to match */
3446 Perl_re_printf( aTHX_
3447 "%sString shorter than required trailing substring, cannot match.%s\n",
3448 PL_colors[4], PL_colors[5]));
3450 } else if (memEQ(checkpos + 1, little, len - 1)) {
3451 /* can match, the end of the string matches without the
3453 last = checkpos + 1;
3454 } else if (checkpos < strbeg) {
3455 /* cant match, string is too short when the "\n" is
3458 Perl_re_printf( aTHX_
3459 "%sString does not contain required trailing substring, cannot match.%s\n",
3460 PL_colors[4], PL_colors[5]));
3462 } else if (!multiline) {
3463 /* non multiline match, so compare with the "\n" at the
3464 * end of the string */
3465 if (memEQ(checkpos, little, len)) {
3469 Perl_re_printf( aTHX_
3470 "%sString does not contain required trailing substring, cannot match.%s\n",
3471 PL_colors[4], PL_colors[5]));
3475 /* multiline match, so we have to search for a place
3476 * where the full string is located */
3482 last = rninstr(s, strend, little, little + len);
3484 last = strend; /* matching "$" */
3487 /* at one point this block contained a comment which was
3488 * probably incorrect, which said that this was a "should not
3489 * happen" case. Even if it was true when it was written I am
3490 * pretty sure it is not anymore, so I have removed the comment
3491 * and replaced it with this one. Yves */
3493 Perl_re_printf( aTHX_
3494 "%sString does not contain required substring, cannot match.%s\n",
3495 PL_colors[4], PL_colors[5]
3499 dontbother = strend - last + prog->float_min_offset;
3501 if (minlen && (dontbother < minlen))
3502 dontbother = minlen - 1;
3503 strend -= dontbother; /* this one's always in bytes! */
3504 /* We don't know much -- general case. */
3507 if (regtry(reginfo, &s))
3516 if (regtry(reginfo, &s))
3518 } while (s++ < strend);
3526 /* s/// doesn't like it if $& is earlier than where we asked it to
3527 * start searching (which can happen on something like /.\G/) */
3528 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
3529 && (prog->offs[0].start < stringarg - strbeg))
3531 /* this should only be possible under \G */
3532 assert(prog->intflags & PREGf_GPOS_SEEN);
3533 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
3534 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3540 Perl_re_exec_indentf( aTHX_
3541 "rex=0x%" UVxf " freeing offs: 0x%" UVxf "\n",
3549 /* clean up; this will trigger destructors that will free all slabs
3550 * above the current one, and cleanup the regmatch_info_aux
3551 * and regmatch_info_aux_eval sructs */
3553 LEAVE_SCOPE(oldsave);
3555 if (RXp_PAREN_NAMES(prog))
3556 (void)hv_iterinit(RXp_PAREN_NAMES(prog));
3558 /* make sure $`, $&, $', and $digit will work later */
3559 if ( !(flags & REXEC_NOT_FIRST) )
3560 S_reg_set_capture_string(aTHX_ rx,
3561 strbeg, reginfo->strend,
3562 sv, flags, utf8_target);
3567 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%sMatch failed%s\n",
3568 PL_colors[4], PL_colors[5]));
3570 /* clean up; this will trigger destructors that will free all slabs
3571 * above the current one, and cleanup the regmatch_info_aux
3572 * and regmatch_info_aux_eval sructs */
3574 LEAVE_SCOPE(oldsave);
3577 /* we failed :-( roll it back */
3578 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_
3579 "rex=0x%" UVxf " rolling back offs: freeing=0x%" UVxf " restoring=0x%" UVxf "\n",
3585 Safefree(prog->offs);
3592 /* Set which rex is pointed to by PL_reg_curpm, handling ref counting.
3593 * Do inc before dec, in case old and new rex are the same */
3594 #define SET_reg_curpm(Re2) \
3595 if (reginfo->info_aux_eval) { \
3596 (void)ReREFCNT_inc(Re2); \
3597 ReREFCNT_dec(PM_GETRE(PL_reg_curpm)); \
3598 PM_SETRE((PL_reg_curpm), (Re2)); \
3603 - regtry - try match at specific point
3605 STATIC bool /* 0 failure, 1 success */
3606 S_regtry(pTHX_ regmatch_info *reginfo, char **startposp)
3609 REGEXP *const rx = reginfo->prog;
3610 regexp *const prog = ReANY(rx);
3613 U32 depth = 0; /* used by REGCP_SET */
3615 RXi_GET_DECL(prog,progi);
3616 GET_RE_DEBUG_FLAGS_DECL;
3618 PERL_ARGS_ASSERT_REGTRY;
3620 reginfo->cutpoint=NULL;
3622 prog->offs[0].start = *startposp - reginfo->strbeg;
3623 prog->lastparen = 0;
3624 prog->lastcloseparen = 0;
3626 /* XXXX What this code is doing here?!!! There should be no need
3627 to do this again and again, prog->lastparen should take care of
3630 /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
3631 * Actually, the code in regcppop() (which Ilya may be meaning by
3632 * prog->lastparen), is not needed at all by the test suite
3633 * (op/regexp, op/pat, op/split), but that code is needed otherwise
3634 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
3635 * Meanwhile, this code *is* needed for the
3636 * above-mentioned test suite tests to succeed. The common theme
3637 * on those tests seems to be returning null fields from matches.
3638 * --jhi updated by dapm */
3640 /* After encountering a variant of the issue mentioned above I think
3641 * the point Ilya was making is that if we properly unwind whenever
3642 * we set lastparen to a smaller value then we should not need to do
3643 * this every time, only when needed. So if we have tests that fail if
3644 * we remove this, then it suggests somewhere else we are improperly
3645 * unwinding the lastparen/paren buffers. See UNWIND_PARENS() and
3646 * places it is called, and related regcp() routines. - Yves */
3648 if (prog->nparens) {
3649 regexp_paren_pair *pp = prog->offs;
3651 for (i = prog->nparens; i > (I32)prog->lastparen; i--) {
3659 result = regmatch(reginfo, *startposp, progi->program + 1);
3661 prog->offs[0].end = result;
3664 if (reginfo->cutpoint)
3665 *startposp= reginfo->cutpoint;
3666 REGCP_UNWIND(lastcp);
3671 #define sayYES goto yes
3672 #define sayNO goto no
3673 #define sayNO_SILENT goto no_silent
3675 /* we dont use STMT_START/END here because it leads to
3676 "unreachable code" warnings, which are bogus, but distracting. */
3677 #define CACHEsayNO \
3678 if (ST.cache_mask) \
3679 reginfo->info_aux->poscache[ST.cache_offset] |= ST.cache_mask; \
3682 /* this is used to determine how far from the left messages like
3683 'failed...' are printed in regexec.c. It should be set such that
3684 messages are inline with the regop output that created them.
3686 #define REPORT_CODE_OFF 29
3687 #define INDENT_CHARS(depth) ((int)(depth) % 20)
3690 Perl_re_exec_indentf(pTHX_ const char *fmt, U32 depth, ...)
3694 PerlIO *f= Perl_debug_log;
3695 PERL_ARGS_ASSERT_RE_EXEC_INDENTF;
3696 va_start(ap, depth);
3697 PerlIO_printf(f, "%*s|%4" UVuf "| %*s", REPORT_CODE_OFF, "", (UV)depth, INDENT_CHARS(depth), "" );
3698 result = PerlIO_vprintf(f, fmt, ap);
3702 #endif /* DEBUGGING */
3705 #define CHRTEST_UNINIT -1001 /* c1/c2 haven't been calculated yet */
3706 #define CHRTEST_VOID -1000 /* the c1/c2 "next char" test should be skipped */
3707 #define CHRTEST_NOT_A_CP_1 -999
3708 #define CHRTEST_NOT_A_CP_2 -998
3710 /* grab a new slab and return the first slot in it */
3712 STATIC regmatch_state *
3715 regmatch_slab *s = PL_regmatch_slab->next;
3717 Newx(s, 1, regmatch_slab);
3718 s->prev = PL_regmatch_slab;
3720 PL_regmatch_slab->next = s;
3722 PL_regmatch_slab = s;
3723 return SLAB_FIRST(s);
3727 /* push a new state then goto it */
3729 #define PUSH_STATE_GOTO(state, node, input) \
3730 pushinput = input; \
3732 st->resume_state = state; \
3735 /* push a new state with success backtracking, then goto it */
3737 #define PUSH_YES_STATE_GOTO(state, node, input) \
3738 pushinput = input; \
3740 st->resume_state = state; \
3741 goto push_yes_state;
3748 regmatch() - main matching routine
3750 This is basically one big switch statement in a loop. We execute an op,
3751 set 'next' to point the next op, and continue. If we come to a point which
3752 we may need to backtrack to on failure such as (A|B|C), we push a
3753 backtrack state onto the backtrack stack. On failure, we pop the top
3754 state, and re-enter the loop at the state indicated. If there are no more
3755 states to pop, we return failure.
3757 Sometimes we also need to backtrack on success; for example /A+/, where
3758 after successfully matching one A, we need to go back and try to
3759 match another one; similarly for lookahead assertions: if the assertion
3760 completes successfully, we backtrack to the state just before the assertion
3761 and then carry on. In these cases, the pushed state is marked as
3762 'backtrack on success too'. This marking is in fact done by a chain of
3763 pointers, each pointing to the previous 'yes' state. On success, we pop to
3764 the nearest yes state, discarding any intermediate failure-only states.
3765 Sometimes a yes state is pushed just to force some cleanup code to be
3766 called at the end of a successful match or submatch; e.g. (??{$re}) uses
3767 it to free the inner regex.
3769 Note that failure backtracking rewinds the cursor position, while
3770 success backtracking leaves it alone.
3772 A pattern is complete when the END op is executed, while a subpattern
3773 such as (?=foo) is complete when the SUCCESS op is executed. Both of these
3774 ops trigger the "pop to last yes state if any, otherwise return true"
3777 A common convention in this function is to use A and B to refer to the two
3778 subpatterns (or to the first nodes thereof) in patterns like /A*B/: so A is
3779 the subpattern to be matched possibly multiple times, while B is the entire
3780 rest of the pattern. Variable and state names reflect this convention.
3782 The states in the main switch are the union of ops and failure/success of
3783 substates associated with with that op. For example, IFMATCH is the op
3784 that does lookahead assertions /(?=A)B/ and so the IFMATCH state means
3785 'execute IFMATCH'; while IFMATCH_A is a state saying that we have just
3786 successfully matched A and IFMATCH_A_fail is a state saying that we have
3787 just failed to match A. Resume states always come in pairs. The backtrack
3788 state we push is marked as 'IFMATCH_A', but when that is popped, we resume
3789 at IFMATCH_A or IFMATCH_A_fail, depending on whether we are backtracking
3790 on success or failure.
3792 The struct that holds a backtracking state is actually a big union, with
3793 one variant for each major type of op. The variable st points to the
3794 top-most backtrack struct. To make the code clearer, within each
3795 block of code we #define ST to alias the relevant union.
3797 Here's a concrete example of a (vastly oversimplified) IFMATCH
3803 #define ST st->u.ifmatch
3805 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3806 ST.foo = ...; // some state we wish to save
3808 // push a yes backtrack state with a resume value of
3809 // IFMATCH_A/IFMATCH_A_fail, then continue execution at the
3811 PUSH_YES_STATE_GOTO(IFMATCH_A, A, newinput);
3814 case IFMATCH_A: // we have successfully executed A; now continue with B
3816 bar = ST.foo; // do something with the preserved value
3819 case IFMATCH_A_fail: // A failed, so the assertion failed
3820 ...; // do some housekeeping, then ...
3821 sayNO; // propagate the failure
3828 For any old-timers reading this who are familiar with the old recursive
3829 approach, the code above is equivalent to:
3831 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3840 ...; // do some housekeeping, then ...
3841 sayNO; // propagate the failure
3844 The topmost backtrack state, pointed to by st, is usually free. If you
3845 want to claim it, populate any ST.foo fields in it with values you wish to
3846 save, then do one of
3848 PUSH_STATE_GOTO(resume_state, node, newinput);
3849 PUSH_YES_STATE_GOTO(resume_state, node, newinput);
3851 which sets that backtrack state's resume value to 'resume_state', pushes a
3852 new free entry to the top of the backtrack stack, then goes to 'node'.
3853 On backtracking, the free slot is popped, and the saved state becomes the
3854 new free state. An ST.foo field in this new top state can be temporarily
3855 accessed to retrieve values, but once the main loop is re-entered, it
3856 becomes available for reuse.
3858 Note that the depth of the backtrack stack constantly increases during the
3859 left-to-right execution of the pattern, rather than going up and down with
3860 the pattern nesting. For example the stack is at its maximum at Z at the
3861 end of the pattern, rather than at X in the following:
3863 /(((X)+)+)+....(Y)+....Z/
3865 The only exceptions to this are lookahead/behind assertions and the cut,
3866 (?>A), which pop all the backtrack states associated with A before
3869 Backtrack state structs are allocated in slabs of about 4K in size.
3870 PL_regmatch_state and st always point to the currently active state,
3871 and PL_regmatch_slab points to the slab currently containing
3872 PL_regmatch_state. The first time regmatch() is called, the first slab is
3873 allocated, and is never freed until interpreter destruction. When the slab
3874 is full, a new one is allocated and chained to the end. At exit from
3875 regmatch(), slabs allocated since entry are freed.
3880 #define DEBUG_STATE_pp(pp) \
3882 DUMP_EXEC_POS(locinput, scan, utf8_target,depth); \
3883 Perl_re_printf( aTHX_ \
3884 "%*s" pp " %s%s%s%s%s\n", \
3885 INDENT_CHARS(depth), "", \
3886 PL_reg_name[st->resume_state], \
3887 ((st==yes_state||st==mark_state) ? "[" : ""), \
3888 ((st==yes_state) ? "Y" : ""), \
3889 ((st==mark_state) ? "M" : ""), \
3890 ((st==yes_state||st==mark_state) ? "]" : "") \
3895 #define REG_NODE_NUM(x) ((x) ? (int)((x)-prog) : -1)
3900 S_debug_start_match(pTHX_ const REGEXP *prog, const bool utf8_target,
3901 const char *start, const char *end, const char *blurb)
3903 const bool utf8_pat = RX_UTF8(prog) ? 1 : 0;
3905 PERL_ARGS_ASSERT_DEBUG_START_MATCH;
3910 RE_PV_QUOTED_DECL(s0, utf8_pat, PERL_DEBUG_PAD_ZERO(0),
3911 RX_PRECOMP_const(prog), RX_PRELEN(prog), PL_dump_re_max_len);
3913 RE_PV_QUOTED_DECL(s1, utf8_target, PERL_DEBUG_PAD_ZERO(1),
3914 start, end - start, PL_dump_re_max_len);
3916 Perl_re_printf( aTHX_
3917 "%s%s REx%s %s against %s\n",
3918 PL_colors[4], blurb, PL_colors[5], s0, s1);
3920 if (utf8_target||utf8_pat)
3921 Perl_re_printf( aTHX_ "UTF-8 %s%s%s...\n",
3922 utf8_pat ? "pattern" : "",
3923 utf8_pat && utf8_target ? " and " : "",
3924 utf8_target ? "string" : ""
3930 S_dump_exec_pos(pTHX_ const char *locinput,
3931 const regnode *scan,
3932 const char *loc_regeol,
3933 const char *loc_bostr,
3934 const char *loc_reg_starttry,
3935 const bool utf8_target,
3939 const int docolor = *PL_colors[0] || *PL_colors[2] || *PL_colors[4];
3940 const int taill = (docolor ? 10 : 7); /* 3 chars for "> <" */
3941 int l = (loc_regeol - locinput) > taill ? taill : (loc_regeol - locinput);
3942 /* The part of the string before starttry has one color
3943 (pref0_len chars), between starttry and current
3944 position another one (pref_len - pref0_len chars),
3945 after the current position the third one.
3946 We assume that pref0_len <= pref_len, otherwise we
3947 decrease pref0_len. */
3948 int pref_len = (locinput - loc_bostr) > (5 + taill) - l
3949 ? (5 + taill) - l : locinput - loc_bostr;
3952 PERL_ARGS_ASSERT_DUMP_EXEC_POS;
3954 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput - pref_len)))
3956 pref0_len = pref_len - (locinput - loc_reg_starttry);
3957 if (l + pref_len < (5 + taill) && l < loc_regeol - locinput)
3958 l = ( loc_regeol - locinput > (5 + taill) - pref_len
3959 ? (5 + taill) - pref_len : loc_regeol - locinput);
3960 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput + l)))
3964 if (pref0_len > pref_len)
3965 pref0_len = pref_len;
3967 const int is_uni = utf8_target ? 1 : 0;
3969 RE_PV_COLOR_DECL(s0,len0,is_uni,PERL_DEBUG_PAD(0),
3970 (locinput - pref_len),pref0_len, PL_dump_re_max_len, 4, 5);
3972 RE_PV_COLOR_DECL(s1,len1,is_uni,PERL_DEBUG_PAD(1),
3973 (locinput - pref_len + pref0_len),
3974 pref_len - pref0_len, PL_dump_re_max_len, 2, 3);
3976 RE_PV_COLOR_DECL(s2,len2,is_uni,PERL_DEBUG_PAD(2),
3977 locinput, loc_regeol - locinput, 10, 0, 1);
3979 const STRLEN tlen=len0+len1+len2;
3980 Perl_re_printf( aTHX_
3981 "%4" IVdf " <%.*s%.*s%s%.*s>%*s|%4u| ",
3982 (IV)(locinput - loc_bostr),
3985 (docolor ? "" : "> <"),
3987 (int)(tlen > 19 ? 0 : 19 - tlen),
3995 /* reg_check_named_buff_matched()
3996 * Checks to see if a named buffer has matched. The data array of
3997 * buffer numbers corresponding to the buffer is expected to reside
3998 * in the regexp->data->data array in the slot stored in the ARG() of
3999 * node involved. Note that this routine doesn't actually care about the
4000 * name, that information is not preserved from compilation to execution.
4001 * Returns the index of the leftmost defined buffer with the given name
4002 * or 0 if non of the buffers matched.
4005 S_reg_check_named_buff_matched(const regexp *rex, const regnode *scan)
4008 RXi_GET_DECL(rex,rexi);
4009 SV *sv_dat= MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
4010 I32 *nums=(I32*)SvPVX(sv_dat);
4012 PERL_ARGS_ASSERT_REG_CHECK_NAMED_BUFF_MATCHED;
4014 for ( n=0; n<SvIVX(sv_dat); n++ ) {
4015 if ((I32)rex->lastparen >= nums[n] &&
4016 rex->offs[nums[n]].end != -1)
4026 S_setup_EXACTISH_ST_c1_c2(pTHX_ const regnode * const text_node, int *c1p,
4027 U8* c1_utf8, int *c2p, U8* c2_utf8, regmatch_info *reginfo)
4029 /* This function determines if there are one or two characters that match
4030 * the first character of the passed-in EXACTish node <text_node>, and if
4031 * so, returns them in the passed-in pointers.
4033 * If it determines that no possible character in the target string can
4034 * match, it returns FALSE; otherwise TRUE. (The FALSE situation occurs if
4035 * the first character in <text_node> requires UTF-8 to represent, and the
4036 * target string isn't in UTF-8.)
4038 * If there are more than two characters that could match the beginning of
4039 * <text_node>, or if more context is required to determine a match or not,
4040 * it sets both *<c1p> and *<c2p> to CHRTEST_VOID.
4042 * The motiviation behind this function is to allow the caller to set up
4043 * tight loops for matching. If <text_node> is of type EXACT, there is
4044 * only one possible character that can match its first character, and so
4045 * the situation is quite simple. But things get much more complicated if
4046 * folding is involved. It may be that the first character of an EXACTFish
4047 * node doesn't participate in any possible fold, e.g., punctuation, so it
4048 * can be matched only by itself. The vast majority of characters that are
4049 * in folds match just two things, their lower and upper-case equivalents.
4050 * But not all are like that; some have multiple possible matches, or match
4051 * sequences of more than one character. This function sorts all that out.
4053 * Consider the patterns A*B or A*?B where A and B are arbitrary. In a
4054 * loop of trying to match A*, we know we can't exit where the thing
4055 * following it isn't a B. And something can't be a B unless it is the
4056 * beginning of B. By putting a quick test for that beginning in a tight
4057 * loop, we can rule out things that can't possibly be B without having to
4058 * break out of the loop, thus avoiding work. Similarly, if A is a single
4059 * character, we can make a tight loop matching A*, using the outputs of
4062 * If the target string to match isn't in UTF-8, and there aren't
4063 * complications which require CHRTEST_VOID, *<c1p> and *<c2p> are set to
4064 * the one or two possible octets (which are characters in this situation)
4065 * that can match. In all cases, if there is only one character that can
4066 * match, *<c1p> and *<c2p> will be identical.
4068 * If the target string is in UTF-8, the buffers pointed to by <c1_utf8>
4069 * and <c2_utf8> will contain the one or two UTF-8 sequences of bytes that
4070 * can match the beginning of <text_node>. They should be declared with at
4071 * least length UTF8_MAXBYTES+1. (If the target string isn't in UTF-8, it is
4072 * undefined what these contain.) If one or both of the buffers are
4073 * invariant under UTF-8, *<c1p>, and *<c2p> will also be set to the
4074 * corresponding invariant. If variant, the corresponding *<c1p> and/or
4075 * *<c2p> will be set to a negative number(s) that shouldn't match any code
4076 * point (unless inappropriately coerced to unsigned). *<c1p> will equal
4077 * *<c2p> if and only if <c1_utf8> and <c2_utf8> are the same. */
4079 const bool utf8_target = reginfo->is_utf8_target;
4081 UV c1 = (UV)CHRTEST_NOT_A_CP_1;
4082 UV c2 = (UV)CHRTEST_NOT_A_CP_2;
4083 bool use_chrtest_void = FALSE;
4084 const bool is_utf8_pat = reginfo->is_utf8_pat;
4086 /* Used when we have both utf8 input and utf8 output, to avoid converting
4087 * to/from code points */
4088 bool utf8_has_been_setup = FALSE;
4092 U8 *pat = (U8*)STRING(text_node);
4093 U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' };
4095 if (OP(text_node) == EXACT || OP(text_node) == EXACTL) {
4097 /* In an exact node, only one thing can be matched, that first
4098 * character. If both the pat and the target are UTF-8, we can just
4099 * copy the input to the output, avoiding finding the code point of
4104 else if (utf8_target) {
4105 Copy(pat, c1_utf8, UTF8SKIP(pat), U8);
4106 Copy(pat, c2_utf8, UTF8SKIP(pat), U8);
4107 utf8_has_been_setup = TRUE;
4110 c2 = c1 = valid_utf8_to_uvchr(pat, NULL);
4113 else { /* an EXACTFish node */
4114 U8 *pat_end = pat + STR_LEN(text_node);
4116 /* An EXACTFL node has at least some characters unfolded, because what
4117 * they match is not known until now. So, now is the time to fold
4118 * the first few of them, as many as are needed to determine 'c1' and
4119 * 'c2' later in the routine. If the pattern isn't UTF-8, we only need
4120 * to fold if in a UTF-8 locale, and then only the Sharp S; everything
4121 * else is 1-1 and isn't assumed to be folded. In a UTF-8 pattern, we
4122 * need to fold as many characters as a single character can fold to,
4123 * so that later we can check if the first ones are such a multi-char
4124 * fold. But, in such a pattern only locale-problematic characters
4125 * aren't folded, so we can skip this completely if the first character
4126 * in the node isn't one of the tricky ones */
4127 if (OP(text_node) == EXACTFL) {
4129 if (! is_utf8_pat) {
4130 if (IN_UTF8_CTYPE_LOCALE && *pat == LATIN_SMALL_LETTER_SHARP_S)
4132 folded[0] = folded[1] = 's';
4134 pat_end = folded + 2;
4137 else if (is_PROBLEMATIC_LOCALE_FOLDEDS_START_utf8(pat)) {
4142 for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < pat_end; i++) {
4144 *(d++) = (U8) toFOLD_LC(*s);
4149 _toFOLD_utf8_flags(s,
4153 FOLD_FLAGS_FULL | FOLD_FLAGS_LOCALE);
4164 if ((is_utf8_pat && is_MULTI_CHAR_FOLD_utf8_safe(pat, pat_end))
4165 || (!is_utf8_pat && is_MULTI_CHAR_FOLD_latin1_safe(pat, pat_end)))
4167 /* Multi-character folds require more context to sort out. Also
4168 * PL_utf8_foldclosures used below doesn't handle them, so have to
4169 * be handled outside this routine */
4170 use_chrtest_void = TRUE;
4172 else { /* an EXACTFish node which doesn't begin with a multi-char fold */
4173 c1 = is_utf8_pat ? valid_utf8_to_uvchr(pat, NULL) : *pat;
4175 /* Load the folds hash, if not already done */
4177 if (! PL_utf8_foldclosures) {
4178 _load_PL_utf8_foldclosures();
4181 /* The fold closures data structure is a hash with the keys
4182 * being the UTF-8 of every character that is folded to, like
4183 * 'k', and the values each an array of all code points that
4184 * fold to its key. e.g. [ 'k', 'K', KELVIN_SIGN ].
4185 * Multi-character folds are not included */
4186 if ((! (listp = hv_fetch(PL_utf8_foldclosures,
4191 /* Not found in the hash, therefore there are no folds
4192 * containing it, so there is only a single character that
4196 else { /* Does participate in folds */
4197 AV* list = (AV*) *listp;
4198 if (av_tindex_skip_len_mg(list) != 1) {
4200 /* If there aren't exactly two folds to this, it is
4201 * outside the scope of this function */
4202 use_chrtest_void = TRUE;
4204 else { /* There are two. Get them */
4205 SV** c_p = av_fetch(list, 0, FALSE);
4207 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
4211 c_p = av_fetch(list, 1, FALSE);
4213 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
4217 /* Folds that cross the 255/256 boundary are forbidden
4218 * if EXACTFL (and isnt a UTF8 locale), or EXACTFA and
4219 * one is ASCIII. Since the pattern character is above
4220 * 255, and its only other match is below 256, the only
4221 * legal match will be to itself. We have thrown away
4222 * the original, so have to compute which is the one
4224 if ((c1 < 256) != (c2 < 256)) {
4225 if ((OP(text_node) == EXACTFL
4226 && ! IN_UTF8_CTYPE_LOCALE)
4227 || ((OP(text_node) == EXACTFA
4228 || OP(text_node) == EXACTFA_NO_TRIE)
4229 && (isASCII(c1) || isASCII(c2))))
4242 else /* Here, c1 is <= 255 */
4244 && HAS_NONLATIN1_FOLD_CLOSURE(c1)
4245 && ( ! (OP(text_node) == EXACTFL && ! IN_UTF8_CTYPE_LOCALE))
4246 && ((OP(text_node) != EXACTFA
4247 && OP(text_node) != EXACTFA_NO_TRIE)
4250 /* Here, there could be something above Latin1 in the target
4251 * which folds to this character in the pattern. All such
4252 * cases except LATIN SMALL LETTER Y WITH DIAERESIS have more
4253 * than two characters involved in their folds, so are outside
4254 * the scope of this function */
4255 if (UNLIKELY(c1 == LATIN_SMALL_LETTER_Y_WITH_DIAERESIS)) {
4256 c2 = LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS;
4259 use_chrtest_void = TRUE;
4262 else { /* Here nothing above Latin1 can fold to the pattern
4264 switch (OP(text_node)) {
4266 case EXACTFL: /* /l rules */
4267 c2 = PL_fold_locale[c1];
4270 case EXACTF: /* This node only generated for non-utf8
4272 assert(! is_utf8_pat);
4273 if (! utf8_target) { /* /d rules */
4278 /* /u rules for all these. This happens to work for
4279 * EXACTFA as nothing in Latin1 folds to ASCII */
4280 case EXACTFA_NO_TRIE: /* This node only generated for
4281 non-utf8 patterns */
4282 assert(! is_utf8_pat);
4287 c2 = PL_fold_latin1[c1];
4291 Perl_croak(aTHX_ "panic: Unexpected op %u", OP(text_node));
4292 NOT_REACHED; /* NOTREACHED */
4298 /* Here have figured things out. Set up the returns */
4299 if (use_chrtest_void) {
4300 *c2p = *c1p = CHRTEST_VOID;
4302 else if (utf8_target) {
4303 if (! utf8_has_been_setup) { /* Don't have the utf8; must get it */
4304 uvchr_to_utf8(c1_utf8, c1);
4305 uvchr_to_utf8(c2_utf8, c2);
4308 /* Invariants are stored in both the utf8 and byte outputs; Use
4309 * negative numbers otherwise for the byte ones. Make sure that the
4310 * byte ones are the same iff the utf8 ones are the same */
4311 *c1p = (UTF8_IS_INVARIANT(*c1_utf8)) ? *c1_utf8 : CHRTEST_NOT_A_CP_1;
4312 *c2p = (UTF8_IS_INVARIANT(*c2_utf8))
4315 ? CHRTEST_NOT_A_CP_1
4316 : CHRTEST_NOT_A_CP_2;
4318 else if (c1 > 255) {
4319 if (c2 > 255) { /* both possibilities are above what a non-utf8 string
4324 *c1p = *c2p = c2; /* c2 is the only representable value */
4326 else { /* c1 is representable; see about c2 */
4328 *c2p = (c2 < 256) ? c2 : c1;
4335 S_isGCB(pTHX_ const GCB_enum before, const GCB_enum after, const U8 * const strbeg, const U8 * const curpos, const bool utf8_target)
4337 /* returns a boolean indicating if there is a Grapheme Cluster Boundary
4338 * between the inputs. See http://www.unicode.org/reports/tr29/. */
4340 PERL_ARGS_ASSERT_ISGCB;
4342 switch (GCB_table[before][after]) {
4349 case GCB_RI_then_RI:
4352 U8 * temp_pos = (U8 *) curpos;
4354 /* Do not break within emoji flag sequences. That is, do not
4355 * break between regional indicator (RI) symbols if there is an
4356 * odd number of RI characters before the break point.
4357 * GB12 sot (RI RI)* RI × RI
4358 * GB13 [^RI] (RI RI)* RI × RI */
4360 while (backup_one_GCB(strbeg,
4362 utf8_target) == GCB_Regional_Indicator)
4367 return RI_count % 2 != 1;
4370 case GCB_EX_then_EM:
4372 /* GB10 ( E_Base | E_Base_GAZ ) Extend* × E_Modifier */
4374 U8 * temp_pos = (U8 *) curpos;
4378 prev = backup_one_GCB(strbeg, &temp_pos, utf8_target);
4380 while (prev == GCB_Extend);
4382 return prev != GCB_E_Base && prev != GCB_E_Base_GAZ;
4390 Perl_re_printf( aTHX_ "Unhandled GCB pair: GCB_table[%d, %d] = %d\n",
4391 before, after, GCB_table[before][after]);
4398 S_backup_one_GCB(pTHX_ const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
4402 PERL_ARGS_ASSERT_BACKUP_ONE_GCB;
4404 if (*curpos < strbeg) {
4409 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
4410 U8 * prev_prev_char_pos;
4412 if (! prev_char_pos) {
4416 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos, -1, strbeg))) {
4417 gcb = getGCB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
4418 *curpos = prev_char_pos;
4419 prev_char_pos = prev_prev_char_pos;
4422 *curpos = (U8 *) strbeg;
4427 if (*curpos - 2 < strbeg) {
4428 *curpos = (U8 *) strbeg;
4432 gcb = getGCB_VAL_CP(*(*curpos - 1));
4438 /* Combining marks attach to most classes that precede them, but this defines
4439 * the exceptions (from TR14) */
4440 #define LB_CM_ATTACHES_TO(prev) ( ! ( prev == LB_EDGE \
4441 || prev == LB_Mandatory_Break \
4442 || prev == LB_Carriage_Return \
4443 || prev == LB_Line_Feed \
4444 || prev == LB_Next_Line \
4445 || prev == LB_Space \
4446 || prev == LB_ZWSpace))
4449 S_isLB(pTHX_ LB_enum before,
4451 const U8 * const strbeg,
4452 const U8 * const curpos,
4453 const U8 * const strend,
4454 const bool utf8_target)
4456 U8 * temp_pos = (U8 *) curpos;
4457 LB_enum prev = before;
4459 /* Is the boundary between 'before' and 'after' line-breakable?
4460 * Most of this is just a table lookup of a generated table from Unicode
4461 * rules. But some rules require context to decide, and so have to be
4462 * implemented in code */
4464 PERL_ARGS_ASSERT_ISLB;
4466 /* Rule numbers in the comments below are as of Unicode 9.0 */
4470 switch (LB_table[before][after]) {
4475 case LB_NOBREAK_EVEN_WITH_SP_BETWEEN:
4478 case LB_SP_foo + LB_BREAKABLE:
4479 case LB_SP_foo + LB_NOBREAK:
4480 case LB_SP_foo + LB_NOBREAK_EVEN_WITH_SP_BETWEEN:
4482 /* When we have something following a SP, we have to look at the
4483 * context in order to know what to do.
4485 * SP SP should not reach here because LB7: Do not break before
4486 * spaces. (For two spaces in a row there is nothing that
4487 * overrides that) */
4488 assert(after != LB_Space);
4490 /* Here we have a space followed by a non-space. Mostly this is a
4491 * case of LB18: "Break after spaces". But there are complications
4492 * as the handling of spaces is somewhat tricky. They are in a
4493 * number of rules, which have to be applied in priority order, but
4494 * something earlier in the string can cause a rule to be skipped
4495 * and a lower priority rule invoked. A prime example is LB7 which
4496 * says don't break before a space. But rule LB8 (lower priority)
4497 * says that the first break opportunity after a ZW is after any
4498 * span of spaces immediately after it. If a ZW comes before a SP
4499 * in the input, rule LB8 applies, and not LB7. Other such rules
4500 * involve combining marks which are rules 9 and 10, but they may
4501 * override higher priority rules if they come earlier in the
4502 * string. Since we're doing random access into the middle of the
4503 * string, we have to look for rules that should get applied based
4504 * on both string position and priority. Combining marks do not
4505 * attach to either ZW nor SP, so we don't have to consider them
4508 * To check for LB8, we have to find the first non-space character
4509 * before this span of spaces */
4511 prev = backup_one_LB(strbeg, &temp_pos, utf8_target);
4513 while (prev == LB_Space);
4515 /* LB8 Break before any character following a zero-width space,
4516 * even if one or more spaces intervene.
4518 * So if we have a ZW just before this span, and to get here this
4519 * is the final space in the span. */
4520 if (prev == LB_ZWSpace) {
4524 /* Here, not ZW SP+. There are several rules that have higher
4525 * priority than LB18 and can be resolved now, as they don't depend
4526 * on anything earlier in the string (except ZW, which we have
4527 * already handled). One of these rules is LB11 Do not break
4528 * before Word joiner, but we have specially encoded that in the
4529 * lookup table so it is caught by the single test below which
4530 * catches the other ones. */
4531 if (LB_table[LB_Space][after] - LB_SP_foo
4532 == LB_NOBREAK_EVEN_WITH_SP_BETWEEN)
4537 /* If we get here, we have to XXX consider combining marks. */
4538 if (prev == LB_Combining_Mark) {
4540 /* What happens with these depends on the character they
4543 prev = backup_one_LB(strbeg, &temp_pos, utf8_target);
4545 while (prev == LB_Combining_Mark);
4547 /* Most times these attach to and inherit the characteristics
4548 * of that character, but not always, and when not, they are to
4549 * be treated as AL by rule LB10. */
4550 if (! LB_CM_ATTACHES_TO(prev)) {
4551 prev = LB_Alphabetic;
4555 /* Here, we have the character preceding the span of spaces all set
4556 * up. We follow LB18: "Break after spaces" unless the table shows
4557 * that is overriden */
4558 return LB_table[prev][after] != LB_NOBREAK_EVEN_WITH_SP_BETWEEN;
4562 /* We don't know how to treat the CM except by looking at the first
4563 * non-CM character preceding it. ZWJ is treated as CM */
4565 prev = backup_one_LB(strbeg, &temp_pos, utf8_target);
4567 while (prev == LB_Combining_Mark || prev == LB_ZWJ);
4569 /* Here, 'prev' is that first earlier non-CM character. If the CM
4570 * attatches to it, then it inherits the behavior of 'prev'. If it
4571 * doesn't attach, it is to be treated as an AL */
4572 if (! LB_CM_ATTACHES_TO(prev)) {
4573 prev = LB_Alphabetic;
4578 case LB_HY_or_BA_then_foo + LB_BREAKABLE:
4579 case LB_HY_or_BA_then_foo + LB_NOBREAK:
4581 /* LB21a Don't break after Hebrew + Hyphen.
4582 * HL (HY | BA) × */
4584 if (backup_one_LB(strbeg, &temp_pos, utf8_target)
4585 == LB_Hebrew_Letter)
4590 return LB_table[prev][after] - LB_HY_or_BA_then_foo == LB_BREAKABLE;
4592 case LB_PR_or_PO_then_OP_or_HY + LB_BREAKABLE:
4593 case LB_PR_or_PO_then_OP_or_HY + LB_NOBREAK:
4595 /* LB25a (PR | PO) × ( OP | HY )? NU */
4596 if (advance_one_LB(&temp_pos, strend, utf8_target) == LB_Numeric) {
4600 return LB_table[prev][after] - LB_PR_or_PO_then_OP_or_HY
4603 case LB_SY_or_IS_then_various + LB_BREAKABLE:
4604 case LB_SY_or_IS_then_various + LB_NOBREAK:
4606 /* LB25d NU (SY | IS)* × (NU | SY | IS | CL | CP ) */
4608 LB_enum temp = prev;
4610 temp = backup_one_LB(strbeg, &temp_pos, utf8_target);
4612 while (temp == LB_Break_Symbols || temp == LB_Infix_Numeric);
4613 if (temp == LB_Numeric) {
4617 return LB_table[prev][after] - LB_SY_or_IS_then_various
4621 case LB_various_then_PO_or_PR + LB_BREAKABLE:
4622 case LB_various_then_PO_or_PR + LB_NOBREAK:
4624 /* LB25e NU (SY | IS)* (CL | CP)? × (PO | PR) */
4626 LB_enum temp = prev;
4627 if (temp == LB_Close_Punctuation || temp == LB_Close_Parenthesis)
4629 temp = backup_one_LB(strbeg, &temp_pos, utf8_target);
4631 while (temp == LB_Break_Symbols || temp == LB_Infix_Numeric) {
4632 temp = backup_one_LB(strbeg, &temp_pos, utf8_target);
4634 if (temp == LB_Numeric) {
4637 return LB_various_then_PO_or_PR;
4640 case LB_RI_then_RI + LB_NOBREAK:
4641 case LB_RI_then_RI + LB_BREAKABLE:
4645 /* LB30a Break between two regional indicator symbols if and
4646 * only if there are an even number of regional indicators
4647 * preceding the position of the break.
4649 * sot (RI RI)* RI × RI
4650 * [^RI] (RI RI)* RI × RI */
4652 while (backup_one_LB(strbeg,
4654 utf8_target) == LB_Regional_Indicator)
4659 return RI_count % 2 == 0;
4667 Perl_re_printf( aTHX_ "Unhandled LB pair: LB_table[%d, %d] = %d\n",
4668 before, after, LB_table[before][after]);
4675 S_advance_one_LB(pTHX_ U8 ** curpos, const U8 * const strend, const bool utf8_target)
4679 PERL_ARGS_ASSERT_ADVANCE_ONE_LB;
4681 if (*curpos >= strend) {
4686 *curpos += UTF8SKIP(*curpos);
4687 if (*curpos >= strend) {
4690 lb = getLB_VAL_UTF8(*curpos, strend);
4694 if (*curpos >= strend) {
4697 lb = getLB_VAL_CP(**curpos);
4704 S_backup_one_LB(pTHX_ const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
4708 PERL_ARGS_ASSERT_BACKUP_ONE_LB;
4710 if (*curpos < strbeg) {
4715 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
4716 U8 * prev_prev_char_pos;
4718 if (! prev_char_pos) {
4722 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos, -1, strbeg))) {
4723 lb = getLB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
4724 *curpos = prev_char_pos;
4725 prev_char_pos = prev_prev_char_pos;
4728 *curpos = (U8 *) strbeg;
4733 if (*curpos - 2 < strbeg) {
4734 *curpos = (U8 *) strbeg;
4738 lb = getLB_VAL_CP(*(*curpos - 1));
4745 S_isSB(pTHX_ SB_enum before,
4747 const U8 * const strbeg,
4748 const U8 * const curpos,
4749 const U8 * const strend,
4750 const bool utf8_target)
4752 /* returns a boolean indicating if there is a Sentence Boundary Break
4753 * between the inputs. See http://www.unicode.org/reports/tr29/ */
4755 U8 * lpos = (U8 *) curpos;
4756 bool has_para_sep = FALSE;
4757 bool has_sp = FALSE;
4759 PERL_ARGS_ASSERT_ISSB;
4761 /* Break at the start and end of text.
4764 But unstated in Unicode is don't break if the text is empty */
4765 if (before == SB_EDGE || after == SB_EDGE) {
4766 return before != after;
4769 /* SB 3: Do not break within CRLF. */
4770 if (before == SB_CR && after == SB_LF) {
4774 /* Break after paragraph separators. CR and LF are considered
4775 * so because Unicode views text as like word processing text where there
4776 * are no newlines except between paragraphs, and the word processor takes
4777 * care of wrapping without there being hard line-breaks in the text *./
4778 SB4. Sep | CR | LF ÷ */
4779 if (before == SB_Sep || before == SB_CR || before == SB_LF) {
4783 /* Ignore Format and Extend characters, except after sot, Sep, CR, or LF.
4784 * (See Section 6.2, Replacing Ignore Rules.)
4785 SB5. X (Extend | Format)* → X */
4786 if (after == SB_Extend || after == SB_Format) {
4788 /* Implied is that the these characters attach to everything
4789 * immediately prior to them except for those separator-type
4790 * characters. And the rules earlier have already handled the case
4791 * when one of those immediately precedes the extend char */
4795 if (before == SB_Extend || before == SB_Format) {
4796 U8 * temp_pos = lpos;
4797 const SB_enum backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4798 if ( backup != SB_EDGE
4807 /* Here, both 'before' and 'backup' are these types; implied is that we
4808 * don't break between them */
4809 if (backup == SB_Extend || backup == SB_Format) {
4814 /* Do not break after ambiguous terminators like period, if they are
4815 * immediately followed by a number or lowercase letter, if they are
4816 * between uppercase letters, if the first following letter (optionally
4817 * after certain punctuation) is lowercase, or if they are followed by
4818 * "continuation" punctuation such as comma, colon, or semicolon. For
4819 * example, a period may be an abbreviation or numeric period, and thus may
4820 * not mark the end of a sentence.
4822 * SB6. ATerm × Numeric */
4823 if (before == SB_ATerm && after == SB_Numeric) {
4827 /* SB7. (Upper | Lower) ATerm × Upper */
4828 if (before == SB_ATerm && after == SB_Upper) {
4829 U8 * temp_pos = lpos;
4830 SB_enum backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4831 if (backup == SB_Upper || backup == SB_Lower) {
4836 /* The remaining rules that aren't the final one, all require an STerm or
4837 * an ATerm after having backed up over some Close* Sp*, and in one case an
4838 * optional Paragraph separator, although one rule doesn't have any Sp's in it.
4839 * So do that backup now, setting flags if either Sp or a paragraph
4840 * separator are found */
4842 if (before == SB_Sep || before == SB_CR || before == SB_LF) {
4843 has_para_sep = TRUE;
4844 before = backup_one_SB(strbeg, &lpos, utf8_target);
4847 if (before == SB_Sp) {
4850 before = backup_one_SB(strbeg, &lpos, utf8_target);
4852 while (before == SB_Sp);
4855 while (before == SB_Close) {
4856 before = backup_one_SB(strbeg, &lpos, utf8_target);
4859 /* The next few rules apply only when the backed-up-to is an ATerm, and in
4860 * most cases an STerm */
4861 if (before == SB_STerm || before == SB_ATerm) {
4863 /* So, here the lhs matches
4864 * (STerm | ATerm) Close* Sp* (Sep | CR | LF)?
4865 * and we have set flags if we found an Sp, or the optional Sep,CR,LF.
4866 * The rules that apply here are:
4868 * SB8 ATerm Close* Sp* × ( ¬(OLetter | Upper | Lower | Sep | CR
4869 | LF | STerm | ATerm) )* Lower
4870 SB8a (STerm | ATerm) Close* Sp* × (SContinue | STerm | ATerm)
4871 SB9 (STerm | ATerm) Close* × (Close | Sp | Sep | CR | LF)
4872 SB10 (STerm | ATerm) Close* Sp* × (Sp | Sep | CR | LF)
4873 SB11 (STerm | ATerm) Close* Sp* (Sep | CR | LF)? ÷
4876 /* And all but SB11 forbid having seen a paragraph separator */
4877 if (! has_para_sep) {
4878 if (before == SB_ATerm) { /* SB8 */
4879 U8 * rpos = (U8 *) curpos;
4880 SB_enum later = after;
4882 while ( later != SB_OLetter
4883 && later != SB_Upper
4884 && later != SB_Lower
4888 && later != SB_STerm
4889 && later != SB_ATerm
4890 && later != SB_EDGE)
4892 later = advance_one_SB(&rpos, strend, utf8_target);
4894 if (later == SB_Lower) {
4899 if ( after == SB_SContinue /* SB8a */
4900 || after == SB_STerm
4901 || after == SB_ATerm)
4906 if (! has_sp) { /* SB9 applies only if there was no Sp* */
4907 if ( after == SB_Close
4917 /* SB10. This and SB9 could probably be combined some way, but khw
4918 * has decided to follow the Unicode rule book precisely for
4919 * simplified maintenance */
4933 /* Otherwise, do not break.
4940 S_advance_one_SB(pTHX_ U8 ** curpos, const U8 * const strend, const bool utf8_target)
4944 PERL_ARGS_ASSERT_ADVANCE_ONE_SB;
4946 if (*curpos >= strend) {
4952 *curpos += UTF8SKIP(*curpos);
4953 if (*curpos >= strend) {
4956 sb = getSB_VAL_UTF8(*curpos, strend);
4957 } while (sb == SB_Extend || sb == SB_Format);
4962 if (*curpos >= strend) {
4965 sb = getSB_VAL_CP(**curpos);
4966 } while (sb == SB_Extend || sb == SB_Format);
4973 S_backup_one_SB(pTHX_ const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
4977 PERL_ARGS_ASSERT_BACKUP_ONE_SB;
4979 if (*curpos < strbeg) {
4984 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
4985 if (! prev_char_pos) {
4989 /* Back up over Extend and Format. curpos is always just to the right
4990 * of the characater whose value we are getting */
4992 U8 * prev_prev_char_pos;
4993 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos, -1,
4996 sb = getSB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
4997 *curpos = prev_char_pos;
4998 prev_char_pos = prev_prev_char_pos;
5001 *curpos = (U8 *) strbeg;
5004 } while (sb == SB_Extend || sb == SB_Format);
5008 if (*curpos - 2 < strbeg) {
5009 *curpos = (U8 *) strbeg;
5013 sb = getSB_VAL_CP(*(*curpos - 1));
5014 } while (sb == SB_Extend || sb == SB_Format);
5021 S_isWB(pTHX_ WB_enum previous,
5024 const U8 * const strbeg,
5025 const U8 * const curpos,
5026 const U8 * const strend,
5027 const bool utf8_target)
5029 /* Return a boolean as to if the boundary between 'before' and 'after' is
5030 * a Unicode word break, using their published algorithm, but tailored for
5031 * Perl by treating spans of white space as one unit. Context may be
5032 * needed to make this determination. If the value for the character
5033 * before 'before' is known, it is passed as 'previous'; otherwise that
5034 * should be set to WB_UNKNOWN. The other input parameters give the
5035 * boundaries and current position in the matching of the string. That
5036 * is, 'curpos' marks the position where the character whose wb value is
5037 * 'after' begins. See http://www.unicode.org/reports/tr29/ */
5039 U8 * before_pos = (U8 *) curpos;
5040 U8 * after_pos = (U8 *) curpos;
5041 WB_enum prev = before;
5044 PERL_ARGS_ASSERT_ISWB;
5046 /* Rule numbers in the comments below are as of Unicode 9.0 */
5050 switch (WB_table[before][after]) {
5057 case WB_hs_then_hs: /* 2 horizontal spaces in a row */
5058 next = advance_one_WB(&after_pos, strend, utf8_target,
5059 FALSE /* Don't skip Extend nor Format */ );
5060 /* A space immediately preceeding an Extend or Format is attached
5061 * to by them, and hence gets separated from previous spaces.
5062 * Otherwise don't break between horizontal white space */
5063 return next == WB_Extend || next == WB_Format;
5065 /* WB4 Ignore Format and Extend characters, except when they appear at
5066 * the beginning of a region of text. This code currently isn't
5067 * general purpose, but it works as the rules are currently and likely
5068 * to be laid out. The reason it works is that when 'they appear at
5069 * the beginning of a region of text', the rule is to break before
5070 * them, just like any other character. Therefore, the default rule
5071 * applies and we don't have to look in more depth. Should this ever
5072 * change, we would have to have 2 'case' statements, like in the rules
5073 * below, and backup a single character (not spacing over the extend
5074 * ones) and then see if that is one of the region-end characters and
5076 case WB_Ex_or_FO_or_ZWJ_then_foo:
5077 prev = backup_one_WB(&previous, strbeg, &before_pos, utf8_target);
5080 case WB_DQ_then_HL + WB_BREAKABLE:
5081 case WB_DQ_then_HL + WB_NOBREAK:
5083 /* WB7c Hebrew_Letter Double_Quote × Hebrew_Letter */
5085 if (backup_one_WB(&previous, strbeg, &before_pos, utf8_target)
5086 == WB_Hebrew_Letter)
5091 return WB_table[before][after] - WB_DQ_then_HL == WB_BREAKABLE;
5093 case WB_HL_then_DQ + WB_BREAKABLE:
5094 case WB_HL_then_DQ + WB_NOBREAK:
5096 /* WB7b Hebrew_Letter × Double_Quote Hebrew_Letter */
5098 if (advance_one_WB(&after_pos, strend, utf8_target,
5099 TRUE /* Do skip Extend and Format */ )
5100 == WB_Hebrew_Letter)
5105 return WB_table[before][after] - WB_HL_then_DQ == WB_BREAKABLE;
5107 case WB_LE_or_HL_then_MB_or_ML_or_SQ + WB_NOBREAK:
5108 case WB_LE_or_HL_then_MB_or_ML_or_SQ + WB_BREAKABLE:
5110 /* WB6 (ALetter | Hebrew_Letter) × (MidLetter | MidNumLet
5111 * | Single_Quote) (ALetter | Hebrew_Letter) */
5113 next = advance_one_WB(&after_pos, strend, utf8_target,
5114 TRUE /* Do skip Extend and Format */ );
5116 if (next == WB_ALetter || next == WB_Hebrew_Letter)
5121 return WB_table[before][after]
5122 - WB_LE_or_HL_then_MB_or_ML_or_SQ == WB_BREAKABLE;
5124 case WB_MB_or_ML_or_SQ_then_LE_or_HL + WB_NOBREAK:
5125 case WB_MB_or_ML_or_SQ_then_LE_or_HL + WB_BREAKABLE:
5127 /* WB7 (ALetter | Hebrew_Letter) (MidLetter | MidNumLet
5128 * | Single_Quote) × (ALetter | Hebrew_Letter) */
5130 prev = backup_one_WB(&previous, strbeg, &before_pos, utf8_target);
5131 if (prev == WB_ALetter || prev == WB_Hebrew_Letter)
5136 return WB_table[before][after]
5137 - WB_MB_or_ML_or_SQ_then_LE_or_HL == WB_BREAKABLE;
5139 case WB_MB_or_MN_or_SQ_then_NU + WB_NOBREAK:
5140 case WB_MB_or_MN_or_SQ_then_NU + WB_BREAKABLE:
5142 /* WB11 Numeric (MidNum | (MidNumLet | Single_Quote)) × Numeric
5145 if (backup_one_WB(&previous, strbeg, &before_pos, utf8_target)
5151 return WB_table[before][after]
5152 - WB_MB_or_MN_or_SQ_then_NU == WB_BREAKABLE;
5154 case WB_NU_then_MB_or_MN_or_SQ + WB_NOBREAK:
5155 case WB_NU_then_MB_or_MN_or_SQ + WB_BREAKABLE:
5157 /* WB12 Numeric × (MidNum | MidNumLet | Single_Quote) Numeric */
5159 if (advance_one_WB(&after_pos, strend, utf8_target,
5160 TRUE /* Do skip Extend and Format */ )
5166 return WB_table[before][after]
5167 - WB_NU_then_MB_or_MN_or_SQ == WB_BREAKABLE;
5169 case WB_RI_then_RI + WB_NOBREAK:
5170 case WB_RI_then_RI + WB_BREAKABLE:
5174 /* Do not break within emoji flag sequences. That is, do not
5175 * break between regional indicator (RI) symbols if there is an
5176 * odd number of RI characters before the potential break
5179 * WB15 sot (RI RI)* RI × RI
5180 * WB16 [^RI] (RI RI)* RI × RI */
5182 while (backup_one_WB(&previous,
5185 utf8_target) == WB_Regional_Indicator)
5190 return RI_count % 2 != 1;
5198 Perl_re_printf( aTHX_ "Unhandled WB pair: WB_table[%d, %d] = %d\n",
5199 before, after, WB_table[before][after]);
5206 S_advance_one_WB(pTHX_ U8 ** curpos,
5207 const U8 * const strend,
5208 const bool utf8_target,
5209 const bool skip_Extend_Format)
5213 PERL_ARGS_ASSERT_ADVANCE_ONE_WB;
5215 if (*curpos >= strend) {
5221 /* Advance over Extend and Format */
5223 *curpos += UTF8SKIP(*curpos);
5224 if (*curpos >= strend) {
5227 wb = getWB_VAL_UTF8(*curpos, strend);
5228 } while ( skip_Extend_Format
5229 && (wb == WB_Extend || wb == WB_Format));
5234 if (*curpos >= strend) {
5237 wb = getWB_VAL_CP(**curpos);
5238 } while ( skip_Extend_Format
5239 && (wb == WB_Extend || wb == WB_Format));
5246 S_backup_one_WB(pTHX_ WB_enum * previous, const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
5250 PERL_ARGS_ASSERT_BACKUP_ONE_WB;
5252 /* If we know what the previous character's break value is, don't have
5254 if (*previous != WB_UNKNOWN) {
5257 /* But we need to move backwards by one */
5259 *curpos = reghopmaybe3(*curpos, -1, strbeg);
5261 *previous = WB_EDGE;
5262 *curpos = (U8 *) strbeg;
5265 *previous = WB_UNKNOWN;
5270 *previous = (*curpos <= strbeg) ? WB_EDGE : WB_UNKNOWN;
5273 /* And we always back up over these three types */
5274 if (wb != WB_Extend && wb != WB_Format && wb != WB_ZWJ) {
5279 if (*curpos < strbeg) {
5284 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
5285 if (! prev_char_pos) {
5289 /* Back up over Extend and Format. curpos is always just to the right
5290 * of the characater whose value we are getting */
5292 U8 * prev_prev_char_pos;
5293 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos,
5297 wb = getWB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
5298 *curpos = prev_char_pos;
5299 prev_char_pos = prev_prev_char_pos;
5302 *curpos = (U8 *) strbeg;
5305 } while (wb == WB_Extend || wb == WB_Format || wb == WB_ZWJ);
5309 if (*curpos - 2 < strbeg) {
5310 *curpos = (U8 *) strbeg;
5314 wb = getWB_VAL_CP(*(*curpos - 1));
5315 } while (wb == WB_Extend || wb == WB_Format);
5321 #define EVAL_CLOSE_PAREN_IS(st,expr) \
5324 ( ( st )->u.eval.close_paren ) && \
5325 ( ( ( st )->u.eval.close_paren ) == ( (expr) + 1 ) ) \
5328 #define EVAL_CLOSE_PAREN_IS_TRUE(st,expr) \
5331 ( ( st )->u.eval.close_paren ) && \
5333 ( ( ( st )->u.eval.close_paren ) == ( (expr) + 1 ) ) \
5337 #define EVAL_CLOSE_PAREN_SET(st,expr) \
5338 (st)->u.eval.close_paren = ( (expr) + 1 )
5340 #define EVAL_CLOSE_PAREN_CLEAR(st) \
5341 (st)->u.eval.close_paren = 0
5343 /* returns -1 on failure, $+[0] on success */
5345 S_regmatch(pTHX_ regmatch_info *reginfo, char *startpos, regnode *prog)
5348 const bool utf8_target = reginfo->is_utf8_target;
5349 const U32 uniflags = UTF8_ALLOW_DEFAULT;
5350 REGEXP *rex_sv = reginfo->prog;
5351 regexp *rex = ReANY(rex_sv);
5352 RXi_GET_DECL(rex,rexi);
5353 /* the current state. This is a cached copy of PL_regmatch_state */
5355 /* cache heavy used fields of st in registers */
5358 U32 n = 0; /* general value; init to avoid compiler warning */
5359 SSize_t ln = 0; /* len or last; init to avoid compiler warning */
5360 SSize_t endref = 0; /* offset of end of backref when ln is start */
5361 char *locinput = startpos;
5362 char *pushinput; /* where to continue after a PUSH */
5363 I32 nextchr; /* is always set to UCHARAT(locinput), or -1 at EOS */
5365 bool result = 0; /* return value of S_regmatch */
5366 U32 depth = 0; /* depth of backtrack stack */
5367 U32 nochange_depth = 0; /* depth of GOSUB recursion with nochange */
5368 const U32 max_nochange_depth =
5369 (3 * rex->nparens > MAX_RECURSE_EVAL_NOCHANGE_DEPTH) ?
5370 3 * rex->nparens : MAX_RECURSE_EVAL_NOCHANGE_DEPTH;
5371 regmatch_state *yes_state = NULL; /* state to pop to on success of
5373 /* mark_state piggy backs on the yes_state logic so that when we unwind
5374 the stack on success we can update the mark_state as we go */
5375 regmatch_state *mark_state = NULL; /* last mark state we have seen */
5376 regmatch_state *cur_eval = NULL; /* most recent EVAL_AB state */
5377 struct regmatch_state *cur_curlyx = NULL; /* most recent curlyx */
5379 bool no_final = 0; /* prevent failure from backtracking? */
5380 bool do_cutgroup = 0; /* no_final only until next branch/trie entry */
5381 char *startpoint = locinput;
5382 SV *popmark = NULL; /* are we looking for a mark? */
5383 SV *sv_commit = NULL; /* last mark name seen in failure */
5384 SV *sv_yes_mark = NULL; /* last mark name we have seen
5385 during a successful match */
5386 U32 lastopen = 0; /* last open we saw */
5387 bool has_cutgroup = RXp_HAS_CUTGROUP(rex) ? 1 : 0;
5388 SV* const oreplsv = GvSVn(PL_replgv);
5389 /* these three flags are set by various ops to signal information to
5390 * the very next op. They have a useful lifetime of exactly one loop
5391 * iteration, and are not preserved or restored by state pushes/pops
5393 bool sw = 0; /* the condition value in (?(cond)a|b) */
5394 bool minmod = 0; /* the next "{n,m}" is a "{n,m}?" */
5395 int logical = 0; /* the following EVAL is:
5399 or the following IFMATCH/UNLESSM is:
5400 false: plain (?=foo)
5401 true: used as a condition: (?(?=foo))
5403 PAD* last_pad = NULL;
5405 U8 gimme = G_SCALAR;
5406 CV *caller_cv = NULL; /* who called us */
5407 CV *last_pushed_cv = NULL; /* most recently called (?{}) CV */
5408 U32 maxopenparen = 0; /* max '(' index seen so far */
5409 int to_complement; /* Invert the result? */
5410 _char_class_number classnum;
5411 bool is_utf8_pat = reginfo->is_utf8_pat;
5413 I32 orig_savestack_ix = PL_savestack_ix;
5415 /* Solaris Studio 12.3 messes up fetching PL_charclass['\n'] */
5416 #if (defined(__SUNPRO_C) && (__SUNPRO_C == 0x5120) && defined(__x86_64) && defined(USE_64_BIT_ALL))
5417 # define SOLARIS_BAD_OPTIMIZER
5418 const U32 *pl_charclass_dup = PL_charclass;
5419 # define PL_charclass pl_charclass_dup
5423 GET_RE_DEBUG_FLAGS_DECL;
5426 /* protect against undef(*^R) */
5427 SAVEFREESV(SvREFCNT_inc_simple_NN(oreplsv));
5429 /* shut up 'may be used uninitialized' compiler warnings for dMULTICALL */
5430 multicall_oldcatch = 0;
5431 PERL_UNUSED_VAR(multicall_cop);
5433 PERL_ARGS_ASSERT_REGMATCH;
5435 st = PL_regmatch_state;
5437 /* Note that nextchr is a byte even in UTF */
5441 DEBUG_OPTIMISE_r( DEBUG_EXECUTE_r({
5442 DUMP_EXEC_POS( locinput, scan, utf8_target, depth );
5443 Perl_re_printf( aTHX_ "regmatch start\n" );
5446 while (scan != NULL) {
5449 next = scan + NEXT_OFF(scan);
5452 state_num = OP(scan);
5456 if (state_num <= REGNODE_MAX) {
5457 SV * const prop = sv_newmortal();
5458 regnode *rnext = regnext(scan);
5460 DUMP_EXEC_POS( locinput, scan, utf8_target, depth );
5461 regprop(rex, prop, scan, reginfo, NULL);
5462 Perl_re_printf( aTHX_
5463 "%*s%" IVdf ":%s(%" IVdf ")\n",
5464 INDENT_CHARS(depth), "",
5465 (IV)(scan - rexi->program),
5467 (PL_regkind[OP(scan)] == END || !rnext) ?
5468 0 : (IV)(rnext - rexi->program));
5475 assert(nextchr < 256 && (nextchr >= 0 || nextchr == NEXTCHR_EOS));
5477 switch (state_num) {
5478 case SBOL: /* /^../ and /\A../ */
5479 if (locinput == reginfo->strbeg)
5483 case MBOL: /* /^../m */
5484 if (locinput == reginfo->strbeg ||
5485 (!NEXTCHR_IS_EOS && locinput[-1] == '\n'))
5492 if (locinput == reginfo->ganch)
5496 case KEEPS: /* \K */
5497 /* update the startpoint */
5498 st->u.keeper.val = rex->offs[0].start;
5499 rex->offs[0].start = locinput - reginfo->strbeg;
5500 PUSH_STATE_GOTO(KEEPS_next, next, locinput);
5501 NOT_REACHED; /* NOTREACHED */
5503 case KEEPS_next_fail:
5504 /* rollback the start point change */
5505 rex->offs[0].start = st->u.keeper.val;
5507 NOT_REACHED; /* NOTREACHED */
5509 case MEOL: /* /..$/m */
5510 if (!NEXTCHR_IS_EOS && nextchr != '\n')
5514 case SEOL: /* /..$/ */
5515 if (!NEXTCHR_IS_EOS && nextchr != '\n')
5517 if (reginfo->strend - locinput > 1)
5522 if (!NEXTCHR_IS_EOS)
5526 case SANY: /* /./s */
5529 goto increment_locinput;
5531 case REG_ANY: /* /./ */
5532 if ((NEXTCHR_IS_EOS) || nextchr == '\n')
5534 goto increment_locinput;
5538 #define ST st->u.trie
5539 case TRIEC: /* (ab|cd) with known charclass */
5540 /* In this case the charclass data is available inline so
5541 we can fail fast without a lot of extra overhead.
5543 if(!NEXTCHR_IS_EOS && !ANYOF_BITMAP_TEST(scan, nextchr)) {
5545 Perl_re_exec_indentf( aTHX_ "%sfailed to match trie start class...%s\n",
5546 depth, PL_colors[4], PL_colors[5])
5549 NOT_REACHED; /* NOTREACHED */
5552 case TRIE: /* (ab|cd) */
5553 /* the basic plan of execution of the trie is:
5554 * At the beginning, run though all the states, and
5555 * find the longest-matching word. Also remember the position
5556 * of the shortest matching word. For example, this pattern:
5559 * when matched against the string "abcde", will generate
5560 * accept states for all words except 3, with the longest
5561 * matching word being 4, and the shortest being 2 (with
5562 * the position being after char 1 of the string).
5564 * Then for each matching word, in word order (i.e. 1,2,4,5),
5565 * we run the remainder of the pattern; on each try setting
5566 * the current position to the character following the word,
5567 * returning to try the next word on failure.
5569 * We avoid having to build a list of words at runtime by
5570 * using a compile-time structure, wordinfo[].prev, which
5571 * gives, for each word, the previous accepting word (if any).
5572 * In the case above it would contain the mappings 1->2, 2->0,
5573 * 3->0, 4->5, 5->1. We can use this table to generate, from
5574 * the longest word (4 above), a list of all words, by
5575 * following the list of prev pointers; this gives us the
5576 * unordered list 4,5,1,2. Then given the current word we have
5577 * just tried, we can go through the list and find the
5578 * next-biggest word to try (so if we just failed on word 2,
5579 * the next in the list is 4).
5581 * Since at runtime we don't record the matching position in
5582 * the string for each word, we have to work that out for
5583 * each word we're about to process. The wordinfo table holds
5584 * the character length of each word; given that we recorded
5585 * at the start: the position of the shortest word and its
5586 * length in chars, we just need to move the pointer the
5587 * difference between the two char lengths. Depending on
5588 * Unicode status and folding, that's cheap or expensive.
5590 * This algorithm is optimised for the case where are only a
5591 * small number of accept states, i.e. 0,1, or maybe 2.
5592 * With lots of accepts states, and having to try all of them,
5593 * it becomes quadratic on number of accept states to find all
5598 /* what type of TRIE am I? (utf8 makes this contextual) */
5599 DECL_TRIE_TYPE(scan);
5601 /* what trie are we using right now */
5602 reg_trie_data * const trie
5603 = (reg_trie_data*)rexi->data->data[ ARG( scan ) ];
5604 HV * widecharmap = MUTABLE_HV(rexi->data->data[ ARG( scan ) + 1 ]);
5605 U32 state = trie->startstate;
5607 if (scan->flags == EXACTL || scan->flags == EXACTFLU8) {
5608 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5610 && nextchr >= 0 /* guard against negative EOS value in nextchr */
5611 && UTF8_IS_ABOVE_LATIN1(nextchr)
5612 && scan->flags == EXACTL)
5614 /* We only output for EXACTL, as we let the folder
5615 * output this message for EXACTFLU8 to avoid
5617 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput,
5622 && (NEXTCHR_IS_EOS || !TRIE_BITMAP_TEST(trie, nextchr)))
5624 if (trie->states[ state ].wordnum) {
5626 Perl_re_exec_indentf( aTHX_ "%smatched empty string...%s\n",
5627 depth, PL_colors[4], PL_colors[5])
5633 Perl_re_exec_indentf( aTHX_ "%sfailed to match trie start class...%s\n",
5634 depth, PL_colors[4], PL_colors[5])
5641 U8 *uc = ( U8* )locinput;
5645 U8 *uscan = (U8*)NULL;
5646 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
5647 U32 charcount = 0; /* how many input chars we have matched */
5648 U32 accepted = 0; /* have we seen any accepting states? */
5650 ST.jump = trie->jump;
5653 ST.longfold = FALSE; /* char longer if folded => it's harder */
5656 /* fully traverse the TRIE; note the position of the
5657 shortest accept state and the wordnum of the longest
5660 while ( state && uc <= (U8*)(reginfo->strend) ) {
5661 U32 base = trie->states[ state ].trans.base;
5665 wordnum = trie->states[ state ].wordnum;
5667 if (wordnum) { /* it's an accept state */
5670 /* record first match position */
5672 ST.firstpos = (U8*)locinput;
5677 ST.firstchars = charcount;
5680 if (!ST.nextword || wordnum < ST.nextword)
5681 ST.nextword = wordnum;
5682 ST.topword = wordnum;
5685 DEBUG_TRIE_EXECUTE_r({
5686 DUMP_EXEC_POS( (char *)uc, scan, utf8_target, depth );
5688 PerlIO_printf( Perl_debug_log,
5689 "%*s%sState: %4" UVxf " Accepted: %c ",
5690 INDENT_CHARS(depth), "", PL_colors[4],
5691 (UV)state, (accepted ? 'Y' : 'N'));
5694 /* read a char and goto next state */
5695 if ( base && (foldlen || uc < (U8*)(reginfo->strend))) {
5697 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
5698 uscan, len, uvc, charid, foldlen,
5705 base + charid - 1 - trie->uniquecharcount)) >= 0)
5707 && ((U32)offset < trie->lasttrans)
5708 && trie->trans[offset].check == state)
5710 state = trie->trans[offset].next;
5721 DEBUG_TRIE_EXECUTE_r(
5722 Perl_re_printf( aTHX_
5723 "Charid:%3x CP:%4" UVxf " After State: %4" UVxf "%s\n",
5724 charid, uvc, (UV)state, PL_colors[5] );
5730 /* calculate total number of accept states */
5735 w = trie->wordinfo[w].prev;
5738 ST.accepted = accepted;
5742 Perl_re_exec_indentf( aTHX_ "%sgot %" IVdf " possible matches%s\n",
5744 PL_colors[4], (IV)ST.accepted, PL_colors[5] );
5746 goto trie_first_try; /* jump into the fail handler */
5748 NOT_REACHED; /* NOTREACHED */
5750 case TRIE_next_fail: /* we failed - try next alternative */
5754 /* undo any captures done in the tail part of a branch,
5756 * /(?:X(.)(.)|Y(.)).../
5757 * where the trie just matches X then calls out to do the
5758 * rest of the branch */
5759 REGCP_UNWIND(ST.cp);
5760 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
5762 if (!--ST.accepted) {
5764 Perl_re_exec_indentf( aTHX_ "%sTRIE failed...%s\n",
5772 /* Find next-highest word to process. Note that this code
5773 * is O(N^2) per trie run (O(N) per branch), so keep tight */
5776 U16 const nextword = ST.nextword;
5777 reg_trie_wordinfo * const wordinfo
5778 = ((reg_trie_data*)rexi->data->data[ARG(ST.me)])->wordinfo;
5779 for (word=ST.topword; word; word=wordinfo[word].prev) {
5780 if (word > nextword && (!min || word < min))
5793 ST.lastparen = rex->lastparen;
5794 ST.lastcloseparen = rex->lastcloseparen;
5798 /* find start char of end of current word */
5800 U32 chars; /* how many chars to skip */
5801 reg_trie_data * const trie
5802 = (reg_trie_data*)rexi->data->data[ARG(ST.me)];
5804 assert((trie->wordinfo[ST.nextword].len - trie->prefixlen)
5806 chars = (trie->wordinfo[ST.nextword].len - trie->prefixlen)
5811 /* the hard option - fold each char in turn and find
5812 * its folded length (which may be different */
5813 U8 foldbuf[UTF8_MAXBYTES_CASE + 1];
5821 uvc = utf8n_to_uvchr((U8*)uc, UTF8_MAXLEN, &len,
5829 uvc = to_uni_fold(uvc, foldbuf, &foldlen);
5834 uvc = utf8n_to_uvchr(uscan, UTF8_MAXLEN, &len,
5850 scan = ST.me + ((ST.jump && ST.jump[ST.nextword])
5851 ? ST.jump[ST.nextword]
5855 Perl_re_exec_indentf( aTHX_ "%sTRIE matched word #%d, continuing%s\n",
5863 if ( ST.accepted > 1 || has_cutgroup || ST.jump ) {
5864 PUSH_STATE_GOTO(TRIE_next, scan, (char*)uc);
5865 NOT_REACHED; /* NOTREACHED */
5867 /* only one choice left - just continue */
5869 AV *const trie_words
5870 = MUTABLE_AV(rexi->data->data[ARG(ST.me)+TRIE_WORDS_OFFSET]);
5871 SV ** const tmp = trie_words
5872 ? av_fetch(trie_words, ST.nextword - 1, 0) : NULL;
5873 SV *sv= tmp ? sv_newmortal() : NULL;
5875 Perl_re_exec_indentf( aTHX_ "%sonly one match left, short-circuiting: #%d <%s>%s\n",
5876 depth, PL_colors[4],
5878 tmp ? pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 0,
5879 PL_colors[0], PL_colors[1],
5880 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)|PERL_PV_ESCAPE_NONASCII
5882 : "not compiled under -Dr",
5886 locinput = (char*)uc;
5887 continue; /* execute rest of RE */
5892 case EXACTL: /* /abc/l */
5893 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5895 /* Complete checking would involve going through every character
5896 * matched by the string to see if any is above latin1. But the
5897 * comparision otherwise might very well be a fast assembly
5898 * language routine, and I (khw) don't think slowing things down
5899 * just to check for this warning is worth it. So this just checks
5900 * the first character */
5901 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*locinput)) {
5902 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput, reginfo->strend);
5905 case EXACT: { /* /abc/ */
5906 char *s = STRING(scan);
5908 if (utf8_target != is_utf8_pat) {
5909 /* The target and the pattern have differing utf8ness. */
5911 const char * const e = s + ln;
5914 /* The target is utf8, the pattern is not utf8.
5915 * Above-Latin1 code points can't match the pattern;
5916 * invariants match exactly, and the other Latin1 ones need
5917 * to be downgraded to a single byte in order to do the
5918 * comparison. (If we could be confident that the target
5919 * is not malformed, this could be refactored to have fewer
5920 * tests by just assuming that if the first bytes match, it
5921 * is an invariant, but there are tests in the test suite
5922 * dealing with (??{...}) which violate this) */
5924 if (l >= reginfo->strend
5925 || UTF8_IS_ABOVE_LATIN1(* (U8*) l))
5929 if (UTF8_IS_INVARIANT(*(U8*)l)) {
5936 if (EIGHT_BIT_UTF8_TO_NATIVE(*l, *(l+1)) != * (U8*) s)
5946 /* The target is not utf8, the pattern is utf8. */
5948 if (l >= reginfo->strend
5949 || UTF8_IS_ABOVE_LATIN1(* (U8*) s))
5953 if (UTF8_IS_INVARIANT(*(U8*)s)) {
5960 if (EIGHT_BIT_UTF8_TO_NATIVE(*s, *(s+1)) != * (U8*) l)
5972 /* The target and the pattern have the same utf8ness. */
5973 /* Inline the first character, for speed. */
5974 if (reginfo->strend - locinput < ln
5975 || UCHARAT(s) != nextchr
5976 || (ln > 1 && memNE(s, locinput, ln)))
5985 case EXACTFL: { /* /abc/il */
5987 const U8 * fold_array;
5989 U32 fold_utf8_flags;
5991 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5992 folder = foldEQ_locale;
5993 fold_array = PL_fold_locale;
5994 fold_utf8_flags = FOLDEQ_LOCALE;
5997 case EXACTFLU8: /* /abc/il; but all 'abc' are above 255, so
5998 is effectively /u; hence to match, target
6000 if (! utf8_target) {
6003 fold_utf8_flags = FOLDEQ_LOCALE | FOLDEQ_S1_ALREADY_FOLDED
6004 | FOLDEQ_S1_FOLDS_SANE;
6005 folder = foldEQ_latin1;
6006 fold_array = PL_fold_latin1;
6009 case EXACTFU_SS: /* /\x{df}/iu */
6010 case EXACTFU: /* /abc/iu */
6011 folder = foldEQ_latin1;
6012 fold_array = PL_fold_latin1;
6013 fold_utf8_flags = is_utf8_pat ? FOLDEQ_S1_ALREADY_FOLDED : 0;
6016 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8
6018 assert(! is_utf8_pat);
6020 case EXACTFA: /* /abc/iaa */
6021 folder = foldEQ_latin1;
6022 fold_array = PL_fold_latin1;
6023 fold_utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
6026 case EXACTF: /* /abc/i This node only generated for
6027 non-utf8 patterns */
6028 assert(! is_utf8_pat);
6030 fold_array = PL_fold;
6031 fold_utf8_flags = 0;
6039 || state_num == EXACTFU_SS
6040 || (state_num == EXACTFL && IN_UTF8_CTYPE_LOCALE))
6042 /* Either target or the pattern are utf8, or has the issue where
6043 * the fold lengths may differ. */
6044 const char * const l = locinput;
6045 char *e = reginfo->strend;
6047 if (! foldEQ_utf8_flags(s, 0, ln, is_utf8_pat,
6048 l, &e, 0, utf8_target, fold_utf8_flags))
6056 /* Neither the target nor the pattern are utf8 */
6057 if (UCHARAT(s) != nextchr
6059 && UCHARAT(s) != fold_array[nextchr])
6063 if (reginfo->strend - locinput < ln)
6065 if (ln > 1 && ! folder(s, locinput, ln))
6071 case NBOUNDL: /* /\B/l */
6075 case BOUNDL: /* /\b/l */
6078 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6080 if (FLAGS(scan) != TRADITIONAL_BOUND) {
6081 if (! IN_UTF8_CTYPE_LOCALE) {
6082 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
6083 B_ON_NON_UTF8_LOCALE_IS_WRONG);
6089 if (locinput == reginfo->strbeg)
6090 b1 = isWORDCHAR_LC('\n');
6092 b1 = isWORDCHAR_LC_utf8_safe(reghop3((U8*)locinput, -1,
6093 (U8*)(reginfo->strbeg)),
6094 (U8*)(reginfo->strend));
6096 b2 = (NEXTCHR_IS_EOS)
6097 ? isWORDCHAR_LC('\n')
6098 : isWORDCHAR_LC_utf8_safe((U8*) locinput,
6099 (U8*) reginfo->strend);
6101 else { /* Here the string isn't utf8 */
6102 b1 = (locinput == reginfo->strbeg)
6103 ? isWORDCHAR_LC('\n')
6104 : isWORDCHAR_LC(UCHARAT(locinput - 1));
6105 b2 = (NEXTCHR_IS_EOS)
6106 ? isWORDCHAR_LC('\n')
6107 : isWORDCHAR_LC(nextchr);
6109 if (to_complement ^ (b1 == b2)) {
6115 case NBOUND: /* /\B/ */
6119 case BOUND: /* /\b/ */
6123 goto bound_ascii_match_only;
6125 case NBOUNDA: /* /\B/a */
6129 case BOUNDA: /* /\b/a */
6133 bound_ascii_match_only:
6134 /* Here the string isn't utf8, or is utf8 and only ascii characters
6135 * are to match \w. In the latter case looking at the byte just
6136 * prior to the current one may be just the final byte of a
6137 * multi-byte character. This is ok. There are two cases:
6138 * 1) it is a single byte character, and then the test is doing
6139 * just what it's supposed to.
6140 * 2) it is a multi-byte character, in which case the final byte is
6141 * never mistakable for ASCII, and so the test will say it is
6142 * not a word character, which is the correct answer. */
6143 b1 = (locinput == reginfo->strbeg)
6144 ? isWORDCHAR_A('\n')
6145 : isWORDCHAR_A(UCHARAT(locinput - 1));
6146 b2 = (NEXTCHR_IS_EOS)
6147 ? isWORDCHAR_A('\n')
6148 : isWORDCHAR_A(nextchr);
6149 if (to_complement ^ (b1 == b2)) {
6155 case NBOUNDU: /* /\B/u */
6159 case BOUNDU: /* /\b/u */
6162 if (UNLIKELY(reginfo->strbeg >= reginfo->strend)) {
6165 else if (utf8_target) {
6167 switch((bound_type) FLAGS(scan)) {
6168 case TRADITIONAL_BOUND:
6171 b1 = (locinput == reginfo->strbeg)
6172 ? 0 /* isWORDCHAR_L1('\n') */
6173 : isWORDCHAR_utf8_safe(
6174 reghop3((U8*)locinput,
6176 (U8*)(reginfo->strbeg)),
6177 (U8*) reginfo->strend);
6178 b2 = (NEXTCHR_IS_EOS)
6179 ? 0 /* isWORDCHAR_L1('\n') */
6180 : isWORDCHAR_utf8_safe((U8*)locinput,
6181 (U8*) reginfo->strend);
6182 match = cBOOL(b1 != b2);
6186 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6187 match = TRUE; /* GCB always matches at begin and
6191 /* Find the gcb values of previous and current
6192 * chars, then see if is a break point */
6193 match = isGCB(getGCB_VAL_UTF8(
6194 reghop3((U8*)locinput,
6196 (U8*)(reginfo->strbeg)),
6197 (U8*) reginfo->strend),
6198 getGCB_VAL_UTF8((U8*) locinput,
6199 (U8*) reginfo->strend),
6200 (U8*) reginfo->strbeg,
6207 if (locinput == reginfo->strbeg) {
6210 else if (NEXTCHR_IS_EOS) {
6214 match = isLB(getLB_VAL_UTF8(
6215 reghop3((U8*)locinput,
6217 (U8*)(reginfo->strbeg)),
6218 (U8*) reginfo->strend),
6219 getLB_VAL_UTF8((U8*) locinput,
6220 (U8*) reginfo->strend),
6221 (U8*) reginfo->strbeg,
6223 (U8*) reginfo->strend,
6228 case SB_BOUND: /* Always matches at begin and end */
6229 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6233 match = isSB(getSB_VAL_UTF8(
6234 reghop3((U8*)locinput,
6236 (U8*)(reginfo->strbeg)),
6237 (U8*) reginfo->strend),
6238 getSB_VAL_UTF8((U8*) locinput,
6239 (U8*) reginfo->strend),
6240 (U8*) reginfo->strbeg,
6242 (U8*) reginfo->strend,
6248 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6252 match = isWB(WB_UNKNOWN,
6254 reghop3((U8*)locinput,
6256 (U8*)(reginfo->strbeg)),
6257 (U8*) reginfo->strend),
6258 getWB_VAL_UTF8((U8*) locinput,
6259 (U8*) reginfo->strend),
6260 (U8*) reginfo->strbeg,
6262 (U8*) reginfo->strend,
6268 else { /* Not utf8 target */
6269 switch((bound_type) FLAGS(scan)) {
6270 case TRADITIONAL_BOUND:
6273 b1 = (locinput == reginfo->strbeg)
6274 ? 0 /* isWORDCHAR_L1('\n') */
6275 : isWORDCHAR_L1(UCHARAT(locinput - 1));
6276 b2 = (NEXTCHR_IS_EOS)
6277 ? 0 /* isWORDCHAR_L1('\n') */
6278 : isWORDCHAR_L1(nextchr);
6279 match = cBOOL(b1 != b2);
6284 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6285 match = TRUE; /* GCB always matches at begin and
6288 else { /* Only CR-LF combo isn't a GCB in 0-255
6290 match = UCHARAT(locinput - 1) != '\r'
6291 || UCHARAT(locinput) != '\n';
6296 if (locinput == reginfo->strbeg) {
6299 else if (NEXTCHR_IS_EOS) {
6303 match = isLB(getLB_VAL_CP(UCHARAT(locinput -1)),
6304 getLB_VAL_CP(UCHARAT(locinput)),
6305 (U8*) reginfo->strbeg,
6307 (U8*) reginfo->strend,
6312 case SB_BOUND: /* Always matches at begin and end */
6313 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6317 match = isSB(getSB_VAL_CP(UCHARAT(locinput -1)),
6318 getSB_VAL_CP(UCHARAT(locinput)),
6319 (U8*) reginfo->strbeg,
6321 (U8*) reginfo->strend,
6327 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6331 match = isWB(WB_UNKNOWN,
6332 getWB_VAL_CP(UCHARAT(locinput -1)),
6333 getWB_VAL_CP(UCHARAT(locinput)),
6334 (U8*) reginfo->strbeg,
6336 (U8*) reginfo->strend,
6343 if (to_complement ^ ! match) {
6348 case ANYOFL: /* /[abc]/l */
6349 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6351 if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(scan)) && ! IN_UTF8_CTYPE_LOCALE)
6353 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
6356 case ANYOFD: /* /[abc]/d */
6357 case ANYOF: /* /[abc]/ */
6360 if (utf8_target && ! UTF8_IS_INVARIANT(*locinput)) {
6361 if (!reginclass(rex, scan, (U8*)locinput, (U8*)reginfo->strend,
6364 locinput += UTF8SKIP(locinput);
6367 if (!REGINCLASS(rex, scan, (U8*)locinput, utf8_target))
6373 /* The argument (FLAGS) to all the POSIX node types is the class number
6376 case NPOSIXL: /* \W or [:^punct:] etc. under /l */
6380 case POSIXL: /* \w or [:punct:] etc. under /l */
6381 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6385 /* Use isFOO_lc() for characters within Latin1. (Note that
6386 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
6387 * wouldn't be invariant) */
6388 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
6389 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan), (U8) nextchr)))) {
6397 if (! UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(locinput, reginfo->strend)) {
6398 /* An above Latin-1 code point, or malformed */
6399 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput,
6401 goto utf8_posix_above_latin1;
6404 /* Here is a UTF-8 variant code point below 256 and the target is
6406 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan),
6407 EIGHT_BIT_UTF8_TO_NATIVE(nextchr,
6408 *(locinput + 1))))))
6413 goto increment_locinput;
6415 case NPOSIXD: /* \W or [:^punct:] etc. under /d */
6419 case POSIXD: /* \w or [:punct:] etc. under /d */
6425 case NPOSIXA: /* \W or [:^punct:] etc. under /a */
6427 if (NEXTCHR_IS_EOS) {
6431 /* All UTF-8 variants match */
6432 if (! UTF8_IS_INVARIANT(nextchr)) {
6433 goto increment_locinput;
6439 case POSIXA: /* \w or [:punct:] etc. under /a */
6442 /* We get here through POSIXD, NPOSIXD, and NPOSIXA when not in
6443 * UTF-8, and also from NPOSIXA even in UTF-8 when the current
6444 * character is a single byte */
6446 if (NEXTCHR_IS_EOS) {
6452 if (! (to_complement ^ cBOOL(_generic_isCC_A(nextchr,
6458 /* Here we are either not in utf8, or we matched a utf8-invariant,
6459 * so the next char is the next byte */
6463 case NPOSIXU: /* \W or [:^punct:] etc. under /u */
6467 case POSIXU: /* \w or [:punct:] etc. under /u */
6469 if (NEXTCHR_IS_EOS) {
6473 /* Use _generic_isCC() for characters within Latin1. (Note that
6474 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
6475 * wouldn't be invariant) */
6476 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
6477 if (! (to_complement ^ cBOOL(_generic_isCC(nextchr,
6484 else if (UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(locinput, reginfo->strend)) {
6485 if (! (to_complement
6486 ^ cBOOL(_generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(nextchr,
6494 else { /* Handle above Latin-1 code points */
6495 utf8_posix_above_latin1:
6496 classnum = (_char_class_number) FLAGS(scan);
6497 if (classnum < _FIRST_NON_SWASH_CC) {
6499 /* Here, uses a swash to find such code points. Load if if
6500 * not done already */
6501 if (! PL_utf8_swash_ptrs[classnum]) {
6502 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
6503 PL_utf8_swash_ptrs[classnum]
6504 = _core_swash_init("utf8",
6507 PL_XPosix_ptrs[classnum], &flags);
6509 if (! (to_complement
6510 ^ cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum],
6511 (U8 *) locinput, TRUE))))
6516 else { /* Here, uses macros to find above Latin-1 code points */
6518 case _CC_ENUM_SPACE:
6519 if (! (to_complement
6520 ^ cBOOL(is_XPERLSPACE_high(locinput))))
6525 case _CC_ENUM_BLANK:
6526 if (! (to_complement
6527 ^ cBOOL(is_HORIZWS_high(locinput))))
6532 case _CC_ENUM_XDIGIT:
6533 if (! (to_complement
6534 ^ cBOOL(is_XDIGIT_high(locinput))))
6539 case _CC_ENUM_VERTSPACE:
6540 if (! (to_complement
6541 ^ cBOOL(is_VERTWS_high(locinput))))
6546 default: /* The rest, e.g. [:cntrl:], can't match
6548 if (! to_complement) {
6554 locinput += UTF8SKIP(locinput);
6558 case CLUMP: /* Match \X: logical Unicode character. This is defined as
6559 a Unicode extended Grapheme Cluster */
6562 if (! utf8_target) {
6564 /* Match either CR LF or '.', as all the other possibilities
6566 locinput++; /* Match the . or CR */
6567 if (nextchr == '\r' /* And if it was CR, and the next is LF,
6569 && locinput < reginfo->strend
6570 && UCHARAT(locinput) == '\n')
6577 /* Get the gcb type for the current character */
6578 GCB_enum prev_gcb = getGCB_VAL_UTF8((U8*) locinput,
6579 (U8*) reginfo->strend);
6581 /* Then scan through the input until we get to the first
6582 * character whose type is supposed to be a gcb with the
6583 * current character. (There is always a break at the
6585 locinput += UTF8SKIP(locinput);
6586 while (locinput < reginfo->strend) {
6587 GCB_enum cur_gcb = getGCB_VAL_UTF8((U8*) locinput,
6588 (U8*) reginfo->strend);
6589 if (isGCB(prev_gcb, cur_gcb,
6590 (U8*) reginfo->strbeg, (U8*) locinput,
6597 locinput += UTF8SKIP(locinput);
6604 case NREFFL: /* /\g{name}/il */
6605 { /* The capture buffer cases. The ones beginning with N for the
6606 named buffers just convert to the equivalent numbered and
6607 pretend they were called as the corresponding numbered buffer
6609 /* don't initialize these in the declaration, it makes C++
6614 const U8 *fold_array;
6617 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6618 folder = foldEQ_locale;
6619 fold_array = PL_fold_locale;
6621 utf8_fold_flags = FOLDEQ_LOCALE;
6624 case NREFFA: /* /\g{name}/iaa */
6625 folder = foldEQ_latin1;
6626 fold_array = PL_fold_latin1;
6628 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
6631 case NREFFU: /* /\g{name}/iu */
6632 folder = foldEQ_latin1;
6633 fold_array = PL_fold_latin1;
6635 utf8_fold_flags = 0;
6638 case NREFF: /* /\g{name}/i */
6640 fold_array = PL_fold;
6642 utf8_fold_flags = 0;
6645 case NREF: /* /\g{name}/ */
6649 utf8_fold_flags = 0;
6652 /* For the named back references, find the corresponding buffer
6654 n = reg_check_named_buff_matched(rex,scan);
6659 goto do_nref_ref_common;
6661 case REFFL: /* /\1/il */
6662 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6663 folder = foldEQ_locale;
6664 fold_array = PL_fold_locale;
6665 utf8_fold_flags = FOLDEQ_LOCALE;
6668 case REFFA: /* /\1/iaa */
6669 folder = foldEQ_latin1;
6670 fold_array = PL_fold_latin1;
6671 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
6674 case REFFU: /* /\1/iu */
6675 folder = foldEQ_latin1;
6676 fold_array = PL_fold_latin1;
6677 utf8_fold_flags = 0;
6680 case REFF: /* /\1/i */
6682 fold_array = PL_fold;
6683 utf8_fold_flags = 0;
6686 case REF: /* /\1/ */
6689 utf8_fold_flags = 0;
6693 n = ARG(scan); /* which paren pair */
6696 ln = rex->offs[n].start;
6697 endref = rex->offs[n].end;
6698 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
6699 if (rex->lastparen < n || ln == -1 || endref == -1)
6700 sayNO; /* Do not match unless seen CLOSEn. */
6704 s = reginfo->strbeg + ln;
6705 if (type != REF /* REF can do byte comparison */
6706 && (utf8_target || type == REFFU || type == REFFL))
6708 char * limit = reginfo->strend;
6710 /* This call case insensitively compares the entire buffer
6711 * at s, with the current input starting at locinput, but
6712 * not going off the end given by reginfo->strend, and
6713 * returns in <limit> upon success, how much of the
6714 * current input was matched */
6715 if (! foldEQ_utf8_flags(s, NULL, endref - ln, utf8_target,
6716 locinput, &limit, 0, utf8_target, utf8_fold_flags))
6724 /* Not utf8: Inline the first character, for speed. */
6725 if (!NEXTCHR_IS_EOS &&
6726 UCHARAT(s) != nextchr &&
6728 UCHARAT(s) != fold_array[nextchr]))
6731 if (locinput + ln > reginfo->strend)
6733 if (ln > 1 && (type == REF
6734 ? memNE(s, locinput, ln)
6735 : ! folder(s, locinput, ln)))
6741 case NOTHING: /* null op; e.g. the 'nothing' following
6742 * the '*' in m{(a+|b)*}' */
6744 case TAIL: /* placeholder while compiling (A|B|C) */
6748 #define ST st->u.eval
6749 #define CUR_EVAL cur_eval->u.eval
6755 regexp_internal *rei;
6756 regnode *startpoint;
6759 case GOSUB: /* /(...(?1))/ /(...(?&foo))/ */
6760 arg= (U32)ARG(scan);
6761 if (cur_eval && cur_eval->locinput == locinput) {
6762 if ( ++nochange_depth > max_nochange_depth )
6764 "Pattern subroutine nesting without pos change"
6765 " exceeded limit in regex");
6772 startpoint = scan + ARG2L(scan);
6773 EVAL_CLOSE_PAREN_SET( st, arg );
6774 /* Detect infinite recursion
6776 * A pattern like /(?R)foo/ or /(?<x>(?&y)foo)(?<y>(?&x)bar)/
6777 * or "a"=~/(.(?2))((?<=(?=(?1)).))/ could recurse forever.
6778 * So we track the position in the string we are at each time
6779 * we recurse and if we try to enter the same routine twice from
6780 * the same position we throw an error.
6782 if ( rex->recurse_locinput[arg] == locinput ) {
6783 /* FIXME: we should show the regop that is failing as part
6784 * of the error message. */
6785 Perl_croak(aTHX_ "Infinite recursion in regex");
6787 ST.prev_recurse_locinput= rex->recurse_locinput[arg];
6788 rex->recurse_locinput[arg]= locinput;
6791 GET_RE_DEBUG_FLAGS_DECL;
6793 Perl_re_exec_indentf( aTHX_
6794 "entering GOSUB, prev_recurse_locinput=%p recurse_locinput[%d]=%p\n",
6795 depth, ST.prev_recurse_locinput, arg, rex->recurse_locinput[arg]
6801 /* Save all the positions seen so far. */
6802 ST.cp = regcppush(rex, 0, maxopenparen);
6803 REGCP_SET(ST.lastcp);
6805 /* and then jump to the code we share with EVAL */
6806 goto eval_recurse_doit;
6809 case EVAL: /* /(?{...})B/ /(??{A})B/ and /(?(?{...})X|Y)B/ */
6810 if (cur_eval && cur_eval->locinput==locinput) {
6811 if ( ++nochange_depth > max_nochange_depth )
6812 Perl_croak(aTHX_ "EVAL without pos change exceeded limit in regex");
6817 /* execute the code in the {...} */
6821 OP * const oop = PL_op;
6822 COP * const ocurcop = PL_curcop;
6826 /* save *all* paren positions */
6827 regcppush(rex, 0, maxopenparen);
6828 REGCP_SET(ST.lastcp);
6831 caller_cv = find_runcv(NULL);
6835 if (rexi->data->what[n] == 'r') { /* code from an external qr */
6837 (REGEXP*)(rexi->data->data[n])
6839 nop = (OP*)rexi->data->data[n+1];
6841 else if (rexi->data->what[n] == 'l') { /* literal code */
6843 nop = (OP*)rexi->data->data[n];
6844 assert(CvDEPTH(newcv));
6847 /* literal with own CV */
6848 assert(rexi->data->what[n] == 'L');
6849 newcv = rex->qr_anoncv;
6850 nop = (OP*)rexi->data->data[n];
6853 /* Some notes about MULTICALL and the context and save stacks.
6856 * /...(?{ my $x)}...(?{ my $y)}...(?{ my $z)}.../
6857 * since codeblocks don't introduce a new scope (so that
6858 * local() etc accumulate), at the end of a successful
6859 * match there will be a SAVEt_CLEARSV on the savestack
6860 * for each of $x, $y, $z. If the three code blocks above
6861 * happen to have come from different CVs (e.g. via
6862 * embedded qr//s), then we must ensure that during any
6863 * savestack unwinding, PL_comppad always points to the
6864 * right pad at each moment. We achieve this by
6865 * interleaving SAVEt_COMPPAD's on the savestack whenever
6866 * there is a change of pad.
6867 * In theory whenever we call a code block, we should
6868 * push a CXt_SUB context, then pop it on return from
6869 * that code block. This causes a bit of an issue in that
6870 * normally popping a context also clears the savestack
6871 * back to cx->blk_oldsaveix, but here we specifically
6872 * don't want to clear the save stack on exit from the
6874 * Also for efficiency we don't want to keep pushing and
6875 * popping the single SUB context as we backtrack etc.
6876 * So instead, we push a single context the first time
6877 * we need, it, then hang onto it until the end of this
6878 * function. Whenever we encounter a new code block, we
6879 * update the CV etc if that's changed. During the times
6880 * in this function where we're not executing a code
6881 * block, having the SUB context still there is a bit
6882 * naughty - but we hope that no-one notices.
6883 * When the SUB context is initially pushed, we fake up
6884 * cx->blk_oldsaveix to be as if we'd pushed this context
6885 * on first entry to S_regmatch rather than at some random
6886 * point during the regexe execution. That way if we
6887 * croak, popping the context stack will ensure that
6888 * *everything* SAVEd by this function is undone and then
6889 * the context popped, rather than e.g., popping the
6890 * context (and restoring the original PL_comppad) then
6891 * popping more of the savestack and restoring a bad
6895 /* If this is the first EVAL, push a MULTICALL. On
6896 * subsequent calls, if we're executing a different CV, or
6897 * if PL_comppad has got messed up from backtracking
6898 * through SAVECOMPPADs, then refresh the context.
6900 if (newcv != last_pushed_cv || PL_comppad != last_pad)
6902 U8 flags = (CXp_SUB_RE |
6903 ((newcv == caller_cv) ? CXp_SUB_RE_FAKE : 0));
6905 if (last_pushed_cv) {
6906 CHANGE_MULTICALL_FLAGS(newcv, flags);
6909 PUSH_MULTICALL_FLAGS(newcv, flags);
6911 /* see notes above */
6912 CX_CUR()->blk_oldsaveix = orig_savestack_ix;
6914 last_pushed_cv = newcv;
6917 /* these assignments are just to silence compiler
6919 multicall_cop = NULL;
6921 last_pad = PL_comppad;
6923 /* the initial nextstate you would normally execute
6924 * at the start of an eval (which would cause error
6925 * messages to come from the eval), may be optimised
6926 * away from the execution path in the regex code blocks;
6927 * so manually set PL_curcop to it initially */
6929 OP *o = cUNOPx(nop)->op_first;
6930 assert(o->op_type == OP_NULL);
6931 if (o->op_targ == OP_SCOPE) {
6932 o = cUNOPo->op_first;
6935 assert(o->op_targ == OP_LEAVE);
6936 o = cUNOPo->op_first;
6937 assert(o->op_type == OP_ENTER);
6941 if (o->op_type != OP_STUB) {
6942 assert( o->op_type == OP_NEXTSTATE
6943 || o->op_type == OP_DBSTATE
6944 || (o->op_type == OP_NULL
6945 && ( o->op_targ == OP_NEXTSTATE
6946 || o->op_targ == OP_DBSTATE
6950 PL_curcop = (COP*)o;
6955 DEBUG_STATE_r( Perl_re_printf( aTHX_
6956 " re EVAL PL_op=0x%" UVxf "\n", PTR2UV(nop)) );
6958 rex->offs[0].end = locinput - reginfo->strbeg;
6959 if (reginfo->info_aux_eval->pos_magic)
6960 MgBYTEPOS_set(reginfo->info_aux_eval->pos_magic,
6961 reginfo->sv, reginfo->strbeg,
6962 locinput - reginfo->strbeg);
6965 SV *sv_mrk = get_sv("REGMARK", 1);
6966 sv_setsv(sv_mrk, sv_yes_mark);
6969 /* we don't use MULTICALL here as we want to call the
6970 * first op of the block of interest, rather than the
6971 * first op of the sub. Also, we don't want to free
6972 * the savestack frame */
6973 before = (IV)(SP-PL_stack_base);
6975 CALLRUNOPS(aTHX); /* Scalar context. */
6977 if ((IV)(SP-PL_stack_base) == before)
6978 ret = &PL_sv_undef; /* protect against empty (?{}) blocks. */
6984 /* before restoring everything, evaluate the returned
6985 * value, so that 'uninit' warnings don't use the wrong
6986 * PL_op or pad. Also need to process any magic vars
6987 * (e.g. $1) *before* parentheses are restored */
6992 if (logical == 0) /* (?{})/ */
6993 sv_setsv(save_scalar(PL_replgv), ret); /* $^R */
6994 else if (logical == 1) { /* /(?(?{...})X|Y)/ */
6995 sw = cBOOL(SvTRUE_NN(ret));
6998 else { /* /(??{}) */
6999 /* if its overloaded, let the regex compiler handle
7000 * it; otherwise extract regex, or stringify */
7001 if (SvGMAGICAL(ret))
7002 ret = sv_mortalcopy(ret);
7003 if (!SvAMAGIC(ret)) {
7007 if (SvTYPE(sv) == SVt_REGEXP)
7008 re_sv = (REGEXP*) sv;
7009 else if (SvSMAGICAL(ret)) {
7010 MAGIC *mg = mg_find(ret, PERL_MAGIC_qr);
7012 re_sv = (REGEXP *) mg->mg_obj;
7015 /* force any undef warnings here */
7016 if (!re_sv && !SvPOK(ret) && !SvNIOK(ret)) {
7017 ret = sv_mortalcopy(ret);
7018 (void) SvPV_force_nolen(ret);
7024 /* *** Note that at this point we don't restore
7025 * PL_comppad, (or pop the CxSUB) on the assumption it may
7026 * be used again soon. This is safe as long as nothing
7027 * in the regexp code uses the pad ! */
7029 PL_curcop = ocurcop;
7030 regcp_restore(rex, ST.lastcp, &maxopenparen);
7031 PL_curpm_under = PL_curpm;
7032 PL_curpm = PL_reg_curpm;
7035 PUSH_STATE_GOTO(EVAL_B, next, locinput);
7040 /* only /(??{})/ from now on */
7043 /* extract RE object from returned value; compiling if
7047 re_sv = reg_temp_copy(NULL, re_sv);
7052 if (SvUTF8(ret) && IN_BYTES) {
7053 /* In use 'bytes': make a copy of the octet
7054 * sequence, but without the flag on */
7056 const char *const p = SvPV(ret, len);
7057 ret = newSVpvn_flags(p, len, SVs_TEMP);
7059 if (rex->intflags & PREGf_USE_RE_EVAL)
7060 pm_flags |= PMf_USE_RE_EVAL;
7062 /* if we got here, it should be an engine which
7063 * supports compiling code blocks and stuff */
7064 assert(rex->engine && rex->engine->op_comp);
7065 assert(!(scan->flags & ~RXf_PMf_COMPILETIME));
7066 re_sv = rex->engine->op_comp(aTHX_ &ret, 1, NULL,
7067 rex->engine, NULL, NULL,
7068 /* copy /msixn etc to inner pattern */
7073 & (SVs_TEMP | SVs_GMG | SVf_ROK))
7074 && (!SvPADTMP(ret) || SvREADONLY(ret))) {
7075 /* This isn't a first class regexp. Instead, it's
7076 caching a regexp onto an existing, Perl visible
7078 sv_magic(ret, MUTABLE_SV(re_sv), PERL_MAGIC_qr, 0, 0);
7084 RXp_MATCH_COPIED_off(re);
7085 re->subbeg = rex->subbeg;
7086 re->sublen = rex->sublen;
7087 re->suboffset = rex->suboffset;
7088 re->subcoffset = rex->subcoffset;
7090 re->lastcloseparen = 0;
7093 debug_start_match(re_sv, utf8_target, locinput,
7094 reginfo->strend, "Matching embedded");
7096 startpoint = rei->program + 1;
7097 EVAL_CLOSE_PAREN_CLEAR(st); /* ST.close_paren = 0;
7098 * close_paren only for GOSUB */
7099 ST.prev_recurse_locinput= NULL; /* only used for GOSUB */
7100 /* Save all the seen positions so far. */
7101 ST.cp = regcppush(rex, 0, maxopenparen);
7102 REGCP_SET(ST.lastcp);
7103 /* and set maxopenparen to 0, since we are starting a "fresh" match */
7105 /* run the pattern returned from (??{...}) */
7107 eval_recurse_doit: /* Share code with GOSUB below this line
7108 * At this point we expect the stack context to be
7109 * set up correctly */
7111 /* invalidate the S-L poscache. We're now executing a
7112 * different set of WHILEM ops (and their associated
7113 * indexes) against the same string, so the bits in the
7114 * cache are meaningless. Setting maxiter to zero forces
7115 * the cache to be invalidated and zeroed before reuse.
7116 * XXX This is too dramatic a measure. Ideally we should
7117 * save the old cache and restore when running the outer
7119 reginfo->poscache_maxiter = 0;
7121 /* the new regexp might have a different is_utf8_pat than we do */
7122 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(re_sv));
7124 ST.prev_rex = rex_sv;
7125 ST.prev_curlyx = cur_curlyx;
7127 SET_reg_curpm(rex_sv);
7132 ST.prev_eval = cur_eval;
7134 /* now continue from first node in postoned RE */
7135 PUSH_YES_STATE_GOTO(EVAL_postponed_AB, startpoint, locinput);
7136 NOT_REACHED; /* NOTREACHED */
7139 case EVAL_postponed_AB: /* cleanup after a successful (??{A})B */
7140 /* note: this is called twice; first after popping B, then A */
7142 Perl_re_exec_indentf( aTHX_ "EVAL_AB cur_eval=%p prev_eval=%p\n",
7143 depth, cur_eval, ST.prev_eval);
7146 #define SET_RECURSE_LOCINPUT(STR,VAL)\
7147 if ( cur_eval && CUR_EVAL.close_paren ) {\
7149 Perl_re_exec_indentf( aTHX_ STR " GOSUB%d ce=%p recurse_locinput=%p\n",\
7151 CUR_EVAL.close_paren - 1,\
7155 rex->recurse_locinput[CUR_EVAL.close_paren - 1] = VAL;\
7158 SET_RECURSE_LOCINPUT("EVAL_AB[before]", CUR_EVAL.prev_recurse_locinput);
7160 rex_sv = ST.prev_rex;
7161 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
7162 SET_reg_curpm(rex_sv);
7163 rex = ReANY(rex_sv);
7164 rexi = RXi_GET(rex);
7166 /* preserve $^R across LEAVE's. See Bug 121070. */
7167 SV *save_sv= GvSV(PL_replgv);
7168 SvREFCNT_inc(save_sv);
7169 regcpblow(ST.cp); /* LEAVE in disguise */
7170 sv_setsv(GvSV(PL_replgv), save_sv);
7171 SvREFCNT_dec(save_sv);
7173 cur_eval = ST.prev_eval;
7174 cur_curlyx = ST.prev_curlyx;
7176 /* Invalidate cache. See "invalidate" comment above. */
7177 reginfo->poscache_maxiter = 0;
7178 if ( nochange_depth )
7181 SET_RECURSE_LOCINPUT("EVAL_AB[after]", cur_eval->locinput);
7185 case EVAL_B_fail: /* unsuccessful B in (?{...})B */
7186 REGCP_UNWIND(ST.lastcp);
7189 case EVAL_postponed_AB_fail: /* unsuccessfully ran A or B in (??{A})B */
7190 /* note: this is called twice; first after popping B, then A */
7192 Perl_re_exec_indentf( aTHX_ "EVAL_AB_fail cur_eval=%p prev_eval=%p\n",
7193 depth, cur_eval, ST.prev_eval);
7196 SET_RECURSE_LOCINPUT("EVAL_AB_fail[before]", CUR_EVAL.prev_recurse_locinput);
7198 rex_sv = ST.prev_rex;
7199 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
7200 SET_reg_curpm(rex_sv);
7201 rex = ReANY(rex_sv);
7202 rexi = RXi_GET(rex);
7204 REGCP_UNWIND(ST.lastcp);
7205 regcppop(rex, &maxopenparen);
7206 cur_eval = ST.prev_eval;
7207 cur_curlyx = ST.prev_curlyx;
7209 /* Invalidate cache. See "invalidate" comment above. */
7210 reginfo->poscache_maxiter = 0;
7211 if ( nochange_depth )
7214 SET_RECURSE_LOCINPUT("EVAL_AB_fail[after]", cur_eval->locinput);
7219 n = ARG(scan); /* which paren pair */
7220 rex->offs[n].start_tmp = locinput - reginfo->strbeg;
7221 if (n > maxopenparen)
7223 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_
7224 "rex=0x%" UVxf " offs=0x%" UVxf ": \\%" UVuf ": set %" IVdf " tmp; maxopenparen=%" UVuf "\n",
7229 (IV)rex->offs[n].start_tmp,
7235 /* XXX really need to log other places start/end are set too */
7236 #define CLOSE_CAPTURE \
7237 rex->offs[n].start = rex->offs[n].start_tmp; \
7238 rex->offs[n].end = locinput - reginfo->strbeg; \
7239 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_ \
7240 "rex=0x%" UVxf " offs=0x%" UVxf ": \\%" UVuf ": set %" IVdf "..%" IVdf "\n", \
7243 PTR2UV(rex->offs), \
7245 (IV)rex->offs[n].start, \
7246 (IV)rex->offs[n].end \
7250 n = ARG(scan); /* which paren pair */
7252 if (n > rex->lastparen)
7254 rex->lastcloseparen = n;
7255 if ( EVAL_CLOSE_PAREN_IS( cur_eval, n ) )
7260 case ACCEPT: /* (*ACCEPT) */
7262 sv_yes_mark = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
7266 cursor && OP(cursor)!=END;
7267 cursor=regnext(cursor))
7269 if ( OP(cursor)==CLOSE ){
7271 if ( n <= lastopen ) {
7273 if (n > rex->lastparen)
7275 rex->lastcloseparen = n;
7276 if ( n == ARG(scan) || EVAL_CLOSE_PAREN_IS(cur_eval, n) )
7285 case GROUPP: /* (?(1)) */
7286 n = ARG(scan); /* which paren pair */
7287 sw = cBOOL(rex->lastparen >= n && rex->offs[n].end != -1);
7290 case NGROUPP: /* (?(<name>)) */
7291 /* reg_check_named_buff_matched returns 0 for no match */
7292 sw = cBOOL(0 < reg_check_named_buff_matched(rex,scan));
7295 case INSUBP: /* (?(R)) */
7297 /* this does not need to use EVAL_CLOSE_PAREN macros, as the arg
7298 * of SCAN is already set up as matches a eval.close_paren */
7299 sw = cur_eval && (n == 0 || CUR_EVAL.close_paren == n);
7302 case DEFINEP: /* (?(DEFINE)) */
7306 case IFTHEN: /* (?(cond)A|B) */
7307 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
7309 next = NEXTOPER(NEXTOPER(scan));
7311 next = scan + ARG(scan);
7312 if (OP(next) == IFTHEN) /* Fake one. */
7313 next = NEXTOPER(NEXTOPER(next));
7317 case LOGICAL: /* modifier for EVAL and IFMATCH */
7318 logical = scan->flags;
7321 /*******************************************************************
7323 The CURLYX/WHILEM pair of ops handle the most generic case of the /A*B/
7324 pattern, where A and B are subpatterns. (For simple A, CURLYM or
7325 STAR/PLUS/CURLY/CURLYN are used instead.)
7327 A*B is compiled as <CURLYX><A><WHILEM><B>
7329 On entry to the subpattern, CURLYX is called. This pushes a CURLYX
7330 state, which contains the current count, initialised to -1. It also sets
7331 cur_curlyx to point to this state, with any previous value saved in the
7334 CURLYX then jumps straight to the WHILEM op, rather than executing A,
7335 since the pattern may possibly match zero times (i.e. it's a while {} loop
7336 rather than a do {} while loop).
7338 Each entry to WHILEM represents a successful match of A. The count in the
7339 CURLYX block is incremented, another WHILEM state is pushed, and execution
7340 passes to A or B depending on greediness and the current count.
7342 For example, if matching against the string a1a2a3b (where the aN are
7343 substrings that match /A/), then the match progresses as follows: (the
7344 pushed states are interspersed with the bits of strings matched so far):
7347 <CURLYX cnt=0><WHILEM>
7348 <CURLYX cnt=1><WHILEM> a1 <WHILEM>
7349 <CURLYX cnt=2><WHILEM> a1 <WHILEM> a2 <WHILEM>
7350 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM>
7351 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM> b
7353 (Contrast this with something like CURLYM, which maintains only a single
7357 a1 <CURLYM cnt=1> a2
7358 a1 a2 <CURLYM cnt=2> a3
7359 a1 a2 a3 <CURLYM cnt=3> b
7362 Each WHILEM state block marks a point to backtrack to upon partial failure
7363 of A or B, and also contains some minor state data related to that
7364 iteration. The CURLYX block, pointed to by cur_curlyx, contains the
7365 overall state, such as the count, and pointers to the A and B ops.
7367 This is complicated slightly by nested CURLYX/WHILEM's. Since cur_curlyx
7368 must always point to the *current* CURLYX block, the rules are:
7370 When executing CURLYX, save the old cur_curlyx in the CURLYX state block,
7371 and set cur_curlyx to point the new block.
7373 When popping the CURLYX block after a successful or unsuccessful match,
7374 restore the previous cur_curlyx.
7376 When WHILEM is about to execute B, save the current cur_curlyx, and set it
7377 to the outer one saved in the CURLYX block.
7379 When popping the WHILEM block after a successful or unsuccessful B match,
7380 restore the previous cur_curlyx.
7382 Here's an example for the pattern (AI* BI)*BO
7383 I and O refer to inner and outer, C and W refer to CURLYX and WHILEM:
7386 curlyx backtrack stack
7387 ------ ---------------
7389 CO <CO prev=NULL> <WO>
7390 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
7391 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
7392 NULL <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi <WO prev=CO> bo
7394 At this point the pattern succeeds, and we work back down the stack to
7395 clean up, restoring as we go:
7397 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
7398 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
7399 CO <CO prev=NULL> <WO>
7402 *******************************************************************/
7404 #define ST st->u.curlyx
7406 case CURLYX: /* start of /A*B/ (for complex A) */
7408 /* No need to save/restore up to this paren */
7409 I32 parenfloor = scan->flags;
7411 assert(next); /* keep Coverity happy */
7412 if (OP(PREVOPER(next)) == NOTHING) /* LONGJMP */
7415 /* XXXX Probably it is better to teach regpush to support
7416 parenfloor > maxopenparen ... */
7417 if (parenfloor > (I32)rex->lastparen)
7418 parenfloor = rex->lastparen; /* Pessimization... */
7420 ST.prev_curlyx= cur_curlyx;
7422 ST.cp = PL_savestack_ix;
7424 /* these fields contain the state of the current curly.
7425 * they are accessed by subsequent WHILEMs */
7426 ST.parenfloor = parenfloor;
7431 ST.count = -1; /* this will be updated by WHILEM */
7432 ST.lastloc = NULL; /* this will be updated by WHILEM */
7434 PUSH_YES_STATE_GOTO(CURLYX_end, PREVOPER(next), locinput);
7435 NOT_REACHED; /* NOTREACHED */
7438 case CURLYX_end: /* just finished matching all of A*B */
7439 cur_curlyx = ST.prev_curlyx;
7441 NOT_REACHED; /* NOTREACHED */
7443 case CURLYX_end_fail: /* just failed to match all of A*B */
7445 cur_curlyx = ST.prev_curlyx;
7447 NOT_REACHED; /* NOTREACHED */
7451 #define ST st->u.whilem
7453 case WHILEM: /* just matched an A in /A*B/ (for complex A) */
7455 /* see the discussion above about CURLYX/WHILEM */
7460 assert(cur_curlyx); /* keep Coverity happy */
7462 min = ARG1(cur_curlyx->u.curlyx.me);
7463 max = ARG2(cur_curlyx->u.curlyx.me);
7464 A = NEXTOPER(cur_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS;
7465 n = ++cur_curlyx->u.curlyx.count; /* how many A's matched */
7466 ST.save_lastloc = cur_curlyx->u.curlyx.lastloc;
7467 ST.cache_offset = 0;
7471 DEBUG_EXECUTE_r( Perl_re_exec_indentf( aTHX_ "whilem: matched %ld out of %d..%d\n",
7472 depth, (long)n, min, max)
7475 /* First just match a string of min A's. */
7478 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor, maxopenparen);
7479 cur_curlyx->u.curlyx.lastloc = locinput;
7480 REGCP_SET(ST.lastcp);
7482 PUSH_STATE_GOTO(WHILEM_A_pre, A, locinput);
7483 NOT_REACHED; /* NOTREACHED */
7486 /* If degenerate A matches "", assume A done. */
7488 if (locinput == cur_curlyx->u.curlyx.lastloc) {
7489 DEBUG_EXECUTE_r( Perl_re_exec_indentf( aTHX_ "whilem: empty match detected, trying continuation...\n",
7492 goto do_whilem_B_max;
7495 /* super-linear cache processing.
7497 * The idea here is that for certain types of CURLYX/WHILEM -
7498 * principally those whose upper bound is infinity (and
7499 * excluding regexes that have things like \1 and other very
7500 * non-regular expresssiony things), then if a pattern like
7501 * /....A*.../ fails and we backtrack to the WHILEM, then we
7502 * make a note that this particular WHILEM op was at string
7503 * position 47 (say) when the rest of pattern failed. Then, if
7504 * we ever find ourselves back at that WHILEM, and at string
7505 * position 47 again, we can just fail immediately rather than
7506 * running the rest of the pattern again.
7508 * This is very handy when patterns start to go
7509 * 'super-linear', like in (a+)*(a+)*(a+)*, where you end up
7510 * with a combinatorial explosion of backtracking.
7512 * The cache is implemented as a bit array, with one bit per
7513 * string byte position per WHILEM op (up to 16) - so its
7514 * between 0.25 and 2x the string size.
7516 * To avoid allocating a poscache buffer every time, we do an
7517 * initially countdown; only after we have executed a WHILEM
7518 * op (string-length x #WHILEMs) times do we allocate the
7521 * The top 4 bits of scan->flags byte say how many different
7522 * relevant CURLLYX/WHILEM op pairs there are, while the
7523 * bottom 4-bits is the identifying index number of this
7529 if (!reginfo->poscache_maxiter) {
7530 /* start the countdown: Postpone detection until we
7531 * know the match is not *that* much linear. */
7532 reginfo->poscache_maxiter
7533 = (reginfo->strend - reginfo->strbeg + 1)
7535 /* possible overflow for long strings and many CURLYX's */
7536 if (reginfo->poscache_maxiter < 0)
7537 reginfo->poscache_maxiter = I32_MAX;
7538 reginfo->poscache_iter = reginfo->poscache_maxiter;
7541 if (reginfo->poscache_iter-- == 0) {
7542 /* initialise cache */
7543 const SSize_t size = (reginfo->poscache_maxiter + 7)/8;
7544 regmatch_info_aux *const aux = reginfo->info_aux;
7545 if (aux->poscache) {
7546 if ((SSize_t)reginfo->poscache_size < size) {
7547 Renew(aux->poscache, size, char);
7548 reginfo->poscache_size = size;
7550 Zero(aux->poscache, size, char);
7553 reginfo->poscache_size = size;
7554 Newxz(aux->poscache, size, char);
7556 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
7557 "%swhilem: Detected a super-linear match, switching on caching%s...\n",
7558 PL_colors[4], PL_colors[5])
7562 if (reginfo->poscache_iter < 0) {
7563 /* have we already failed at this position? */
7564 SSize_t offset, mask;
7566 reginfo->poscache_iter = -1; /* stop eventual underflow */
7567 offset = (scan->flags & 0xf) - 1
7568 + (locinput - reginfo->strbeg)
7570 mask = 1 << (offset % 8);
7572 if (reginfo->info_aux->poscache[offset] & mask) {
7573 DEBUG_EXECUTE_r( Perl_re_exec_indentf( aTHX_ "whilem: (cache) already tried at this position...\n",
7576 cur_curlyx->u.curlyx.count--;
7577 sayNO; /* cache records failure */
7579 ST.cache_offset = offset;
7580 ST.cache_mask = mask;
7584 /* Prefer B over A for minimal matching. */
7586 if (cur_curlyx->u.curlyx.minmod) {
7587 ST.save_curlyx = cur_curlyx;
7588 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
7589 PUSH_YES_STATE_GOTO(WHILEM_B_min, ST.save_curlyx->u.curlyx.B,
7591 NOT_REACHED; /* NOTREACHED */
7594 /* Prefer A over B for maximal matching. */
7596 if (n < max) { /* More greed allowed? */
7597 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
7599 cur_curlyx->u.curlyx.lastloc = locinput;
7600 REGCP_SET(ST.lastcp);
7601 PUSH_STATE_GOTO(WHILEM_A_max, A, locinput);
7602 NOT_REACHED; /* NOTREACHED */
7604 goto do_whilem_B_max;
7606 NOT_REACHED; /* NOTREACHED */
7608 case WHILEM_B_min: /* just matched B in a minimal match */
7609 case WHILEM_B_max: /* just matched B in a maximal match */
7610 cur_curlyx = ST.save_curlyx;
7612 NOT_REACHED; /* NOTREACHED */
7614 case WHILEM_B_max_fail: /* just failed to match B in a maximal match */
7615 cur_curlyx = ST.save_curlyx;
7616 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
7617 cur_curlyx->u.curlyx.count--;
7619 NOT_REACHED; /* NOTREACHED */
7621 case WHILEM_A_pre_fail: /* just failed to match even minimal A */
7622 REGCP_UNWIND(ST.lastcp);
7623 regcppop(rex, &maxopenparen);
7625 case WHILEM_A_min_fail: /* just failed to match A in a minimal match */
7626 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
7627 cur_curlyx->u.curlyx.count--;
7629 NOT_REACHED; /* NOTREACHED */
7631 case WHILEM_A_max_fail: /* just failed to match A in a maximal match */
7632 REGCP_UNWIND(ST.lastcp);
7633 regcppop(rex, &maxopenparen); /* Restore some previous $<digit>s? */
7634 DEBUG_EXECUTE_r(Perl_re_exec_indentf( aTHX_ "whilem: failed, trying continuation...\n",
7638 if (cur_curlyx->u.curlyx.count >= REG_INFTY
7639 && ckWARN(WARN_REGEXP)
7640 && !reginfo->warned)
7642 reginfo->warned = TRUE;
7643 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
7644 "Complex regular subexpression recursion limit (%d) "
7650 ST.save_curlyx = cur_curlyx;
7651 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
7652 PUSH_YES_STATE_GOTO(WHILEM_B_max, ST.save_curlyx->u.curlyx.B,
7654 NOT_REACHED; /* NOTREACHED */
7656 case WHILEM_B_min_fail: /* just failed to match B in a minimal match */
7657 cur_curlyx = ST.save_curlyx;
7659 if (cur_curlyx->u.curlyx.count >= /*max*/ARG2(cur_curlyx->u.curlyx.me)) {
7660 /* Maximum greed exceeded */
7661 if (cur_curlyx->u.curlyx.count >= REG_INFTY
7662 && ckWARN(WARN_REGEXP)
7663 && !reginfo->warned)
7665 reginfo->warned = TRUE;
7666 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
7667 "Complex regular subexpression recursion "
7668 "limit (%d) exceeded",
7671 cur_curlyx->u.curlyx.count--;
7675 DEBUG_EXECUTE_r(Perl_re_exec_indentf( aTHX_ "trying longer...\n", depth)
7677 /* Try grabbing another A and see if it helps. */
7678 cur_curlyx->u.curlyx.lastloc = locinput;
7679 PUSH_STATE_GOTO(WHILEM_A_min,
7680 /*A*/ NEXTOPER(ST.save_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS,
7682 NOT_REACHED; /* NOTREACHED */
7685 #define ST st->u.branch
7687 case BRANCHJ: /* /(...|A|...)/ with long next pointer */
7688 next = scan + ARG(scan);
7691 scan = NEXTOPER(scan);
7694 case BRANCH: /* /(...|A|...)/ */
7695 scan = NEXTOPER(scan); /* scan now points to inner node */
7696 ST.lastparen = rex->lastparen;
7697 ST.lastcloseparen = rex->lastcloseparen;
7698 ST.next_branch = next;
7701 /* Now go into the branch */
7703 PUSH_YES_STATE_GOTO(BRANCH_next, scan, locinput);
7705 PUSH_STATE_GOTO(BRANCH_next, scan, locinput);
7707 NOT_REACHED; /* NOTREACHED */
7709 case CUTGROUP: /* /(*THEN)/ */
7710 sv_yes_mark = st->u.mark.mark_name = scan->flags
7711 ? MUTABLE_SV(rexi->data->data[ ARG( scan ) ])
7713 PUSH_STATE_GOTO(CUTGROUP_next, next, locinput);
7714 NOT_REACHED; /* NOTREACHED */
7716 case CUTGROUP_next_fail:
7719 if (st->u.mark.mark_name)
7720 sv_commit = st->u.mark.mark_name;
7722 NOT_REACHED; /* NOTREACHED */
7726 NOT_REACHED; /* NOTREACHED */
7728 case BRANCH_next_fail: /* that branch failed; try the next, if any */
7733 REGCP_UNWIND(ST.cp);
7734 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7735 scan = ST.next_branch;
7736 /* no more branches? */
7737 if (!scan || (OP(scan) != BRANCH && OP(scan) != BRANCHJ)) {
7739 Perl_re_exec_indentf( aTHX_ "%sBRANCH failed...%s\n",
7746 continue; /* execute next BRANCH[J] op */
7749 case MINMOD: /* next op will be non-greedy, e.g. A*? */
7754 #define ST st->u.curlym
7756 case CURLYM: /* /A{m,n}B/ where A is fixed-length */
7758 /* This is an optimisation of CURLYX that enables us to push
7759 * only a single backtracking state, no matter how many matches
7760 * there are in {m,n}. It relies on the pattern being constant
7761 * length, with no parens to influence future backrefs
7765 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
7767 ST.lastparen = rex->lastparen;
7768 ST.lastcloseparen = rex->lastcloseparen;
7770 /* if paren positive, emulate an OPEN/CLOSE around A */
7772 U32 paren = ST.me->flags;
7773 if (paren > maxopenparen)
7774 maxopenparen = paren;
7775 scan += NEXT_OFF(scan); /* Skip former OPEN. */
7783 ST.c1 = CHRTEST_UNINIT;
7786 if (!(ST.minmod ? ARG1(ST.me) : ARG2(ST.me))) /* min/max */
7789 curlym_do_A: /* execute the A in /A{m,n}B/ */
7790 PUSH_YES_STATE_GOTO(CURLYM_A, ST.A, locinput); /* match A */
7791 NOT_REACHED; /* NOTREACHED */
7793 case CURLYM_A: /* we've just matched an A */
7795 /* after first match, determine A's length: u.curlym.alen */
7796 if (ST.count == 1) {
7797 if (reginfo->is_utf8_target) {
7798 char *s = st->locinput;
7799 while (s < locinput) {
7805 ST.alen = locinput - st->locinput;
7808 ST.count = ST.minmod ? ARG1(ST.me) : ARG2(ST.me);
7811 Perl_re_exec_indentf( aTHX_ "CURLYM now matched %" IVdf " times, len=%" IVdf "...\n",
7812 depth, (IV) ST.count, (IV)ST.alen)
7815 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.me->flags))
7819 I32 max = (ST.minmod ? ARG1(ST.me) : ARG2(ST.me));
7820 if ( max == REG_INFTY || ST.count < max )
7821 goto curlym_do_A; /* try to match another A */
7823 goto curlym_do_B; /* try to match B */
7825 case CURLYM_A_fail: /* just failed to match an A */
7826 REGCP_UNWIND(ST.cp);
7829 if (ST.minmod || ST.count < ARG1(ST.me) /* min*/
7830 || EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.me->flags))
7833 curlym_do_B: /* execute the B in /A{m,n}B/ */
7834 if (ST.c1 == CHRTEST_UNINIT) {
7835 /* calculate c1 and c2 for possible match of 1st char
7836 * following curly */
7837 ST.c1 = ST.c2 = CHRTEST_VOID;
7839 if (HAS_TEXT(ST.B) || JUMPABLE(ST.B)) {
7840 regnode *text_node = ST.B;
7841 if (! HAS_TEXT(text_node))
7842 FIND_NEXT_IMPT(text_node);
7845 (HAS_TEXT(text_node) && PL_regkind[OP(text_node)] == EXACT)
7847 But the former is redundant in light of the latter.
7849 if this changes back then the macro for
7850 IS_TEXT and friends need to change.
7852 if (PL_regkind[OP(text_node)] == EXACT) {
7853 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
7854 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
7864 Perl_re_exec_indentf( aTHX_ "CURLYM trying tail with matches=%" IVdf "...\n",
7865 depth, (IV)ST.count)
7867 if (! NEXTCHR_IS_EOS && ST.c1 != CHRTEST_VOID) {
7868 if (! UTF8_IS_INVARIANT(nextchr) && utf8_target) {
7869 if (memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
7870 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
7872 /* simulate B failing */
7874 Perl_re_exec_indentf( aTHX_ "CURLYM Fast bail next target=0x%" UVXf " c1=0x%" UVXf " c2=0x%" UVXf "\n",
7876 valid_utf8_to_uvchr((U8 *) locinput, NULL),
7877 valid_utf8_to_uvchr(ST.c1_utf8, NULL),
7878 valid_utf8_to_uvchr(ST.c2_utf8, NULL))
7880 state_num = CURLYM_B_fail;
7881 goto reenter_switch;
7884 else if (nextchr != ST.c1 && nextchr != ST.c2) {
7885 /* simulate B failing */
7887 Perl_re_exec_indentf( aTHX_ "CURLYM Fast bail next target=0x%X c1=0x%X c2=0x%X\n",
7889 (int) nextchr, ST.c1, ST.c2)
7891 state_num = CURLYM_B_fail;
7892 goto reenter_switch;
7897 /* emulate CLOSE: mark current A as captured */
7898 I32 paren = ST.me->flags;
7900 rex->offs[paren].start
7901 = HOPc(locinput, -ST.alen) - reginfo->strbeg;
7902 rex->offs[paren].end = locinput - reginfo->strbeg;
7903 if ((U32)paren > rex->lastparen)
7904 rex->lastparen = paren;
7905 rex->lastcloseparen = paren;
7908 rex->offs[paren].end = -1;
7910 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.me->flags))
7919 PUSH_STATE_GOTO(CURLYM_B, ST.B, locinput); /* match B */
7920 NOT_REACHED; /* NOTREACHED */
7922 case CURLYM_B_fail: /* just failed to match a B */
7923 REGCP_UNWIND(ST.cp);
7924 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7926 I32 max = ARG2(ST.me);
7927 if (max != REG_INFTY && ST.count == max)
7929 goto curlym_do_A; /* try to match a further A */
7931 /* backtrack one A */
7932 if (ST.count == ARG1(ST.me) /* min */)
7935 SET_locinput(HOPc(locinput, -ST.alen));
7936 goto curlym_do_B; /* try to match B */
7939 #define ST st->u.curly
7941 #define CURLY_SETPAREN(paren, success) \
7944 rex->offs[paren].start = HOPc(locinput, -1) - reginfo->strbeg; \
7945 rex->offs[paren].end = locinput - reginfo->strbeg; \
7946 if (paren > rex->lastparen) \
7947 rex->lastparen = paren; \
7948 rex->lastcloseparen = paren; \
7951 rex->offs[paren].end = -1; \
7952 rex->lastparen = ST.lastparen; \
7953 rex->lastcloseparen = ST.lastcloseparen; \
7957 case STAR: /* /A*B/ where A is width 1 char */
7961 scan = NEXTOPER(scan);
7964 case PLUS: /* /A+B/ where A is width 1 char */
7968 scan = NEXTOPER(scan);
7971 case CURLYN: /* /(A){m,n}B/ where A is width 1 char */
7972 ST.paren = scan->flags; /* Which paren to set */
7973 ST.lastparen = rex->lastparen;
7974 ST.lastcloseparen = rex->lastcloseparen;
7975 if (ST.paren > maxopenparen)
7976 maxopenparen = ST.paren;
7977 ST.min = ARG1(scan); /* min to match */
7978 ST.max = ARG2(scan); /* max to match */
7979 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.paren))
7984 scan = regnext(NEXTOPER(scan) + NODE_STEP_REGNODE);
7987 case CURLY: /* /A{m,n}B/ where A is width 1 char */
7989 ST.min = ARG1(scan); /* min to match */
7990 ST.max = ARG2(scan); /* max to match */
7991 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
7994 * Lookahead to avoid useless match attempts
7995 * when we know what character comes next.
7997 * Used to only do .*x and .*?x, but now it allows
7998 * for )'s, ('s and (?{ ... })'s to be in the way
7999 * of the quantifier and the EXACT-like node. -- japhy
8002 assert(ST.min <= ST.max);
8003 if (! HAS_TEXT(next) && ! JUMPABLE(next)) {
8004 ST.c1 = ST.c2 = CHRTEST_VOID;
8007 regnode *text_node = next;
8009 if (! HAS_TEXT(text_node))
8010 FIND_NEXT_IMPT(text_node);
8012 if (! HAS_TEXT(text_node))
8013 ST.c1 = ST.c2 = CHRTEST_VOID;
8015 if ( PL_regkind[OP(text_node)] != EXACT ) {
8016 ST.c1 = ST.c2 = CHRTEST_VOID;
8020 /* Currently we only get here when
8022 PL_rekind[OP(text_node)] == EXACT
8024 if this changes back then the macro for IS_TEXT and
8025 friends need to change. */
8026 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
8027 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
8039 char *li = locinput;
8042 regrepeat(rex, &li, ST.A, reginfo, ST.min)
8048 if (ST.c1 == CHRTEST_VOID)
8049 goto curly_try_B_min;
8051 ST.oldloc = locinput;
8053 /* set ST.maxpos to the furthest point along the
8054 * string that could possibly match */
8055 if (ST.max == REG_INFTY) {
8056 ST.maxpos = reginfo->strend - 1;
8058 while (UTF8_IS_CONTINUATION(*(U8*)ST.maxpos))
8061 else if (utf8_target) {
8062 int m = ST.max - ST.min;
8063 for (ST.maxpos = locinput;
8064 m >0 && ST.maxpos < reginfo->strend; m--)
8065 ST.maxpos += UTF8SKIP(ST.maxpos);
8068 ST.maxpos = locinput + ST.max - ST.min;
8069 if (ST.maxpos >= reginfo->strend)
8070 ST.maxpos = reginfo->strend - 1;
8072 goto curly_try_B_min_known;
8076 /* avoid taking address of locinput, so it can remain
8078 char *li = locinput;
8079 ST.count = regrepeat(rex, &li, ST.A, reginfo, ST.max);
8080 if (ST.count < ST.min)
8083 if ((ST.count > ST.min)
8084 && (PL_regkind[OP(ST.B)] == EOL) && (OP(ST.B) != MEOL))
8086 /* A{m,n} must come at the end of the string, there's
8087 * no point in backing off ... */
8089 /* ...except that $ and \Z can match before *and* after
8090 newline at the end. Consider "\n\n" =~ /\n+\Z\n/.
8091 We may back off by one in this case. */
8092 if (UCHARAT(locinput - 1) == '\n' && OP(ST.B) != EOS)
8096 goto curly_try_B_max;
8098 NOT_REACHED; /* NOTREACHED */
8100 case CURLY_B_min_known_fail:
8101 /* failed to find B in a non-greedy match where c1,c2 valid */
8103 REGCP_UNWIND(ST.cp);
8105 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
8107 /* Couldn't or didn't -- move forward. */
8108 ST.oldloc = locinput;
8110 locinput += UTF8SKIP(locinput);
8114 curly_try_B_min_known:
8115 /* find the next place where 'B' could work, then call B */
8119 n = (ST.oldloc == locinput) ? 0 : 1;
8120 if (ST.c1 == ST.c2) {
8121 /* set n to utf8_distance(oldloc, locinput) */
8122 while (locinput <= ST.maxpos
8123 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput)))
8125 locinput += UTF8SKIP(locinput);
8130 /* set n to utf8_distance(oldloc, locinput) */
8131 while (locinput <= ST.maxpos
8132 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
8133 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
8135 locinput += UTF8SKIP(locinput);
8140 else { /* Not utf8_target */
8141 if (ST.c1 == ST.c2) {
8142 while (locinput <= ST.maxpos &&
8143 UCHARAT(locinput) != ST.c1)
8147 while (locinput <= ST.maxpos
8148 && UCHARAT(locinput) != ST.c1
8149 && UCHARAT(locinput) != ST.c2)
8152 n = locinput - ST.oldloc;
8154 if (locinput > ST.maxpos)
8157 /* In /a{m,n}b/, ST.oldloc is at "a" x m, locinput is
8158 * at b; check that everything between oldloc and
8159 * locinput matches */
8160 char *li = ST.oldloc;
8162 if (regrepeat(rex, &li, ST.A, reginfo, n) < n)
8164 assert(n == REG_INFTY || locinput == li);
8166 CURLY_SETPAREN(ST.paren, ST.count);
8167 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.paren))
8169 PUSH_STATE_GOTO(CURLY_B_min_known, ST.B, locinput);
8171 NOT_REACHED; /* NOTREACHED */
8173 case CURLY_B_min_fail:
8174 /* failed to find B in a non-greedy match where c1,c2 invalid */
8176 REGCP_UNWIND(ST.cp);
8178 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
8180 /* failed -- move forward one */
8182 char *li = locinput;
8183 if (!regrepeat(rex, &li, ST.A, reginfo, 1)) {
8190 if (ST.count <= ST.max || (ST.max == REG_INFTY &&
8191 ST.count > 0)) /* count overflow ? */
8194 CURLY_SETPAREN(ST.paren, ST.count);
8195 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.paren))
8197 PUSH_STATE_GOTO(CURLY_B_min, ST.B, locinput);
8201 NOT_REACHED; /* NOTREACHED */
8204 /* a successful greedy match: now try to match B */
8205 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.paren))
8208 bool could_match = locinput < reginfo->strend;
8210 /* If it could work, try it. */
8211 if (ST.c1 != CHRTEST_VOID && could_match) {
8212 if (! UTF8_IS_INVARIANT(UCHARAT(locinput)) && utf8_target)
8214 could_match = memEQ(locinput,
8219 UTF8SKIP(locinput));
8222 could_match = UCHARAT(locinput) == ST.c1
8223 || UCHARAT(locinput) == ST.c2;
8226 if (ST.c1 == CHRTEST_VOID || could_match) {
8227 CURLY_SETPAREN(ST.paren, ST.count);
8228 PUSH_STATE_GOTO(CURLY_B_max, ST.B, locinput);
8229 NOT_REACHED; /* NOTREACHED */
8234 case CURLY_B_max_fail:
8235 /* failed to find B in a greedy match */
8237 REGCP_UNWIND(ST.cp);
8239 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
8242 if (--ST.count < ST.min)
8244 locinput = HOPc(locinput, -1);
8245 goto curly_try_B_max;
8249 case END: /* last op of main pattern */
8252 /* we've just finished A in /(??{A})B/; now continue with B */
8253 SET_RECURSE_LOCINPUT("FAKE-END[before]", CUR_EVAL.prev_recurse_locinput);
8254 st->u.eval.prev_rex = rex_sv; /* inner */
8256 /* Save *all* the positions. */
8257 st->u.eval.cp = regcppush(rex, 0, maxopenparen);
8258 rex_sv = CUR_EVAL.prev_rex;
8259 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
8260 SET_reg_curpm(rex_sv);
8261 rex = ReANY(rex_sv);
8262 rexi = RXi_GET(rex);
8264 st->u.eval.prev_curlyx = cur_curlyx;
8265 cur_curlyx = CUR_EVAL.prev_curlyx;
8267 REGCP_SET(st->u.eval.lastcp);
8269 /* Restore parens of the outer rex without popping the
8271 regcp_restore(rex, CUR_EVAL.lastcp, &maxopenparen);
8273 st->u.eval.prev_eval = cur_eval;
8274 cur_eval = CUR_EVAL.prev_eval;
8276 Perl_re_exec_indentf( aTHX_ "EVAL trying tail ... (cur_eval=%p)\n",
8278 if ( nochange_depth )
8281 SET_RECURSE_LOCINPUT("FAKE-END[after]", cur_eval->locinput);
8283 PUSH_YES_STATE_GOTO(EVAL_postponed_AB, st->u.eval.prev_eval->u.eval.B,
8284 locinput); /* match B */
8287 if (locinput < reginfo->till) {
8288 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
8289 "%sMatch possible, but length=%ld is smaller than requested=%ld, failing!%s\n",
8291 (long)(locinput - startpos),
8292 (long)(reginfo->till - startpos),
8295 sayNO_SILENT; /* Cannot match: too short. */
8297 sayYES; /* Success! */
8299 case SUCCEED: /* successful SUSPEND/UNLESSM/IFMATCH/CURLYM */
8301 Perl_re_exec_indentf( aTHX_ "%ssubpattern success...%s\n",
8302 depth, PL_colors[4], PL_colors[5]));
8303 sayYES; /* Success! */
8306 #define ST st->u.ifmatch
8311 case SUSPEND: /* (?>A) */
8313 newstart = locinput;
8316 case UNLESSM: /* -ve lookaround: (?!A), or with flags, (?<!A) */
8318 goto ifmatch_trivial_fail_test;
8320 case IFMATCH: /* +ve lookaround: (?=A), or with flags, (?<=A) */
8322 ifmatch_trivial_fail_test:
8324 char * const s = HOPBACKc(locinput, scan->flags);
8329 sw = 1 - cBOOL(ST.wanted);
8333 next = scan + ARG(scan);
8341 newstart = locinput;
8345 ST.logical = logical;
8346 logical = 0; /* XXX: reset state of logical once it has been saved into ST */
8348 /* execute body of (?...A) */
8349 PUSH_YES_STATE_GOTO(IFMATCH_A, NEXTOPER(NEXTOPER(scan)), newstart);
8350 NOT_REACHED; /* NOTREACHED */
8353 case IFMATCH_A_fail: /* body of (?...A) failed */
8354 ST.wanted = !ST.wanted;
8357 case IFMATCH_A: /* body of (?...A) succeeded */
8359 sw = cBOOL(ST.wanted);
8361 else if (!ST.wanted)
8364 if (OP(ST.me) != SUSPEND) {
8365 /* restore old position except for (?>...) */
8366 locinput = st->locinput;
8368 scan = ST.me + ARG(ST.me);
8371 continue; /* execute B */
8375 case LONGJMP: /* alternative with many branches compiles to
8376 * (BRANCHJ; EXACT ...; LONGJMP ) x N */
8377 next = scan + ARG(scan);
8382 case COMMIT: /* (*COMMIT) */
8383 reginfo->cutpoint = reginfo->strend;
8386 case PRUNE: /* (*PRUNE) */
8388 sv_yes_mark = sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8389 PUSH_STATE_GOTO(COMMIT_next, next, locinput);
8390 NOT_REACHED; /* NOTREACHED */
8392 case COMMIT_next_fail:
8396 NOT_REACHED; /* NOTREACHED */
8398 case OPFAIL: /* (*FAIL) */
8400 sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8402 /* deal with (?(?!)X|Y) properly,
8403 * make sure we trigger the no branch
8404 * of the trailing IFTHEN structure*/
8410 NOT_REACHED; /* NOTREACHED */
8412 #define ST st->u.mark
8413 case MARKPOINT: /* (*MARK:foo) */
8414 ST.prev_mark = mark_state;
8415 ST.mark_name = sv_commit = sv_yes_mark
8416 = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8418 ST.mark_loc = locinput;
8419 PUSH_YES_STATE_GOTO(MARKPOINT_next, next, locinput);
8420 NOT_REACHED; /* NOTREACHED */
8422 case MARKPOINT_next:
8423 mark_state = ST.prev_mark;
8425 NOT_REACHED; /* NOTREACHED */
8427 case MARKPOINT_next_fail:
8428 if (popmark && sv_eq(ST.mark_name,popmark))
8430 if (ST.mark_loc > startpoint)
8431 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
8432 popmark = NULL; /* we found our mark */
8433 sv_commit = ST.mark_name;
8436 Perl_re_exec_indentf( aTHX_ "%ssetting cutpoint to mark:%" SVf "...%s\n",
8438 PL_colors[4], SVfARG(sv_commit), PL_colors[5]);
8441 mark_state = ST.prev_mark;
8442 sv_yes_mark = mark_state ?
8443 mark_state->u.mark.mark_name : NULL;
8445 NOT_REACHED; /* NOTREACHED */
8447 case SKIP: /* (*SKIP) */
8449 /* (*SKIP) : if we fail we cut here*/
8450 ST.mark_name = NULL;
8451 ST.mark_loc = locinput;
8452 PUSH_STATE_GOTO(SKIP_next,next, locinput);
8454 /* (*SKIP:NAME) : if there is a (*MARK:NAME) fail where it was,
8455 otherwise do nothing. Meaning we need to scan
8457 regmatch_state *cur = mark_state;
8458 SV *find = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8461 if ( sv_eq( cur->u.mark.mark_name,
8464 ST.mark_name = find;
8465 PUSH_STATE_GOTO( SKIP_next, next, locinput);
8467 cur = cur->u.mark.prev_mark;
8470 /* Didn't find our (*MARK:NAME) so ignore this (*SKIP:NAME) */
8473 case SKIP_next_fail:
8475 /* (*CUT:NAME) - Set up to search for the name as we
8476 collapse the stack*/
8477 popmark = ST.mark_name;
8479 /* (*CUT) - No name, we cut here.*/
8480 if (ST.mark_loc > startpoint)
8481 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
8482 /* but we set sv_commit to latest mark_name if there
8483 is one so they can test to see how things lead to this
8486 sv_commit=mark_state->u.mark.mark_name;
8490 NOT_REACHED; /* NOTREACHED */
8493 case LNBREAK: /* \R */
8494 if ((n=is_LNBREAK_safe(locinput, reginfo->strend, utf8_target))) {
8501 PerlIO_printf(Perl_error_log, "%" UVxf " %d\n",
8502 PTR2UV(scan), OP(scan));
8503 Perl_croak(aTHX_ "regexp memory corruption");
8505 /* this is a point to jump to in order to increment
8506 * locinput by one character */
8508 assert(!NEXTCHR_IS_EOS);
8510 locinput += PL_utf8skip[nextchr];
8511 /* locinput is allowed to go 1 char off the end (signifying
8512 * EOS), but not 2+ */
8513 if (locinput > reginfo->strend)
8522 /* switch break jumps here */
8523 scan = next; /* prepare to execute the next op and ... */
8524 continue; /* ... jump back to the top, reusing st */
8528 /* push a state that backtracks on success */
8529 st->u.yes.prev_yes_state = yes_state;
8533 /* push a new regex state, then continue at scan */
8535 regmatch_state *newst;
8538 regmatch_state *cur = st;
8539 regmatch_state *curyes = yes_state;
8541 regmatch_slab *slab = PL_regmatch_slab;
8542 for (i = 0; i < 3 && i <= depth; cur--,i++) {
8543 if (cur < SLAB_FIRST(slab)) {
8545 cur = SLAB_LAST(slab);
8547 Perl_re_exec_indentf( aTHX_ "%4s #%-3d %-10s %s\n",
8550 depth - i, PL_reg_name[cur->resume_state],
8551 (curyes == cur) ? "yes" : ""
8554 curyes = cur->u.yes.prev_yes_state;
8557 DEBUG_STATE_pp("push")
8560 st->locinput = locinput;
8562 if (newst > SLAB_LAST(PL_regmatch_slab))
8563 newst = S_push_slab(aTHX);
8564 PL_regmatch_state = newst;
8566 locinput = pushinput;
8572 #ifdef SOLARIS_BAD_OPTIMIZER
8573 # undef PL_charclass
8577 * We get here only if there's trouble -- normally "case END" is
8578 * the terminating point.
8580 Perl_croak(aTHX_ "corrupted regexp pointers");
8581 NOT_REACHED; /* NOTREACHED */
8585 /* we have successfully completed a subexpression, but we must now
8586 * pop to the state marked by yes_state and continue from there */
8587 assert(st != yes_state);
8589 while (st != yes_state) {
8591 if (st < SLAB_FIRST(PL_regmatch_slab)) {
8592 PL_regmatch_slab = PL_regmatch_slab->prev;
8593 st = SLAB_LAST(PL_regmatch_slab);
8597 DEBUG_STATE_pp("pop (no final)");
8599 DEBUG_STATE_pp("pop (yes)");
8605 while (yes_state < SLAB_FIRST(PL_regmatch_slab)
8606 || yes_state > SLAB_LAST(PL_regmatch_slab))
8608 /* not in this slab, pop slab */
8609 depth -= (st - SLAB_FIRST(PL_regmatch_slab) + 1);
8610 PL_regmatch_slab = PL_regmatch_slab->prev;
8611 st = SLAB_LAST(PL_regmatch_slab);
8613 depth -= (st - yes_state);
8616 yes_state = st->u.yes.prev_yes_state;
8617 PL_regmatch_state = st;
8620 locinput= st->locinput;
8621 state_num = st->resume_state + no_final;
8622 goto reenter_switch;
8625 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%sMatch successful!%s\n",
8626 PL_colors[4], PL_colors[5]));
8628 if (reginfo->info_aux_eval) {
8629 /* each successfully executed (?{...}) block does the equivalent of
8630 * local $^R = do {...}
8631 * When popping the save stack, all these locals would be undone;
8632 * bypass this by setting the outermost saved $^R to the latest
8634 /* I dont know if this is needed or works properly now.
8635 * see code related to PL_replgv elsewhere in this file.
8638 if (oreplsv != GvSV(PL_replgv))
8639 sv_setsv(oreplsv, GvSV(PL_replgv));
8646 Perl_re_exec_indentf( aTHX_ "%sfailed...%s\n",
8648 PL_colors[4], PL_colors[5])
8660 /* there's a previous state to backtrack to */
8662 if (st < SLAB_FIRST(PL_regmatch_slab)) {
8663 PL_regmatch_slab = PL_regmatch_slab->prev;
8664 st = SLAB_LAST(PL_regmatch_slab);
8666 PL_regmatch_state = st;
8667 locinput= st->locinput;
8669 DEBUG_STATE_pp("pop");
8671 if (yes_state == st)
8672 yes_state = st->u.yes.prev_yes_state;
8674 state_num = st->resume_state + 1; /* failure = success + 1 */
8676 goto reenter_switch;
8681 if (rex->intflags & PREGf_VERBARG_SEEN) {
8682 SV *sv_err = get_sv("REGERROR", 1);
8683 SV *sv_mrk = get_sv("REGMARK", 1);
8685 sv_commit = &PL_sv_no;
8687 sv_yes_mark = &PL_sv_yes;
8690 sv_commit = &PL_sv_yes;
8691 sv_yes_mark = &PL_sv_no;
8695 sv_setsv(sv_err, sv_commit);
8696 sv_setsv(sv_mrk, sv_yes_mark);
8700 if (last_pushed_cv) {
8702 /* see "Some notes about MULTICALL" above */
8704 PERL_UNUSED_VAR(SP);
8707 LEAVE_SCOPE(orig_savestack_ix);
8709 assert(!result || locinput - reginfo->strbeg >= 0);
8710 return result ? locinput - reginfo->strbeg : -1;
8714 - regrepeat - repeatedly match something simple, report how many
8716 * What 'simple' means is a node which can be the operand of a quantifier like
8719 * startposp - pointer a pointer to the start position. This is updated
8720 * to point to the byte following the highest successful
8722 * p - the regnode to be repeatedly matched against.
8723 * reginfo - struct holding match state, such as strend
8724 * max - maximum number of things to match.
8725 * depth - (for debugging) backtracking depth.
8728 S_regrepeat(pTHX_ regexp *prog, char **startposp, const regnode *p,
8729 regmatch_info *const reginfo, I32 max _pDEPTH)
8731 char *scan; /* Pointer to current position in target string */
8733 char *loceol = reginfo->strend; /* local version */
8734 I32 hardcount = 0; /* How many matches so far */
8735 bool utf8_target = reginfo->is_utf8_target;
8736 unsigned int to_complement = 0; /* Invert the result? */
8738 _char_class_number classnum;
8740 PERL_ARGS_ASSERT_REGREPEAT;
8743 if (max == REG_INFTY)
8745 else if (! utf8_target && loceol - scan > max)
8746 loceol = scan + max;
8748 /* Here, for the case of a non-UTF-8 target we have adjusted <loceol> down
8749 * to the maximum of how far we should go in it (leaving it set to the real
8750 * end, if the maximum permissible would take us beyond that). This allows
8751 * us to make the loop exit condition that we haven't gone past <loceol> to
8752 * also mean that we haven't exceeded the max permissible count, saving a
8753 * test each time through the loop. But it assumes that the OP matches a
8754 * single byte, which is true for most of the OPs below when applied to a
8755 * non-UTF-8 target. Those relatively few OPs that don't have this
8756 * characteristic will have to compensate.
8758 * There is no adjustment for UTF-8 targets, as the number of bytes per
8759 * character varies. OPs will have to test both that the count is less
8760 * than the max permissible (using <hardcount> to keep track), and that we
8761 * are still within the bounds of the string (using <loceol>. A few OPs
8762 * match a single byte no matter what the encoding. They can omit the max
8763 * test if, for the UTF-8 case, they do the adjustment that was skipped
8766 * Thus, the code above sets things up for the common case; and exceptional
8767 * cases need extra work; the common case is to make sure <scan> doesn't
8768 * go past <loceol>, and for UTF-8 to also use <hardcount> to make sure the
8769 * count doesn't exceed the maximum permissible */
8774 while (scan < loceol && hardcount < max && *scan != '\n') {
8775 scan += UTF8SKIP(scan);
8779 while (scan < loceol && *scan != '\n')
8785 while (scan < loceol && hardcount < max) {
8786 scan += UTF8SKIP(scan);
8794 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8795 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*scan)) {
8796 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(scan, loceol);
8800 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
8804 /* Can use a simple loop if the pattern char to match on is invariant
8805 * under UTF-8, or both target and pattern aren't UTF-8. Note that we
8806 * can use UTF8_IS_INVARIANT() even if the pattern isn't UTF-8, as it's
8807 * true iff it doesn't matter if the argument is in UTF-8 or not */
8808 if (UTF8_IS_INVARIANT(c) || (! utf8_target && ! reginfo->is_utf8_pat)) {
8809 if (utf8_target && loceol - scan > max) {
8810 /* We didn't adjust <loceol> because is UTF-8, but ok to do so,
8811 * since here, to match at all, 1 char == 1 byte */
8812 loceol = scan + max;
8814 while (scan < loceol && UCHARAT(scan) == c) {
8818 else if (reginfo->is_utf8_pat) {
8820 STRLEN scan_char_len;
8822 /* When both target and pattern are UTF-8, we have to do
8824 while (hardcount < max
8826 && (scan_char_len = UTF8SKIP(scan)) <= STR_LEN(p)
8827 && memEQ(scan, STRING(p), scan_char_len))
8829 scan += scan_char_len;
8833 else if (! UTF8_IS_ABOVE_LATIN1(c)) {
8835 /* Target isn't utf8; convert the character in the UTF-8
8836 * pattern to non-UTF8, and do a simple loop */
8837 c = EIGHT_BIT_UTF8_TO_NATIVE(c, *(STRING(p) + 1));
8838 while (scan < loceol && UCHARAT(scan) == c) {
8841 } /* else pattern char is above Latin1, can't possibly match the
8846 /* Here, the string must be utf8; pattern isn't, and <c> is
8847 * different in utf8 than not, so can't compare them directly.
8848 * Outside the loop, find the two utf8 bytes that represent c, and
8849 * then look for those in sequence in the utf8 string */
8850 U8 high = UTF8_TWO_BYTE_HI(c);
8851 U8 low = UTF8_TWO_BYTE_LO(c);
8853 while (hardcount < max
8854 && scan + 1 < loceol
8855 && UCHARAT(scan) == high
8856 && UCHARAT(scan + 1) == low)
8864 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
8865 assert(! reginfo->is_utf8_pat);
8868 utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
8872 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8873 utf8_flags = FOLDEQ_LOCALE;
8876 case EXACTF: /* This node only generated for non-utf8 patterns */
8877 assert(! reginfo->is_utf8_pat);
8882 if (! utf8_target) {
8885 utf8_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
8886 | FOLDEQ_S2_FOLDS_SANE;
8891 utf8_flags = reginfo->is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
8895 U8 c1_utf8[UTF8_MAXBYTES+1], c2_utf8[UTF8_MAXBYTES+1];
8897 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
8899 if (S_setup_EXACTISH_ST_c1_c2(aTHX_ p, &c1, c1_utf8, &c2, c2_utf8,
8902 if (c1 == CHRTEST_VOID) {
8903 /* Use full Unicode fold matching */
8904 char *tmpeol = reginfo->strend;
8905 STRLEN pat_len = reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1;
8906 while (hardcount < max
8907 && foldEQ_utf8_flags(scan, &tmpeol, 0, utf8_target,
8908 STRING(p), NULL, pat_len,
8909 reginfo->is_utf8_pat, utf8_flags))
8912 tmpeol = reginfo->strend;
8916 else if (utf8_target) {
8918 while (scan < loceol
8920 && memEQ(scan, c1_utf8, UTF8SKIP(scan)))
8922 scan += UTF8SKIP(scan);
8927 while (scan < loceol
8929 && (memEQ(scan, c1_utf8, UTF8SKIP(scan))
8930 || memEQ(scan, c2_utf8, UTF8SKIP(scan))))
8932 scan += UTF8SKIP(scan);
8937 else if (c1 == c2) {
8938 while (scan < loceol && UCHARAT(scan) == c1) {
8943 while (scan < loceol &&
8944 (UCHARAT(scan) == c1 || UCHARAT(scan) == c2))
8953 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8955 if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(p)) && ! IN_UTF8_CTYPE_LOCALE) {
8956 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
8962 while (hardcount < max
8964 && reginclass(prog, p, (U8*)scan, (U8*) loceol, utf8_target))
8966 scan += UTF8SKIP(scan);
8970 else if (ANYOF_FLAGS(p)) {
8971 while (scan < loceol
8972 && reginclass(prog, p, (U8*)scan, (U8*)scan+1, 0))
8976 while (scan < loceol && ANYOF_BITMAP_TEST(p, *((U8*)scan)))
8981 /* The argument (FLAGS) to all the POSIX node types is the class number */
8988 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8989 if (! utf8_target) {
8990 while (scan < loceol && to_complement ^ cBOOL(isFOO_lc(FLAGS(p),
8996 while (hardcount < max && scan < loceol
8997 && to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(p),
9000 scan += UTF8SKIP(scan);
9013 if (utf8_target && loceol - scan > max) {
9015 /* We didn't adjust <loceol> at the beginning of this routine
9016 * because is UTF-8, but it is actually ok to do so, since here, to
9017 * match, 1 char == 1 byte. */
9018 loceol = scan + max;
9020 while (scan < loceol && _generic_isCC_A((U8) *scan, FLAGS(p))) {
9033 if (! utf8_target) {
9034 while (scan < loceol && ! _generic_isCC_A((U8) *scan, FLAGS(p))) {
9040 /* The complement of something that matches only ASCII matches all
9041 * non-ASCII, plus everything in ASCII that isn't in the class. */
9042 while (hardcount < max && scan < loceol
9043 && ( ! isASCII_utf8_safe(scan, reginfo->strend)
9044 || ! _generic_isCC_A((U8) *scan, FLAGS(p))))
9046 scan += UTF8SKIP(scan);
9057 if (! utf8_target) {
9058 while (scan < loceol && to_complement
9059 ^ cBOOL(_generic_isCC((U8) *scan, FLAGS(p))))
9066 classnum = (_char_class_number) FLAGS(p);
9067 if (classnum < _FIRST_NON_SWASH_CC) {
9069 /* Here, a swash is needed for above-Latin1 code points.
9070 * Process as many Latin1 code points using the built-in rules.
9071 * Go to another loop to finish processing upon encountering
9072 * the first Latin1 code point. We could do that in this loop
9073 * as well, but the other way saves having to test if the swash
9074 * has been loaded every time through the loop: extra space to
9076 while (hardcount < max && scan < loceol) {
9077 if (UTF8_IS_INVARIANT(*scan)) {
9078 if (! (to_complement ^ cBOOL(_generic_isCC((U8) *scan,
9085 else if (UTF8_IS_DOWNGRADEABLE_START(*scan)) {
9086 if (! (to_complement
9087 ^ cBOOL(_generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(*scan,
9096 goto found_above_latin1;
9103 /* For these character classes, the knowledge of how to handle
9104 * every code point is compiled in to Perl via a macro. This
9105 * code is written for making the loops as tight as possible.
9106 * It could be refactored to save space instead */
9108 case _CC_ENUM_SPACE:
9109 while (hardcount < max
9112 ^ cBOOL(isSPACE_utf8_safe(scan, loceol))))
9114 scan += UTF8SKIP(scan);
9118 case _CC_ENUM_BLANK:
9119 while (hardcount < max
9122 ^ cBOOL(isBLANK_utf8_safe(scan, loceol))))
9124 scan += UTF8SKIP(scan);
9128 case _CC_ENUM_XDIGIT:
9129 while (hardcount < max
9132 ^ cBOOL(isXDIGIT_utf8_safe(scan, loceol))))
9134 scan += UTF8SKIP(scan);
9138 case _CC_ENUM_VERTSPACE:
9139 while (hardcount < max
9142 ^ cBOOL(isVERTWS_utf8_safe(scan, loceol))))
9144 scan += UTF8SKIP(scan);
9148 case _CC_ENUM_CNTRL:
9149 while (hardcount < max
9152 ^ cBOOL(isCNTRL_utf8_safe(scan, loceol))))
9154 scan += UTF8SKIP(scan);
9159 Perl_croak(aTHX_ "panic: regrepeat() node %d='%s' has an unexpected character class '%d'", OP(p), PL_reg_name[OP(p)], classnum);
9165 found_above_latin1: /* Continuation of POSIXU and NPOSIXU */
9167 /* Load the swash if not already present */
9168 if (! PL_utf8_swash_ptrs[classnum]) {
9169 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
9170 PL_utf8_swash_ptrs[classnum] = _core_swash_init(
9174 PL_XPosix_ptrs[classnum], &flags);
9177 while (hardcount < max && scan < loceol
9178 && to_complement ^ cBOOL(_generic_utf8_safe(
9182 swash_fetch(PL_utf8_swash_ptrs[classnum],
9186 scan += UTF8SKIP(scan);
9193 while (hardcount < max && scan < loceol &&
9194 (c=is_LNBREAK_utf8_safe(scan, loceol))) {
9199 /* LNBREAK can match one or two latin chars, which is ok, but we
9200 * have to use hardcount in this situation, and throw away the
9201 * adjustment to <loceol> done before the switch statement */
9202 loceol = reginfo->strend;
9203 while (scan < loceol && (c=is_LNBREAK_latin1_safe(scan, loceol))) {
9212 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
9226 /* These are all 0 width, so match right here or not at all. */
9230 Perl_croak(aTHX_ "panic: regrepeat() called with unrecognized node type %d='%s'", OP(p), PL_reg_name[OP(p)]);
9231 NOT_REACHED; /* NOTREACHED */
9238 c = scan - *startposp;
9242 GET_RE_DEBUG_FLAGS_DECL;
9244 SV * const prop = sv_newmortal();
9245 regprop(prog, prop, p, reginfo, NULL);
9246 Perl_re_exec_indentf( aTHX_ "%s can match %" IVdf " times out of %" IVdf "...\n",
9247 depth, SvPVX_const(prop),(IV)c,(IV)max);
9255 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
9257 - regclass_swash - prepare the utf8 swash. Wraps the shared core version to
9258 create a copy so that changes the caller makes won't change the shared one.
9259 If <altsvp> is non-null, will return NULL in it, for back-compat.
9262 Perl_regclass_swash(pTHX_ const regexp *prog, const regnode* node, bool doinit, SV** listsvp, SV **altsvp)
9264 PERL_ARGS_ASSERT_REGCLASS_SWASH;
9270 return newSVsv(_get_regclass_nonbitmap_data(prog, node, doinit, listsvp, NULL, NULL));
9273 #endif /* !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION) */
9276 - reginclass - determine if a character falls into a character class
9278 n is the ANYOF-type regnode
9279 p is the target string
9280 p_end points to one byte beyond the end of the target string
9281 utf8_target tells whether p is in UTF-8.
9283 Returns true if matched; false otherwise.
9285 Note that this can be a synthetic start class, a combination of various
9286 nodes, so things you think might be mutually exclusive, such as locale,
9287 aren't. It can match both locale and non-locale
9292 S_reginclass(pTHX_ regexp * const prog, const regnode * const n, const U8* const p, const U8* const p_end, const bool utf8_target)
9295 const char flags = ANYOF_FLAGS(n);
9299 PERL_ARGS_ASSERT_REGINCLASS;
9301 /* If c is not already the code point, get it. Note that
9302 * UTF8_IS_INVARIANT() works even if not in UTF-8 */
9303 if (! UTF8_IS_INVARIANT(c) && utf8_target) {
9305 const U32 utf8n_flags = UTF8_ALLOW_DEFAULT;
9306 c = utf8n_to_uvchr(p, p_end - p, &c_len, utf8n_flags | UTF8_CHECK_ONLY);
9307 if (c_len == (STRLEN)-1) {
9308 _force_out_malformed_utf8_message(p, p_end,
9310 1 /* 1 means die */ );
9311 NOT_REACHED; /* NOTREACHED */
9313 if (c > 255 && OP(n) == ANYOFL && ! ANYOFL_UTF8_LOCALE_REQD(flags)) {
9314 _CHECK_AND_OUTPUT_WIDE_LOCALE_CP_MSG(c);
9318 /* If this character is potentially in the bitmap, check it */
9319 if (c < NUM_ANYOF_CODE_POINTS) {
9320 if (ANYOF_BITMAP_TEST(n, c))
9323 & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
9330 else if (flags & ANYOF_LOCALE_FLAGS) {
9331 if ((flags & ANYOFL_FOLD)
9333 && ANYOF_BITMAP_TEST(n, PL_fold_locale[c]))
9337 else if (ANYOF_POSIXL_TEST_ANY_SET(n)
9341 /* The data structure is arranged so bits 0, 2, 4, ... are set
9342 * if the class includes the Posix character class given by
9343 * bit/2; and 1, 3, 5, ... are set if the class includes the
9344 * complemented Posix class given by int(bit/2). So we loop
9345 * through the bits, each time changing whether we complement
9346 * the result or not. Suppose for the sake of illustration
9347 * that bits 0-3 mean respectively, \w, \W, \s, \S. If bit 0
9348 * is set, it means there is a match for this ANYOF node if the
9349 * character is in the class given by the expression (0 / 2 = 0
9350 * = \w). If it is in that class, isFOO_lc() will return 1,
9351 * and since 'to_complement' is 0, the result will stay TRUE,
9352 * and we exit the loop. Suppose instead that bit 0 is 0, but
9353 * bit 1 is 1. That means there is a match if the character
9354 * matches \W. We won't bother to call isFOO_lc() on bit 0,
9355 * but will on bit 1. On the second iteration 'to_complement'
9356 * will be 1, so the exclusive or will reverse things, so we
9357 * are testing for \W. On the third iteration, 'to_complement'
9358 * will be 0, and we would be testing for \s; the fourth
9359 * iteration would test for \S, etc.
9361 * Note that this code assumes that all the classes are closed
9362 * under folding. For example, if a character matches \w, then
9363 * its fold does too; and vice versa. This should be true for
9364 * any well-behaved locale for all the currently defined Posix
9365 * classes, except for :lower: and :upper:, which are handled
9366 * by the pseudo-class :cased: which matches if either of the
9367 * other two does. To get rid of this assumption, an outer
9368 * loop could be used below to iterate over both the source
9369 * character, and its fold (if different) */
9372 int to_complement = 0;
9374 while (count < ANYOF_MAX) {
9375 if (ANYOF_POSIXL_TEST(n, count)
9376 && to_complement ^ cBOOL(isFOO_lc(count/2, (U8) c)))
9389 /* If the bitmap didn't (or couldn't) match, and something outside the
9390 * bitmap could match, try that. */
9392 if (c >= NUM_ANYOF_CODE_POINTS
9393 && (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP))
9395 match = TRUE; /* Everything above the bitmap matches */
9397 /* Here doesn't match everything above the bitmap. If there is
9398 * some information available beyond the bitmap, we may find a
9399 * match in it. If so, this is most likely because the code point
9400 * is outside the bitmap range. But rarely, it could be because of
9401 * some other reason. If so, various flags are set to indicate
9402 * this possibility. On ANYOFD nodes, there may be matches that
9403 * happen only when the target string is UTF-8; or for other node
9404 * types, because runtime lookup is needed, regardless of the
9405 * UTF-8ness of the target string. Finally, under /il, there may
9406 * be some matches only possible if the locale is a UTF-8 one. */
9407 else if ( ARG(n) != ANYOF_ONLY_HAS_BITMAP
9408 && ( c >= NUM_ANYOF_CODE_POINTS
9409 || ( (flags & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)
9410 && ( UNLIKELY(OP(n) != ANYOFD)
9411 || (utf8_target && ! isASCII_uni(c)
9412 # if NUM_ANYOF_CODE_POINTS > 256
9416 || ( ANYOFL_SOME_FOLDS_ONLY_IN_UTF8_LOCALE(flags)
9417 && IN_UTF8_CTYPE_LOCALE)))
9419 SV* only_utf8_locale = NULL;
9420 SV * const sw = _get_regclass_nonbitmap_data(prog, n, TRUE, 0,
9421 &only_utf8_locale, NULL);
9427 } else { /* Convert to utf8 */
9428 utf8_p = utf8_buffer;
9429 append_utf8_from_native_byte(*p, &utf8_p);
9430 utf8_p = utf8_buffer;
9433 if (swash_fetch(sw, utf8_p, TRUE)) {
9437 if (! match && only_utf8_locale && IN_UTF8_CTYPE_LOCALE) {
9438 match = _invlist_contains_cp(only_utf8_locale, c);
9442 if (UNICODE_IS_SUPER(c)
9444 & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
9446 && ckWARN_d(WARN_NON_UNICODE))
9448 Perl_warner(aTHX_ packWARN(WARN_NON_UNICODE),
9449 "Matched non-Unicode code point 0x%04" UVXf " against Unicode property; may not be portable", c);
9453 #if ANYOF_INVERT != 1
9454 /* Depending on compiler optimization cBOOL takes time, so if don't have to
9456 # error ANYOF_INVERT needs to be set to 1, or guarded with cBOOL below,
9459 /* The xor complements the return if to invert: 1^1 = 0, 1^0 = 1 */
9460 return (flags & ANYOF_INVERT) ^ match;
9464 S_reghop3(U8 *s, SSize_t off, const U8* lim)
9466 /* return the position 'off' UTF-8 characters away from 's', forward if
9467 * 'off' >= 0, backwards if negative. But don't go outside of position
9468 * 'lim', which better be < s if off < 0 */
9470 PERL_ARGS_ASSERT_REGHOP3;
9473 while (off-- && s < lim) {
9474 /* XXX could check well-formedness here */
9479 while (off++ && s > lim) {
9481 if (UTF8_IS_CONTINUED(*s)) {
9482 while (s > lim && UTF8_IS_CONTINUATION(*s))
9484 if (! UTF8_IS_START(*s)) {
9485 Perl_croak_nocontext("Malformed UTF-8 character (fatal)");
9488 /* XXX could check well-formedness here */
9495 S_reghop4(U8 *s, SSize_t off, const U8* llim, const U8* rlim)
9497 PERL_ARGS_ASSERT_REGHOP4;
9500 while (off-- && s < rlim) {
9501 /* XXX could check well-formedness here */
9506 while (off++ && s > llim) {
9508 if (UTF8_IS_CONTINUED(*s)) {
9509 while (s > llim && UTF8_IS_CONTINUATION(*s))
9511 if (! UTF8_IS_START(*s)) {
9512 Perl_croak_nocontext("Malformed UTF-8 character (fatal)");
9515 /* XXX could check well-formedness here */
9521 /* like reghop3, but returns NULL on overrun, rather than returning last
9525 S_reghopmaybe3(U8* s, SSize_t off, const U8* const lim)
9527 PERL_ARGS_ASSERT_REGHOPMAYBE3;
9530 while (off-- && s < lim) {
9531 /* XXX could check well-formedness here */
9538 while (off++ && s > lim) {
9540 if (UTF8_IS_CONTINUED(*s)) {
9541 while (s > lim && UTF8_IS_CONTINUATION(*s))
9543 if (! UTF8_IS_START(*s)) {
9544 Perl_croak_nocontext("Malformed UTF-8 character (fatal)");
9547 /* XXX could check well-formedness here */
9556 /* when executing a regex that may have (?{}), extra stuff needs setting
9557 up that will be visible to the called code, even before the current
9558 match has finished. In particular:
9560 * $_ is localised to the SV currently being matched;
9561 * pos($_) is created if necessary, ready to be updated on each call-out
9563 * a fake PMOP is created that can be set to PL_curpm (normally PL_curpm
9564 isn't set until the current pattern is successfully finished), so that
9565 $1 etc of the match-so-far can be seen;
9566 * save the old values of subbeg etc of the current regex, and set then
9567 to the current string (again, this is normally only done at the end
9572 S_setup_eval_state(pTHX_ regmatch_info *const reginfo)
9575 regexp *const rex = ReANY(reginfo->prog);
9576 regmatch_info_aux_eval *eval_state = reginfo->info_aux_eval;
9578 eval_state->rex = rex;
9581 /* Make $_ available to executed code. */
9582 if (reginfo->sv != DEFSV) {
9584 DEFSV_set(reginfo->sv);
9587 if (!(mg = mg_find_mglob(reginfo->sv))) {
9588 /* prepare for quick setting of pos */
9589 mg = sv_magicext_mglob(reginfo->sv);
9592 eval_state->pos_magic = mg;
9593 eval_state->pos = mg->mg_len;
9594 eval_state->pos_flags = mg->mg_flags;
9597 eval_state->pos_magic = NULL;
9599 if (!PL_reg_curpm) {
9600 /* PL_reg_curpm is a fake PMOP that we can attach the current
9601 * regex to and point PL_curpm at, so that $1 et al are visible
9602 * within a /(?{})/. It's just allocated once per interpreter the
9603 * first time its needed */
9604 Newxz(PL_reg_curpm, 1, PMOP);
9607 SV* const repointer = &PL_sv_undef;
9608 /* this regexp is also owned by the new PL_reg_curpm, which
9609 will try to free it. */
9610 av_push(PL_regex_padav, repointer);
9611 PL_reg_curpm->op_pmoffset = av_tindex(PL_regex_padav);
9612 PL_regex_pad = AvARRAY(PL_regex_padav);
9616 SET_reg_curpm(reginfo->prog);
9617 eval_state->curpm = PL_curpm;
9618 PL_curpm_under = PL_curpm;
9619 PL_curpm = PL_reg_curpm;
9620 if (RXp_MATCH_COPIED(rex)) {
9621 /* Here is a serious problem: we cannot rewrite subbeg,
9622 since it may be needed if this match fails. Thus
9623 $` inside (?{}) could fail... */
9624 eval_state->subbeg = rex->subbeg;
9625 eval_state->sublen = rex->sublen;
9626 eval_state->suboffset = rex->suboffset;
9627 eval_state->subcoffset = rex->subcoffset;
9629 eval_state->saved_copy = rex->saved_copy;
9631 RXp_MATCH_COPIED_off(rex);
9634 eval_state->subbeg = NULL;
9635 rex->subbeg = (char *)reginfo->strbeg;
9637 rex->subcoffset = 0;
9638 rex->sublen = reginfo->strend - reginfo->strbeg;
9642 /* destructor to clear up regmatch_info_aux and regmatch_info_aux_eval */
9645 S_cleanup_regmatch_info_aux(pTHX_ void *arg)
9647 regmatch_info_aux *aux = (regmatch_info_aux *) arg;
9648 regmatch_info_aux_eval *eval_state = aux->info_aux_eval;
9651 Safefree(aux->poscache);
9655 /* undo the effects of S_setup_eval_state() */
9657 if (eval_state->subbeg) {
9658 regexp * const rex = eval_state->rex;
9659 rex->subbeg = eval_state->subbeg;
9660 rex->sublen = eval_state->sublen;
9661 rex->suboffset = eval_state->suboffset;
9662 rex->subcoffset = eval_state->subcoffset;
9664 rex->saved_copy = eval_state->saved_copy;
9666 RXp_MATCH_COPIED_on(rex);
9668 if (eval_state->pos_magic)
9670 eval_state->pos_magic->mg_len = eval_state->pos;
9671 eval_state->pos_magic->mg_flags =
9672 (eval_state->pos_magic->mg_flags & ~MGf_BYTES)
9673 | (eval_state->pos_flags & MGf_BYTES);
9676 PL_curpm = eval_state->curpm;
9679 PL_regmatch_state = aux->old_regmatch_state;
9680 PL_regmatch_slab = aux->old_regmatch_slab;
9682 /* free all slabs above current one - this must be the last action
9683 * of this function, as aux and eval_state are allocated within
9684 * slabs and may be freed here */
9686 s = PL_regmatch_slab->next;
9688 PL_regmatch_slab->next = NULL;
9690 regmatch_slab * const osl = s;
9699 S_to_utf8_substr(pTHX_ regexp *prog)
9701 /* Converts substr fields in prog from bytes to UTF-8, calling fbm_compile
9702 * on the converted value */
9706 PERL_ARGS_ASSERT_TO_UTF8_SUBSTR;
9709 if (prog->substrs->data[i].substr
9710 && !prog->substrs->data[i].utf8_substr) {
9711 SV* const sv = newSVsv(prog->substrs->data[i].substr);
9712 prog->substrs->data[i].utf8_substr = sv;
9713 sv_utf8_upgrade(sv);
9714 if (SvVALID(prog->substrs->data[i].substr)) {
9715 if (SvTAIL(prog->substrs->data[i].substr)) {
9716 /* Trim the trailing \n that fbm_compile added last
9718 SvCUR_set(sv, SvCUR(sv) - 1);
9719 /* Whilst this makes the SV technically "invalid" (as its
9720 buffer is no longer followed by "\0") when fbm_compile()
9721 adds the "\n" back, a "\0" is restored. */
9722 fbm_compile(sv, FBMcf_TAIL);
9726 if (prog->substrs->data[i].substr == prog->check_substr)
9727 prog->check_utf8 = sv;
9733 S_to_byte_substr(pTHX_ regexp *prog)
9735 /* Converts substr fields in prog from UTF-8 to bytes, calling fbm_compile
9736 * on the converted value; returns FALSE if can't be converted. */
9740 PERL_ARGS_ASSERT_TO_BYTE_SUBSTR;
9743 if (prog->substrs->data[i].utf8_substr
9744 && !prog->substrs->data[i].substr) {
9745 SV* sv = newSVsv(prog->substrs->data[i].utf8_substr);
9746 if (! sv_utf8_downgrade(sv, TRUE)) {
9749 if (SvVALID(prog->substrs->data[i].utf8_substr)) {
9750 if (SvTAIL(prog->substrs->data[i].utf8_substr)) {
9751 /* Trim the trailing \n that fbm_compile added last
9753 SvCUR_set(sv, SvCUR(sv) - 1);
9754 fbm_compile(sv, FBMcf_TAIL);
9758 prog->substrs->data[i].substr = sv;
9759 if (prog->substrs->data[i].utf8_substr == prog->check_utf8)
9760 prog->check_substr = sv;
9767 #ifndef PERL_IN_XSUB_RE
9770 Perl__is_grapheme(pTHX_ const U8 * strbeg, const U8 * s, const U8 * strend, const UV cp)
9772 /* Temporary helper function for toke.c. Verify that the code point 'cp'
9773 * is a stand-alone grapheme. The UTF-8 for 'cp' begins at position 's' in
9774 * the larger string bounded by 'strbeg' and 'strend'.
9776 * 'cp' needs to be assigned (if not a future version of the Unicode
9777 * Standard could make it something that combines with adjacent characters,
9778 * so code using it would then break), and there has to be a GCB break
9779 * before and after the character. */
9781 GCB_enum cp_gcb_val, prev_cp_gcb_val, next_cp_gcb_val;
9782 const U8 * prev_cp_start;
9784 PERL_ARGS_ASSERT__IS_GRAPHEME;
9786 /* Unassigned code points are forbidden */
9787 if (UNLIKELY(! ELEMENT_RANGE_MATCHES_INVLIST(
9788 _invlist_search(PL_Assigned_invlist, cp))))
9793 cp_gcb_val = getGCB_VAL_CP(cp);
9795 /* Find the GCB value of the previous code point in the input */
9796 prev_cp_start = utf8_hop_back(s, -1, strbeg);
9797 if (UNLIKELY(prev_cp_start == s)) {
9798 prev_cp_gcb_val = GCB_EDGE;
9801 prev_cp_gcb_val = getGCB_VAL_UTF8(prev_cp_start, strend);
9804 /* And check that is a grapheme boundary */
9805 if (! isGCB(prev_cp_gcb_val, cp_gcb_val, strbeg, s,
9806 TRUE /* is UTF-8 encoded */ ))
9811 /* Similarly verify there is a break between the current character and the
9815 next_cp_gcb_val = GCB_EDGE;
9818 next_cp_gcb_val = getGCB_VAL_UTF8(s, strend);
9821 return isGCB(cp_gcb_val, next_cp_gcb_val, strbeg, s, TRUE);
9829 * ex: set ts=8 sts=4 sw=4 et: