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))
122 #define CHR_DIST(a,b) (reginfo->is_utf8_target ? utf8_distance(a,b) : a - b)
124 #define HOPc(pos,off) \
125 (char *)(reginfo->is_utf8_target \
126 ? reghop3((U8*)pos, off, \
127 (U8*)(off >= 0 ? reginfo->strend : reginfo->strbeg)) \
130 #define HOPBACKc(pos, off) \
131 (char*)(reginfo->is_utf8_target \
132 ? reghopmaybe3((U8*)pos, (SSize_t)0-off, (U8*)(reginfo->strbeg)) \
133 : (pos - off >= reginfo->strbeg) \
137 #define HOP3(pos,off,lim) (reginfo->is_utf8_target ? reghop3((U8*)(pos), off, (U8*)(lim)) : (U8*)(pos + off))
138 #define HOP3c(pos,off,lim) ((char*)HOP3(pos,off,lim))
140 /* lim must be +ve. Returns NULL on overshoot */
141 #define HOPMAYBE3(pos,off,lim) \
142 (reginfo->is_utf8_target \
143 ? reghopmaybe3((U8*)pos, off, (U8*)(lim)) \
144 : ((U8*)pos + off <= lim) \
148 /* like HOP3, but limits the result to <= lim even for the non-utf8 case.
149 * off must be >=0; args should be vars rather than expressions */
150 #define HOP3lim(pos,off,lim) (reginfo->is_utf8_target \
151 ? reghop3((U8*)(pos), off, (U8*)(lim)) \
152 : (U8*)((pos + off) > lim ? lim : (pos + off)))
154 #define HOP4(pos,off,llim, rlim) (reginfo->is_utf8_target \
155 ? reghop4((U8*)(pos), off, (U8*)(llim), (U8*)(rlim)) \
157 #define HOP4c(pos,off,llim, rlim) ((char*)HOP4(pos,off,llim, rlim))
159 #define NEXTCHR_EOS -10 /* nextchr has fallen off the end */
160 #define NEXTCHR_IS_EOS (nextchr < 0)
162 #define SET_nextchr \
163 nextchr = ((locinput < reginfo->strend) ? UCHARAT(locinput) : NEXTCHR_EOS)
165 #define SET_locinput(p) \
170 #define LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist) STMT_START { \
172 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST; \
173 swash_ptr = _core_swash_init("utf8", property_name, &PL_sv_undef, \
174 1, 0, invlist, &flags); \
179 /* If in debug mode, we test that a known character properly matches */
181 # define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
184 utf8_char_in_property) \
185 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist); \
186 assert(swash_fetch(swash_ptr, (U8 *) utf8_char_in_property, TRUE));
188 # define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
191 utf8_char_in_property) \
192 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist)
195 #define LOAD_UTF8_CHARCLASS_ALNUM() LOAD_UTF8_CHARCLASS_DEBUG_TEST( \
196 PL_utf8_swash_ptrs[_CC_WORDCHAR], \
198 PL_XPosix_ptrs[_CC_WORDCHAR], \
199 LATIN_SMALL_LIGATURE_LONG_S_T_UTF8);
201 #define PLACEHOLDER /* Something for the preprocessor to grab onto */
202 /* TODO: Combine JUMPABLE and HAS_TEXT to cache OP(rn) */
204 /* for use after a quantifier and before an EXACT-like node -- japhy */
205 /* it would be nice to rework regcomp.sym to generate this stuff. sigh
207 * NOTE that *nothing* that affects backtracking should be in here, specifically
208 * VERBS must NOT be included. JUMPABLE is used to determine if we can ignore a
209 * node that is in between two EXACT like nodes when ascertaining what the required
210 * "follow" character is. This should probably be moved to regex compile time
211 * although it may be done at run time beause of the REF possibility - more
212 * investigation required. -- demerphq
214 #define JUMPABLE(rn) ( \
216 (OP(rn) == CLOSE && \
217 !EVAL_CLOSE_PAREN_IS(cur_eval,ARG(rn)) ) || \
219 OP(rn) == SUSPEND || OP(rn) == IFMATCH || \
220 OP(rn) == PLUS || OP(rn) == MINMOD || \
222 (PL_regkind[OP(rn)] == CURLY && ARG1(rn) > 0) \
224 #define IS_EXACT(rn) (PL_regkind[OP(rn)] == EXACT)
226 #define HAS_TEXT(rn) ( IS_EXACT(rn) || PL_regkind[OP(rn)] == REF )
229 /* Currently these are only used when PL_regkind[OP(rn)] == EXACT so
230 we don't need this definition. XXX These are now out-of-sync*/
231 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==REF || OP(rn)==NREF )
232 #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 )
233 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL || OP(rn)==REFFL || OP(rn)==NREFFL )
236 /* ... so we use this as its faster. */
237 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==EXACTL )
238 #define IS_TEXTFU(rn) ( OP(rn)==EXACTFU || OP(rn)==EXACTFLU8 || OP(rn)==EXACTFU_SS || OP(rn) == EXACTFA || OP(rn) == EXACTFA_NO_TRIE)
239 #define IS_TEXTF(rn) ( OP(rn)==EXACTF )
240 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL )
245 Search for mandatory following text node; for lookahead, the text must
246 follow but for lookbehind (rn->flags != 0) we skip to the next step.
248 #define FIND_NEXT_IMPT(rn) STMT_START { \
249 while (JUMPABLE(rn)) { \
250 const OPCODE type = OP(rn); \
251 if (type == SUSPEND || PL_regkind[type] == CURLY) \
252 rn = NEXTOPER(NEXTOPER(rn)); \
253 else if (type == PLUS) \
255 else if (type == IFMATCH) \
256 rn = (rn->flags == 0) ? NEXTOPER(NEXTOPER(rn)) : rn + ARG(rn); \
257 else rn += NEXT_OFF(rn); \
261 #define SLAB_FIRST(s) (&(s)->states[0])
262 #define SLAB_LAST(s) (&(s)->states[PERL_REGMATCH_SLAB_SLOTS-1])
264 static void S_setup_eval_state(pTHX_ regmatch_info *const reginfo);
265 static void S_cleanup_regmatch_info_aux(pTHX_ void *arg);
266 static regmatch_state * S_push_slab(pTHX);
268 #define REGCP_PAREN_ELEMS 3
269 #define REGCP_OTHER_ELEMS 3
270 #define REGCP_FRAME_ELEMS 1
271 /* REGCP_FRAME_ELEMS are not part of the REGCP_OTHER_ELEMS and
272 * are needed for the regexp context stack bookkeeping. */
275 S_regcppush(pTHX_ const regexp *rex, I32 parenfloor, U32 maxopenparen _pDEPTH)
277 const int retval = PL_savestack_ix;
278 const int paren_elems_to_push =
279 (maxopenparen - parenfloor) * REGCP_PAREN_ELEMS;
280 const UV total_elems = paren_elems_to_push + REGCP_OTHER_ELEMS;
281 const UV elems_shifted = total_elems << SAVE_TIGHT_SHIFT;
283 GET_RE_DEBUG_FLAGS_DECL;
285 PERL_ARGS_ASSERT_REGCPPUSH;
287 if (paren_elems_to_push < 0)
288 Perl_croak(aTHX_ "panic: paren_elems_to_push, %i < 0, maxopenparen: %i parenfloor: %i REGCP_PAREN_ELEMS: %u",
289 (int)paren_elems_to_push, (int)maxopenparen,
290 (int)parenfloor, (unsigned)REGCP_PAREN_ELEMS);
292 if ((elems_shifted >> SAVE_TIGHT_SHIFT) != total_elems)
293 Perl_croak(aTHX_ "panic: paren_elems_to_push offset %" UVuf
294 " out of range (%lu-%ld)",
296 (unsigned long)maxopenparen,
299 SSGROW(total_elems + REGCP_FRAME_ELEMS);
302 if ((int)maxopenparen > (int)parenfloor)
303 Perl_re_exec_indentf( aTHX_
304 "rex=0x%" UVxf " offs=0x%" UVxf ": saving capture indices:\n",
310 for (p = parenfloor+1; p <= (I32)maxopenparen; p++) {
311 /* REGCP_PARENS_ELEMS are pushed per pairs of parentheses. */
312 SSPUSHIV(rex->offs[p].end);
313 SSPUSHIV(rex->offs[p].start);
314 SSPUSHINT(rex->offs[p].start_tmp);
315 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_
316 " \\%" UVuf ": %" IVdf "(%" IVdf ")..%" IVdf "\n",
319 (IV)rex->offs[p].start,
320 (IV)rex->offs[p].start_tmp,
324 /* REGCP_OTHER_ELEMS are pushed in any case, parentheses or no. */
325 SSPUSHINT(maxopenparen);
326 SSPUSHINT(rex->lastparen);
327 SSPUSHINT(rex->lastcloseparen);
328 SSPUSHUV(SAVEt_REGCONTEXT | elems_shifted); /* Magic cookie. */
333 /* These are needed since we do not localize EVAL nodes: */
334 #define REGCP_SET(cp) \
336 Perl_re_exec_indentf( aTHX_ \
337 "Setting an EVAL scope, savestack=%" IVdf ",\n", \
338 depth, (IV)PL_savestack_ix \
343 #define REGCP_UNWIND(cp) \
345 if (cp != PL_savestack_ix) \
346 Perl_re_exec_indentf( aTHX_ \
347 "Clearing an EVAL scope, savestack=%" \
348 IVdf "..%" IVdf "\n", \
349 depth, (IV)(cp), (IV)PL_savestack_ix \
354 #define UNWIND_PAREN(lp, lcp) \
355 for (n = rex->lastparen; n > lp; n--) \
356 rex->offs[n].end = -1; \
357 rex->lastparen = n; \
358 rex->lastcloseparen = lcp;
362 S_regcppop(pTHX_ regexp *rex, U32 *maxopenparen_p _pDEPTH)
366 GET_RE_DEBUG_FLAGS_DECL;
368 PERL_ARGS_ASSERT_REGCPPOP;
370 /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
372 assert((i & SAVE_MASK) == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
373 i >>= SAVE_TIGHT_SHIFT; /* Parentheses elements to pop. */
374 rex->lastcloseparen = SSPOPINT;
375 rex->lastparen = SSPOPINT;
376 *maxopenparen_p = SSPOPINT;
378 i -= REGCP_OTHER_ELEMS;
379 /* Now restore the parentheses context. */
381 if (i || rex->lastparen + 1 <= rex->nparens)
382 Perl_re_exec_indentf( aTHX_
383 "rex=0x%" UVxf " offs=0x%" UVxf ": restoring capture indices to:\n",
389 paren = *maxopenparen_p;
390 for ( ; i > 0; i -= REGCP_PAREN_ELEMS) {
392 rex->offs[paren].start_tmp = SSPOPINT;
393 rex->offs[paren].start = SSPOPIV;
395 if (paren <= rex->lastparen)
396 rex->offs[paren].end = tmps;
397 DEBUG_BUFFERS_r( Perl_re_exec_indentf( aTHX_
398 " \\%" UVuf ": %" IVdf "(%" IVdf ")..%" IVdf "%s\n",
401 (IV)rex->offs[paren].start,
402 (IV)rex->offs[paren].start_tmp,
403 (IV)rex->offs[paren].end,
404 (paren > rex->lastparen ? "(skipped)" : ""));
409 /* It would seem that the similar code in regtry()
410 * already takes care of this, and in fact it is in
411 * a better location to since this code can #if 0-ed out
412 * but the code in regtry() is needed or otherwise tests
413 * requiring null fields (pat.t#187 and split.t#{13,14}
414 * (as of patchlevel 7877) will fail. Then again,
415 * this code seems to be necessary or otherwise
416 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
417 * --jhi updated by dapm */
418 for (i = rex->lastparen + 1; i <= rex->nparens; i++) {
419 if (i > *maxopenparen_p)
420 rex->offs[i].start = -1;
421 rex->offs[i].end = -1;
422 DEBUG_BUFFERS_r( Perl_re_exec_indentf( aTHX_
423 " \\%" UVuf ": %s ..-1 undeffing\n",
426 (i > *maxopenparen_p) ? "-1" : " "
432 /* restore the parens and associated vars at savestack position ix,
433 * but without popping the stack */
436 S_regcp_restore(pTHX_ regexp *rex, I32 ix, U32 *maxopenparen_p _pDEPTH)
438 I32 tmpix = PL_savestack_ix;
439 PERL_ARGS_ASSERT_REGCP_RESTORE;
441 PL_savestack_ix = ix;
442 regcppop(rex, maxopenparen_p);
443 PL_savestack_ix = tmpix;
446 #define regcpblow(cp) LEAVE_SCOPE(cp) /* Ignores regcppush()ed data. */
449 S_isFOO_lc(pTHX_ const U8 classnum, const U8 character)
451 /* Returns a boolean as to whether or not 'character' is a member of the
452 * Posix character class given by 'classnum' that should be equivalent to a
453 * value in the typedef '_char_class_number'.
455 * Ideally this could be replaced by a just an array of function pointers
456 * to the C library functions that implement the macros this calls.
457 * However, to compile, the precise function signatures are required, and
458 * these may vary from platform to to platform. To avoid having to figure
459 * out what those all are on each platform, I (khw) am using this method,
460 * which adds an extra layer of function call overhead (unless the C
461 * optimizer strips it away). But we don't particularly care about
462 * performance with locales anyway. */
464 switch ((_char_class_number) classnum) {
465 case _CC_ENUM_ALPHANUMERIC: return isALPHANUMERIC_LC(character);
466 case _CC_ENUM_ALPHA: return isALPHA_LC(character);
467 case _CC_ENUM_ASCII: return isASCII_LC(character);
468 case _CC_ENUM_BLANK: return isBLANK_LC(character);
469 case _CC_ENUM_CASED: return isLOWER_LC(character)
470 || isUPPER_LC(character);
471 case _CC_ENUM_CNTRL: return isCNTRL_LC(character);
472 case _CC_ENUM_DIGIT: return isDIGIT_LC(character);
473 case _CC_ENUM_GRAPH: return isGRAPH_LC(character);
474 case _CC_ENUM_LOWER: return isLOWER_LC(character);
475 case _CC_ENUM_PRINT: return isPRINT_LC(character);
476 case _CC_ENUM_PUNCT: return isPUNCT_LC(character);
477 case _CC_ENUM_SPACE: return isSPACE_LC(character);
478 case _CC_ENUM_UPPER: return isUPPER_LC(character);
479 case _CC_ENUM_WORDCHAR: return isWORDCHAR_LC(character);
480 case _CC_ENUM_XDIGIT: return isXDIGIT_LC(character);
481 default: /* VERTSPACE should never occur in locales */
482 Perl_croak(aTHX_ "panic: isFOO_lc() has an unexpected character class '%d'", classnum);
485 NOT_REACHED; /* NOTREACHED */
490 S_isFOO_utf8_lc(pTHX_ const U8 classnum, const U8* character)
492 /* Returns a boolean as to whether or not the (well-formed) UTF-8-encoded
493 * 'character' is a member of the Posix character class given by 'classnum'
494 * that should be equivalent to a value in the typedef
495 * '_char_class_number'.
497 * This just calls isFOO_lc on the code point for the character if it is in
498 * the range 0-255. Outside that range, all characters use Unicode
499 * rules, ignoring any locale. So use the Unicode function if this class
500 * requires a swash, and use the Unicode macro otherwise. */
502 PERL_ARGS_ASSERT_ISFOO_UTF8_LC;
504 if (UTF8_IS_INVARIANT(*character)) {
505 return isFOO_lc(classnum, *character);
507 else if (UTF8_IS_DOWNGRADEABLE_START(*character)) {
508 return isFOO_lc(classnum,
509 EIGHT_BIT_UTF8_TO_NATIVE(*character, *(character + 1)));
512 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(character, character + UTF8SKIP(character));
514 if (classnum < _FIRST_NON_SWASH_CC) {
516 /* Initialize the swash unless done already */
517 if (! PL_utf8_swash_ptrs[classnum]) {
518 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
519 PL_utf8_swash_ptrs[classnum] =
520 _core_swash_init("utf8",
523 PL_XPosix_ptrs[classnum], &flags);
526 return cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum], (U8 *)
528 TRUE /* is UTF */ ));
531 switch ((_char_class_number) classnum) {
532 case _CC_ENUM_SPACE: return is_XPERLSPACE_high(character);
533 case _CC_ENUM_BLANK: return is_HORIZWS_high(character);
534 case _CC_ENUM_XDIGIT: return is_XDIGIT_high(character);
535 case _CC_ENUM_VERTSPACE: return is_VERTWS_high(character);
539 return FALSE; /* Things like CNTRL are always below 256 */
543 * pregexec and friends
546 #ifndef PERL_IN_XSUB_RE
548 - pregexec - match a regexp against a string
551 Perl_pregexec(pTHX_ REGEXP * const prog, char* stringarg, char *strend,
552 char *strbeg, SSize_t minend, SV *screamer, U32 nosave)
553 /* stringarg: the point in the string at which to begin matching */
554 /* strend: pointer to null at end of string */
555 /* strbeg: real beginning of string */
556 /* minend: end of match must be >= minend bytes after stringarg. */
557 /* screamer: SV being matched: only used for utf8 flag, pos() etc; string
558 * itself is accessed via the pointers above */
559 /* nosave: For optimizations. */
561 PERL_ARGS_ASSERT_PREGEXEC;
564 regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
565 nosave ? 0 : REXEC_COPY_STR);
571 /* re_intuit_start():
573 * Based on some optimiser hints, try to find the earliest position in the
574 * string where the regex could match.
576 * rx: the regex to match against
577 * sv: the SV being matched: only used for utf8 flag; the string
578 * itself is accessed via the pointers below. Note that on
579 * something like an overloaded SV, SvPOK(sv) may be false
580 * and the string pointers may point to something unrelated to
582 * strbeg: real beginning of string
583 * strpos: the point in the string at which to begin matching
584 * strend: pointer to the byte following the last char of the string
585 * flags currently unused; set to 0
586 * data: currently unused; set to NULL
588 * The basic idea of re_intuit_start() is to use some known information
589 * about the pattern, namely:
591 * a) the longest known anchored substring (i.e. one that's at a
592 * constant offset from the beginning of the pattern; but not
593 * necessarily at a fixed offset from the beginning of the
595 * b) the longest floating substring (i.e. one that's not at a constant
596 * offset from the beginning of the pattern);
597 * c) Whether the pattern is anchored to the string; either
598 * an absolute anchor: /^../, or anchored to \n: /^.../m,
599 * or anchored to pos(): /\G/;
600 * d) A start class: a real or synthetic character class which
601 * represents which characters are legal at the start of the pattern;
603 * to either quickly reject the match, or to find the earliest position
604 * within the string at which the pattern might match, thus avoiding
605 * running the full NFA engine at those earlier locations, only to
606 * eventually fail and retry further along.
608 * Returns NULL if the pattern can't match, or returns the address within
609 * the string which is the earliest place the match could occur.
611 * The longest of the anchored and floating substrings is called 'check'
612 * and is checked first. The other is called 'other' and is checked
613 * second. The 'other' substring may not be present. For example,
615 * /(abc|xyz)ABC\d{0,3}DEFG/
619 * check substr (float) = "DEFG", offset 6..9 chars
620 * other substr (anchored) = "ABC", offset 3..3 chars
623 * Be aware that during the course of this function, sometimes 'anchored'
624 * refers to a substring being anchored relative to the start of the
625 * pattern, and sometimes to the pattern itself being anchored relative to
626 * the string. For example:
628 * /\dabc/: "abc" is anchored to the pattern;
629 * /^\dabc/: "abc" is anchored to the pattern and the string;
630 * /\d+abc/: "abc" is anchored to neither the pattern nor the string;
631 * /^\d+abc/: "abc" is anchored to neither the pattern nor the string,
632 * but the pattern is anchored to the string.
636 Perl_re_intuit_start(pTHX_
639 const char * const strbeg,
643 re_scream_pos_data *data)
645 struct regexp *const prog = ReANY(rx);
646 SSize_t start_shift = prog->check_offset_min;
647 /* Should be nonnegative! */
648 SSize_t end_shift = 0;
649 /* current lowest pos in string where the regex can start matching */
650 char *rx_origin = strpos;
652 const bool utf8_target = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
653 U8 other_ix = 1 - prog->substrs->check_ix;
655 char *other_last = strpos;/* latest pos 'other' substr already checked to */
656 char *check_at = NULL; /* check substr found at this pos */
657 const I32 multiline = prog->extflags & RXf_PMf_MULTILINE;
658 RXi_GET_DECL(prog,progi);
659 regmatch_info reginfo_buf; /* create some info to pass to find_byclass */
660 regmatch_info *const reginfo = ®info_buf;
661 GET_RE_DEBUG_FLAGS_DECL;
663 PERL_ARGS_ASSERT_RE_INTUIT_START;
664 PERL_UNUSED_ARG(flags);
665 PERL_UNUSED_ARG(data);
667 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
668 "Intuit: trying to determine minimum start position...\n"));
670 /* for now, assume that all substr offsets are positive. If at some point
671 * in the future someone wants to do clever things with lookbehind and
672 * -ve offsets, they'll need to fix up any code in this function
673 * which uses these offsets. See the thread beginning
674 * <20140113145929.GF27210@iabyn.com>
676 assert(prog->substrs->data[0].min_offset >= 0);
677 assert(prog->substrs->data[0].max_offset >= 0);
678 assert(prog->substrs->data[1].min_offset >= 0);
679 assert(prog->substrs->data[1].max_offset >= 0);
680 assert(prog->substrs->data[2].min_offset >= 0);
681 assert(prog->substrs->data[2].max_offset >= 0);
683 /* for now, assume that if both present, that the floating substring
684 * doesn't start before the anchored substring.
685 * If you break this assumption (e.g. doing better optimisations
686 * with lookahead/behind), then you'll need to audit the code in this
687 * function carefully first
690 ! ( (prog->anchored_utf8 || prog->anchored_substr)
691 && (prog->float_utf8 || prog->float_substr))
692 || (prog->float_min_offset >= prog->anchored_offset));
694 /* byte rather than char calculation for efficiency. It fails
695 * to quickly reject some cases that can't match, but will reject
696 * them later after doing full char arithmetic */
697 if (prog->minlen > strend - strpos) {
698 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
699 " String too short...\n"));
703 RX_MATCH_UTF8_set(rx,utf8_target);
704 reginfo->is_utf8_target = cBOOL(utf8_target);
705 reginfo->info_aux = NULL;
706 reginfo->strbeg = strbeg;
707 reginfo->strend = strend;
708 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
710 /* not actually used within intuit, but zero for safety anyway */
711 reginfo->poscache_maxiter = 0;
714 if ((!prog->anchored_utf8 && prog->anchored_substr)
715 || (!prog->float_utf8 && prog->float_substr))
716 to_utf8_substr(prog);
717 check = prog->check_utf8;
719 if (!prog->check_substr && prog->check_utf8) {
720 if (! to_byte_substr(prog)) {
721 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(fail);
724 check = prog->check_substr;
727 /* dump the various substring data */
728 DEBUG_OPTIMISE_MORE_r({
730 for (i=0; i<=2; i++) {
731 SV *sv = (utf8_target ? prog->substrs->data[i].utf8_substr
732 : prog->substrs->data[i].substr);
736 Perl_re_printf( aTHX_
737 " substrs[%d]: min=%" IVdf " max=%" IVdf " end shift=%" IVdf
738 " useful=%" IVdf " utf8=%d [%s]\n",
740 (IV)prog->substrs->data[i].min_offset,
741 (IV)prog->substrs->data[i].max_offset,
742 (IV)prog->substrs->data[i].end_shift,
749 if (prog->intflags & PREGf_ANCH) { /* Match at \G, beg-of-str or after \n */
751 /* ml_anch: check after \n?
753 * A note about PREGf_IMPLICIT: on an un-anchored pattern beginning
754 * with /.*.../, these flags will have been added by the
756 * /.*abc/, /.*abc/m: PREGf_IMPLICIT | PREGf_ANCH_MBOL
757 * /.*abc/s: PREGf_IMPLICIT | PREGf_ANCH_SBOL
759 ml_anch = (prog->intflags & PREGf_ANCH_MBOL)
760 && !(prog->intflags & PREGf_IMPLICIT);
762 if (!ml_anch && !(prog->intflags & PREGf_IMPLICIT)) {
763 /* we are only allowed to match at BOS or \G */
765 /* trivially reject if there's a BOS anchor and we're not at BOS.
767 * Note that we don't try to do a similar quick reject for
768 * \G, since generally the caller will have calculated strpos
769 * based on pos() and gofs, so the string is already correctly
770 * anchored by definition; and handling the exceptions would
771 * be too fiddly (e.g. REXEC_IGNOREPOS).
773 if ( strpos != strbeg
774 && (prog->intflags & PREGf_ANCH_SBOL))
776 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
777 " Not at start...\n"));
781 /* in the presence of an anchor, the anchored (relative to the
782 * start of the regex) substr must also be anchored relative
783 * to strpos. So quickly reject if substr isn't found there.
784 * This works for \G too, because the caller will already have
785 * subtracted gofs from pos, and gofs is the offset from the
786 * \G to the start of the regex. For example, in /.abc\Gdef/,
787 * where substr="abcdef", pos()=3, gofs=4, offset_min=1:
788 * caller will have set strpos=pos()-4; we look for the substr
789 * at position pos()-4+1, which lines up with the "a" */
791 if (prog->check_offset_min == prog->check_offset_max) {
792 /* Substring at constant offset from beg-of-str... */
793 SSize_t slen = SvCUR(check);
794 char *s = HOP3c(strpos, prog->check_offset_min, strend);
796 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
797 " Looking for check substr at fixed offset %" IVdf "...\n",
798 (IV)prog->check_offset_min));
801 /* In this case, the regex is anchored at the end too.
802 * Unless it's a multiline match, the lengths must match
803 * exactly, give or take a \n. NB: slen >= 1 since
804 * the last char of check is \n */
806 && ( strend - s > slen
807 || strend - s < slen - 1
808 || (strend - s == slen && strend[-1] != '\n')))
810 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
811 " String too long...\n"));
814 /* Now should match s[0..slen-2] */
817 if (slen && (strend - s < slen
818 || *SvPVX_const(check) != *s
819 || (slen > 1 && (memNE(SvPVX_const(check), s, slen)))))
821 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
822 " String not equal...\n"));
827 goto success_at_start;
832 end_shift = prog->check_end_shift;
834 #ifdef DEBUGGING /* 7/99: reports of failure (with the older version) */
836 Perl_croak(aTHX_ "panic: end_shift: %" IVdf " pattern:\n%s\n ",
837 (IV)end_shift, RX_PRECOMP(prog));
842 /* This is the (re)entry point of the main loop in this function.
843 * The goal of this loop is to:
844 * 1) find the "check" substring in the region rx_origin..strend
845 * (adjusted by start_shift / end_shift). If not found, reject
847 * 2) If it exists, look for the "other" substr too if defined; for
848 * example, if the check substr maps to the anchored substr, then
849 * check the floating substr, and vice-versa. If not found, go
850 * back to (1) with rx_origin suitably incremented.
851 * 3) If we find an rx_origin position that doesn't contradict
852 * either of the substrings, then check the possible additional
853 * constraints on rx_origin of /^.../m or a known start class.
854 * If these fail, then depending on which constraints fail, jump
855 * back to here, or to various other re-entry points further along
856 * that skip some of the first steps.
857 * 4) If we pass all those tests, update the BmUSEFUL() count on the
858 * substring. If the start position was determined to be at the
859 * beginning of the string - so, not rejected, but not optimised,
860 * since we have to run regmatch from position 0 - decrement the
861 * BmUSEFUL() count. Otherwise increment it.
865 /* first, look for the 'check' substring */
871 DEBUG_OPTIMISE_MORE_r({
872 Perl_re_printf( aTHX_
873 " At restart: rx_origin=%" IVdf " Check offset min: %" IVdf
874 " Start shift: %" IVdf " End shift %" IVdf
875 " Real end Shift: %" IVdf "\n",
876 (IV)(rx_origin - strbeg),
877 (IV)prog->check_offset_min,
880 (IV)prog->check_end_shift);
883 end_point = HOP3(strend, -end_shift, strbeg);
884 start_point = HOPMAYBE3(rx_origin, start_shift, end_point);
889 /* If the regex is absolutely anchored to either the start of the
890 * string (SBOL) or to pos() (ANCH_GPOS), then
891 * check_offset_max represents an upper bound on the string where
892 * the substr could start. For the ANCH_GPOS case, we assume that
893 * the caller of intuit will have already set strpos to
894 * pos()-gofs, so in this case strpos + offset_max will still be
895 * an upper bound on the substr.
898 && prog->intflags & PREGf_ANCH
899 && prog->check_offset_max != SSize_t_MAX)
901 SSize_t len = SvCUR(check) - !!SvTAIL(check);
902 const char * const anchor =
903 (prog->intflags & PREGf_ANCH_GPOS ? strpos : strbeg);
905 /* do a bytes rather than chars comparison. It's conservative;
906 * so it skips doing the HOP if the result can't possibly end
907 * up earlier than the old value of end_point.
909 if ((char*)end_point - anchor > prog->check_offset_max) {
910 end_point = HOP3lim((U8*)anchor,
911 prog->check_offset_max,
917 check_at = fbm_instr( start_point, end_point,
918 check, multiline ? FBMrf_MULTILINE : 0);
920 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
921 " doing 'check' fbm scan, [%" IVdf "..%" IVdf "] gave %" IVdf "\n",
922 (IV)((char*)start_point - strbeg),
923 (IV)((char*)end_point - strbeg),
924 (IV)(check_at ? check_at - strbeg : -1)
927 /* Update the count-of-usability, remove useless subpatterns,
931 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
932 SvPVX_const(check), RE_SV_DUMPLEN(check), 30);
933 Perl_re_printf( aTHX_ " %s %s substr %s%s%s",
934 (check_at ? "Found" : "Did not find"),
935 (check == (utf8_target ? prog->anchored_utf8 : prog->anchored_substr)
936 ? "anchored" : "floating"),
939 (check_at ? " at offset " : "...\n") );
944 /* set rx_origin to the minimum position where the regex could start
945 * matching, given the constraint of the just-matched check substring.
946 * But don't set it lower than previously.
949 if (check_at - rx_origin > prog->check_offset_max)
950 rx_origin = HOP3c(check_at, -prog->check_offset_max, rx_origin);
951 /* Finish the diagnostic message */
952 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
953 "%ld (rx_origin now %" IVdf ")...\n",
954 (long)(check_at - strbeg),
955 (IV)(rx_origin - strbeg)
960 /* now look for the 'other' substring if defined */
962 if (utf8_target ? prog->substrs->data[other_ix].utf8_substr
963 : prog->substrs->data[other_ix].substr)
965 /* Take into account the "other" substring. */
969 struct reg_substr_datum *other;
972 other = &prog->substrs->data[other_ix];
974 /* if "other" is anchored:
975 * we've previously found a floating substr starting at check_at.
976 * This means that the regex origin must lie somewhere
977 * between min (rx_origin): HOP3(check_at, -check_offset_max)
978 * and max: HOP3(check_at, -check_offset_min)
979 * (except that min will be >= strpos)
980 * So the fixed substr must lie somewhere between
981 * HOP3(min, anchored_offset)
982 * HOP3(max, anchored_offset) + SvCUR(substr)
985 /* if "other" is floating
986 * Calculate last1, the absolute latest point where the
987 * floating substr could start in the string, ignoring any
988 * constraints from the earlier fixed match. It is calculated
991 * strend - prog->minlen (in chars) is the absolute latest
992 * position within the string where the origin of the regex
993 * could appear. The latest start point for the floating
994 * substr is float_min_offset(*) on from the start of the
995 * regex. last1 simply combines thee two offsets.
997 * (*) You might think the latest start point should be
998 * float_max_offset from the regex origin, and technically
999 * you'd be correct. However, consider
1001 * Here, float min, max are 3,5 and minlen is 7.
1002 * This can match either
1006 * In the first case, the regex matches minlen chars; in the
1007 * second, minlen+1, in the third, minlen+2.
1008 * In the first case, the floating offset is 3 (which equals
1009 * float_min), in the second, 4, and in the third, 5 (which
1010 * equals float_max). In all cases, the floating string bcd
1011 * can never start more than 4 chars from the end of the
1012 * string, which equals minlen - float_min. As the substring
1013 * starts to match more than float_min from the start of the
1014 * regex, it makes the regex match more than minlen chars,
1015 * and the two cancel each other out. So we can always use
1016 * float_min - minlen, rather than float_max - minlen for the
1017 * latest position in the string.
1019 * Note that -minlen + float_min_offset is equivalent (AFAIKT)
1020 * to CHR_SVLEN(must) - !!SvTAIL(must) + prog->float_end_shift
1023 assert(prog->minlen >= other->min_offset);
1024 last1 = HOP3c(strend,
1025 other->min_offset - prog->minlen, strbeg);
1027 if (other_ix) {/* i.e. if (other-is-float) */
1028 /* last is the latest point where the floating substr could
1029 * start, *given* any constraints from the earlier fixed
1030 * match. This constraint is that the floating string starts
1031 * <= float_max_offset chars from the regex origin (rx_origin).
1032 * If this value is less than last1, use it instead.
1034 assert(rx_origin <= last1);
1036 /* this condition handles the offset==infinity case, and
1037 * is a short-cut otherwise. Although it's comparing a
1038 * byte offset to a char length, it does so in a safe way,
1039 * since 1 char always occupies 1 or more bytes,
1040 * so if a string range is (last1 - rx_origin) bytes,
1041 * it will be less than or equal to (last1 - rx_origin)
1042 * chars; meaning it errs towards doing the accurate HOP3
1043 * rather than just using last1 as a short-cut */
1044 (last1 - rx_origin) < other->max_offset
1046 : (char*)HOP3lim(rx_origin, other->max_offset, last1);
1049 assert(strpos + start_shift <= check_at);
1050 last = HOP4c(check_at, other->min_offset - start_shift,
1054 s = HOP3c(rx_origin, other->min_offset, strend);
1055 if (s < other_last) /* These positions already checked */
1058 must = utf8_target ? other->utf8_substr : other->substr;
1059 assert(SvPOK(must));
1062 char *to = last + SvCUR(must) - (SvTAIL(must)!=0);
1068 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1069 " skipping 'other' fbm scan: %" IVdf " > %" IVdf "\n",
1070 (IV)(from - strbeg),
1076 (unsigned char*)from,
1079 multiline ? FBMrf_MULTILINE : 0
1081 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1082 " doing 'other' fbm scan, [%" IVdf "..%" IVdf "] gave %" IVdf "\n",
1083 (IV)(from - strbeg),
1085 (IV)(s ? s - strbeg : -1)
1091 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
1092 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
1093 Perl_re_printf( aTHX_ " %s %s substr %s%s",
1094 s ? "Found" : "Contradicts",
1095 other_ix ? "floating" : "anchored",
1096 quoted, RE_SV_TAIL(must));
1101 /* last1 is latest possible substr location. If we didn't
1102 * find it before there, we never will */
1103 if (last >= last1) {
1104 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1105 "; giving up...\n"));
1109 /* try to find the check substr again at a later
1110 * position. Maybe next time we'll find the "other" substr
1112 other_last = HOP3c(last, 1, strend) /* highest failure */;
1114 other_ix /* i.e. if other-is-float */
1115 ? HOP3c(rx_origin, 1, strend)
1116 : HOP4c(last, 1 - other->min_offset, strbeg, strend);
1117 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1118 "; about to retry %s at offset %ld (rx_origin now %" IVdf ")...\n",
1119 (other_ix ? "floating" : "anchored"),
1120 (long)(HOP3c(check_at, 1, strend) - strbeg),
1121 (IV)(rx_origin - strbeg)
1126 if (other_ix) { /* if (other-is-float) */
1127 /* other_last is set to s, not s+1, since its possible for
1128 * a floating substr to fail first time, then succeed
1129 * second time at the same floating position; e.g.:
1130 * "-AB--AABZ" =~ /\wAB\d*Z/
1131 * The first time round, anchored and float match at
1132 * "-(AB)--AAB(Z)" then fail on the initial \w character
1133 * class. Second time round, they match at "-AB--A(AB)(Z)".
1138 rx_origin = HOP3c(s, -other->min_offset, strbeg);
1139 other_last = HOP3c(s, 1, strend);
1141 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1142 " at offset %ld (rx_origin now %" IVdf ")...\n",
1144 (IV)(rx_origin - strbeg)
1150 DEBUG_OPTIMISE_MORE_r(
1151 Perl_re_printf( aTHX_
1152 " Check-only match: offset min:%" IVdf " max:%" IVdf
1153 " check_at:%" IVdf " rx_origin:%" IVdf " rx_origin-check_at:%" IVdf
1154 " strend:%" IVdf "\n",
1155 (IV)prog->check_offset_min,
1156 (IV)prog->check_offset_max,
1157 (IV)(check_at-strbeg),
1158 (IV)(rx_origin-strbeg),
1159 (IV)(rx_origin-check_at),
1165 postprocess_substr_matches:
1167 /* handle the extra constraint of /^.../m if present */
1169 if (ml_anch && rx_origin != strbeg && rx_origin[-1] != '\n') {
1172 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1173 " looking for /^/m anchor"));
1175 /* we have failed the constraint of a \n before rx_origin.
1176 * Find the next \n, if any, even if it's beyond the current
1177 * anchored and/or floating substrings. Whether we should be
1178 * scanning ahead for the next \n or the next substr is debatable.
1179 * On the one hand you'd expect rare substrings to appear less
1180 * often than \n's. On the other hand, searching for \n means
1181 * we're effectively flipping between check_substr and "\n" on each
1182 * iteration as the current "rarest" string candidate, which
1183 * means for example that we'll quickly reject the whole string if
1184 * hasn't got a \n, rather than trying every substr position
1188 s = HOP3c(strend, - prog->minlen, strpos);
1189 if (s <= rx_origin ||
1190 ! ( rx_origin = (char *)memchr(rx_origin, '\n', s - rx_origin)))
1192 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1193 " Did not find /%s^%s/m...\n",
1194 PL_colors[0], PL_colors[1]));
1198 /* earliest possible origin is 1 char after the \n.
1199 * (since *rx_origin == '\n', it's safe to ++ here rather than
1200 * HOP(rx_origin, 1)) */
1203 if (prog->substrs->check_ix == 0 /* check is anchored */
1204 || rx_origin >= HOP3c(check_at, - prog->check_offset_min, strpos))
1206 /* Position contradicts check-string; either because
1207 * check was anchored (and thus has no wiggle room),
1208 * or check was float and rx_origin is above the float range */
1209 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1210 " Found /%s^%s/m, about to restart lookup for check-string with rx_origin %ld...\n",
1211 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1215 /* if we get here, the check substr must have been float,
1216 * is in range, and we may or may not have had an anchored
1217 * "other" substr which still contradicts */
1218 assert(prog->substrs->check_ix); /* check is float */
1220 if (utf8_target ? prog->anchored_utf8 : prog->anchored_substr) {
1221 /* whoops, the anchored "other" substr exists, so we still
1222 * contradict. On the other hand, the float "check" substr
1223 * didn't contradict, so just retry the anchored "other"
1225 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1226 " Found /%s^%s/m, rescanning for anchored from offset %" IVdf " (rx_origin now %" IVdf ")...\n",
1227 PL_colors[0], PL_colors[1],
1228 (IV)(rx_origin - strbeg + prog->anchored_offset),
1229 (IV)(rx_origin - strbeg)
1231 goto do_other_substr;
1234 /* success: we don't contradict the found floating substring
1235 * (and there's no anchored substr). */
1236 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1237 " Found /%s^%s/m with rx_origin %ld...\n",
1238 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1241 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1242 " (multiline anchor test skipped)\n"));
1248 /* if we have a starting character class, then test that extra constraint.
1249 * (trie stclasses are too expensive to use here, we are better off to
1250 * leave it to regmatch itself) */
1252 if (progi->regstclass && PL_regkind[OP(progi->regstclass)]!=TRIE) {
1253 const U8* const str = (U8*)STRING(progi->regstclass);
1255 /* XXX this value could be pre-computed */
1256 const int cl_l = (PL_regkind[OP(progi->regstclass)] == EXACT
1257 ? (reginfo->is_utf8_pat
1258 ? utf8_distance(str + STR_LEN(progi->regstclass), str)
1259 : STR_LEN(progi->regstclass))
1263 /* latest pos that a matching float substr constrains rx start to */
1264 char *rx_max_float = NULL;
1266 /* if the current rx_origin is anchored, either by satisfying an
1267 * anchored substring constraint, or a /^.../m constraint, then we
1268 * can reject the current origin if the start class isn't found
1269 * at the current position. If we have a float-only match, then
1270 * rx_origin is constrained to a range; so look for the start class
1271 * in that range. if neither, then look for the start class in the
1272 * whole rest of the string */
1274 /* XXX DAPM it's not clear what the minlen test is for, and why
1275 * it's not used in the floating case. Nothing in the test suite
1276 * causes minlen == 0 here. See <20140313134639.GS12844@iabyn.com>.
1277 * Here are some old comments, which may or may not be correct:
1279 * minlen == 0 is possible if regstclass is \b or \B,
1280 * and the fixed substr is ''$.
1281 * Since minlen is already taken into account, rx_origin+1 is
1282 * before strend; accidentally, minlen >= 1 guaranties no false
1283 * positives at rx_origin + 1 even for \b or \B. But (minlen? 1 :
1284 * 0) below assumes that regstclass does not come from lookahead...
1285 * If regstclass takes bytelength more than 1: If charlength==1, OK.
1286 * This leaves EXACTF-ish only, which are dealt with in
1290 if (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
1291 endpos= HOP3c(rx_origin, (prog->minlen ? cl_l : 0), strend);
1292 else if (prog->float_substr || prog->float_utf8) {
1293 rx_max_float = HOP3c(check_at, -start_shift, strbeg);
1294 endpos= HOP3c(rx_max_float, cl_l, strend);
1299 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1300 " looking for class: start_shift: %" IVdf " check_at: %" IVdf
1301 " rx_origin: %" IVdf " endpos: %" IVdf "\n",
1302 (IV)start_shift, (IV)(check_at - strbeg),
1303 (IV)(rx_origin - strbeg), (IV)(endpos - strbeg)));
1305 s = find_byclass(prog, progi->regstclass, rx_origin, endpos,
1308 if (endpos == strend) {
1309 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1310 " Could not match STCLASS...\n") );
1313 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1314 " This position contradicts STCLASS...\n") );
1315 if ((prog->intflags & PREGf_ANCH) && !ml_anch
1316 && !(prog->intflags & PREGf_IMPLICIT))
1319 /* Contradict one of substrings */
1320 if (prog->anchored_substr || prog->anchored_utf8) {
1321 if (prog->substrs->check_ix == 1) { /* check is float */
1322 /* Have both, check_string is floating */
1323 assert(rx_origin + start_shift <= check_at);
1324 if (rx_origin + start_shift != check_at) {
1325 /* not at latest position float substr could match:
1326 * Recheck anchored substring, but not floating.
1327 * The condition above is in bytes rather than
1328 * chars for efficiency. It's conservative, in
1329 * that it errs on the side of doing 'goto
1330 * do_other_substr'. In this case, at worst,
1331 * an extra anchored search may get done, but in
1332 * practice the extra fbm_instr() is likely to
1333 * get skipped anyway. */
1334 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1335 " about to retry anchored at offset %ld (rx_origin now %" IVdf ")...\n",
1336 (long)(other_last - strbeg),
1337 (IV)(rx_origin - strbeg)
1339 goto do_other_substr;
1347 /* In the presence of ml_anch, we might be able to
1348 * find another \n without breaking the current float
1351 /* strictly speaking this should be HOP3c(..., 1, ...),
1352 * but since we goto a block of code that's going to
1353 * search for the next \n if any, its safe here */
1355 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1356 " about to look for /%s^%s/m starting at rx_origin %ld...\n",
1357 PL_colors[0], PL_colors[1],
1358 (long)(rx_origin - strbeg)) );
1359 goto postprocess_substr_matches;
1362 /* strictly speaking this can never be true; but might
1363 * be if we ever allow intuit without substrings */
1364 if (!(utf8_target ? prog->float_utf8 : prog->float_substr))
1367 rx_origin = rx_max_float;
1370 /* at this point, any matching substrings have been
1371 * contradicted. Start again... */
1373 rx_origin = HOP3c(rx_origin, 1, strend);
1375 /* uses bytes rather than char calculations for efficiency.
1376 * It's conservative: it errs on the side of doing 'goto restart',
1377 * where there is code that does a proper char-based test */
1378 if (rx_origin + start_shift + end_shift > strend) {
1379 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1380 " Could not match STCLASS...\n") );
1383 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
1384 " about to look for %s substr starting at offset %ld (rx_origin now %" IVdf ")...\n",
1385 (prog->substrs->check_ix ? "floating" : "anchored"),
1386 (long)(rx_origin + start_shift - strbeg),
1387 (IV)(rx_origin - strbeg)
1394 if (rx_origin != s) {
1395 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1396 " By STCLASS: moving %ld --> %ld\n",
1397 (long)(rx_origin - strbeg), (long)(s - strbeg))
1401 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1402 " Does not contradict STCLASS...\n");
1407 /* Decide whether using the substrings helped */
1409 if (rx_origin != strpos) {
1410 /* Fixed substring is found far enough so that the match
1411 cannot start at strpos. */
1413 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ " try at offset...\n"));
1414 ++BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr); /* hooray/5 */
1417 /* The found rx_origin position does not prohibit matching at
1418 * strpos, so calling intuit didn't gain us anything. Decrement
1419 * the BmUSEFUL() count on the check substring, and if we reach
1421 if (!(prog->intflags & PREGf_NAUGHTY)
1423 prog->check_utf8 /* Could be deleted already */
1424 && --BmUSEFUL(prog->check_utf8) < 0
1425 && (prog->check_utf8 == prog->float_utf8)
1427 prog->check_substr /* Could be deleted already */
1428 && --BmUSEFUL(prog->check_substr) < 0
1429 && (prog->check_substr == prog->float_substr)
1432 /* If flags & SOMETHING - do not do it many times on the same match */
1433 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ " ... Disabling check substring...\n"));
1434 /* XXX Does the destruction order has to change with utf8_target? */
1435 SvREFCNT_dec(utf8_target ? prog->check_utf8 : prog->check_substr);
1436 SvREFCNT_dec(utf8_target ? prog->check_substr : prog->check_utf8);
1437 prog->check_substr = prog->check_utf8 = NULL; /* disable */
1438 prog->float_substr = prog->float_utf8 = NULL; /* clear */
1439 check = NULL; /* abort */
1440 /* XXXX This is a remnant of the old implementation. It
1441 looks wasteful, since now INTUIT can use many
1442 other heuristics. */
1443 prog->extflags &= ~RXf_USE_INTUIT;
1447 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
1448 "Intuit: %sSuccessfully guessed:%s match at offset %ld\n",
1449 PL_colors[4], PL_colors[5], (long)(rx_origin - strbeg)) );
1453 fail_finish: /* Substring not found */
1454 if (prog->check_substr || prog->check_utf8) /* could be removed already */
1455 BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
1457 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%sMatch rejected by optimizer%s\n",
1458 PL_colors[4], PL_colors[5]));
1463 #define DECL_TRIE_TYPE(scan) \
1464 const enum { trie_plain, trie_utf8, trie_utf8_fold, trie_latin_utf8_fold, \
1465 trie_utf8_exactfa_fold, trie_latin_utf8_exactfa_fold, \
1466 trie_utf8l, trie_flu8 } \
1467 trie_type = ((scan->flags == EXACT) \
1468 ? (utf8_target ? trie_utf8 : trie_plain) \
1469 : (scan->flags == EXACTL) \
1470 ? (utf8_target ? trie_utf8l : trie_plain) \
1471 : (scan->flags == EXACTFA) \
1473 ? trie_utf8_exactfa_fold \
1474 : trie_latin_utf8_exactfa_fold) \
1475 : (scan->flags == EXACTFLU8 \
1479 : trie_latin_utf8_fold)))
1481 #define REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc, uscan, len, uvc, charid, foldlen, foldbuf, uniflags) \
1484 U8 flags = FOLD_FLAGS_FULL; \
1485 switch (trie_type) { \
1487 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1488 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1489 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1491 goto do_trie_utf8_fold; \
1492 case trie_utf8_exactfa_fold: \
1493 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1495 case trie_utf8_fold: \
1496 do_trie_utf8_fold: \
1497 if ( foldlen>0 ) { \
1498 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1503 uvc = _to_utf8_fold_flags( (const U8*) uc, foldbuf, &foldlen, flags); \
1504 len = UTF8SKIP(uc); \
1505 skiplen = UVCHR_SKIP( uvc ); \
1506 foldlen -= skiplen; \
1507 uscan = foldbuf + skiplen; \
1510 case trie_latin_utf8_exactfa_fold: \
1511 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1513 case trie_latin_utf8_fold: \
1514 if ( foldlen>0 ) { \
1515 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1521 uvc = _to_fold_latin1( (U8) *uc, foldbuf, &foldlen, flags); \
1522 skiplen = UVCHR_SKIP( uvc ); \
1523 foldlen -= skiplen; \
1524 uscan = foldbuf + skiplen; \
1528 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1529 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1530 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1534 uvc = utf8n_to_uvchr( (const U8*) uc, UTF8_MAXLEN, &len, uniflags ); \
1541 charid = trie->charmap[ uvc ]; \
1545 if (widecharmap) { \
1546 SV** const svpp = hv_fetch(widecharmap, \
1547 (char*)&uvc, sizeof(UV), 0); \
1549 charid = (U16)SvIV(*svpp); \
1554 #define DUMP_EXEC_POS(li,s,doutf8,depth) \
1555 dump_exec_pos(li,s,(reginfo->strend),(reginfo->strbeg), \
1556 startpos, doutf8, depth)
1558 #define REXEC_FBC_EXACTISH_SCAN(COND) \
1562 && (ln == 1 || folder(s, pat_string, ln)) \
1563 && (reginfo->intuit || regtry(reginfo, &s)) )\
1569 #define REXEC_FBC_UTF8_SCAN(CODE) \
1571 while (s < strend) { \
1577 #define REXEC_FBC_SCAN(CODE) \
1579 while (s < strend) { \
1585 #define REXEC_FBC_UTF8_CLASS_SCAN(COND) \
1586 REXEC_FBC_UTF8_SCAN( /* Loops while (s < strend) */ \
1588 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1597 #define REXEC_FBC_CLASS_SCAN(COND) \
1598 REXEC_FBC_SCAN( /* Loops while (s < strend) */ \
1600 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1609 #define REXEC_FBC_CSCAN(CONDUTF8,COND) \
1610 if (utf8_target) { \
1611 REXEC_FBC_UTF8_CLASS_SCAN(CONDUTF8); \
1614 REXEC_FBC_CLASS_SCAN(COND); \
1617 /* The three macros below are slightly different versions of the same logic.
1619 * The first is for /a and /aa when the target string is UTF-8. This can only
1620 * match ascii, but it must advance based on UTF-8. The other two handle the
1621 * non-UTF-8 and the more generic UTF-8 cases. In all three, we are looking
1622 * for the boundary (or non-boundary) between a word and non-word character.
1623 * The utf8 and non-utf8 cases have the same logic, but the details must be
1624 * different. Find the "wordness" of the character just prior to this one, and
1625 * compare it with the wordness of this one. If they differ, we have a
1626 * boundary. At the beginning of the string, pretend that the previous
1627 * character was a new-line.
1629 * All these macros uncleanly have side-effects with each other and outside
1630 * variables. So far it's been too much trouble to clean-up
1632 * TEST_NON_UTF8 is the macro or function to call to test if its byte input is
1633 * a word character or not.
1634 * IF_SUCCESS is code to do if it finds that we are at a boundary between
1636 * IF_FAIL is code to do if we aren't at a boundary between word/non-word
1638 * Exactly one of the two IF_FOO parameters is a no-op, depending on whether we
1639 * are looking for a boundary or for a non-boundary. If we are looking for a
1640 * boundary, we want IF_FAIL to be the no-op, and for IF_SUCCESS to go out and
1641 * see if this tentative match actually works, and if so, to quit the loop
1642 * here. And vice-versa if we are looking for a non-boundary.
1644 * 'tmp' below in the next three macros in the REXEC_FBC_SCAN and
1645 * REXEC_FBC_UTF8_SCAN loops is a loop invariant, a bool giving the return of
1646 * TEST_NON_UTF8(s-1). To see this, note that that's what it is defined to be
1647 * at entry to the loop, and to get to the IF_FAIL branch, tmp must equal
1648 * TEST_NON_UTF8(s), and in the opposite branch, IF_SUCCESS, tmp is that
1649 * complement. But in that branch we complement tmp, meaning that at the
1650 * bottom of the loop tmp is always going to be equal to TEST_NON_UTF8(s),
1651 * which means at the top of the loop in the next iteration, it is
1652 * TEST_NON_UTF8(s-1) */
1653 #define FBC_UTF8_A(TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1654 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1655 tmp = TEST_NON_UTF8(tmp); \
1656 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1657 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1659 IF_SUCCESS; /* Is a boundary if values for s-1 and s differ */ \
1666 /* Like FBC_UTF8_A, but TEST_UV is a macro which takes a UV as its input, and
1667 * TEST_UTF8 is a macro that for the same input code points returns identically
1668 * to TEST_UV, but takes a pointer to a UTF-8 encoded string instead */
1669 #define FBC_UTF8(TEST_UV, TEST_UTF8, IF_SUCCESS, IF_FAIL) \
1670 if (s == reginfo->strbeg) { \
1673 else { /* Back-up to the start of the previous character */ \
1674 U8 * const r = reghop3((U8*)s, -1, (U8*)reginfo->strbeg); \
1675 tmp = utf8n_to_uvchr(r, (U8*) reginfo->strend - r, \
1676 0, UTF8_ALLOW_DEFAULT); \
1678 tmp = TEST_UV(tmp); \
1679 LOAD_UTF8_CHARCLASS_ALNUM(); \
1680 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1681 if (tmp == ! (TEST_UTF8((U8 *) s))) { \
1690 /* Like the above two macros. UTF8_CODE is the complete code for handling
1691 * UTF-8. Common to the BOUND and NBOUND cases, set-up by the FBC_BOUND, etc
1693 #define FBC_BOUND_COMMON(UTF8_CODE, TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1694 if (utf8_target) { \
1697 else { /* Not utf8 */ \
1698 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1699 tmp = TEST_NON_UTF8(tmp); \
1700 REXEC_FBC_SCAN( /* advances s while s < strend */ \
1701 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1710 /* Here, things have been set up by the previous code so that tmp is the \
1711 * return of TEST_NON_UTF(s-1) or TEST_UTF8(s-1) (depending on the \
1712 * utf8ness of the target). We also have to check if this matches against \
1713 * the EOS, which we treat as a \n (which is the same value in both UTF-8 \
1714 * or non-UTF8, so can use the non-utf8 test condition even for a UTF-8 \
1716 if (tmp == ! TEST_NON_UTF8('\n')) { \
1723 /* This is the macro to use when we want to see if something that looks like it
1724 * could match, actually does, and if so exits the loop */
1725 #define REXEC_FBC_TRYIT \
1726 if ((reginfo->intuit || regtry(reginfo, &s))) \
1729 /* The only difference between the BOUND and NBOUND cases is that
1730 * REXEC_FBC_TRYIT is called when matched in BOUND, and when non-matched in
1731 * NBOUND. This is accomplished by passing it as either the if or else clause,
1732 * with the other one being empty (PLACEHOLDER is defined as empty).
1734 * The TEST_FOO parameters are for operating on different forms of input, but
1735 * all should be ones that return identically for the same underlying code
1737 #define FBC_BOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1739 FBC_UTF8(TEST_UV, TEST_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1740 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1742 #define FBC_BOUND_A(TEST_NON_UTF8) \
1744 FBC_UTF8_A(TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1745 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1747 #define FBC_NBOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1749 FBC_UTF8(TEST_UV, TEST_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1750 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1752 #define FBC_NBOUND_A(TEST_NON_UTF8) \
1754 FBC_UTF8_A(TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1755 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1759 S_get_break_val_cp_checked(SV* const invlist, const UV cp_in) {
1760 IV cp_out = Perl__invlist_search(invlist, cp_in);
1761 assert(cp_out >= 0);
1764 # define _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp) \
1765 invmap[S_get_break_val_cp_checked(invlist, cp)]
1767 # define _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp) \
1768 invmap[_invlist_search(invlist, cp)]
1771 /* Takes a pointer to an inversion list, a pointer to its corresponding
1772 * inversion map, and a code point, and returns the code point's value
1773 * according to the two arrays. It assumes that all code points have a value.
1774 * This is used as the base macro for macros for particular properties */
1775 #define _generic_GET_BREAK_VAL_CP(invlist, invmap, cp) \
1776 _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp)
1778 /* Same as above, but takes begin, end ptrs to a UTF-8 encoded string instead
1779 * of a code point, returning the value for the first code point in the string.
1780 * And it takes the particular macro name that finds the desired value given a
1781 * code point. Merely convert the UTF-8 to code point and call the cp macro */
1782 #define _generic_GET_BREAK_VAL_UTF8(cp_macro, pos, strend) \
1783 (__ASSERT_(pos < strend) \
1784 /* Note assumes is valid UTF-8 */ \
1785 (cp_macro(utf8_to_uvchr_buf((pos), (strend), NULL))))
1787 /* Returns the GCB value for the input code point */
1788 #define getGCB_VAL_CP(cp) \
1789 _generic_GET_BREAK_VAL_CP( \
1794 /* Returns the GCB value for the first code point in the UTF-8 encoded string
1795 * bounded by pos and strend */
1796 #define getGCB_VAL_UTF8(pos, strend) \
1797 _generic_GET_BREAK_VAL_UTF8(getGCB_VAL_CP, pos, strend)
1799 /* Returns the LB value for the input code point */
1800 #define getLB_VAL_CP(cp) \
1801 _generic_GET_BREAK_VAL_CP( \
1806 /* Returns the LB value for the first code point in the UTF-8 encoded string
1807 * bounded by pos and strend */
1808 #define getLB_VAL_UTF8(pos, strend) \
1809 _generic_GET_BREAK_VAL_UTF8(getLB_VAL_CP, pos, strend)
1812 /* Returns the SB value for the input code point */
1813 #define getSB_VAL_CP(cp) \
1814 _generic_GET_BREAK_VAL_CP( \
1819 /* Returns the SB value for the first code point in the UTF-8 encoded string
1820 * bounded by pos and strend */
1821 #define getSB_VAL_UTF8(pos, strend) \
1822 _generic_GET_BREAK_VAL_UTF8(getSB_VAL_CP, pos, strend)
1824 /* Returns the WB value for the input code point */
1825 #define getWB_VAL_CP(cp) \
1826 _generic_GET_BREAK_VAL_CP( \
1831 /* Returns the WB value for the first code point in the UTF-8 encoded string
1832 * bounded by pos and strend */
1833 #define getWB_VAL_UTF8(pos, strend) \
1834 _generic_GET_BREAK_VAL_UTF8(getWB_VAL_CP, pos, strend)
1836 /* We know what class REx starts with. Try to find this position... */
1837 /* if reginfo->intuit, its a dryrun */
1838 /* annoyingly all the vars in this routine have different names from their counterparts
1839 in regmatch. /grrr */
1841 S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
1842 const char *strend, regmatch_info *reginfo)
1845 const I32 doevery = (prog->intflags & PREGf_SKIP) == 0;
1846 char *pat_string; /* The pattern's exactish string */
1847 char *pat_end; /* ptr to end char of pat_string */
1848 re_fold_t folder; /* Function for computing non-utf8 folds */
1849 const U8 *fold_array; /* array for folding ords < 256 */
1855 I32 tmp = 1; /* Scratch variable? */
1856 const bool utf8_target = reginfo->is_utf8_target;
1857 UV utf8_fold_flags = 0;
1858 const bool is_utf8_pat = reginfo->is_utf8_pat;
1859 bool to_complement = FALSE; /* Invert the result? Taking the xor of this
1860 with a result inverts that result, as 0^1 =
1862 _char_class_number classnum;
1864 RXi_GET_DECL(prog,progi);
1866 PERL_ARGS_ASSERT_FIND_BYCLASS;
1868 /* We know what class it must start with. */
1871 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1873 if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(c)) && ! IN_UTF8_CTYPE_LOCALE) {
1874 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
1881 REXEC_FBC_UTF8_CLASS_SCAN(
1882 reginclass(prog, c, (U8*)s, (U8*) strend, utf8_target));
1885 REXEC_FBC_CLASS_SCAN(REGINCLASS(prog, c, (U8*)s, 0));
1889 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
1890 assert(! is_utf8_pat);
1893 if (is_utf8_pat || utf8_target) {
1894 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
1895 goto do_exactf_utf8;
1897 fold_array = PL_fold_latin1; /* Latin1 folds are not affected by */
1898 folder = foldEQ_latin1; /* /a, except the sharp s one which */
1899 goto do_exactf_non_utf8; /* isn't dealt with by these */
1901 case EXACTF: /* This node only generated for non-utf8 patterns */
1902 assert(! is_utf8_pat);
1904 utf8_fold_flags = 0;
1905 goto do_exactf_utf8;
1907 fold_array = PL_fold;
1909 goto do_exactf_non_utf8;
1912 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1913 if (is_utf8_pat || utf8_target || IN_UTF8_CTYPE_LOCALE) {
1914 utf8_fold_flags = FOLDEQ_LOCALE;
1915 goto do_exactf_utf8;
1917 fold_array = PL_fold_locale;
1918 folder = foldEQ_locale;
1919 goto do_exactf_non_utf8;
1923 utf8_fold_flags = FOLDEQ_S2_ALREADY_FOLDED;
1925 goto do_exactf_utf8;
1928 if (! utf8_target) { /* All code points in this node require
1929 UTF-8 to express. */
1932 utf8_fold_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
1933 | FOLDEQ_S2_FOLDS_SANE;
1934 goto do_exactf_utf8;
1937 if (is_utf8_pat || utf8_target) {
1938 utf8_fold_flags = is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
1939 goto do_exactf_utf8;
1942 /* Any 'ss' in the pattern should have been replaced by regcomp,
1943 * so we don't have to worry here about this single special case
1944 * in the Latin1 range */
1945 fold_array = PL_fold_latin1;
1946 folder = foldEQ_latin1;
1950 do_exactf_non_utf8: /* Neither pattern nor string are UTF8, and there
1951 are no glitches with fold-length differences
1952 between the target string and pattern */
1954 /* The idea in the non-utf8 EXACTF* cases is to first find the
1955 * first character of the EXACTF* node and then, if necessary,
1956 * case-insensitively compare the full text of the node. c1 is the
1957 * first character. c2 is its fold. This logic will not work for
1958 * Unicode semantics and the german sharp ss, which hence should
1959 * not be compiled into a node that gets here. */
1960 pat_string = STRING(c);
1961 ln = STR_LEN(c); /* length to match in octets/bytes */
1963 /* We know that we have to match at least 'ln' bytes (which is the
1964 * same as characters, since not utf8). If we have to match 3
1965 * characters, and there are only 2 availabe, we know without
1966 * trying that it will fail; so don't start a match past the
1967 * required minimum number from the far end */
1968 e = HOP3c(strend, -((SSize_t)ln), s);
1970 if (reginfo->intuit && e < s) {
1971 e = s; /* Due to minlen logic of intuit() */
1975 c2 = fold_array[c1];
1976 if (c1 == c2) { /* If char and fold are the same */
1977 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1);
1980 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1 || *(U8*)s == c2);
1988 /* If one of the operands is in utf8, we can't use the simpler folding
1989 * above, due to the fact that many different characters can have the
1990 * same fold, or portion of a fold, or different- length fold */
1991 pat_string = STRING(c);
1992 ln = STR_LEN(c); /* length to match in octets/bytes */
1993 pat_end = pat_string + ln;
1994 lnc = is_utf8_pat /* length to match in characters */
1995 ? utf8_length((U8 *) pat_string, (U8 *) pat_end)
1998 /* We have 'lnc' characters to match in the pattern, but because of
1999 * multi-character folding, each character in the target can match
2000 * up to 3 characters (Unicode guarantees it will never exceed
2001 * this) if it is utf8-encoded; and up to 2 if not (based on the
2002 * fact that the Latin 1 folds are already determined, and the
2003 * only multi-char fold in that range is the sharp-s folding to
2004 * 'ss'. Thus, a pattern character can match as little as 1/3 of a
2005 * string character. Adjust lnc accordingly, rounding up, so that
2006 * if we need to match at least 4+1/3 chars, that really is 5. */
2007 expansion = (utf8_target) ? UTF8_MAX_FOLD_CHAR_EXPAND : 2;
2008 lnc = (lnc + expansion - 1) / expansion;
2010 /* As in the non-UTF8 case, if we have to match 3 characters, and
2011 * only 2 are left, it's guaranteed to fail, so don't start a
2012 * match that would require us to go beyond the end of the string
2014 e = HOP3c(strend, -((SSize_t)lnc), s);
2016 if (reginfo->intuit && e < s) {
2017 e = s; /* Due to minlen logic of intuit() */
2020 /* XXX Note that we could recalculate e to stop the loop earlier,
2021 * as the worst case expansion above will rarely be met, and as we
2022 * go along we would usually find that e moves further to the left.
2023 * This would happen only after we reached the point in the loop
2024 * where if there were no expansion we should fail. Unclear if
2025 * worth the expense */
2028 char *my_strend= (char *)strend;
2029 if (foldEQ_utf8_flags(s, &my_strend, 0, utf8_target,
2030 pat_string, NULL, ln, is_utf8_pat, utf8_fold_flags)
2031 && (reginfo->intuit || regtry(reginfo, &s)) )
2035 s += (utf8_target) ? UTF8SKIP(s) : 1;
2041 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2042 if (FLAGS(c) != TRADITIONAL_BOUND) {
2043 if (! IN_UTF8_CTYPE_LOCALE) {
2044 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2045 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2050 FBC_BOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8);
2054 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2055 if (FLAGS(c) != TRADITIONAL_BOUND) {
2056 if (! IN_UTF8_CTYPE_LOCALE) {
2057 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2058 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2063 FBC_NBOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8);
2066 case BOUND: /* regcomp.c makes sure that this only has the traditional \b
2068 assert(FLAGS(c) == TRADITIONAL_BOUND);
2070 FBC_BOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8);
2073 case BOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2075 assert(FLAGS(c) == TRADITIONAL_BOUND);
2077 FBC_BOUND_A(isWORDCHAR_A);
2080 case NBOUND: /* regcomp.c makes sure that this only has the traditional \b
2082 assert(FLAGS(c) == TRADITIONAL_BOUND);
2084 FBC_NBOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8);
2087 case NBOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2089 assert(FLAGS(c) == TRADITIONAL_BOUND);
2091 FBC_NBOUND_A(isWORDCHAR_A);
2095 if ((bound_type) FLAGS(c) == TRADITIONAL_BOUND) {
2096 FBC_NBOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8);
2107 switch((bound_type) FLAGS(c)) {
2108 case TRADITIONAL_BOUND:
2109 FBC_BOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8);
2112 if (s == reginfo->strbeg) {
2113 if (reginfo->intuit || regtry(reginfo, &s))
2118 /* Didn't match. Try at the next position (if there is one) */
2119 s += (utf8_target) ? UTF8SKIP(s) : 1;
2120 if (UNLIKELY(s >= reginfo->strend)) {
2126 GCB_enum before = getGCB_VAL_UTF8(
2128 (U8*)(reginfo->strbeg)),
2129 (U8*) reginfo->strend);
2130 while (s < strend) {
2131 GCB_enum after = getGCB_VAL_UTF8((U8*) s,
2132 (U8*) reginfo->strend);
2133 if ( (to_complement ^ isGCB(before,
2135 (U8*) reginfo->strbeg,
2138 && (reginfo->intuit || regtry(reginfo, &s)))
2146 else { /* Not utf8. Everything is a GCB except between CR and
2148 while (s < strend) {
2149 if ((to_complement ^ ( UCHARAT(s - 1) != '\r'
2150 || UCHARAT(s) != '\n'))
2151 && (reginfo->intuit || regtry(reginfo, &s)))
2159 /* And, since this is a bound, it can match after the final
2160 * character in the string */
2161 if ((reginfo->intuit || regtry(reginfo, &s))) {
2167 if (s == reginfo->strbeg) {
2168 if (reginfo->intuit || regtry(reginfo, &s)) {
2171 s += (utf8_target) ? UTF8SKIP(s) : 1;
2172 if (UNLIKELY(s >= reginfo->strend)) {
2178 LB_enum before = getLB_VAL_UTF8(reghop3((U8*)s,
2180 (U8*)(reginfo->strbeg)),
2181 (U8*) reginfo->strend);
2182 while (s < strend) {
2183 LB_enum after = getLB_VAL_UTF8((U8*) s, (U8*) reginfo->strend);
2184 if (to_complement ^ isLB(before,
2186 (U8*) reginfo->strbeg,
2188 (U8*) reginfo->strend,
2190 && (reginfo->intuit || regtry(reginfo, &s)))
2198 else { /* Not utf8. */
2199 LB_enum before = getLB_VAL_CP((U8) *(s -1));
2200 while (s < strend) {
2201 LB_enum after = getLB_VAL_CP((U8) *s);
2202 if (to_complement ^ isLB(before,
2204 (U8*) reginfo->strbeg,
2206 (U8*) reginfo->strend,
2208 && (reginfo->intuit || regtry(reginfo, &s)))
2217 if (reginfo->intuit || regtry(reginfo, &s)) {
2224 if (s == reginfo->strbeg) {
2225 if (reginfo->intuit || regtry(reginfo, &s)) {
2228 s += (utf8_target) ? UTF8SKIP(s) : 1;
2229 if (UNLIKELY(s >= reginfo->strend)) {
2235 SB_enum before = getSB_VAL_UTF8(reghop3((U8*)s,
2237 (U8*)(reginfo->strbeg)),
2238 (U8*) reginfo->strend);
2239 while (s < strend) {
2240 SB_enum after = getSB_VAL_UTF8((U8*) s,
2241 (U8*) reginfo->strend);
2242 if ((to_complement ^ isSB(before,
2244 (U8*) reginfo->strbeg,
2246 (U8*) reginfo->strend,
2248 && (reginfo->intuit || regtry(reginfo, &s)))
2256 else { /* Not utf8. */
2257 SB_enum before = getSB_VAL_CP((U8) *(s -1));
2258 while (s < strend) {
2259 SB_enum after = getSB_VAL_CP((U8) *s);
2260 if ((to_complement ^ isSB(before,
2262 (U8*) reginfo->strbeg,
2264 (U8*) reginfo->strend,
2266 && (reginfo->intuit || regtry(reginfo, &s)))
2275 /* Here are at the final position in the target string. The SB
2276 * value is always true here, so matches, depending on other
2278 if (reginfo->intuit || regtry(reginfo, &s)) {
2285 if (s == reginfo->strbeg) {
2286 if (reginfo->intuit || regtry(reginfo, &s)) {
2289 s += (utf8_target) ? UTF8SKIP(s) : 1;
2290 if (UNLIKELY(s >= reginfo->strend)) {
2296 /* We are at a boundary between char_sub_0 and char_sub_1.
2297 * We also keep track of the value for char_sub_-1 as we
2298 * loop through the line. Context may be needed to make a
2299 * determination, and if so, this can save having to
2301 WB_enum previous = WB_UNKNOWN;
2302 WB_enum before = getWB_VAL_UTF8(
2305 (U8*)(reginfo->strbeg)),
2306 (U8*) reginfo->strend);
2307 while (s < strend) {
2308 WB_enum after = getWB_VAL_UTF8((U8*) s,
2309 (U8*) reginfo->strend);
2310 if ((to_complement ^ isWB(previous,
2313 (U8*) reginfo->strbeg,
2315 (U8*) reginfo->strend,
2317 && (reginfo->intuit || regtry(reginfo, &s)))
2326 else { /* Not utf8. */
2327 WB_enum previous = WB_UNKNOWN;
2328 WB_enum before = getWB_VAL_CP((U8) *(s -1));
2329 while (s < strend) {
2330 WB_enum after = getWB_VAL_CP((U8) *s);
2331 if ((to_complement ^ isWB(previous,
2334 (U8*) reginfo->strbeg,
2336 (U8*) reginfo->strend,
2338 && (reginfo->intuit || regtry(reginfo, &s)))
2348 if (reginfo->intuit || regtry(reginfo, &s)) {
2355 REXEC_FBC_CSCAN(is_LNBREAK_utf8_safe(s, strend),
2356 is_LNBREAK_latin1_safe(s, strend)
2360 /* The argument to all the POSIX node types is the class number to pass to
2361 * _generic_isCC() to build a mask for searching in PL_charclass[] */
2368 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2369 REXEC_FBC_CSCAN(to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(c), (U8 *) s)),
2370 to_complement ^ cBOOL(isFOO_lc(FLAGS(c), *s)));
2385 /* The complement of something that matches only ASCII matches all
2386 * non-ASCII, plus everything in ASCII that isn't in the class. */
2387 REXEC_FBC_UTF8_CLASS_SCAN(! isASCII_utf8(s)
2388 || ! _generic_isCC_A(*s, FLAGS(c)));
2397 /* Don't need to worry about utf8, as it can match only a single
2398 * byte invariant character. */
2399 REXEC_FBC_CLASS_SCAN(
2400 to_complement ^ cBOOL(_generic_isCC_A(*s, FLAGS(c))));
2408 if (! utf8_target) {
2409 REXEC_FBC_CLASS_SCAN(to_complement ^ cBOOL(_generic_isCC(*s,
2415 classnum = (_char_class_number) FLAGS(c);
2416 if (classnum < _FIRST_NON_SWASH_CC) {
2417 while (s < strend) {
2419 /* We avoid loading in the swash as long as possible, but
2420 * should we have to, we jump to a separate loop. This
2421 * extra 'if' statement is what keeps this code from being
2422 * just a call to REXEC_FBC_UTF8_CLASS_SCAN() */
2423 if (UTF8_IS_ABOVE_LATIN1(*s)) {
2424 goto found_above_latin1;
2426 if ((UTF8_IS_INVARIANT(*s)
2427 && to_complement ^ cBOOL(_generic_isCC((U8) *s,
2429 || (UTF8_IS_DOWNGRADEABLE_START(*s)
2430 && to_complement ^ cBOOL(
2431 _generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(*s,
2435 if (tmp && (reginfo->intuit || regtry(reginfo, &s)))
2447 else switch (classnum) { /* These classes are implemented as
2449 case _CC_ENUM_SPACE:
2450 REXEC_FBC_UTF8_CLASS_SCAN(
2451 to_complement ^ cBOOL(isSPACE_utf8(s)));
2454 case _CC_ENUM_BLANK:
2455 REXEC_FBC_UTF8_CLASS_SCAN(
2456 to_complement ^ cBOOL(isBLANK_utf8(s)));
2459 case _CC_ENUM_XDIGIT:
2460 REXEC_FBC_UTF8_CLASS_SCAN(
2461 to_complement ^ cBOOL(isXDIGIT_utf8(s)));
2464 case _CC_ENUM_VERTSPACE:
2465 REXEC_FBC_UTF8_CLASS_SCAN(
2466 to_complement ^ cBOOL(isVERTWS_utf8(s)));
2469 case _CC_ENUM_CNTRL:
2470 REXEC_FBC_UTF8_CLASS_SCAN(
2471 to_complement ^ cBOOL(isCNTRL_utf8(s)));
2475 Perl_croak(aTHX_ "panic: find_byclass() node %d='%s' has an unexpected character class '%d'", OP(c), PL_reg_name[OP(c)], classnum);
2476 NOT_REACHED; /* NOTREACHED */
2481 found_above_latin1: /* Here we have to load a swash to get the result
2482 for the current code point */
2483 if (! PL_utf8_swash_ptrs[classnum]) {
2484 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
2485 PL_utf8_swash_ptrs[classnum] =
2486 _core_swash_init("utf8",
2489 PL_XPosix_ptrs[classnum], &flags);
2492 /* This is a copy of the loop above for swash classes, though using the
2493 * FBC macro instead of being expanded out. Since we've loaded the
2494 * swash, we don't have to check for that each time through the loop */
2495 REXEC_FBC_UTF8_CLASS_SCAN(
2496 to_complement ^ cBOOL(_generic_utf8(
2499 swash_fetch(PL_utf8_swash_ptrs[classnum],
2507 /* what trie are we using right now */
2508 reg_ac_data *aho = (reg_ac_data*)progi->data->data[ ARG( c ) ];
2509 reg_trie_data *trie = (reg_trie_data*)progi->data->data[ aho->trie ];
2510 HV *widecharmap = MUTABLE_HV(progi->data->data[ aho->trie + 1 ]);
2512 const char *last_start = strend - trie->minlen;
2514 const char *real_start = s;
2516 STRLEN maxlen = trie->maxlen;
2518 U8 **points; /* map of where we were in the input string
2519 when reading a given char. For ASCII this
2520 is unnecessary overhead as the relationship
2521 is always 1:1, but for Unicode, especially
2522 case folded Unicode this is not true. */
2523 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
2527 GET_RE_DEBUG_FLAGS_DECL;
2529 /* We can't just allocate points here. We need to wrap it in
2530 * an SV so it gets freed properly if there is a croak while
2531 * running the match */
2534 sv_points=newSV(maxlen * sizeof(U8 *));
2535 SvCUR_set(sv_points,
2536 maxlen * sizeof(U8 *));
2537 SvPOK_on(sv_points);
2538 sv_2mortal(sv_points);
2539 points=(U8**)SvPV_nolen(sv_points );
2540 if ( trie_type != trie_utf8_fold
2541 && (trie->bitmap || OP(c)==AHOCORASICKC) )
2544 bitmap=(U8*)trie->bitmap;
2546 bitmap=(U8*)ANYOF_BITMAP(c);
2548 /* this is the Aho-Corasick algorithm modified a touch
2549 to include special handling for long "unknown char" sequences.
2550 The basic idea being that we use AC as long as we are dealing
2551 with a possible matching char, when we encounter an unknown char
2552 (and we have not encountered an accepting state) we scan forward
2553 until we find a legal starting char.
2554 AC matching is basically that of trie matching, except that when
2555 we encounter a failing transition, we fall back to the current
2556 states "fail state", and try the current char again, a process
2557 we repeat until we reach the root state, state 1, or a legal
2558 transition. If we fail on the root state then we can either
2559 terminate if we have reached an accepting state previously, or
2560 restart the entire process from the beginning if we have not.
2563 while (s <= last_start) {
2564 const U32 uniflags = UTF8_ALLOW_DEFAULT;
2572 U8 *uscan = (U8*)NULL;
2573 U8 *leftmost = NULL;
2575 U32 accepted_word= 0;
2579 while ( state && uc <= (U8*)strend ) {
2581 U32 word = aho->states[ state ].wordnum;
2585 DEBUG_TRIE_EXECUTE_r(
2586 if ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2587 dump_exec_pos( (char *)uc, c, strend, real_start,
2588 (char *)uc, utf8_target, 0 );
2589 Perl_re_printf( aTHX_
2590 " Scanning for legal start char...\n");
2594 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2598 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2604 if (uc >(U8*)last_start) break;
2608 U8 *lpos= points[ (pointpos - trie->wordinfo[word].len) % maxlen ];
2609 if (!leftmost || lpos < leftmost) {
2610 DEBUG_r(accepted_word=word);
2616 points[pointpos++ % maxlen]= uc;
2617 if (foldlen || uc < (U8*)strend) {
2618 REXEC_TRIE_READ_CHAR(trie_type, trie,
2620 uscan, len, uvc, charid, foldlen,
2622 DEBUG_TRIE_EXECUTE_r({
2623 dump_exec_pos( (char *)uc, c, strend,
2624 real_start, s, utf8_target, 0);
2625 Perl_re_printf( aTHX_
2626 " Charid:%3u CP:%4" UVxf " ",
2638 word = aho->states[ state ].wordnum;
2640 base = aho->states[ state ].trans.base;
2642 DEBUG_TRIE_EXECUTE_r({
2644 dump_exec_pos( (char *)uc, c, strend, real_start,
2645 s, utf8_target, 0 );
2646 Perl_re_printf( aTHX_
2647 "%sState: %4" UVxf ", word=%" UVxf,
2648 failed ? " Fail transition to " : "",
2649 (UV)state, (UV)word);
2655 ( ((offset = base + charid
2656 - 1 - trie->uniquecharcount)) >= 0)
2657 && ((U32)offset < trie->lasttrans)
2658 && trie->trans[offset].check == state
2659 && (tmp=trie->trans[offset].next))
2661 DEBUG_TRIE_EXECUTE_r(
2662 Perl_re_printf( aTHX_ " - legal\n"));
2667 DEBUG_TRIE_EXECUTE_r(
2668 Perl_re_printf( aTHX_ " - fail\n"));
2670 state = aho->fail[state];
2674 /* we must be accepting here */
2675 DEBUG_TRIE_EXECUTE_r(
2676 Perl_re_printf( aTHX_ " - accepting\n"));
2685 if (!state) state = 1;
2688 if ( aho->states[ state ].wordnum ) {
2689 U8 *lpos = points[ (pointpos - trie->wordinfo[aho->states[ state ].wordnum].len) % maxlen ];
2690 if (!leftmost || lpos < leftmost) {
2691 DEBUG_r(accepted_word=aho->states[ state ].wordnum);
2696 s = (char*)leftmost;
2697 DEBUG_TRIE_EXECUTE_r({
2698 Perl_re_printf( aTHX_ "Matches word #%" UVxf " at position %" IVdf ". Trying full pattern...\n",
2699 (UV)accepted_word, (IV)(s - real_start)
2702 if (reginfo->intuit || regtry(reginfo, &s)) {
2708 DEBUG_TRIE_EXECUTE_r({
2709 Perl_re_printf( aTHX_ "Pattern failed. Looking for new start point...\n");
2712 DEBUG_TRIE_EXECUTE_r(
2713 Perl_re_printf( aTHX_ "No match.\n"));
2722 Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
2729 /* set RX_SAVED_COPY, RX_SUBBEG etc.
2730 * flags have same meanings as with regexec_flags() */
2733 S_reg_set_capture_string(pTHX_ REGEXP * const rx,
2740 struct regexp *const prog = ReANY(rx);
2742 if (flags & REXEC_COPY_STR) {
2745 DEBUG_C(Perl_re_printf( aTHX_
2746 "Copy on write: regexp capture, type %d\n",
2748 /* Create a new COW SV to share the match string and store
2749 * in saved_copy, unless the current COW SV in saved_copy
2750 * is valid and suitable for our purpose */
2751 if (( prog->saved_copy
2752 && SvIsCOW(prog->saved_copy)
2753 && SvPOKp(prog->saved_copy)
2756 && SvPVX(sv) == SvPVX(prog->saved_copy)))
2758 /* just reuse saved_copy SV */
2759 if (RXp_MATCH_COPIED(prog)) {
2760 Safefree(prog->subbeg);
2761 RXp_MATCH_COPIED_off(prog);
2765 /* create new COW SV to share string */
2766 RX_MATCH_COPY_FREE(rx);
2767 prog->saved_copy = sv_setsv_cow(prog->saved_copy, sv);
2769 prog->subbeg = (char *)SvPVX_const(prog->saved_copy);
2770 assert (SvPOKp(prog->saved_copy));
2771 prog->sublen = strend - strbeg;
2772 prog->suboffset = 0;
2773 prog->subcoffset = 0;
2778 SSize_t max = strend - strbeg;
2781 if ( (flags & REXEC_COPY_SKIP_POST)
2782 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2783 && !(PL_sawampersand & SAWAMPERSAND_RIGHT)
2784 ) { /* don't copy $' part of string */
2787 /* calculate the right-most part of the string covered
2788 * by a capture. Due to lookahead, this may be to
2789 * the right of $&, so we have to scan all captures */
2790 while (n <= prog->lastparen) {
2791 if (prog->offs[n].end > max)
2792 max = prog->offs[n].end;
2796 max = (PL_sawampersand & SAWAMPERSAND_LEFT)
2797 ? prog->offs[0].start
2799 assert(max >= 0 && max <= strend - strbeg);
2802 if ( (flags & REXEC_COPY_SKIP_PRE)
2803 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2804 && !(PL_sawampersand & SAWAMPERSAND_LEFT)
2805 ) { /* don't copy $` part of string */
2808 /* calculate the left-most part of the string covered
2809 * by a capture. Due to lookbehind, this may be to
2810 * the left of $&, so we have to scan all captures */
2811 while (min && n <= prog->lastparen) {
2812 if ( prog->offs[n].start != -1
2813 && prog->offs[n].start < min)
2815 min = prog->offs[n].start;
2819 if ((PL_sawampersand & SAWAMPERSAND_RIGHT)
2820 && min > prog->offs[0].end
2822 min = prog->offs[0].end;
2826 assert(min >= 0 && min <= max && min <= strend - strbeg);
2829 if (RX_MATCH_COPIED(rx)) {
2830 if (sublen > prog->sublen)
2832 (char*)saferealloc(prog->subbeg, sublen+1);
2835 prog->subbeg = (char*)safemalloc(sublen+1);
2836 Copy(strbeg + min, prog->subbeg, sublen, char);
2837 prog->subbeg[sublen] = '\0';
2838 prog->suboffset = min;
2839 prog->sublen = sublen;
2840 RX_MATCH_COPIED_on(rx);
2842 prog->subcoffset = prog->suboffset;
2843 if (prog->suboffset && utf8_target) {
2844 /* Convert byte offset to chars.
2845 * XXX ideally should only compute this if @-/@+
2846 * has been seen, a la PL_sawampersand ??? */
2848 /* If there's a direct correspondence between the
2849 * string which we're matching and the original SV,
2850 * then we can use the utf8 len cache associated with
2851 * the SV. In particular, it means that under //g,
2852 * sv_pos_b2u() will use the previously cached
2853 * position to speed up working out the new length of
2854 * subcoffset, rather than counting from the start of
2855 * the string each time. This stops
2856 * $x = "\x{100}" x 1E6; 1 while $x =~ /(.)/g;
2857 * from going quadratic */
2858 if (SvPOKp(sv) && SvPVX(sv) == strbeg)
2859 prog->subcoffset = sv_pos_b2u_flags(sv, prog->subcoffset,
2860 SV_GMAGIC|SV_CONST_RETURN);
2862 prog->subcoffset = utf8_length((U8*)strbeg,
2863 (U8*)(strbeg+prog->suboffset));
2867 RX_MATCH_COPY_FREE(rx);
2868 prog->subbeg = strbeg;
2869 prog->suboffset = 0;
2870 prog->subcoffset = 0;
2871 prog->sublen = strend - strbeg;
2879 - regexec_flags - match a regexp against a string
2882 Perl_regexec_flags(pTHX_ REGEXP * const rx, char *stringarg, char *strend,
2883 char *strbeg, SSize_t minend, SV *sv, void *data, U32 flags)
2884 /* stringarg: the point in the string at which to begin matching */
2885 /* strend: pointer to null at end of string */
2886 /* strbeg: real beginning of string */
2887 /* minend: end of match must be >= minend bytes after stringarg. */
2888 /* sv: SV being matched: only used for utf8 flag, pos() etc; string
2889 * itself is accessed via the pointers above */
2890 /* data: May be used for some additional optimizations.
2891 Currently unused. */
2892 /* flags: For optimizations. See REXEC_* in regexp.h */
2895 struct regexp *const prog = ReANY(rx);
2899 SSize_t minlen; /* must match at least this many chars */
2900 SSize_t dontbother = 0; /* how many characters not to try at end */
2901 const bool utf8_target = cBOOL(DO_UTF8(sv));
2903 RXi_GET_DECL(prog,progi);
2904 regmatch_info reginfo_buf; /* create some info to pass to regtry etc */
2905 regmatch_info *const reginfo = ®info_buf;
2906 regexp_paren_pair *swap = NULL;
2908 GET_RE_DEBUG_FLAGS_DECL;
2910 PERL_ARGS_ASSERT_REGEXEC_FLAGS;
2911 PERL_UNUSED_ARG(data);
2913 /* Be paranoid... */
2915 Perl_croak(aTHX_ "NULL regexp parameter");
2919 debug_start_match(rx, utf8_target, stringarg, strend,
2923 startpos = stringarg;
2925 /* set these early as they may be used by the HOP macros below */
2926 reginfo->strbeg = strbeg;
2927 reginfo->strend = strend;
2928 reginfo->is_utf8_target = cBOOL(utf8_target);
2930 if (prog->intflags & PREGf_GPOS_SEEN) {
2933 /* set reginfo->ganch, the position where \G can match */
2936 (flags & REXEC_IGNOREPOS)
2937 ? stringarg /* use start pos rather than pos() */
2938 : ((mg = mg_find_mglob(sv)) && mg->mg_len >= 0)
2939 /* Defined pos(): */
2940 ? strbeg + MgBYTEPOS(mg, sv, strbeg, strend-strbeg)
2941 : strbeg; /* pos() not defined; use start of string */
2943 DEBUG_GPOS_r(Perl_re_printf( aTHX_
2944 "GPOS ganch set to strbeg[%" IVdf "]\n", (IV)(reginfo->ganch - strbeg)));
2946 /* in the presence of \G, we may need to start looking earlier in
2947 * the string than the suggested start point of stringarg:
2948 * if prog->gofs is set, then that's a known, fixed minimum
2951 * /ab|c\G/: gofs = 1
2952 * or if the minimum offset isn't known, then we have to go back
2953 * to the start of the string, e.g. /w+\G/
2956 if (prog->intflags & PREGf_ANCH_GPOS) {
2958 startpos = HOPBACKc(reginfo->ganch, prog->gofs);
2960 ((flags & REXEC_FAIL_ON_UNDERFLOW) && startpos < stringarg))
2962 DEBUG_r(Perl_re_printf( aTHX_
2963 "fail: ganch-gofs before earliest possible start\n"));
2968 startpos = reginfo->ganch;
2970 else if (prog->gofs) {
2971 startpos = HOPBACKc(startpos, prog->gofs);
2975 else if (prog->intflags & PREGf_GPOS_FLOAT)
2979 minlen = prog->minlen;
2980 if ((startpos + minlen) > strend || startpos < strbeg) {
2981 DEBUG_r(Perl_re_printf( aTHX_
2982 "Regex match can't succeed, so not even tried\n"));
2986 /* at the end of this function, we'll do a LEAVE_SCOPE(oldsave),
2987 * which will call destuctors to reset PL_regmatch_state, free higher
2988 * PL_regmatch_slabs, and clean up regmatch_info_aux and
2989 * regmatch_info_aux_eval */
2991 oldsave = PL_savestack_ix;
2995 if ((prog->extflags & RXf_USE_INTUIT)
2996 && !(flags & REXEC_CHECKED))
2998 s = re_intuit_start(rx, sv, strbeg, startpos, strend,
3003 if (prog->extflags & RXf_CHECK_ALL) {
3004 /* we can match based purely on the result of INTUIT.
3005 * Set up captures etc just for $& and $-[0]
3006 * (an intuit-only match wont have $1,$2,..) */
3007 assert(!prog->nparens);
3009 /* s/// doesn't like it if $& is earlier than where we asked it to
3010 * start searching (which can happen on something like /.\G/) */
3011 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
3014 /* this should only be possible under \G */
3015 assert(prog->intflags & PREGf_GPOS_SEEN);
3016 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
3017 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3021 /* match via INTUIT shouldn't have any captures.
3022 * Let @-, @+, $^N know */
3023 prog->lastparen = prog->lastcloseparen = 0;
3024 RX_MATCH_UTF8_set(rx, utf8_target);
3025 prog->offs[0].start = s - strbeg;
3026 prog->offs[0].end = utf8_target
3027 ? (char*)utf8_hop((U8*)s, prog->minlenret) - strbeg
3028 : s - strbeg + prog->minlenret;
3029 if ( !(flags & REXEC_NOT_FIRST) )
3030 S_reg_set_capture_string(aTHX_ rx,
3032 sv, flags, utf8_target);
3038 multiline = prog->extflags & RXf_PMf_MULTILINE;
3040 if (strend - s < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
3041 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
3042 "String too short [regexec_flags]...\n"));
3046 /* Check validity of program. */
3047 if (UCHARAT(progi->program) != REG_MAGIC) {
3048 Perl_croak(aTHX_ "corrupted regexp program");
3051 RX_MATCH_TAINTED_off(rx);
3052 RX_MATCH_UTF8_set(rx, utf8_target);
3054 reginfo->prog = rx; /* Yes, sorry that this is confusing. */
3055 reginfo->intuit = 0;
3056 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
3057 reginfo->warned = FALSE;
3059 reginfo->poscache_maxiter = 0; /* not yet started a countdown */
3060 /* see how far we have to get to not match where we matched before */
3061 reginfo->till = stringarg + minend;
3063 if (prog->extflags & RXf_EVAL_SEEN && SvPADTMP(sv)) {
3064 /* SAVEFREESV, not sv_mortalcopy, as this SV must last until after
3065 S_cleanup_regmatch_info_aux has executed (registered by
3066 SAVEDESTRUCTOR_X below). S_cleanup_regmatch_info_aux modifies
3067 magic belonging to this SV.
3068 Not newSVsv, either, as it does not COW.
3070 reginfo->sv = newSV(0);
3071 SvSetSV_nosteal(reginfo->sv, sv);
3072 SAVEFREESV(reginfo->sv);
3075 /* reserve next 2 or 3 slots in PL_regmatch_state:
3076 * slot N+0: may currently be in use: skip it
3077 * slot N+1: use for regmatch_info_aux struct
3078 * slot N+2: use for regmatch_info_aux_eval struct if we have (?{})'s
3079 * slot N+3: ready for use by regmatch()
3083 regmatch_state *old_regmatch_state;
3084 regmatch_slab *old_regmatch_slab;
3085 int i, max = (prog->extflags & RXf_EVAL_SEEN) ? 2 : 1;
3087 /* on first ever match, allocate first slab */
3088 if (!PL_regmatch_slab) {
3089 Newx(PL_regmatch_slab, 1, regmatch_slab);
3090 PL_regmatch_slab->prev = NULL;
3091 PL_regmatch_slab->next = NULL;
3092 PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
3095 old_regmatch_state = PL_regmatch_state;
3096 old_regmatch_slab = PL_regmatch_slab;
3098 for (i=0; i <= max; i++) {
3100 reginfo->info_aux = &(PL_regmatch_state->u.info_aux);
3102 reginfo->info_aux_eval =
3103 reginfo->info_aux->info_aux_eval =
3104 &(PL_regmatch_state->u.info_aux_eval);
3106 if (++PL_regmatch_state > SLAB_LAST(PL_regmatch_slab))
3107 PL_regmatch_state = S_push_slab(aTHX);
3110 /* note initial PL_regmatch_state position; at end of match we'll
3111 * pop back to there and free any higher slabs */
3113 reginfo->info_aux->old_regmatch_state = old_regmatch_state;
3114 reginfo->info_aux->old_regmatch_slab = old_regmatch_slab;
3115 reginfo->info_aux->poscache = NULL;
3117 SAVEDESTRUCTOR_X(S_cleanup_regmatch_info_aux, reginfo->info_aux);
3119 if ((prog->extflags & RXf_EVAL_SEEN))
3120 S_setup_eval_state(aTHX_ reginfo);
3122 reginfo->info_aux_eval = reginfo->info_aux->info_aux_eval = NULL;
3125 /* If there is a "must appear" string, look for it. */
3127 if (PL_curpm && (PM_GETRE(PL_curpm) == rx)) {
3128 /* We have to be careful. If the previous successful match
3129 was from this regex we don't want a subsequent partially
3130 successful match to clobber the old results.
3131 So when we detect this possibility we add a swap buffer
3132 to the re, and switch the buffer each match. If we fail,
3133 we switch it back; otherwise we leave it swapped.
3136 /* do we need a save destructor here for eval dies? */
3137 Newxz(prog->offs, (prog->nparens + 1), regexp_paren_pair);
3138 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_
3139 "rex=0x%" UVxf " saving offs: orig=0x%" UVxf " new=0x%" UVxf "\n",
3147 if (prog->recurse_locinput)
3148 Zero(prog->recurse_locinput,prog->nparens + 1, char *);
3150 /* Simplest case: anchored match need be tried only once, or with
3151 * MBOL, only at the beginning of each line.
3153 * Note that /.*.../ sets PREGf_IMPLICIT|MBOL, while /.*.../s sets
3154 * PREGf_IMPLICIT|SBOL. The idea is that with /.*.../s, if it doesn't
3155 * match at the start of the string then it won't match anywhere else
3156 * either; while with /.*.../, if it doesn't match at the beginning,
3157 * the earliest it could match is at the start of the next line */
3159 if (prog->intflags & (PREGf_ANCH & ~PREGf_ANCH_GPOS)) {
3162 if (regtry(reginfo, &s))
3165 if (!(prog->intflags & PREGf_ANCH_MBOL))
3168 /* didn't match at start, try at other newline positions */
3171 dontbother = minlen - 1;
3172 end = HOP3c(strend, -dontbother, strbeg) - 1;
3174 /* skip to next newline */
3176 while (s <= end) { /* note it could be possible to match at the end of the string */
3177 /* NB: newlines are the same in unicode as they are in latin */
3180 if (prog->check_substr || prog->check_utf8) {
3181 /* note that with PREGf_IMPLICIT, intuit can only fail
3182 * or return the start position, so it's of limited utility.
3183 * Nevertheless, I made the decision that the potential for
3184 * quick fail was still worth it - DAPM */
3185 s = re_intuit_start(rx, sv, strbeg, s, strend, flags, NULL);
3189 if (regtry(reginfo, &s))
3193 } /* end anchored search */
3195 if (prog->intflags & PREGf_ANCH_GPOS)
3197 /* PREGf_ANCH_GPOS should never be true if PREGf_GPOS_SEEN is not true */
3198 assert(prog->intflags & PREGf_GPOS_SEEN);
3199 /* For anchored \G, the only position it can match from is
3200 * (ganch-gofs); we already set startpos to this above; if intuit
3201 * moved us on from there, we can't possibly succeed */
3202 assert(startpos == HOPBACKc(reginfo->ganch, prog->gofs));
3203 if (s == startpos && regtry(reginfo, &s))
3208 /* Messy cases: unanchored match. */
3209 if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
3210 /* we have /x+whatever/ */
3211 /* it must be a one character string (XXXX Except is_utf8_pat?) */
3217 if (! prog->anchored_utf8) {
3218 to_utf8_substr(prog);
3220 ch = SvPVX_const(prog->anchored_utf8)[0];
3223 DEBUG_EXECUTE_r( did_match = 1 );
3224 if (regtry(reginfo, &s)) goto got_it;
3226 while (s < strend && *s == ch)
3233 if (! prog->anchored_substr) {
3234 if (! to_byte_substr(prog)) {
3235 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3238 ch = SvPVX_const(prog->anchored_substr)[0];
3241 DEBUG_EXECUTE_r( did_match = 1 );
3242 if (regtry(reginfo, &s)) goto got_it;
3244 while (s < strend && *s == ch)
3249 DEBUG_EXECUTE_r(if (!did_match)
3250 Perl_re_printf( aTHX_
3251 "Did not find anchored character...\n")
3254 else if (prog->anchored_substr != NULL
3255 || prog->anchored_utf8 != NULL
3256 || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
3257 && prog->float_max_offset < strend - s)) {
3262 char *last1; /* Last position checked before */
3266 if (prog->anchored_substr || prog->anchored_utf8) {
3268 if (! prog->anchored_utf8) {
3269 to_utf8_substr(prog);
3271 must = prog->anchored_utf8;
3274 if (! prog->anchored_substr) {
3275 if (! to_byte_substr(prog)) {
3276 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3279 must = prog->anchored_substr;
3281 back_max = back_min = prog->anchored_offset;
3284 if (! prog->float_utf8) {
3285 to_utf8_substr(prog);
3287 must = prog->float_utf8;
3290 if (! prog->float_substr) {
3291 if (! to_byte_substr(prog)) {
3292 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3295 must = prog->float_substr;
3297 back_max = prog->float_max_offset;
3298 back_min = prog->float_min_offset;
3304 last = HOP3c(strend, /* Cannot start after this */
3305 -(SSize_t)(CHR_SVLEN(must)
3306 - (SvTAIL(must) != 0) + back_min), strbeg);
3308 if (s > reginfo->strbeg)
3309 last1 = HOPc(s, -1);
3311 last1 = s - 1; /* bogus */
3313 /* XXXX check_substr already used to find "s", can optimize if
3314 check_substr==must. */
3316 strend = HOPc(strend, -dontbother);
3317 while ( (s <= last) &&
3318 (s = fbm_instr((unsigned char*)HOP4c(s, back_min, strbeg, strend),
3319 (unsigned char*)strend, must,
3320 multiline ? FBMrf_MULTILINE : 0)) ) {
3321 DEBUG_EXECUTE_r( did_match = 1 );
3322 if (HOPc(s, -back_max) > last1) {
3323 last1 = HOPc(s, -back_min);
3324 s = HOPc(s, -back_max);
3327 char * const t = (last1 >= reginfo->strbeg)
3328 ? HOPc(last1, 1) : last1 + 1;
3330 last1 = HOPc(s, -back_min);
3334 while (s <= last1) {
3335 if (regtry(reginfo, &s))
3338 s++; /* to break out of outer loop */
3345 while (s <= last1) {
3346 if (regtry(reginfo, &s))
3352 DEBUG_EXECUTE_r(if (!did_match) {
3353 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
3354 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
3355 Perl_re_printf( aTHX_ "Did not find %s substr %s%s...\n",
3356 ((must == prog->anchored_substr || must == prog->anchored_utf8)
3357 ? "anchored" : "floating"),
3358 quoted, RE_SV_TAIL(must));
3362 else if ( (c = progi->regstclass) ) {
3364 const OPCODE op = OP(progi->regstclass);
3365 /* don't bother with what can't match */
3366 if (PL_regkind[op] != EXACT && PL_regkind[op] != TRIE)
3367 strend = HOPc(strend, -(minlen - 1));
3370 SV * const prop = sv_newmortal();
3371 regprop(prog, prop, c, reginfo, NULL);
3373 RE_PV_QUOTED_DECL(quoted,utf8_target,PERL_DEBUG_PAD_ZERO(1),
3375 Perl_re_printf( aTHX_
3376 "Matching stclass %.*s against %s (%d bytes)\n",
3377 (int)SvCUR(prop), SvPVX_const(prop),
3378 quoted, (int)(strend - s));
3381 if (find_byclass(prog, c, s, strend, reginfo))
3383 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "Contradicts stclass... [regexec_flags]\n"));
3387 if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
3395 if (! prog->float_utf8) {
3396 to_utf8_substr(prog);
3398 float_real = prog->float_utf8;
3401 if (! prog->float_substr) {
3402 if (! to_byte_substr(prog)) {
3403 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3406 float_real = prog->float_substr;
3409 little = SvPV_const(float_real, len);
3410 if (SvTAIL(float_real)) {
3411 /* This means that float_real contains an artificial \n on
3412 * the end due to the presence of something like this:
3413 * /foo$/ where we can match both "foo" and "foo\n" at the
3414 * end of the string. So we have to compare the end of the
3415 * string first against the float_real without the \n and
3416 * then against the full float_real with the string. We
3417 * have to watch out for cases where the string might be
3418 * smaller than the float_real or the float_real without
3420 char *checkpos= strend - len;
3422 Perl_re_printf( aTHX_
3423 "%sChecking for float_real.%s\n",
3424 PL_colors[4], PL_colors[5]));
3425 if (checkpos + 1 < strbeg) {
3426 /* can't match, even if we remove the trailing \n
3427 * string is too short to match */
3429 Perl_re_printf( aTHX_
3430 "%sString shorter than required trailing substring, cannot match.%s\n",
3431 PL_colors[4], PL_colors[5]));
3433 } else if (memEQ(checkpos + 1, little, len - 1)) {
3434 /* can match, the end of the string matches without the
3436 last = checkpos + 1;
3437 } else if (checkpos < strbeg) {
3438 /* cant match, string is too short when the "\n" is
3441 Perl_re_printf( aTHX_
3442 "%sString does not contain required trailing substring, cannot match.%s\n",
3443 PL_colors[4], PL_colors[5]));
3445 } else if (!multiline) {
3446 /* non multiline match, so compare with the "\n" at the
3447 * end of the string */
3448 if (memEQ(checkpos, little, len)) {
3452 Perl_re_printf( aTHX_
3453 "%sString does not contain required trailing substring, cannot match.%s\n",
3454 PL_colors[4], PL_colors[5]));
3458 /* multiline match, so we have to search for a place
3459 * where the full string is located */
3465 last = rninstr(s, strend, little, little + len);
3467 last = strend; /* matching "$" */
3470 /* at one point this block contained a comment which was
3471 * probably incorrect, which said that this was a "should not
3472 * happen" case. Even if it was true when it was written I am
3473 * pretty sure it is not anymore, so I have removed the comment
3474 * and replaced it with this one. Yves */
3476 Perl_re_printf( aTHX_
3477 "%sString does not contain required substring, cannot match.%s\n",
3478 PL_colors[4], PL_colors[5]
3482 dontbother = strend - last + prog->float_min_offset;
3484 if (minlen && (dontbother < minlen))
3485 dontbother = minlen - 1;
3486 strend -= dontbother; /* this one's always in bytes! */
3487 /* We don't know much -- general case. */
3490 if (regtry(reginfo, &s))
3499 if (regtry(reginfo, &s))
3501 } while (s++ < strend);
3509 /* s/// doesn't like it if $& is earlier than where we asked it to
3510 * start searching (which can happen on something like /.\G/) */
3511 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
3512 && (prog->offs[0].start < stringarg - strbeg))
3514 /* this should only be possible under \G */
3515 assert(prog->intflags & PREGf_GPOS_SEEN);
3516 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
3517 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3523 Perl_re_exec_indentf( aTHX_
3524 "rex=0x%" UVxf " freeing offs: 0x%" UVxf "\n",
3532 /* clean up; this will trigger destructors that will free all slabs
3533 * above the current one, and cleanup the regmatch_info_aux
3534 * and regmatch_info_aux_eval sructs */
3536 LEAVE_SCOPE(oldsave);
3538 if (RXp_PAREN_NAMES(prog))
3539 (void)hv_iterinit(RXp_PAREN_NAMES(prog));
3541 /* make sure $`, $&, $', and $digit will work later */
3542 if ( !(flags & REXEC_NOT_FIRST) )
3543 S_reg_set_capture_string(aTHX_ rx,
3544 strbeg, reginfo->strend,
3545 sv, flags, utf8_target);
3550 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%sMatch failed%s\n",
3551 PL_colors[4], PL_colors[5]));
3553 /* clean up; this will trigger destructors that will free all slabs
3554 * above the current one, and cleanup the regmatch_info_aux
3555 * and regmatch_info_aux_eval sructs */
3557 LEAVE_SCOPE(oldsave);
3560 /* we failed :-( roll it back */
3561 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_
3562 "rex=0x%" UVxf " rolling back offs: freeing=0x%" UVxf " restoring=0x%" UVxf "\n",
3568 Safefree(prog->offs);
3575 /* Set which rex is pointed to by PL_reg_curpm, handling ref counting.
3576 * Do inc before dec, in case old and new rex are the same */
3577 #define SET_reg_curpm(Re2) \
3578 if (reginfo->info_aux_eval) { \
3579 (void)ReREFCNT_inc(Re2); \
3580 ReREFCNT_dec(PM_GETRE(PL_reg_curpm)); \
3581 PM_SETRE((PL_reg_curpm), (Re2)); \
3586 - regtry - try match at specific point
3588 STATIC bool /* 0 failure, 1 success */
3589 S_regtry(pTHX_ regmatch_info *reginfo, char **startposp)
3592 REGEXP *const rx = reginfo->prog;
3593 regexp *const prog = ReANY(rx);
3596 U32 depth = 0; /* used by REGCP_SET */
3598 RXi_GET_DECL(prog,progi);
3599 GET_RE_DEBUG_FLAGS_DECL;
3601 PERL_ARGS_ASSERT_REGTRY;
3603 reginfo->cutpoint=NULL;
3605 prog->offs[0].start = *startposp - reginfo->strbeg;
3606 prog->lastparen = 0;
3607 prog->lastcloseparen = 0;
3609 /* XXXX What this code is doing here?!!! There should be no need
3610 to do this again and again, prog->lastparen should take care of
3613 /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
3614 * Actually, the code in regcppop() (which Ilya may be meaning by
3615 * prog->lastparen), is not needed at all by the test suite
3616 * (op/regexp, op/pat, op/split), but that code is needed otherwise
3617 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
3618 * Meanwhile, this code *is* needed for the
3619 * above-mentioned test suite tests to succeed. The common theme
3620 * on those tests seems to be returning null fields from matches.
3621 * --jhi updated by dapm */
3623 /* After encountering a variant of the issue mentioned above I think
3624 * the point Ilya was making is that if we properly unwind whenever
3625 * we set lastparen to a smaller value then we should not need to do
3626 * this every time, only when needed. So if we have tests that fail if
3627 * we remove this, then it suggests somewhere else we are improperly
3628 * unwinding the lastparen/paren buffers. See UNWIND_PARENS() and
3629 * places it is called, and related regcp() routines. - Yves */
3631 if (prog->nparens) {
3632 regexp_paren_pair *pp = prog->offs;
3634 for (i = prog->nparens; i > (I32)prog->lastparen; i--) {
3642 result = regmatch(reginfo, *startposp, progi->program + 1);
3644 prog->offs[0].end = result;
3647 if (reginfo->cutpoint)
3648 *startposp= reginfo->cutpoint;
3649 REGCP_UNWIND(lastcp);
3654 #define sayYES goto yes
3655 #define sayNO goto no
3656 #define sayNO_SILENT goto no_silent
3658 /* we dont use STMT_START/END here because it leads to
3659 "unreachable code" warnings, which are bogus, but distracting. */
3660 #define CACHEsayNO \
3661 if (ST.cache_mask) \
3662 reginfo->info_aux->poscache[ST.cache_offset] |= ST.cache_mask; \
3665 /* this is used to determine how far from the left messages like
3666 'failed...' are printed in regexec.c. It should be set such that
3667 messages are inline with the regop output that created them.
3669 #define REPORT_CODE_OFF 29
3670 #define INDENT_CHARS(depth) ((int)(depth) % 20)
3673 Perl_re_exec_indentf(pTHX_ const char *fmt, U32 depth, ...)
3677 PerlIO *f= Perl_debug_log;
3678 PERL_ARGS_ASSERT_RE_EXEC_INDENTF;
3679 va_start(ap, depth);
3680 PerlIO_printf(f, "%*s|%4" UVuf "| %*s", REPORT_CODE_OFF, "", (UV)depth, INDENT_CHARS(depth), "" );
3681 result = PerlIO_vprintf(f, fmt, ap);
3685 #endif /* DEBUGGING */
3688 #define CHRTEST_UNINIT -1001 /* c1/c2 haven't been calculated yet */
3689 #define CHRTEST_VOID -1000 /* the c1/c2 "next char" test should be skipped */
3690 #define CHRTEST_NOT_A_CP_1 -999
3691 #define CHRTEST_NOT_A_CP_2 -998
3693 /* grab a new slab and return the first slot in it */
3695 STATIC regmatch_state *
3698 regmatch_slab *s = PL_regmatch_slab->next;
3700 Newx(s, 1, regmatch_slab);
3701 s->prev = PL_regmatch_slab;
3703 PL_regmatch_slab->next = s;
3705 PL_regmatch_slab = s;
3706 return SLAB_FIRST(s);
3710 /* push a new state then goto it */
3712 #define PUSH_STATE_GOTO(state, node, input) \
3713 pushinput = input; \
3715 st->resume_state = state; \
3718 /* push a new state with success backtracking, then goto it */
3720 #define PUSH_YES_STATE_GOTO(state, node, input) \
3721 pushinput = input; \
3723 st->resume_state = state; \
3724 goto push_yes_state;
3731 regmatch() - main matching routine
3733 This is basically one big switch statement in a loop. We execute an op,
3734 set 'next' to point the next op, and continue. If we come to a point which
3735 we may need to backtrack to on failure such as (A|B|C), we push a
3736 backtrack state onto the backtrack stack. On failure, we pop the top
3737 state, and re-enter the loop at the state indicated. If there are no more
3738 states to pop, we return failure.
3740 Sometimes we also need to backtrack on success; for example /A+/, where
3741 after successfully matching one A, we need to go back and try to
3742 match another one; similarly for lookahead assertions: if the assertion
3743 completes successfully, we backtrack to the state just before the assertion
3744 and then carry on. In these cases, the pushed state is marked as
3745 'backtrack on success too'. This marking is in fact done by a chain of
3746 pointers, each pointing to the previous 'yes' state. On success, we pop to
3747 the nearest yes state, discarding any intermediate failure-only states.
3748 Sometimes a yes state is pushed just to force some cleanup code to be
3749 called at the end of a successful match or submatch; e.g. (??{$re}) uses
3750 it to free the inner regex.
3752 Note that failure backtracking rewinds the cursor position, while
3753 success backtracking leaves it alone.
3755 A pattern is complete when the END op is executed, while a subpattern
3756 such as (?=foo) is complete when the SUCCESS op is executed. Both of these
3757 ops trigger the "pop to last yes state if any, otherwise return true"
3760 A common convention in this function is to use A and B to refer to the two
3761 subpatterns (or to the first nodes thereof) in patterns like /A*B/: so A is
3762 the subpattern to be matched possibly multiple times, while B is the entire
3763 rest of the pattern. Variable and state names reflect this convention.
3765 The states in the main switch are the union of ops and failure/success of
3766 substates associated with with that op. For example, IFMATCH is the op
3767 that does lookahead assertions /(?=A)B/ and so the IFMATCH state means
3768 'execute IFMATCH'; while IFMATCH_A is a state saying that we have just
3769 successfully matched A and IFMATCH_A_fail is a state saying that we have
3770 just failed to match A. Resume states always come in pairs. The backtrack
3771 state we push is marked as 'IFMATCH_A', but when that is popped, we resume
3772 at IFMATCH_A or IFMATCH_A_fail, depending on whether we are backtracking
3773 on success or failure.
3775 The struct that holds a backtracking state is actually a big union, with
3776 one variant for each major type of op. The variable st points to the
3777 top-most backtrack struct. To make the code clearer, within each
3778 block of code we #define ST to alias the relevant union.
3780 Here's a concrete example of a (vastly oversimplified) IFMATCH
3786 #define ST st->u.ifmatch
3788 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3789 ST.foo = ...; // some state we wish to save
3791 // push a yes backtrack state with a resume value of
3792 // IFMATCH_A/IFMATCH_A_fail, then continue execution at the
3794 PUSH_YES_STATE_GOTO(IFMATCH_A, A, newinput);
3797 case IFMATCH_A: // we have successfully executed A; now continue with B
3799 bar = ST.foo; // do something with the preserved value
3802 case IFMATCH_A_fail: // A failed, so the assertion failed
3803 ...; // do some housekeeping, then ...
3804 sayNO; // propagate the failure
3811 For any old-timers reading this who are familiar with the old recursive
3812 approach, the code above is equivalent to:
3814 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3823 ...; // do some housekeeping, then ...
3824 sayNO; // propagate the failure
3827 The topmost backtrack state, pointed to by st, is usually free. If you
3828 want to claim it, populate any ST.foo fields in it with values you wish to
3829 save, then do one of
3831 PUSH_STATE_GOTO(resume_state, node, newinput);
3832 PUSH_YES_STATE_GOTO(resume_state, node, newinput);
3834 which sets that backtrack state's resume value to 'resume_state', pushes a
3835 new free entry to the top of the backtrack stack, then goes to 'node'.
3836 On backtracking, the free slot is popped, and the saved state becomes the
3837 new free state. An ST.foo field in this new top state can be temporarily
3838 accessed to retrieve values, but once the main loop is re-entered, it
3839 becomes available for reuse.
3841 Note that the depth of the backtrack stack constantly increases during the
3842 left-to-right execution of the pattern, rather than going up and down with
3843 the pattern nesting. For example the stack is at its maximum at Z at the
3844 end of the pattern, rather than at X in the following:
3846 /(((X)+)+)+....(Y)+....Z/
3848 The only exceptions to this are lookahead/behind assertions and the cut,
3849 (?>A), which pop all the backtrack states associated with A before
3852 Backtrack state structs are allocated in slabs of about 4K in size.
3853 PL_regmatch_state and st always point to the currently active state,
3854 and PL_regmatch_slab points to the slab currently containing
3855 PL_regmatch_state. The first time regmatch() is called, the first slab is
3856 allocated, and is never freed until interpreter destruction. When the slab
3857 is full, a new one is allocated and chained to the end. At exit from
3858 regmatch(), slabs allocated since entry are freed.
3863 #define DEBUG_STATE_pp(pp) \
3865 DUMP_EXEC_POS(locinput, scan, utf8_target,depth); \
3866 Perl_re_printf( aTHX_ \
3867 "%*s" pp " %s%s%s%s%s\n", \
3868 INDENT_CHARS(depth), "", \
3869 PL_reg_name[st->resume_state], \
3870 ((st==yes_state||st==mark_state) ? "[" : ""), \
3871 ((st==yes_state) ? "Y" : ""), \
3872 ((st==mark_state) ? "M" : ""), \
3873 ((st==yes_state||st==mark_state) ? "]" : "") \
3878 #define REG_NODE_NUM(x) ((x) ? (int)((x)-prog) : -1)
3883 S_debug_start_match(pTHX_ const REGEXP *prog, const bool utf8_target,
3884 const char *start, const char *end, const char *blurb)
3886 const bool utf8_pat = RX_UTF8(prog) ? 1 : 0;
3888 PERL_ARGS_ASSERT_DEBUG_START_MATCH;
3893 RE_PV_QUOTED_DECL(s0, utf8_pat, PERL_DEBUG_PAD_ZERO(0),
3894 RX_PRECOMP_const(prog), RX_PRELEN(prog), 60);
3896 RE_PV_QUOTED_DECL(s1, utf8_target, PERL_DEBUG_PAD_ZERO(1),
3897 start, end - start, 60);
3899 Perl_re_printf( aTHX_
3900 "%s%s REx%s %s against %s\n",
3901 PL_colors[4], blurb, PL_colors[5], s0, s1);
3903 if (utf8_target||utf8_pat)
3904 Perl_re_printf( aTHX_ "UTF-8 %s%s%s...\n",
3905 utf8_pat ? "pattern" : "",
3906 utf8_pat && utf8_target ? " and " : "",
3907 utf8_target ? "string" : ""
3913 S_dump_exec_pos(pTHX_ const char *locinput,
3914 const regnode *scan,
3915 const char *loc_regeol,
3916 const char *loc_bostr,
3917 const char *loc_reg_starttry,
3918 const bool utf8_target,
3922 const int docolor = *PL_colors[0] || *PL_colors[2] || *PL_colors[4];
3923 const int taill = (docolor ? 10 : 7); /* 3 chars for "> <" */
3924 int l = (loc_regeol - locinput) > taill ? taill : (loc_regeol - locinput);
3925 /* The part of the string before starttry has one color
3926 (pref0_len chars), between starttry and current
3927 position another one (pref_len - pref0_len chars),
3928 after the current position the third one.
3929 We assume that pref0_len <= pref_len, otherwise we
3930 decrease pref0_len. */
3931 int pref_len = (locinput - loc_bostr) > (5 + taill) - l
3932 ? (5 + taill) - l : locinput - loc_bostr;
3935 PERL_ARGS_ASSERT_DUMP_EXEC_POS;
3937 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput - pref_len)))
3939 pref0_len = pref_len - (locinput - loc_reg_starttry);
3940 if (l + pref_len < (5 + taill) && l < loc_regeol - locinput)
3941 l = ( loc_regeol - locinput > (5 + taill) - pref_len
3942 ? (5 + taill) - pref_len : loc_regeol - locinput);
3943 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput + l)))
3947 if (pref0_len > pref_len)
3948 pref0_len = pref_len;
3950 const int is_uni = utf8_target ? 1 : 0;
3952 RE_PV_COLOR_DECL(s0,len0,is_uni,PERL_DEBUG_PAD(0),
3953 (locinput - pref_len),pref0_len, 60, 4, 5);
3955 RE_PV_COLOR_DECL(s1,len1,is_uni,PERL_DEBUG_PAD(1),
3956 (locinput - pref_len + pref0_len),
3957 pref_len - pref0_len, 60, 2, 3);
3959 RE_PV_COLOR_DECL(s2,len2,is_uni,PERL_DEBUG_PAD(2),
3960 locinput, loc_regeol - locinput, 10, 0, 1);
3962 const STRLEN tlen=len0+len1+len2;
3963 Perl_re_printf( aTHX_
3964 "%4" IVdf " <%.*s%.*s%s%.*s>%*s|%4u| ",
3965 (IV)(locinput - loc_bostr),
3968 (docolor ? "" : "> <"),
3970 (int)(tlen > 19 ? 0 : 19 - tlen),
3978 /* reg_check_named_buff_matched()
3979 * Checks to see if a named buffer has matched. The data array of
3980 * buffer numbers corresponding to the buffer is expected to reside
3981 * in the regexp->data->data array in the slot stored in the ARG() of
3982 * node involved. Note that this routine doesn't actually care about the
3983 * name, that information is not preserved from compilation to execution.
3984 * Returns the index of the leftmost defined buffer with the given name
3985 * or 0 if non of the buffers matched.
3988 S_reg_check_named_buff_matched(const regexp *rex, const regnode *scan)
3991 RXi_GET_DECL(rex,rexi);
3992 SV *sv_dat= MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
3993 I32 *nums=(I32*)SvPVX(sv_dat);
3995 PERL_ARGS_ASSERT_REG_CHECK_NAMED_BUFF_MATCHED;
3997 for ( n=0; n<SvIVX(sv_dat); n++ ) {
3998 if ((I32)rex->lastparen >= nums[n] &&
3999 rex->offs[nums[n]].end != -1)
4009 S_setup_EXACTISH_ST_c1_c2(pTHX_ const regnode * const text_node, int *c1p,
4010 U8* c1_utf8, int *c2p, U8* c2_utf8, regmatch_info *reginfo)
4012 /* This function determines if there are one or two characters that match
4013 * the first character of the passed-in EXACTish node <text_node>, and if
4014 * so, returns them in the passed-in pointers.
4016 * If it determines that no possible character in the target string can
4017 * match, it returns FALSE; otherwise TRUE. (The FALSE situation occurs if
4018 * the first character in <text_node> requires UTF-8 to represent, and the
4019 * target string isn't in UTF-8.)
4021 * If there are more than two characters that could match the beginning of
4022 * <text_node>, or if more context is required to determine a match or not,
4023 * it sets both *<c1p> and *<c2p> to CHRTEST_VOID.
4025 * The motiviation behind this function is to allow the caller to set up
4026 * tight loops for matching. If <text_node> is of type EXACT, there is
4027 * only one possible character that can match its first character, and so
4028 * the situation is quite simple. But things get much more complicated if
4029 * folding is involved. It may be that the first character of an EXACTFish
4030 * node doesn't participate in any possible fold, e.g., punctuation, so it
4031 * can be matched only by itself. The vast majority of characters that are
4032 * in folds match just two things, their lower and upper-case equivalents.
4033 * But not all are like that; some have multiple possible matches, or match
4034 * sequences of more than one character. This function sorts all that out.
4036 * Consider the patterns A*B or A*?B where A and B are arbitrary. In a
4037 * loop of trying to match A*, we know we can't exit where the thing
4038 * following it isn't a B. And something can't be a B unless it is the
4039 * beginning of B. By putting a quick test for that beginning in a tight
4040 * loop, we can rule out things that can't possibly be B without having to
4041 * break out of the loop, thus avoiding work. Similarly, if A is a single
4042 * character, we can make a tight loop matching A*, using the outputs of
4045 * If the target string to match isn't in UTF-8, and there aren't
4046 * complications which require CHRTEST_VOID, *<c1p> and *<c2p> are set to
4047 * the one or two possible octets (which are characters in this situation)
4048 * that can match. In all cases, if there is only one character that can
4049 * match, *<c1p> and *<c2p> will be identical.
4051 * If the target string is in UTF-8, the buffers pointed to by <c1_utf8>
4052 * and <c2_utf8> will contain the one or two UTF-8 sequences of bytes that
4053 * can match the beginning of <text_node>. They should be declared with at
4054 * least length UTF8_MAXBYTES+1. (If the target string isn't in UTF-8, it is
4055 * undefined what these contain.) If one or both of the buffers are
4056 * invariant under UTF-8, *<c1p>, and *<c2p> will also be set to the
4057 * corresponding invariant. If variant, the corresponding *<c1p> and/or
4058 * *<c2p> will be set to a negative number(s) that shouldn't match any code
4059 * point (unless inappropriately coerced to unsigned). *<c1p> will equal
4060 * *<c2p> if and only if <c1_utf8> and <c2_utf8> are the same. */
4062 const bool utf8_target = reginfo->is_utf8_target;
4064 UV c1 = (UV)CHRTEST_NOT_A_CP_1;
4065 UV c2 = (UV)CHRTEST_NOT_A_CP_2;
4066 bool use_chrtest_void = FALSE;
4067 const bool is_utf8_pat = reginfo->is_utf8_pat;
4069 /* Used when we have both utf8 input and utf8 output, to avoid converting
4070 * to/from code points */
4071 bool utf8_has_been_setup = FALSE;
4075 U8 *pat = (U8*)STRING(text_node);
4076 U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' };
4078 if (OP(text_node) == EXACT || OP(text_node) == EXACTL) {
4080 /* In an exact node, only one thing can be matched, that first
4081 * character. If both the pat and the target are UTF-8, we can just
4082 * copy the input to the output, avoiding finding the code point of
4087 else if (utf8_target) {
4088 Copy(pat, c1_utf8, UTF8SKIP(pat), U8);
4089 Copy(pat, c2_utf8, UTF8SKIP(pat), U8);
4090 utf8_has_been_setup = TRUE;
4093 c2 = c1 = valid_utf8_to_uvchr(pat, NULL);
4096 else { /* an EXACTFish node */
4097 U8 *pat_end = pat + STR_LEN(text_node);
4099 /* An EXACTFL node has at least some characters unfolded, because what
4100 * they match is not known until now. So, now is the time to fold
4101 * the first few of them, as many as are needed to determine 'c1' and
4102 * 'c2' later in the routine. If the pattern isn't UTF-8, we only need
4103 * to fold if in a UTF-8 locale, and then only the Sharp S; everything
4104 * else is 1-1 and isn't assumed to be folded. In a UTF-8 pattern, we
4105 * need to fold as many characters as a single character can fold to,
4106 * so that later we can check if the first ones are such a multi-char
4107 * fold. But, in such a pattern only locale-problematic characters
4108 * aren't folded, so we can skip this completely if the first character
4109 * in the node isn't one of the tricky ones */
4110 if (OP(text_node) == EXACTFL) {
4112 if (! is_utf8_pat) {
4113 if (IN_UTF8_CTYPE_LOCALE && *pat == LATIN_SMALL_LETTER_SHARP_S)
4115 folded[0] = folded[1] = 's';
4117 pat_end = folded + 2;
4120 else if (is_PROBLEMATIC_LOCALE_FOLDEDS_START_utf8(pat)) {
4125 for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < pat_end; i++) {
4127 *(d++) = (U8) toFOLD_LC(*s);
4132 _to_utf8_fold_flags(s,
4135 FOLD_FLAGS_FULL | FOLD_FLAGS_LOCALE);
4146 if ((is_utf8_pat && is_MULTI_CHAR_FOLD_utf8_safe(pat, pat_end))
4147 || (!is_utf8_pat && is_MULTI_CHAR_FOLD_latin1_safe(pat, pat_end)))
4149 /* Multi-character folds require more context to sort out. Also
4150 * PL_utf8_foldclosures used below doesn't handle them, so have to
4151 * be handled outside this routine */
4152 use_chrtest_void = TRUE;
4154 else { /* an EXACTFish node which doesn't begin with a multi-char fold */
4155 c1 = is_utf8_pat ? valid_utf8_to_uvchr(pat, NULL) : *pat;
4157 /* Load the folds hash, if not already done */
4159 if (! PL_utf8_foldclosures) {
4160 _load_PL_utf8_foldclosures();
4163 /* The fold closures data structure is a hash with the keys
4164 * being the UTF-8 of every character that is folded to, like
4165 * 'k', and the values each an array of all code points that
4166 * fold to its key. e.g. [ 'k', 'K', KELVIN_SIGN ].
4167 * Multi-character folds are not included */
4168 if ((! (listp = hv_fetch(PL_utf8_foldclosures,
4173 /* Not found in the hash, therefore there are no folds
4174 * containing it, so there is only a single character that
4178 else { /* Does participate in folds */
4179 AV* list = (AV*) *listp;
4180 if (av_tindex_nomg(list) != 1) {
4182 /* If there aren't exactly two folds to this, it is
4183 * outside the scope of this function */
4184 use_chrtest_void = TRUE;
4186 else { /* There are two. Get them */
4187 SV** c_p = av_fetch(list, 0, FALSE);
4189 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
4193 c_p = av_fetch(list, 1, FALSE);
4195 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
4199 /* Folds that cross the 255/256 boundary are forbidden
4200 * if EXACTFL (and isnt a UTF8 locale), or EXACTFA and
4201 * one is ASCIII. Since the pattern character is above
4202 * 255, and its only other match is below 256, the only
4203 * legal match will be to itself. We have thrown away
4204 * the original, so have to compute which is the one
4206 if ((c1 < 256) != (c2 < 256)) {
4207 if ((OP(text_node) == EXACTFL
4208 && ! IN_UTF8_CTYPE_LOCALE)
4209 || ((OP(text_node) == EXACTFA
4210 || OP(text_node) == EXACTFA_NO_TRIE)
4211 && (isASCII(c1) || isASCII(c2))))
4224 else /* Here, c1 is <= 255 */
4226 && HAS_NONLATIN1_FOLD_CLOSURE(c1)
4227 && ( ! (OP(text_node) == EXACTFL && ! IN_UTF8_CTYPE_LOCALE))
4228 && ((OP(text_node) != EXACTFA
4229 && OP(text_node) != EXACTFA_NO_TRIE)
4232 /* Here, there could be something above Latin1 in the target
4233 * which folds to this character in the pattern. All such
4234 * cases except LATIN SMALL LETTER Y WITH DIAERESIS have more
4235 * than two characters involved in their folds, so are outside
4236 * the scope of this function */
4237 if (UNLIKELY(c1 == LATIN_SMALL_LETTER_Y_WITH_DIAERESIS)) {
4238 c2 = LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS;
4241 use_chrtest_void = TRUE;
4244 else { /* Here nothing above Latin1 can fold to the pattern
4246 switch (OP(text_node)) {
4248 case EXACTFL: /* /l rules */
4249 c2 = PL_fold_locale[c1];
4252 case EXACTF: /* This node only generated for non-utf8
4254 assert(! is_utf8_pat);
4255 if (! utf8_target) { /* /d rules */
4260 /* /u rules for all these. This happens to work for
4261 * EXACTFA as nothing in Latin1 folds to ASCII */
4262 case EXACTFA_NO_TRIE: /* This node only generated for
4263 non-utf8 patterns */
4264 assert(! is_utf8_pat);
4269 c2 = PL_fold_latin1[c1];
4273 Perl_croak(aTHX_ "panic: Unexpected op %u", OP(text_node));
4274 NOT_REACHED; /* NOTREACHED */
4280 /* Here have figured things out. Set up the returns */
4281 if (use_chrtest_void) {
4282 *c2p = *c1p = CHRTEST_VOID;
4284 else if (utf8_target) {
4285 if (! utf8_has_been_setup) { /* Don't have the utf8; must get it */
4286 uvchr_to_utf8(c1_utf8, c1);
4287 uvchr_to_utf8(c2_utf8, c2);
4290 /* Invariants are stored in both the utf8 and byte outputs; Use
4291 * negative numbers otherwise for the byte ones. Make sure that the
4292 * byte ones are the same iff the utf8 ones are the same */
4293 *c1p = (UTF8_IS_INVARIANT(*c1_utf8)) ? *c1_utf8 : CHRTEST_NOT_A_CP_1;
4294 *c2p = (UTF8_IS_INVARIANT(*c2_utf8))
4297 ? CHRTEST_NOT_A_CP_1
4298 : CHRTEST_NOT_A_CP_2;
4300 else if (c1 > 255) {
4301 if (c2 > 255) { /* both possibilities are above what a non-utf8 string
4306 *c1p = *c2p = c2; /* c2 is the only representable value */
4308 else { /* c1 is representable; see about c2 */
4310 *c2p = (c2 < 256) ? c2 : c1;
4317 S_isGCB(pTHX_ const GCB_enum before, const GCB_enum after, const U8 * const strbeg, const U8 * const curpos, const bool utf8_target)
4319 /* returns a boolean indicating if there is a Grapheme Cluster Boundary
4320 * between the inputs. See http://www.unicode.org/reports/tr29/. */
4322 PERL_ARGS_ASSERT_ISGCB;
4324 switch (GCB_table[before][after]) {
4331 case GCB_RI_then_RI:
4334 U8 * temp_pos = (U8 *) curpos;
4336 /* Do not break within emoji flag sequences. That is, do not
4337 * break between regional indicator (RI) symbols if there is an
4338 * odd number of RI characters before the break point.
4339 * GB12 ^ (RI RI)* RI × RI
4340 * GB13 [^RI] (RI RI)* RI × RI */
4342 while (backup_one_GCB(strbeg,
4344 utf8_target) == GCB_Regional_Indicator)
4349 return RI_count % 2 != 1;
4352 case GCB_EX_then_EM:
4354 /* GB10 ( E_Base | E_Base_GAZ ) Extend* × E_Modifier */
4356 U8 * temp_pos = (U8 *) curpos;
4360 prev = backup_one_GCB(strbeg, &temp_pos, utf8_target);
4362 while (prev == GCB_Extend);
4364 return prev != GCB_E_Base && prev != GCB_E_Base_GAZ;
4372 Perl_re_printf( aTHX_ "Unhandled GCB pair: GCB_table[%d, %d] = %d\n",
4373 before, after, GCB_table[before][after]);
4380 S_backup_one_GCB(pTHX_ const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
4384 PERL_ARGS_ASSERT_BACKUP_ONE_GCB;
4386 if (*curpos < strbeg) {
4391 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
4392 U8 * prev_prev_char_pos;
4394 if (! prev_char_pos) {
4398 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos, -1, strbeg))) {
4399 gcb = getGCB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
4400 *curpos = prev_char_pos;
4401 prev_char_pos = prev_prev_char_pos;
4404 *curpos = (U8 *) strbeg;
4409 if (*curpos - 2 < strbeg) {
4410 *curpos = (U8 *) strbeg;
4414 gcb = getGCB_VAL_CP(*(*curpos - 1));
4420 /* Combining marks attach to most classes that precede them, but this defines
4421 * the exceptions (from TR14) */
4422 #define LB_CM_ATTACHES_TO(prev) ( ! ( prev == LB_EDGE \
4423 || prev == LB_Mandatory_Break \
4424 || prev == LB_Carriage_Return \
4425 || prev == LB_Line_Feed \
4426 || prev == LB_Next_Line \
4427 || prev == LB_Space \
4428 || prev == LB_ZWSpace))
4431 S_isLB(pTHX_ LB_enum before,
4433 const U8 * const strbeg,
4434 const U8 * const curpos,
4435 const U8 * const strend,
4436 const bool utf8_target)
4438 U8 * temp_pos = (U8 *) curpos;
4439 LB_enum prev = before;
4441 /* Is the boundary between 'before' and 'after' line-breakable?
4442 * Most of this is just a table lookup of a generated table from Unicode
4443 * rules. But some rules require context to decide, and so have to be
4444 * implemented in code */
4446 PERL_ARGS_ASSERT_ISLB;
4448 /* Rule numbers in the comments below are as of Unicode 9.0 */
4452 switch (LB_table[before][after]) {
4457 case LB_NOBREAK_EVEN_WITH_SP_BETWEEN:
4460 case LB_SP_foo + LB_BREAKABLE:
4461 case LB_SP_foo + LB_NOBREAK:
4462 case LB_SP_foo + LB_NOBREAK_EVEN_WITH_SP_BETWEEN:
4464 /* When we have something following a SP, we have to look at the
4465 * context in order to know what to do.
4467 * SP SP should not reach here because LB7: Do not break before
4468 * spaces. (For two spaces in a row there is nothing that
4469 * overrides that) */
4470 assert(after != LB_Space);
4472 /* Here we have a space followed by a non-space. Mostly this is a
4473 * case of LB18: "Break after spaces". But there are complications
4474 * as the handling of spaces is somewhat tricky. They are in a
4475 * number of rules, which have to be applied in priority order, but
4476 * something earlier in the string can cause a rule to be skipped
4477 * and a lower priority rule invoked. A prime example is LB7 which
4478 * says don't break before a space. But rule LB8 (lower priority)
4479 * says that the first break opportunity after a ZW is after any
4480 * span of spaces immediately after it. If a ZW comes before a SP
4481 * in the input, rule LB8 applies, and not LB7. Other such rules
4482 * involve combining marks which are rules 9 and 10, but they may
4483 * override higher priority rules if they come earlier in the
4484 * string. Since we're doing random access into the middle of the
4485 * string, we have to look for rules that should get applied based
4486 * on both string position and priority. Combining marks do not
4487 * attach to either ZW nor SP, so we don't have to consider them
4490 * To check for LB8, we have to find the first non-space character
4491 * before this span of spaces */
4493 prev = backup_one_LB(strbeg, &temp_pos, utf8_target);
4495 while (prev == LB_Space);
4497 /* LB8 Break before any character following a zero-width space,
4498 * even if one or more spaces intervene.
4500 * So if we have a ZW just before this span, and to get here this
4501 * is the final space in the span. */
4502 if (prev == LB_ZWSpace) {
4506 /* Here, not ZW SP+. There are several rules that have higher
4507 * priority than LB18 and can be resolved now, as they don't depend
4508 * on anything earlier in the string (except ZW, which we have
4509 * already handled). One of these rules is LB11 Do not break
4510 * before Word joiner, but we have specially encoded that in the
4511 * lookup table so it is caught by the single test below which
4512 * catches the other ones. */
4513 if (LB_table[LB_Space][after] - LB_SP_foo
4514 == LB_NOBREAK_EVEN_WITH_SP_BETWEEN)
4519 /* If we get here, we have to XXX consider combining marks. */
4520 if (prev == LB_Combining_Mark) {
4522 /* What happens with these depends on the character they
4525 prev = backup_one_LB(strbeg, &temp_pos, utf8_target);
4527 while (prev == LB_Combining_Mark);
4529 /* Most times these attach to and inherit the characteristics
4530 * of that character, but not always, and when not, they are to
4531 * be treated as AL by rule LB10. */
4532 if (! LB_CM_ATTACHES_TO(prev)) {
4533 prev = LB_Alphabetic;
4537 /* Here, we have the character preceding the span of spaces all set
4538 * up. We follow LB18: "Break after spaces" unless the table shows
4539 * that is overriden */
4540 return LB_table[prev][after] != LB_NOBREAK_EVEN_WITH_SP_BETWEEN;
4544 /* We don't know how to treat the CM except by looking at the first
4545 * non-CM character preceding it. ZWJ is treated as CM */
4547 prev = backup_one_LB(strbeg, &temp_pos, utf8_target);
4549 while (prev == LB_Combining_Mark || prev == LB_ZWJ);
4551 /* Here, 'prev' is that first earlier non-CM character. If the CM
4552 * attatches to it, then it inherits the behavior of 'prev'. If it
4553 * doesn't attach, it is to be treated as an AL */
4554 if (! LB_CM_ATTACHES_TO(prev)) {
4555 prev = LB_Alphabetic;
4560 case LB_HY_or_BA_then_foo + LB_BREAKABLE:
4561 case LB_HY_or_BA_then_foo + LB_NOBREAK:
4563 /* LB21a Don't break after Hebrew + Hyphen.
4564 * HL (HY | BA) × */
4566 if (backup_one_LB(strbeg, &temp_pos, utf8_target)
4567 == LB_Hebrew_Letter)
4572 return LB_table[prev][after] - LB_HY_or_BA_then_foo == LB_BREAKABLE;
4574 case LB_PR_or_PO_then_OP_or_HY + LB_BREAKABLE:
4575 case LB_PR_or_PO_then_OP_or_HY + LB_NOBREAK:
4577 /* LB25a (PR | PO) × ( OP | HY )? NU */
4578 if (advance_one_LB(&temp_pos, strend, utf8_target) == LB_Numeric) {
4582 return LB_table[prev][after] - LB_PR_or_PO_then_OP_or_HY
4585 case LB_SY_or_IS_then_various + LB_BREAKABLE:
4586 case LB_SY_or_IS_then_various + LB_NOBREAK:
4588 /* LB25d NU (SY | IS)* × (NU | SY | IS | CL | CP ) */
4590 LB_enum temp = prev;
4592 temp = backup_one_LB(strbeg, &temp_pos, utf8_target);
4594 while (temp == LB_Break_Symbols || temp == LB_Infix_Numeric);
4595 if (temp == LB_Numeric) {
4599 return LB_table[prev][after] - LB_SY_or_IS_then_various
4603 case LB_various_then_PO_or_PR + LB_BREAKABLE:
4604 case LB_various_then_PO_or_PR + LB_NOBREAK:
4606 /* LB25e NU (SY | IS)* (CL | CP)? × (PO | PR) */
4608 LB_enum temp = prev;
4609 if (temp == LB_Close_Punctuation || temp == LB_Close_Parenthesis)
4611 temp = backup_one_LB(strbeg, &temp_pos, utf8_target);
4613 while (temp == LB_Break_Symbols || temp == LB_Infix_Numeric) {
4614 temp = backup_one_LB(strbeg, &temp_pos, utf8_target);
4616 if (temp == LB_Numeric) {
4619 return LB_various_then_PO_or_PR;
4622 case LB_RI_then_RI + LB_NOBREAK:
4623 case LB_RI_then_RI + LB_BREAKABLE:
4627 /* LB30a Break between two regional indicator symbols if and
4628 * only if there are an even number of regional indicators
4629 * preceding the position of the break.
4631 * sot (RI RI)* RI × RI
4632 * [^RI] (RI RI)* RI × RI */
4634 while (backup_one_LB(strbeg,
4636 utf8_target) == LB_Regional_Indicator)
4641 return RI_count % 2 == 0;
4649 Perl_re_printf( aTHX_ "Unhandled LB pair: LB_table[%d, %d] = %d\n",
4650 before, after, LB_table[before][after]);
4657 S_advance_one_LB(pTHX_ U8 ** curpos, const U8 * const strend, const bool utf8_target)
4661 PERL_ARGS_ASSERT_ADVANCE_ONE_LB;
4663 if (*curpos >= strend) {
4668 *curpos += UTF8SKIP(*curpos);
4669 if (*curpos >= strend) {
4672 lb = getLB_VAL_UTF8(*curpos, strend);
4676 if (*curpos >= strend) {
4679 lb = getLB_VAL_CP(**curpos);
4686 S_backup_one_LB(pTHX_ const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
4690 PERL_ARGS_ASSERT_BACKUP_ONE_LB;
4692 if (*curpos < strbeg) {
4697 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
4698 U8 * prev_prev_char_pos;
4700 if (! prev_char_pos) {
4704 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos, -1, strbeg))) {
4705 lb = getLB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
4706 *curpos = prev_char_pos;
4707 prev_char_pos = prev_prev_char_pos;
4710 *curpos = (U8 *) strbeg;
4715 if (*curpos - 2 < strbeg) {
4716 *curpos = (U8 *) strbeg;
4720 lb = getLB_VAL_CP(*(*curpos - 1));
4727 S_isSB(pTHX_ SB_enum before,
4729 const U8 * const strbeg,
4730 const U8 * const curpos,
4731 const U8 * const strend,
4732 const bool utf8_target)
4734 /* returns a boolean indicating if there is a Sentence Boundary Break
4735 * between the inputs. See http://www.unicode.org/reports/tr29/ */
4737 U8 * lpos = (U8 *) curpos;
4738 bool has_para_sep = FALSE;
4739 bool has_sp = FALSE;
4741 PERL_ARGS_ASSERT_ISSB;
4743 /* Break at the start and end of text.
4746 But unstated in Unicode is don't break if the text is empty */
4747 if (before == SB_EDGE || after == SB_EDGE) {
4748 return before != after;
4751 /* SB 3: Do not break within CRLF. */
4752 if (before == SB_CR && after == SB_LF) {
4756 /* Break after paragraph separators. CR and LF are considered
4757 * so because Unicode views text as like word processing text where there
4758 * are no newlines except between paragraphs, and the word processor takes
4759 * care of wrapping without there being hard line-breaks in the text *./
4760 SB4. Sep | CR | LF ÷ */
4761 if (before == SB_Sep || before == SB_CR || before == SB_LF) {
4765 /* Ignore Format and Extend characters, except after sot, Sep, CR, or LF.
4766 * (See Section 6.2, Replacing Ignore Rules.)
4767 SB5. X (Extend | Format)* → X */
4768 if (after == SB_Extend || after == SB_Format) {
4770 /* Implied is that the these characters attach to everything
4771 * immediately prior to them except for those separator-type
4772 * characters. And the rules earlier have already handled the case
4773 * when one of those immediately precedes the extend char */
4777 if (before == SB_Extend || before == SB_Format) {
4778 U8 * temp_pos = lpos;
4779 const SB_enum backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4780 if ( backup != SB_EDGE
4789 /* Here, both 'before' and 'backup' are these types; implied is that we
4790 * don't break between them */
4791 if (backup == SB_Extend || backup == SB_Format) {
4796 /* Do not break after ambiguous terminators like period, if they are
4797 * immediately followed by a number or lowercase letter, if they are
4798 * between uppercase letters, if the first following letter (optionally
4799 * after certain punctuation) is lowercase, or if they are followed by
4800 * "continuation" punctuation such as comma, colon, or semicolon. For
4801 * example, a period may be an abbreviation or numeric period, and thus may
4802 * not mark the end of a sentence.
4804 * SB6. ATerm × Numeric */
4805 if (before == SB_ATerm && after == SB_Numeric) {
4809 /* SB7. (Upper | Lower) ATerm × Upper */
4810 if (before == SB_ATerm && after == SB_Upper) {
4811 U8 * temp_pos = lpos;
4812 SB_enum backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4813 if (backup == SB_Upper || backup == SB_Lower) {
4818 /* The remaining rules that aren't the final one, all require an STerm or
4819 * an ATerm after having backed up over some Close* Sp*, and in one case an
4820 * optional Paragraph separator, although one rule doesn't have any Sp's in it.
4821 * So do that backup now, setting flags if either Sp or a paragraph
4822 * separator are found */
4824 if (before == SB_Sep || before == SB_CR || before == SB_LF) {
4825 has_para_sep = TRUE;
4826 before = backup_one_SB(strbeg, &lpos, utf8_target);
4829 if (before == SB_Sp) {
4832 before = backup_one_SB(strbeg, &lpos, utf8_target);
4834 while (before == SB_Sp);
4837 while (before == SB_Close) {
4838 before = backup_one_SB(strbeg, &lpos, utf8_target);
4841 /* The next few rules apply only when the backed-up-to is an ATerm, and in
4842 * most cases an STerm */
4843 if (before == SB_STerm || before == SB_ATerm) {
4845 /* So, here the lhs matches
4846 * (STerm | ATerm) Close* Sp* (Sep | CR | LF)?
4847 * and we have set flags if we found an Sp, or the optional Sep,CR,LF.
4848 * The rules that apply here are:
4850 * SB8 ATerm Close* Sp* × ( ¬(OLetter | Upper | Lower | Sep | CR
4851 | LF | STerm | ATerm) )* Lower
4852 SB8a (STerm | ATerm) Close* Sp* × (SContinue | STerm | ATerm)
4853 SB9 (STerm | ATerm) Close* × (Close | Sp | Sep | CR | LF)
4854 SB10 (STerm | ATerm) Close* Sp* × (Sp | Sep | CR | LF)
4855 SB11 (STerm | ATerm) Close* Sp* (Sep | CR | LF)? ÷
4858 /* And all but SB11 forbid having seen a paragraph separator */
4859 if (! has_para_sep) {
4860 if (before == SB_ATerm) { /* SB8 */
4861 U8 * rpos = (U8 *) curpos;
4862 SB_enum later = after;
4864 while ( later != SB_OLetter
4865 && later != SB_Upper
4866 && later != SB_Lower
4870 && later != SB_STerm
4871 && later != SB_ATerm
4872 && later != SB_EDGE)
4874 later = advance_one_SB(&rpos, strend, utf8_target);
4876 if (later == SB_Lower) {
4881 if ( after == SB_SContinue /* SB8a */
4882 || after == SB_STerm
4883 || after == SB_ATerm)
4888 if (! has_sp) { /* SB9 applies only if there was no Sp* */
4889 if ( after == SB_Close
4899 /* SB10. This and SB9 could probably be combined some way, but khw
4900 * has decided to follow the Unicode rule book precisely for
4901 * simplified maintenance */
4915 /* Otherwise, do not break.
4922 S_advance_one_SB(pTHX_ U8 ** curpos, const U8 * const strend, const bool utf8_target)
4926 PERL_ARGS_ASSERT_ADVANCE_ONE_SB;
4928 if (*curpos >= strend) {
4934 *curpos += UTF8SKIP(*curpos);
4935 if (*curpos >= strend) {
4938 sb = getSB_VAL_UTF8(*curpos, strend);
4939 } while (sb == SB_Extend || sb == SB_Format);
4944 if (*curpos >= strend) {
4947 sb = getSB_VAL_CP(**curpos);
4948 } while (sb == SB_Extend || sb == SB_Format);
4955 S_backup_one_SB(pTHX_ const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
4959 PERL_ARGS_ASSERT_BACKUP_ONE_SB;
4961 if (*curpos < strbeg) {
4966 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
4967 if (! prev_char_pos) {
4971 /* Back up over Extend and Format. curpos is always just to the right
4972 * of the characater whose value we are getting */
4974 U8 * prev_prev_char_pos;
4975 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos, -1,
4978 sb = getSB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
4979 *curpos = prev_char_pos;
4980 prev_char_pos = prev_prev_char_pos;
4983 *curpos = (U8 *) strbeg;
4986 } while (sb == SB_Extend || sb == SB_Format);
4990 if (*curpos - 2 < strbeg) {
4991 *curpos = (U8 *) strbeg;
4995 sb = getSB_VAL_CP(*(*curpos - 1));
4996 } while (sb == SB_Extend || sb == SB_Format);
5003 S_isWB(pTHX_ WB_enum previous,
5006 const U8 * const strbeg,
5007 const U8 * const curpos,
5008 const U8 * const strend,
5009 const bool utf8_target)
5011 /* Return a boolean as to if the boundary between 'before' and 'after' is
5012 * a Unicode word break, using their published algorithm, but tailored for
5013 * Perl by treating spans of white space as one unit. Context may be
5014 * needed to make this determination. If the value for the character
5015 * before 'before' is known, it is passed as 'previous'; otherwise that
5016 * should be set to WB_UNKNOWN. The other input parameters give the
5017 * boundaries and current position in the matching of the string. That
5018 * is, 'curpos' marks the position where the character whose wb value is
5019 * 'after' begins. See http://www.unicode.org/reports/tr29/ */
5021 U8 * before_pos = (U8 *) curpos;
5022 U8 * after_pos = (U8 *) curpos;
5023 WB_enum prev = before;
5026 PERL_ARGS_ASSERT_ISWB;
5028 /* Rule numbers in the comments below are as of Unicode 9.0 */
5032 switch (WB_table[before][after]) {
5039 case WB_hs_then_hs: /* 2 horizontal spaces in a row */
5040 next = advance_one_WB(&after_pos, strend, utf8_target,
5041 FALSE /* Don't skip Extend nor Format */ );
5042 /* A space immediately preceeding an Extend or Format is attached
5043 * to by them, and hence gets separated from previous spaces.
5044 * Otherwise don't break between horizontal white space */
5045 return next == WB_Extend || next == WB_Format;
5047 /* WB4 Ignore Format and Extend characters, except when they appear at
5048 * the beginning of a region of text. This code currently isn't
5049 * general purpose, but it works as the rules are currently and likely
5050 * to be laid out. The reason it works is that when 'they appear at
5051 * the beginning of a region of text', the rule is to break before
5052 * them, just like any other character. Therefore, the default rule
5053 * applies and we don't have to look in more depth. Should this ever
5054 * change, we would have to have 2 'case' statements, like in the rules
5055 * below, and backup a single character (not spacing over the extend
5056 * ones) and then see if that is one of the region-end characters and
5058 case WB_Ex_or_FO_or_ZWJ_then_foo:
5059 prev = backup_one_WB(&previous, strbeg, &before_pos, utf8_target);
5062 case WB_DQ_then_HL + WB_BREAKABLE:
5063 case WB_DQ_then_HL + WB_NOBREAK:
5065 /* WB7c Hebrew_Letter Double_Quote × Hebrew_Letter */
5067 if (backup_one_WB(&previous, strbeg, &before_pos, utf8_target)
5068 == WB_Hebrew_Letter)
5073 return WB_table[before][after] - WB_DQ_then_HL == WB_BREAKABLE;
5075 case WB_HL_then_DQ + WB_BREAKABLE:
5076 case WB_HL_then_DQ + WB_NOBREAK:
5078 /* WB7b Hebrew_Letter × Double_Quote Hebrew_Letter */
5080 if (advance_one_WB(&after_pos, strend, utf8_target,
5081 TRUE /* Do skip Extend and Format */ )
5082 == WB_Hebrew_Letter)
5087 return WB_table[before][after] - WB_HL_then_DQ == WB_BREAKABLE;
5089 case WB_LE_or_HL_then_MB_or_ML_or_SQ + WB_NOBREAK:
5090 case WB_LE_or_HL_then_MB_or_ML_or_SQ + WB_BREAKABLE:
5092 /* WB6 (ALetter | Hebrew_Letter) × (MidLetter | MidNumLet
5093 * | Single_Quote) (ALetter | Hebrew_Letter) */
5095 next = advance_one_WB(&after_pos, strend, utf8_target,
5096 TRUE /* Do skip Extend and Format */ );
5098 if (next == WB_ALetter || next == WB_Hebrew_Letter)
5103 return WB_table[before][after]
5104 - WB_LE_or_HL_then_MB_or_ML_or_SQ == WB_BREAKABLE;
5106 case WB_MB_or_ML_or_SQ_then_LE_or_HL + WB_NOBREAK:
5107 case WB_MB_or_ML_or_SQ_then_LE_or_HL + WB_BREAKABLE:
5109 /* WB7 (ALetter | Hebrew_Letter) (MidLetter | MidNumLet
5110 * | Single_Quote) × (ALetter | Hebrew_Letter) */
5112 prev = backup_one_WB(&previous, strbeg, &before_pos, utf8_target);
5113 if (prev == WB_ALetter || prev == WB_Hebrew_Letter)
5118 return WB_table[before][after]
5119 - WB_MB_or_ML_or_SQ_then_LE_or_HL == WB_BREAKABLE;
5121 case WB_MB_or_MN_or_SQ_then_NU + WB_NOBREAK:
5122 case WB_MB_or_MN_or_SQ_then_NU + WB_BREAKABLE:
5124 /* WB11 Numeric (MidNum | (MidNumLet | Single_Quote)) × Numeric
5127 if (backup_one_WB(&previous, strbeg, &before_pos, utf8_target)
5133 return WB_table[before][after]
5134 - WB_MB_or_MN_or_SQ_then_NU == WB_BREAKABLE;
5136 case WB_NU_then_MB_or_MN_or_SQ + WB_NOBREAK:
5137 case WB_NU_then_MB_or_MN_or_SQ + WB_BREAKABLE:
5139 /* WB12 Numeric × (MidNum | MidNumLet | Single_Quote) Numeric */
5141 if (advance_one_WB(&after_pos, strend, utf8_target,
5142 TRUE /* Do skip Extend and Format */ )
5148 return WB_table[before][after]
5149 - WB_NU_then_MB_or_MN_or_SQ == WB_BREAKABLE;
5151 case WB_RI_then_RI + WB_NOBREAK:
5152 case WB_RI_then_RI + WB_BREAKABLE:
5156 /* Do not break within emoji flag sequences. That is, do not
5157 * break between regional indicator (RI) symbols if there is an
5158 * odd number of RI characters before the potential break
5161 * WB15 ^ (RI RI)* RI × RI
5162 * WB16 [^RI] (RI RI)* RI × RI */
5164 while (backup_one_WB(&previous,
5167 utf8_target) == WB_Regional_Indicator)
5172 return RI_count % 2 != 1;
5180 Perl_re_printf( aTHX_ "Unhandled WB pair: WB_table[%d, %d] = %d\n",
5181 before, after, WB_table[before][after]);
5188 S_advance_one_WB(pTHX_ U8 ** curpos,
5189 const U8 * const strend,
5190 const bool utf8_target,
5191 const bool skip_Extend_Format)
5195 PERL_ARGS_ASSERT_ADVANCE_ONE_WB;
5197 if (*curpos >= strend) {
5203 /* Advance over Extend and Format */
5205 *curpos += UTF8SKIP(*curpos);
5206 if (*curpos >= strend) {
5209 wb = getWB_VAL_UTF8(*curpos, strend);
5210 } while ( skip_Extend_Format
5211 && (wb == WB_Extend || wb == WB_Format));
5216 if (*curpos >= strend) {
5219 wb = getWB_VAL_CP(**curpos);
5220 } while ( skip_Extend_Format
5221 && (wb == WB_Extend || wb == WB_Format));
5228 S_backup_one_WB(pTHX_ WB_enum * previous, const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
5232 PERL_ARGS_ASSERT_BACKUP_ONE_WB;
5234 /* If we know what the previous character's break value is, don't have
5236 if (*previous != WB_UNKNOWN) {
5239 /* But we need to move backwards by one */
5241 *curpos = reghopmaybe3(*curpos, -1, strbeg);
5243 *previous = WB_EDGE;
5244 *curpos = (U8 *) strbeg;
5247 *previous = WB_UNKNOWN;
5252 *previous = (*curpos <= strbeg) ? WB_EDGE : WB_UNKNOWN;
5255 /* And we always back up over these three types */
5256 if (wb != WB_Extend && wb != WB_Format && wb != WB_ZWJ) {
5261 if (*curpos < strbeg) {
5266 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
5267 if (! prev_char_pos) {
5271 /* Back up over Extend and Format. curpos is always just to the right
5272 * of the characater whose value we are getting */
5274 U8 * prev_prev_char_pos;
5275 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos,
5279 wb = getWB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
5280 *curpos = prev_char_pos;
5281 prev_char_pos = prev_prev_char_pos;
5284 *curpos = (U8 *) strbeg;
5287 } while (wb == WB_Extend || wb == WB_Format || wb == WB_ZWJ);
5291 if (*curpos - 2 < strbeg) {
5292 *curpos = (U8 *) strbeg;
5296 wb = getWB_VAL_CP(*(*curpos - 1));
5297 } while (wb == WB_Extend || wb == WB_Format);
5303 #define EVAL_CLOSE_PAREN_IS(st,expr) \
5306 ( ( st )->u.eval.close_paren ) && \
5307 ( ( ( st )->u.eval.close_paren ) == ( (expr) + 1 ) ) \
5310 #define EVAL_CLOSE_PAREN_IS_TRUE(st,expr) \
5313 ( ( st )->u.eval.close_paren ) && \
5315 ( ( ( st )->u.eval.close_paren ) == ( (expr) + 1 ) ) \
5319 #define EVAL_CLOSE_PAREN_SET(st,expr) \
5320 (st)->u.eval.close_paren = ( (expr) + 1 )
5322 #define EVAL_CLOSE_PAREN_CLEAR(st) \
5323 (st)->u.eval.close_paren = 0
5325 /* returns -1 on failure, $+[0] on success */
5327 S_regmatch(pTHX_ regmatch_info *reginfo, char *startpos, regnode *prog)
5330 const bool utf8_target = reginfo->is_utf8_target;
5331 const U32 uniflags = UTF8_ALLOW_DEFAULT;
5332 REGEXP *rex_sv = reginfo->prog;
5333 regexp *rex = ReANY(rex_sv);
5334 RXi_GET_DECL(rex,rexi);
5335 /* the current state. This is a cached copy of PL_regmatch_state */
5337 /* cache heavy used fields of st in registers */
5340 U32 n = 0; /* general value; init to avoid compiler warning */
5341 SSize_t ln = 0; /* len or last; init to avoid compiler warning */
5342 char *locinput = startpos;
5343 char *pushinput; /* where to continue after a PUSH */
5344 I32 nextchr; /* is always set to UCHARAT(locinput), or -1 at EOS */
5346 bool result = 0; /* return value of S_regmatch */
5347 U32 depth = 0; /* depth of backtrack stack */
5348 U32 nochange_depth = 0; /* depth of GOSUB recursion with nochange */
5349 const U32 max_nochange_depth =
5350 (3 * rex->nparens > MAX_RECURSE_EVAL_NOCHANGE_DEPTH) ?
5351 3 * rex->nparens : MAX_RECURSE_EVAL_NOCHANGE_DEPTH;
5352 regmatch_state *yes_state = NULL; /* state to pop to on success of
5354 /* mark_state piggy backs on the yes_state logic so that when we unwind
5355 the stack on success we can update the mark_state as we go */
5356 regmatch_state *mark_state = NULL; /* last mark state we have seen */
5357 regmatch_state *cur_eval = NULL; /* most recent EVAL_AB state */
5358 struct regmatch_state *cur_curlyx = NULL; /* most recent curlyx */
5360 bool no_final = 0; /* prevent failure from backtracking? */
5361 bool do_cutgroup = 0; /* no_final only until next branch/trie entry */
5362 char *startpoint = locinput;
5363 SV *popmark = NULL; /* are we looking for a mark? */
5364 SV *sv_commit = NULL; /* last mark name seen in failure */
5365 SV *sv_yes_mark = NULL; /* last mark name we have seen
5366 during a successful match */
5367 U32 lastopen = 0; /* last open we saw */
5368 bool has_cutgroup = RX_HAS_CUTGROUP(rex) ? 1 : 0;
5369 SV* const oreplsv = GvSVn(PL_replgv);
5370 /* these three flags are set by various ops to signal information to
5371 * the very next op. They have a useful lifetime of exactly one loop
5372 * iteration, and are not preserved or restored by state pushes/pops
5374 bool sw = 0; /* the condition value in (?(cond)a|b) */
5375 bool minmod = 0; /* the next "{n,m}" is a "{n,m}?" */
5376 int logical = 0; /* the following EVAL is:
5380 or the following IFMATCH/UNLESSM is:
5381 false: plain (?=foo)
5382 true: used as a condition: (?(?=foo))
5384 PAD* last_pad = NULL;
5386 U8 gimme = G_SCALAR;
5387 CV *caller_cv = NULL; /* who called us */
5388 CV *last_pushed_cv = NULL; /* most recently called (?{}) CV */
5389 CHECKPOINT runops_cp; /* savestack position before executing EVAL */
5390 U32 maxopenparen = 0; /* max '(' index seen so far */
5391 int to_complement; /* Invert the result? */
5392 _char_class_number classnum;
5393 bool is_utf8_pat = reginfo->is_utf8_pat;
5396 /* Solaris Studio 12.3 messes up fetching PL_charclass['\n'] */
5397 #if (defined(__SUNPRO_C) && (__SUNPRO_C == 0x5120) && defined(__x86_64) && defined(USE_64_BIT_ALL))
5398 # define SOLARIS_BAD_OPTIMIZER
5399 const U32 *pl_charclass_dup = PL_charclass;
5400 # define PL_charclass pl_charclass_dup
5404 GET_RE_DEBUG_FLAGS_DECL;
5407 /* protect against undef(*^R) */
5408 SAVEFREESV(SvREFCNT_inc_simple_NN(oreplsv));
5410 /* shut up 'may be used uninitialized' compiler warnings for dMULTICALL */
5411 multicall_oldcatch = 0;
5412 PERL_UNUSED_VAR(multicall_cop);
5414 PERL_ARGS_ASSERT_REGMATCH;
5416 st = PL_regmatch_state;
5418 /* Note that nextchr is a byte even in UTF */
5422 DEBUG_OPTIMISE_r( DEBUG_EXECUTE_r({
5423 DUMP_EXEC_POS( locinput, scan, utf8_target, depth );
5424 Perl_re_printf( aTHX_ "regmatch start\n" );
5427 while (scan != NULL) {
5430 next = scan + NEXT_OFF(scan);
5433 state_num = OP(scan);
5437 if (state_num <= REGNODE_MAX) {
5438 SV * const prop = sv_newmortal();
5439 regnode *rnext = regnext(scan);
5441 DUMP_EXEC_POS( locinput, scan, utf8_target, depth );
5442 regprop(rex, prop, scan, reginfo, NULL);
5443 Perl_re_printf( aTHX_
5444 "%*s%" IVdf ":%s(%" IVdf ")\n",
5445 INDENT_CHARS(depth), "",
5446 (IV)(scan - rexi->program),
5448 (PL_regkind[OP(scan)] == END || !rnext) ?
5449 0 : (IV)(rnext - rexi->program));
5456 assert(nextchr < 256 && (nextchr >= 0 || nextchr == NEXTCHR_EOS));
5458 switch (state_num) {
5459 case SBOL: /* /^../ and /\A../ */
5460 if (locinput == reginfo->strbeg)
5464 case MBOL: /* /^../m */
5465 if (locinput == reginfo->strbeg ||
5466 (!NEXTCHR_IS_EOS && locinput[-1] == '\n'))
5473 if (locinput == reginfo->ganch)
5477 case KEEPS: /* \K */
5478 /* update the startpoint */
5479 st->u.keeper.val = rex->offs[0].start;
5480 rex->offs[0].start = locinput - reginfo->strbeg;
5481 PUSH_STATE_GOTO(KEEPS_next, next, locinput);
5482 NOT_REACHED; /* NOTREACHED */
5484 case KEEPS_next_fail:
5485 /* rollback the start point change */
5486 rex->offs[0].start = st->u.keeper.val;
5488 NOT_REACHED; /* NOTREACHED */
5490 case MEOL: /* /..$/m */
5491 if (!NEXTCHR_IS_EOS && nextchr != '\n')
5495 case SEOL: /* /..$/ */
5496 if (!NEXTCHR_IS_EOS && nextchr != '\n')
5498 if (reginfo->strend - locinput > 1)
5503 if (!NEXTCHR_IS_EOS)
5507 case SANY: /* /./s */
5510 goto increment_locinput;
5512 case REG_ANY: /* /./ */
5513 if ((NEXTCHR_IS_EOS) || nextchr == '\n')
5515 goto increment_locinput;
5519 #define ST st->u.trie
5520 case TRIEC: /* (ab|cd) with known charclass */
5521 /* In this case the charclass data is available inline so
5522 we can fail fast without a lot of extra overhead.
5524 if(!NEXTCHR_IS_EOS && !ANYOF_BITMAP_TEST(scan, nextchr)) {
5526 Perl_re_exec_indentf( aTHX_ "%sfailed to match trie start class...%s\n",
5527 depth, PL_colors[4], PL_colors[5])
5530 NOT_REACHED; /* NOTREACHED */
5533 case TRIE: /* (ab|cd) */
5534 /* the basic plan of execution of the trie is:
5535 * At the beginning, run though all the states, and
5536 * find the longest-matching word. Also remember the position
5537 * of the shortest matching word. For example, this pattern:
5540 * when matched against the string "abcde", will generate
5541 * accept states for all words except 3, with the longest
5542 * matching word being 4, and the shortest being 2 (with
5543 * the position being after char 1 of the string).
5545 * Then for each matching word, in word order (i.e. 1,2,4,5),
5546 * we run the remainder of the pattern; on each try setting
5547 * the current position to the character following the word,
5548 * returning to try the next word on failure.
5550 * We avoid having to build a list of words at runtime by
5551 * using a compile-time structure, wordinfo[].prev, which
5552 * gives, for each word, the previous accepting word (if any).
5553 * In the case above it would contain the mappings 1->2, 2->0,
5554 * 3->0, 4->5, 5->1. We can use this table to generate, from
5555 * the longest word (4 above), a list of all words, by
5556 * following the list of prev pointers; this gives us the
5557 * unordered list 4,5,1,2. Then given the current word we have
5558 * just tried, we can go through the list and find the
5559 * next-biggest word to try (so if we just failed on word 2,
5560 * the next in the list is 4).
5562 * Since at runtime we don't record the matching position in
5563 * the string for each word, we have to work that out for
5564 * each word we're about to process. The wordinfo table holds
5565 * the character length of each word; given that we recorded
5566 * at the start: the position of the shortest word and its
5567 * length in chars, we just need to move the pointer the
5568 * difference between the two char lengths. Depending on
5569 * Unicode status and folding, that's cheap or expensive.
5571 * This algorithm is optimised for the case where are only a
5572 * small number of accept states, i.e. 0,1, or maybe 2.
5573 * With lots of accepts states, and having to try all of them,
5574 * it becomes quadratic on number of accept states to find all
5579 /* what type of TRIE am I? (utf8 makes this contextual) */
5580 DECL_TRIE_TYPE(scan);
5582 /* what trie are we using right now */
5583 reg_trie_data * const trie
5584 = (reg_trie_data*)rexi->data->data[ ARG( scan ) ];
5585 HV * widecharmap = MUTABLE_HV(rexi->data->data[ ARG( scan ) + 1 ]);
5586 U32 state = trie->startstate;
5588 if (scan->flags == EXACTL || scan->flags == EXACTFLU8) {
5589 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5591 && UTF8_IS_ABOVE_LATIN1(nextchr)
5592 && scan->flags == EXACTL)
5594 /* We only output for EXACTL, as we let the folder
5595 * output this message for EXACTFLU8 to avoid
5597 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput,
5602 && (NEXTCHR_IS_EOS || !TRIE_BITMAP_TEST(trie, nextchr)))
5604 if (trie->states[ state ].wordnum) {
5606 Perl_re_exec_indentf( aTHX_ "%smatched empty string...%s\n",
5607 depth, PL_colors[4], PL_colors[5])
5613 Perl_re_exec_indentf( aTHX_ "%sfailed to match trie start class...%s\n",
5614 depth, PL_colors[4], PL_colors[5])
5621 U8 *uc = ( U8* )locinput;
5625 U8 *uscan = (U8*)NULL;
5626 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
5627 U32 charcount = 0; /* how many input chars we have matched */
5628 U32 accepted = 0; /* have we seen any accepting states? */
5630 ST.jump = trie->jump;
5633 ST.longfold = FALSE; /* char longer if folded => it's harder */
5636 /* fully traverse the TRIE; note the position of the
5637 shortest accept state and the wordnum of the longest
5640 while ( state && uc <= (U8*)(reginfo->strend) ) {
5641 U32 base = trie->states[ state ].trans.base;
5645 wordnum = trie->states[ state ].wordnum;
5647 if (wordnum) { /* it's an accept state */
5650 /* record first match position */
5652 ST.firstpos = (U8*)locinput;
5657 ST.firstchars = charcount;
5660 if (!ST.nextword || wordnum < ST.nextword)
5661 ST.nextword = wordnum;
5662 ST.topword = wordnum;
5665 DEBUG_TRIE_EXECUTE_r({
5666 DUMP_EXEC_POS( (char *)uc, scan, utf8_target, depth );
5668 PerlIO_printf( Perl_debug_log,
5669 "%*s%sState: %4" UVxf " Accepted: %c ",
5670 INDENT_CHARS(depth), "", PL_colors[4],
5671 (UV)state, (accepted ? 'Y' : 'N'));
5674 /* read a char and goto next state */
5675 if ( base && (foldlen || uc < (U8*)(reginfo->strend))) {
5677 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
5678 uscan, len, uvc, charid, foldlen,
5685 base + charid - 1 - trie->uniquecharcount)) >= 0)
5687 && ((U32)offset < trie->lasttrans)
5688 && trie->trans[offset].check == state)
5690 state = trie->trans[offset].next;
5701 DEBUG_TRIE_EXECUTE_r(
5702 Perl_re_printf( aTHX_
5703 "Charid:%3x CP:%4" UVxf " After State: %4" UVxf "%s\n",
5704 charid, uvc, (UV)state, PL_colors[5] );
5710 /* calculate total number of accept states */
5715 w = trie->wordinfo[w].prev;
5718 ST.accepted = accepted;
5722 Perl_re_exec_indentf( aTHX_ "%sgot %" IVdf " possible matches%s\n",
5724 PL_colors[4], (IV)ST.accepted, PL_colors[5] );
5726 goto trie_first_try; /* jump into the fail handler */
5728 NOT_REACHED; /* NOTREACHED */
5730 case TRIE_next_fail: /* we failed - try next alternative */
5734 REGCP_UNWIND(ST.cp);
5735 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
5737 if (!--ST.accepted) {
5739 Perl_re_exec_indentf( aTHX_ "%sTRIE failed...%s\n",
5747 /* Find next-highest word to process. Note that this code
5748 * is O(N^2) per trie run (O(N) per branch), so keep tight */
5751 U16 const nextword = ST.nextword;
5752 reg_trie_wordinfo * const wordinfo
5753 = ((reg_trie_data*)rexi->data->data[ARG(ST.me)])->wordinfo;
5754 for (word=ST.topword; word; word=wordinfo[word].prev) {
5755 if (word > nextword && (!min || word < min))
5768 ST.lastparen = rex->lastparen;
5769 ST.lastcloseparen = rex->lastcloseparen;
5773 /* find start char of end of current word */
5775 U32 chars; /* how many chars to skip */
5776 reg_trie_data * const trie
5777 = (reg_trie_data*)rexi->data->data[ARG(ST.me)];
5779 assert((trie->wordinfo[ST.nextword].len - trie->prefixlen)
5781 chars = (trie->wordinfo[ST.nextword].len - trie->prefixlen)
5786 /* the hard option - fold each char in turn and find
5787 * its folded length (which may be different */
5788 U8 foldbuf[UTF8_MAXBYTES_CASE + 1];
5796 uvc = utf8n_to_uvchr((U8*)uc, UTF8_MAXLEN, &len,
5804 uvc = to_uni_fold(uvc, foldbuf, &foldlen);
5809 uvc = utf8n_to_uvchr(uscan, UTF8_MAXLEN, &len,
5825 scan = ST.me + ((ST.jump && ST.jump[ST.nextword])
5826 ? ST.jump[ST.nextword]
5830 Perl_re_exec_indentf( aTHX_ "%sTRIE matched word #%d, continuing%s\n",
5838 if ( ST.accepted > 1 || has_cutgroup || ST.jump ) {
5839 PUSH_STATE_GOTO(TRIE_next, scan, (char*)uc);
5840 NOT_REACHED; /* NOTREACHED */
5842 /* only one choice left - just continue */
5844 AV *const trie_words
5845 = MUTABLE_AV(rexi->data->data[ARG(ST.me)+TRIE_WORDS_OFFSET]);
5846 SV ** const tmp = trie_words
5847 ? av_fetch(trie_words, ST.nextword - 1, 0) : NULL;
5848 SV *sv= tmp ? sv_newmortal() : NULL;
5850 Perl_re_exec_indentf( aTHX_ "%sonly one match left, short-circuiting: #%d <%s>%s\n",
5851 depth, PL_colors[4],
5853 tmp ? pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 0,
5854 PL_colors[0], PL_colors[1],
5855 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)|PERL_PV_ESCAPE_NONASCII
5857 : "not compiled under -Dr",
5861 locinput = (char*)uc;
5862 continue; /* execute rest of RE */
5867 case EXACTL: /* /abc/l */
5868 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5870 /* Complete checking would involve going through every character
5871 * matched by the string to see if any is above latin1. But the
5872 * comparision otherwise might very well be a fast assembly
5873 * language routine, and I (khw) don't think slowing things down
5874 * just to check for this warning is worth it. So this just checks
5875 * the first character */
5876 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*locinput)) {
5877 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput, reginfo->strend);
5880 case EXACT: { /* /abc/ */
5881 char *s = STRING(scan);
5883 if (utf8_target != is_utf8_pat) {
5884 /* The target and the pattern have differing utf8ness. */
5886 const char * const e = s + ln;
5889 /* The target is utf8, the pattern is not utf8.
5890 * Above-Latin1 code points can't match the pattern;
5891 * invariants match exactly, and the other Latin1 ones need
5892 * to be downgraded to a single byte in order to do the
5893 * comparison. (If we could be confident that the target
5894 * is not malformed, this could be refactored to have fewer
5895 * tests by just assuming that if the first bytes match, it
5896 * is an invariant, but there are tests in the test suite
5897 * dealing with (??{...}) which violate this) */
5899 if (l >= reginfo->strend
5900 || UTF8_IS_ABOVE_LATIN1(* (U8*) l))
5904 if (UTF8_IS_INVARIANT(*(U8*)l)) {
5911 if (EIGHT_BIT_UTF8_TO_NATIVE(*l, *(l+1)) != * (U8*) s)
5921 /* The target is not utf8, the pattern is utf8. */
5923 if (l >= reginfo->strend
5924 || UTF8_IS_ABOVE_LATIN1(* (U8*) s))
5928 if (UTF8_IS_INVARIANT(*(U8*)s)) {
5935 if (EIGHT_BIT_UTF8_TO_NATIVE(*s, *(s+1)) != * (U8*) l)
5947 /* The target and the pattern have the same utf8ness. */
5948 /* Inline the first character, for speed. */
5949 if (reginfo->strend - locinput < ln
5950 || UCHARAT(s) != nextchr
5951 || (ln > 1 && memNE(s, locinput, ln)))
5960 case EXACTFL: { /* /abc/il */
5962 const U8 * fold_array;
5964 U32 fold_utf8_flags;
5966 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5967 folder = foldEQ_locale;
5968 fold_array = PL_fold_locale;
5969 fold_utf8_flags = FOLDEQ_LOCALE;
5972 case EXACTFLU8: /* /abc/il; but all 'abc' are above 255, so
5973 is effectively /u; hence to match, target
5975 if (! utf8_target) {
5978 fold_utf8_flags = FOLDEQ_LOCALE | FOLDEQ_S1_ALREADY_FOLDED
5979 | FOLDEQ_S1_FOLDS_SANE;
5980 folder = foldEQ_latin1;
5981 fold_array = PL_fold_latin1;
5984 case EXACTFU_SS: /* /\x{df}/iu */
5985 case EXACTFU: /* /abc/iu */
5986 folder = foldEQ_latin1;
5987 fold_array = PL_fold_latin1;
5988 fold_utf8_flags = is_utf8_pat ? FOLDEQ_S1_ALREADY_FOLDED : 0;
5991 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8
5993 assert(! is_utf8_pat);
5995 case EXACTFA: /* /abc/iaa */
5996 folder = foldEQ_latin1;
5997 fold_array = PL_fold_latin1;
5998 fold_utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
6001 case EXACTF: /* /abc/i This node only generated for
6002 non-utf8 patterns */
6003 assert(! is_utf8_pat);
6005 fold_array = PL_fold;
6006 fold_utf8_flags = 0;
6014 || state_num == EXACTFU_SS
6015 || (state_num == EXACTFL && IN_UTF8_CTYPE_LOCALE))
6017 /* Either target or the pattern are utf8, or has the issue where
6018 * the fold lengths may differ. */
6019 const char * const l = locinput;
6020 char *e = reginfo->strend;
6022 if (! foldEQ_utf8_flags(s, 0, ln, is_utf8_pat,
6023 l, &e, 0, utf8_target, fold_utf8_flags))
6031 /* Neither the target nor the pattern are utf8 */
6032 if (UCHARAT(s) != nextchr
6034 && UCHARAT(s) != fold_array[nextchr])
6038 if (reginfo->strend - locinput < ln)
6040 if (ln > 1 && ! folder(s, locinput, ln))
6046 case NBOUNDL: /* /\B/l */
6050 case BOUNDL: /* /\b/l */
6053 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6055 if (FLAGS(scan) != TRADITIONAL_BOUND) {
6056 if (! IN_UTF8_CTYPE_LOCALE) {
6057 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
6058 B_ON_NON_UTF8_LOCALE_IS_WRONG);
6064 if (locinput == reginfo->strbeg)
6065 b1 = isWORDCHAR_LC('\n');
6067 b1 = isWORDCHAR_LC_utf8(reghop3((U8*)locinput, -1,
6068 (U8*)(reginfo->strbeg)));
6070 b2 = (NEXTCHR_IS_EOS)
6071 ? isWORDCHAR_LC('\n')
6072 : isWORDCHAR_LC_utf8((U8*)locinput);
6074 else { /* Here the string isn't utf8 */
6075 b1 = (locinput == reginfo->strbeg)
6076 ? isWORDCHAR_LC('\n')
6077 : isWORDCHAR_LC(UCHARAT(locinput - 1));
6078 b2 = (NEXTCHR_IS_EOS)
6079 ? isWORDCHAR_LC('\n')
6080 : isWORDCHAR_LC(nextchr);
6082 if (to_complement ^ (b1 == b2)) {
6088 case NBOUND: /* /\B/ */
6092 case BOUND: /* /\b/ */
6096 goto bound_ascii_match_only;
6098 case NBOUNDA: /* /\B/a */
6102 case BOUNDA: /* /\b/a */
6106 bound_ascii_match_only:
6107 /* Here the string isn't utf8, or is utf8 and only ascii characters
6108 * are to match \w. In the latter case looking at the byte just
6109 * prior to the current one may be just the final byte of a
6110 * multi-byte character. This is ok. There are two cases:
6111 * 1) it is a single byte character, and then the test is doing
6112 * just what it's supposed to.
6113 * 2) it is a multi-byte character, in which case the final byte is
6114 * never mistakable for ASCII, and so the test will say it is
6115 * not a word character, which is the correct answer. */
6116 b1 = (locinput == reginfo->strbeg)
6117 ? isWORDCHAR_A('\n')
6118 : isWORDCHAR_A(UCHARAT(locinput - 1));
6119 b2 = (NEXTCHR_IS_EOS)
6120 ? isWORDCHAR_A('\n')
6121 : isWORDCHAR_A(nextchr);
6122 if (to_complement ^ (b1 == b2)) {
6128 case NBOUNDU: /* /\B/u */
6132 case BOUNDU: /* /\b/u */
6135 if (UNLIKELY(reginfo->strbeg >= reginfo->strend)) {
6138 else if (utf8_target) {
6140 switch((bound_type) FLAGS(scan)) {
6141 case TRADITIONAL_BOUND:
6144 b1 = (locinput == reginfo->strbeg)
6145 ? 0 /* isWORDCHAR_L1('\n') */
6146 : isWORDCHAR_utf8(reghop3((U8*)locinput, -1,
6147 (U8*)(reginfo->strbeg)));
6148 b2 = (NEXTCHR_IS_EOS)
6149 ? 0 /* isWORDCHAR_L1('\n') */
6150 : isWORDCHAR_utf8((U8*)locinput);
6151 match = cBOOL(b1 != b2);
6155 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6156 match = TRUE; /* GCB always matches at begin and
6160 /* Find the gcb values of previous and current
6161 * chars, then see if is a break point */
6162 match = isGCB(getGCB_VAL_UTF8(
6163 reghop3((U8*)locinput,
6165 (U8*)(reginfo->strbeg)),
6166 (U8*) reginfo->strend),
6167 getGCB_VAL_UTF8((U8*) locinput,
6168 (U8*) reginfo->strend),
6169 (U8*) reginfo->strbeg,
6176 if (locinput == reginfo->strbeg) {
6179 else if (NEXTCHR_IS_EOS) {
6183 match = isLB(getLB_VAL_UTF8(
6184 reghop3((U8*)locinput,
6186 (U8*)(reginfo->strbeg)),
6187 (U8*) reginfo->strend),
6188 getLB_VAL_UTF8((U8*) locinput,
6189 (U8*) reginfo->strend),
6190 (U8*) reginfo->strbeg,
6192 (U8*) reginfo->strend,
6197 case SB_BOUND: /* Always matches at begin and end */
6198 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6202 match = isSB(getSB_VAL_UTF8(
6203 reghop3((U8*)locinput,
6205 (U8*)(reginfo->strbeg)),
6206 (U8*) reginfo->strend),
6207 getSB_VAL_UTF8((U8*) locinput,
6208 (U8*) reginfo->strend),
6209 (U8*) reginfo->strbeg,
6211 (U8*) reginfo->strend,
6217 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6221 match = isWB(WB_UNKNOWN,
6223 reghop3((U8*)locinput,
6225 (U8*)(reginfo->strbeg)),
6226 (U8*) reginfo->strend),
6227 getWB_VAL_UTF8((U8*) locinput,
6228 (U8*) reginfo->strend),
6229 (U8*) reginfo->strbeg,
6231 (U8*) reginfo->strend,
6237 else { /* Not utf8 target */
6238 switch((bound_type) FLAGS(scan)) {
6239 case TRADITIONAL_BOUND:
6242 b1 = (locinput == reginfo->strbeg)
6243 ? 0 /* isWORDCHAR_L1('\n') */
6244 : isWORDCHAR_L1(UCHARAT(locinput - 1));
6245 b2 = (NEXTCHR_IS_EOS)
6246 ? 0 /* isWORDCHAR_L1('\n') */
6247 : isWORDCHAR_L1(nextchr);
6248 match = cBOOL(b1 != b2);
6253 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6254 match = TRUE; /* GCB always matches at begin and
6257 else { /* Only CR-LF combo isn't a GCB in 0-255
6259 match = UCHARAT(locinput - 1) != '\r'
6260 || UCHARAT(locinput) != '\n';
6265 if (locinput == reginfo->strbeg) {
6268 else if (NEXTCHR_IS_EOS) {
6272 match = isLB(getLB_VAL_CP(UCHARAT(locinput -1)),
6273 getLB_VAL_CP(UCHARAT(locinput)),
6274 (U8*) reginfo->strbeg,
6276 (U8*) reginfo->strend,
6281 case SB_BOUND: /* Always matches at begin and end */
6282 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6286 match = isSB(getSB_VAL_CP(UCHARAT(locinput -1)),
6287 getSB_VAL_CP(UCHARAT(locinput)),
6288 (U8*) reginfo->strbeg,
6290 (U8*) reginfo->strend,
6296 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6300 match = isWB(WB_UNKNOWN,
6301 getWB_VAL_CP(UCHARAT(locinput -1)),
6302 getWB_VAL_CP(UCHARAT(locinput)),
6303 (U8*) reginfo->strbeg,
6305 (U8*) reginfo->strend,
6312 if (to_complement ^ ! match) {
6317 case ANYOFL: /* /[abc]/l */
6318 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6320 if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(scan)) && ! IN_UTF8_CTYPE_LOCALE)
6322 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
6325 case ANYOFD: /* /[abc]/d */
6326 case ANYOF: /* /[abc]/ */
6329 if (utf8_target && ! UTF8_IS_INVARIANT(*locinput)) {
6330 if (!reginclass(rex, scan, (U8*)locinput, (U8*)reginfo->strend,
6333 locinput += UTF8SKIP(locinput);
6336 if (!REGINCLASS(rex, scan, (U8*)locinput, utf8_target))
6342 /* The argument (FLAGS) to all the POSIX node types is the class number
6345 case NPOSIXL: /* \W or [:^punct:] etc. under /l */
6349 case POSIXL: /* \w or [:punct:] etc. under /l */
6350 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6354 /* Use isFOO_lc() for characters within Latin1. (Note that
6355 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
6356 * wouldn't be invariant) */
6357 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
6358 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan), (U8) nextchr)))) {
6366 if (! UTF8_IS_DOWNGRADEABLE_START(nextchr)) { /* An above Latin-1 code point */
6367 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput, reginfo->strend);
6368 goto utf8_posix_above_latin1;
6371 /* Here is a UTF-8 variant code point below 256 and the target is
6373 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan),
6374 EIGHT_BIT_UTF8_TO_NATIVE(nextchr,
6375 *(locinput + 1))))))
6380 goto increment_locinput;
6382 case NPOSIXD: /* \W or [:^punct:] etc. under /d */
6386 case POSIXD: /* \w or [:punct:] etc. under /d */
6392 case NPOSIXA: /* \W or [:^punct:] etc. under /a */
6394 if (NEXTCHR_IS_EOS) {
6398 /* All UTF-8 variants match */
6399 if (! UTF8_IS_INVARIANT(nextchr)) {
6400 goto increment_locinput;
6406 case POSIXA: /* \w or [:punct:] etc. under /a */
6409 /* We get here through POSIXD, NPOSIXD, and NPOSIXA when not in
6410 * UTF-8, and also from NPOSIXA even in UTF-8 when the current
6411 * character is a single byte */
6413 if (NEXTCHR_IS_EOS) {
6419 if (! (to_complement ^ cBOOL(_generic_isCC_A(nextchr,
6425 /* Here we are either not in utf8, or we matched a utf8-invariant,
6426 * so the next char is the next byte */
6430 case NPOSIXU: /* \W or [:^punct:] etc. under /u */
6434 case POSIXU: /* \w or [:punct:] etc. under /u */
6436 if (NEXTCHR_IS_EOS) {
6440 /* Use _generic_isCC() for characters within Latin1. (Note that
6441 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
6442 * wouldn't be invariant) */
6443 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
6444 if (! (to_complement ^ cBOOL(_generic_isCC(nextchr,
6451 else if (UTF8_IS_DOWNGRADEABLE_START(nextchr)) {
6452 if (! (to_complement
6453 ^ cBOOL(_generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(nextchr,
6461 else { /* Handle above Latin-1 code points */
6462 utf8_posix_above_latin1:
6463 classnum = (_char_class_number) FLAGS(scan);
6464 if (classnum < _FIRST_NON_SWASH_CC) {
6466 /* Here, uses a swash to find such code points. Load if if
6467 * not done already */
6468 if (! PL_utf8_swash_ptrs[classnum]) {
6469 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
6470 PL_utf8_swash_ptrs[classnum]
6471 = _core_swash_init("utf8",
6474 PL_XPosix_ptrs[classnum], &flags);
6476 if (! (to_complement
6477 ^ cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum],
6478 (U8 *) locinput, TRUE))))
6483 else { /* Here, uses macros to find above Latin-1 code points */
6485 case _CC_ENUM_SPACE:
6486 if (! (to_complement
6487 ^ cBOOL(is_XPERLSPACE_high(locinput))))
6492 case _CC_ENUM_BLANK:
6493 if (! (to_complement
6494 ^ cBOOL(is_HORIZWS_high(locinput))))
6499 case _CC_ENUM_XDIGIT:
6500 if (! (to_complement
6501 ^ cBOOL(is_XDIGIT_high(locinput))))
6506 case _CC_ENUM_VERTSPACE:
6507 if (! (to_complement
6508 ^ cBOOL(is_VERTWS_high(locinput))))
6513 default: /* The rest, e.g. [:cntrl:], can't match
6515 if (! to_complement) {
6521 locinput += UTF8SKIP(locinput);
6525 case CLUMP: /* Match \X: logical Unicode character. This is defined as
6526 a Unicode extended Grapheme Cluster */
6529 if (! utf8_target) {
6531 /* Match either CR LF or '.', as all the other possibilities
6533 locinput++; /* Match the . or CR */
6534 if (nextchr == '\r' /* And if it was CR, and the next is LF,
6536 && locinput < reginfo->strend
6537 && UCHARAT(locinput) == '\n')
6544 /* Get the gcb type for the current character */
6545 GCB_enum prev_gcb = getGCB_VAL_UTF8((U8*) locinput,
6546 (U8*) reginfo->strend);
6548 /* Then scan through the input until we get to the first
6549 * character whose type is supposed to be a gcb with the
6550 * current character. (There is always a break at the
6552 locinput += UTF8SKIP(locinput);
6553 while (locinput < reginfo->strend) {
6554 GCB_enum cur_gcb = getGCB_VAL_UTF8((U8*) locinput,
6555 (U8*) reginfo->strend);
6556 if (isGCB(prev_gcb, cur_gcb,
6557 (U8*) reginfo->strbeg, (U8*) locinput,
6564 locinput += UTF8SKIP(locinput);
6571 case NREFFL: /* /\g{name}/il */
6572 { /* The capture buffer cases. The ones beginning with N for the
6573 named buffers just convert to the equivalent numbered and
6574 pretend they were called as the corresponding numbered buffer
6576 /* don't initialize these in the declaration, it makes C++
6581 const U8 *fold_array;
6584 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6585 folder = foldEQ_locale;
6586 fold_array = PL_fold_locale;
6588 utf8_fold_flags = FOLDEQ_LOCALE;
6591 case NREFFA: /* /\g{name}/iaa */
6592 folder = foldEQ_latin1;
6593 fold_array = PL_fold_latin1;
6595 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
6598 case NREFFU: /* /\g{name}/iu */
6599 folder = foldEQ_latin1;
6600 fold_array = PL_fold_latin1;
6602 utf8_fold_flags = 0;
6605 case NREFF: /* /\g{name}/i */
6607 fold_array = PL_fold;
6609 utf8_fold_flags = 0;
6612 case NREF: /* /\g{name}/ */
6616 utf8_fold_flags = 0;
6619 /* For the named back references, find the corresponding buffer
6621 n = reg_check_named_buff_matched(rex,scan);
6626 goto do_nref_ref_common;
6628 case REFFL: /* /\1/il */
6629 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6630 folder = foldEQ_locale;
6631 fold_array = PL_fold_locale;
6632 utf8_fold_flags = FOLDEQ_LOCALE;
6635 case REFFA: /* /\1/iaa */
6636 folder = foldEQ_latin1;
6637 fold_array = PL_fold_latin1;
6638 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
6641 case REFFU: /* /\1/iu */
6642 folder = foldEQ_latin1;
6643 fold_array = PL_fold_latin1;
6644 utf8_fold_flags = 0;
6647 case REFF: /* /\1/i */
6649 fold_array = PL_fold;
6650 utf8_fold_flags = 0;
6653 case REF: /* /\1/ */
6656 utf8_fold_flags = 0;
6660 n = ARG(scan); /* which paren pair */
6663 ln = rex->offs[n].start;
6664 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
6665 if (rex->lastparen < n || ln == -1)
6666 sayNO; /* Do not match unless seen CLOSEn. */
6667 if (ln == rex->offs[n].end)
6670 s = reginfo->strbeg + ln;
6671 if (type != REF /* REF can do byte comparison */
6672 && (utf8_target || type == REFFU || type == REFFL))
6674 char * limit = reginfo->strend;
6676 /* This call case insensitively compares the entire buffer
6677 * at s, with the current input starting at locinput, but
6678 * not going off the end given by reginfo->strend, and
6679 * returns in <limit> upon success, how much of the
6680 * current input was matched */
6681 if (! foldEQ_utf8_flags(s, NULL, rex->offs[n].end - ln, utf8_target,
6682 locinput, &limit, 0, utf8_target, utf8_fold_flags))
6690 /* Not utf8: Inline the first character, for speed. */
6691 if (!NEXTCHR_IS_EOS &&
6692 UCHARAT(s) != nextchr &&
6694 UCHARAT(s) != fold_array[nextchr]))
6696 ln = rex->offs[n].end - ln;
6697 if (locinput + ln > reginfo->strend)
6699 if (ln > 1 && (type == REF
6700 ? memNE(s, locinput, ln)
6701 : ! folder(s, locinput, ln)))
6707 case NOTHING: /* null op; e.g. the 'nothing' following
6708 * the '*' in m{(a+|b)*}' */
6710 case TAIL: /* placeholder while compiling (A|B|C) */
6714 #define ST st->u.eval
6715 #define CUR_EVAL cur_eval->u.eval
6721 regexp_internal *rei;
6722 regnode *startpoint;
6725 case GOSUB: /* /(...(?1))/ /(...(?&foo))/ */
6726 arg= (U32)ARG(scan);
6727 if (cur_eval && cur_eval->locinput == locinput) {
6728 if ( ++nochange_depth > max_nochange_depth )
6730 "Pattern subroutine nesting without pos change"
6731 " exceeded limit in regex");
6738 startpoint = scan + ARG2L(scan);
6739 EVAL_CLOSE_PAREN_SET( st, arg );
6740 /* Detect infinite recursion
6742 * A pattern like /(?R)foo/ or /(?<x>(?&y)foo)(?<y>(?&x)bar)/
6743 * or "a"=~/(.(?2))((?<=(?=(?1)).))/ could recurse forever.
6744 * So we track the position in the string we are at each time
6745 * we recurse and if we try to enter the same routine twice from
6746 * the same position we throw an error.
6748 if ( rex->recurse_locinput[arg] == locinput ) {
6749 /* FIXME: we should show the regop that is failing as part
6750 * of the error message. */
6751 Perl_croak(aTHX_ "Infinite recursion in regex");
6753 ST.prev_recurse_locinput= rex->recurse_locinput[arg];
6754 rex->recurse_locinput[arg]= locinput;
6757 GET_RE_DEBUG_FLAGS_DECL;
6759 Perl_re_exec_indentf( aTHX_
6760 "entering GOSUB, prev_recurse_locinput=%p recurse_locinput[%d]=%p\n",
6761 depth, ST.prev_recurse_locinput, arg, rex->recurse_locinput[arg]
6767 /* Save all the positions seen so far. */
6768 ST.cp = regcppush(rex, 0, maxopenparen);
6769 REGCP_SET(ST.lastcp);
6771 /* and then jump to the code we share with EVAL */
6772 goto eval_recurse_doit;
6775 case EVAL: /* /(?{A})B/ /(??{A})B/ and /(?(?{A})X|Y)B/ */
6776 if (cur_eval && cur_eval->locinput==locinput) {
6777 if ( ++nochange_depth > max_nochange_depth )
6778 Perl_croak(aTHX_ "EVAL without pos change exceeded limit in regex");
6783 /* execute the code in the {...} */
6787 OP * const oop = PL_op;
6788 COP * const ocurcop = PL_curcop;
6792 /* save *all* paren positions */
6793 regcppush(rex, 0, maxopenparen);
6794 REGCP_SET(runops_cp);
6797 caller_cv = find_runcv(NULL);
6801 if (rexi->data->what[n] == 'r') { /* code from an external qr */
6803 (REGEXP*)(rexi->data->data[n])
6805 nop = (OP*)rexi->data->data[n+1];
6807 else if (rexi->data->what[n] == 'l') { /* literal code */
6809 nop = (OP*)rexi->data->data[n];
6810 assert(CvDEPTH(newcv));
6813 /* literal with own CV */
6814 assert(rexi->data->what[n] == 'L');
6815 newcv = rex->qr_anoncv;
6816 nop = (OP*)rexi->data->data[n];
6819 /* normally if we're about to execute code from the same
6820 * CV that we used previously, we just use the existing
6821 * CX stack entry. However, its possible that in the
6822 * meantime we may have backtracked, popped from the save
6823 * stack, and undone the SAVECOMPPAD(s) associated with
6824 * PUSH_MULTICALL; in which case PL_comppad no longer
6825 * points to newcv's pad. */
6826 if (newcv != last_pushed_cv || PL_comppad != last_pad)
6828 U8 flags = (CXp_SUB_RE |
6829 ((newcv == caller_cv) ? CXp_SUB_RE_FAKE : 0));
6830 if (last_pushed_cv) {
6831 /* PUSH/POP_MULTICALL save and restore the
6832 * caller's PL_comppad; if we call multiple subs
6833 * using the same CX block, we have to save and
6834 * unwind the varying PL_comppad's ourselves,
6835 * especially restoring the right PL_comppad on
6836 * backtrack - so save it on the save stack */
6838 CHANGE_MULTICALL_FLAGS(newcv, flags);
6841 PUSH_MULTICALL_FLAGS(newcv, flags);
6843 last_pushed_cv = newcv;
6846 /* these assignments are just to silence compiler
6848 multicall_cop = NULL;
6850 last_pad = PL_comppad;
6852 /* the initial nextstate you would normally execute
6853 * at the start of an eval (which would cause error
6854 * messages to come from the eval), may be optimised
6855 * away from the execution path in the regex code blocks;
6856 * so manually set PL_curcop to it initially */
6858 OP *o = cUNOPx(nop)->op_first;
6859 assert(o->op_type == OP_NULL);
6860 if (o->op_targ == OP_SCOPE) {
6861 o = cUNOPo->op_first;
6864 assert(o->op_targ == OP_LEAVE);
6865 o = cUNOPo->op_first;
6866 assert(o->op_type == OP_ENTER);
6870 if (o->op_type != OP_STUB) {
6871 assert( o->op_type == OP_NEXTSTATE
6872 || o->op_type == OP_DBSTATE
6873 || (o->op_type == OP_NULL
6874 && ( o->op_targ == OP_NEXTSTATE
6875 || o->op_targ == OP_DBSTATE
6879 PL_curcop = (COP*)o;
6884 DEBUG_STATE_r( Perl_re_printf( aTHX_
6885 " re EVAL PL_op=0x%" UVxf "\n", PTR2UV(nop)) );
6887 rex->offs[0].end = locinput - reginfo->strbeg;
6888 if (reginfo->info_aux_eval->pos_magic)
6889 MgBYTEPOS_set(reginfo->info_aux_eval->pos_magic,
6890 reginfo->sv, reginfo->strbeg,
6891 locinput - reginfo->strbeg);
6894 SV *sv_mrk = get_sv("REGMARK", 1);
6895 sv_setsv(sv_mrk, sv_yes_mark);
6898 /* we don't use MULTICALL here as we want to call the
6899 * first op of the block of interest, rather than the
6900 * first op of the sub. Also, we don't want to free
6901 * the savestack frame */
6902 before = (IV)(SP-PL_stack_base);
6904 CALLRUNOPS(aTHX); /* Scalar context. */
6906 if ((IV)(SP-PL_stack_base) == before)
6907 ret = &PL_sv_undef; /* protect against empty (?{}) blocks. */
6913 /* before restoring everything, evaluate the returned
6914 * value, so that 'uninit' warnings don't use the wrong
6915 * PL_op or pad. Also need to process any magic vars
6916 * (e.g. $1) *before* parentheses are restored */
6921 if (logical == 0) /* (?{})/ */
6922 sv_setsv(save_scalar(PL_replgv), ret); /* $^R */
6923 else if (logical == 1) { /* /(?(?{...})X|Y)/ */
6924 sw = cBOOL(SvTRUE(ret));
6927 else { /* /(??{}) */
6928 /* if its overloaded, let the regex compiler handle
6929 * it; otherwise extract regex, or stringify */
6930 if (SvGMAGICAL(ret))
6931 ret = sv_mortalcopy(ret);
6932 if (!SvAMAGIC(ret)) {
6936 if (SvTYPE(sv) == SVt_REGEXP)
6937 re_sv = (REGEXP*) sv;
6938 else if (SvSMAGICAL(ret)) {
6939 MAGIC *mg = mg_find(ret, PERL_MAGIC_qr);
6941 re_sv = (REGEXP *) mg->mg_obj;
6944 /* force any undef warnings here */
6945 if (!re_sv && !SvPOK(ret) && !SvNIOK(ret)) {
6946 ret = sv_mortalcopy(ret);
6947 (void) SvPV_force_nolen(ret);
6953 /* *** Note that at this point we don't restore
6954 * PL_comppad, (or pop the CxSUB) on the assumption it may
6955 * be used again soon. This is safe as long as nothing
6956 * in the regexp code uses the pad ! */
6958 PL_curcop = ocurcop;
6959 regcp_restore(rex, runops_cp, &maxopenparen);
6960 PL_curpm_under = PL_curpm;
6961 PL_curpm = PL_reg_curpm;
6967 /* only /(??{})/ from now on */
6970 /* extract RE object from returned value; compiling if
6974 re_sv = reg_temp_copy(NULL, re_sv);
6979 if (SvUTF8(ret) && IN_BYTES) {
6980 /* In use 'bytes': make a copy of the octet
6981 * sequence, but without the flag on */
6983 const char *const p = SvPV(ret, len);
6984 ret = newSVpvn_flags(p, len, SVs_TEMP);
6986 if (rex->intflags & PREGf_USE_RE_EVAL)
6987 pm_flags |= PMf_USE_RE_EVAL;
6989 /* if we got here, it should be an engine which
6990 * supports compiling code blocks and stuff */
6991 assert(rex->engine && rex->engine->op_comp);
6992 assert(!(scan->flags & ~RXf_PMf_COMPILETIME));
6993 re_sv = rex->engine->op_comp(aTHX_ &ret, 1, NULL,
6994 rex->engine, NULL, NULL,
6995 /* copy /msixn etc to inner pattern */
7000 & (SVs_TEMP | SVs_GMG | SVf_ROK))
7001 && (!SvPADTMP(ret) || SvREADONLY(ret))) {
7002 /* This isn't a first class regexp. Instead, it's
7003 caching a regexp onto an existing, Perl visible
7005 sv_magic(ret, MUTABLE_SV(re_sv), PERL_MAGIC_qr, 0, 0);
7011 RXp_MATCH_COPIED_off(re);
7012 re->subbeg = rex->subbeg;
7013 re->sublen = rex->sublen;
7014 re->suboffset = rex->suboffset;
7015 re->subcoffset = rex->subcoffset;
7017 re->lastcloseparen = 0;
7020 debug_start_match(re_sv, utf8_target, locinput,
7021 reginfo->strend, "Matching embedded");
7023 startpoint = rei->program + 1;
7024 EVAL_CLOSE_PAREN_CLEAR(st); /* ST.close_paren = 0;
7025 * close_paren only for GOSUB */
7026 ST.prev_recurse_locinput= NULL; /* only used for GOSUB */
7027 /* Save all the seen positions so far. */
7028 ST.cp = regcppush(rex, 0, maxopenparen);
7029 REGCP_SET(ST.lastcp);
7030 /* and set maxopenparen to 0, since we are starting a "fresh" match */
7032 /* run the pattern returned from (??{...}) */
7034 eval_recurse_doit: /* Share code with GOSUB below this line
7035 * At this point we expect the stack context to be
7036 * set up correctly */
7038 /* invalidate the S-L poscache. We're now executing a
7039 * different set of WHILEM ops (and their associated
7040 * indexes) against the same string, so the bits in the
7041 * cache are meaningless. Setting maxiter to zero forces
7042 * the cache to be invalidated and zeroed before reuse.
7043 * XXX This is too dramatic a measure. Ideally we should
7044 * save the old cache and restore when running the outer
7046 reginfo->poscache_maxiter = 0;
7048 /* the new regexp might have a different is_utf8_pat than we do */
7049 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(re_sv));
7051 ST.prev_rex = rex_sv;
7052 ST.prev_curlyx = cur_curlyx;
7054 SET_reg_curpm(rex_sv);
7059 ST.prev_eval = cur_eval;
7061 /* now continue from first node in postoned RE */
7062 PUSH_YES_STATE_GOTO(EVAL_AB, startpoint, locinput);
7063 NOT_REACHED; /* NOTREACHED */
7066 case EVAL_AB: /* cleanup after a successful (??{A})B */
7067 /* note: this is called twice; first after popping B, then A */
7069 Perl_re_exec_indentf( aTHX_ "EVAL_AB cur_eval=%p prev_eval=%p\n",
7070 depth, cur_eval, ST.prev_eval);
7073 #define SET_RECURSE_LOCINPUT(STR,VAL)\
7074 if ( cur_eval && CUR_EVAL.close_paren ) {\
7076 Perl_re_exec_indentf( aTHX_ STR " GOSUB%d ce=%p recurse_locinput=%p\n",\
7078 CUR_EVAL.close_paren - 1,\
7082 rex->recurse_locinput[CUR_EVAL.close_paren - 1] = VAL;\
7085 SET_RECURSE_LOCINPUT("EVAL_AB[before]", CUR_EVAL.prev_recurse_locinput);
7087 rex_sv = ST.prev_rex;
7088 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
7089 SET_reg_curpm(rex_sv);
7090 rex = ReANY(rex_sv);
7091 rexi = RXi_GET(rex);
7093 /* preserve $^R across LEAVE's. See Bug 121070. */
7094 SV *save_sv= GvSV(PL_replgv);
7095 SvREFCNT_inc(save_sv);
7096 regcpblow(ST.cp); /* LEAVE in disguise */
7097 sv_setsv(GvSV(PL_replgv), save_sv);
7098 SvREFCNT_dec(save_sv);
7100 cur_eval = ST.prev_eval;
7101 cur_curlyx = ST.prev_curlyx;
7103 /* Invalidate cache. See "invalidate" comment above. */
7104 reginfo->poscache_maxiter = 0;
7105 if ( nochange_depth )
7108 SET_RECURSE_LOCINPUT("EVAL_AB[after]", cur_eval->locinput);
7112 case EVAL_AB_fail: /* unsuccessfully ran A or B in (??{A})B */
7113 /* note: this is called twice; first after popping B, then A */
7115 Perl_re_exec_indentf( aTHX_ "EVAL_AB_fail cur_eval=%p prev_eval=%p\n",
7116 depth, cur_eval, ST.prev_eval);
7119 SET_RECURSE_LOCINPUT("EVAL_AB_fail[before]", CUR_EVAL.prev_recurse_locinput);
7121 rex_sv = ST.prev_rex;
7122 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
7123 SET_reg_curpm(rex_sv);
7124 rex = ReANY(rex_sv);
7125 rexi = RXi_GET(rex);
7127 REGCP_UNWIND(ST.lastcp);
7128 regcppop(rex, &maxopenparen);
7129 cur_eval = ST.prev_eval;
7130 cur_curlyx = ST.prev_curlyx;
7132 /* Invalidate cache. See "invalidate" comment above. */
7133 reginfo->poscache_maxiter = 0;
7134 if ( nochange_depth )
7137 SET_RECURSE_LOCINPUT("EVAL_AB_fail[after]", cur_eval->locinput);
7142 n = ARG(scan); /* which paren pair */
7143 rex->offs[n].start_tmp = locinput - reginfo->strbeg;
7144 if (n > maxopenparen)
7146 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_
7147 "rex=0x%" UVxf " offs=0x%" UVxf ": \\%" UVuf ": set %" IVdf " tmp; maxopenparen=%" UVuf "\n",
7152 (IV)rex->offs[n].start_tmp,
7158 /* XXX really need to log other places start/end are set too */
7159 #define CLOSE_CAPTURE \
7160 rex->offs[n].start = rex->offs[n].start_tmp; \
7161 rex->offs[n].end = locinput - reginfo->strbeg; \
7162 DEBUG_BUFFERS_r(Perl_re_exec_indentf( aTHX_ \
7163 "rex=0x%" UVxf " offs=0x%" UVxf ": \\%" UVuf ": set %" IVdf "..%" IVdf "\n", \
7166 PTR2UV(rex->offs), \
7168 (IV)rex->offs[n].start, \
7169 (IV)rex->offs[n].end \
7173 n = ARG(scan); /* which paren pair */
7175 if (n > rex->lastparen)
7177 rex->lastcloseparen = n;
7178 if ( EVAL_CLOSE_PAREN_IS( cur_eval, n ) )
7183 case ACCEPT: /* (*ACCEPT) */
7185 sv_yes_mark = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
7189 cursor && OP(cursor)!=END;
7190 cursor=regnext(cursor))
7192 if ( OP(cursor)==CLOSE ){
7194 if ( n <= lastopen ) {
7196 if (n > rex->lastparen)
7198 rex->lastcloseparen = n;
7199 if ( n == ARG(scan) || EVAL_CLOSE_PAREN_IS(cur_eval, n) )
7208 case GROUPP: /* (?(1)) */
7209 n = ARG(scan); /* which paren pair */
7210 sw = cBOOL(rex->lastparen >= n && rex->offs[n].end != -1);
7213 case NGROUPP: /* (?(<name>)) */
7214 /* reg_check_named_buff_matched returns 0 for no match */
7215 sw = cBOOL(0 < reg_check_named_buff_matched(rex,scan));
7218 case INSUBP: /* (?(R)) */
7220 /* this does not need to use EVAL_CLOSE_PAREN macros, as the arg
7221 * of SCAN is already set up as matches a eval.close_paren */
7222 sw = cur_eval && (n == 0 || CUR_EVAL.close_paren == n);
7225 case DEFINEP: /* (?(DEFINE)) */
7229 case IFTHEN: /* (?(cond)A|B) */
7230 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
7232 next = NEXTOPER(NEXTOPER(scan));
7234 next = scan + ARG(scan);
7235 if (OP(next) == IFTHEN) /* Fake one. */
7236 next = NEXTOPER(NEXTOPER(next));
7240 case LOGICAL: /* modifier for EVAL and IFMATCH */
7241 logical = scan->flags;
7244 /*******************************************************************
7246 The CURLYX/WHILEM pair of ops handle the most generic case of the /A*B/
7247 pattern, where A and B are subpatterns. (For simple A, CURLYM or
7248 STAR/PLUS/CURLY/CURLYN are used instead.)
7250 A*B is compiled as <CURLYX><A><WHILEM><B>
7252 On entry to the subpattern, CURLYX is called. This pushes a CURLYX
7253 state, which contains the current count, initialised to -1. It also sets
7254 cur_curlyx to point to this state, with any previous value saved in the
7257 CURLYX then jumps straight to the WHILEM op, rather than executing A,
7258 since the pattern may possibly match zero times (i.e. it's a while {} loop
7259 rather than a do {} while loop).
7261 Each entry to WHILEM represents a successful match of A. The count in the
7262 CURLYX block is incremented, another WHILEM state is pushed, and execution
7263 passes to A or B depending on greediness and the current count.
7265 For example, if matching against the string a1a2a3b (where the aN are
7266 substrings that match /A/), then the match progresses as follows: (the
7267 pushed states are interspersed with the bits of strings matched so far):
7270 <CURLYX cnt=0><WHILEM>
7271 <CURLYX cnt=1><WHILEM> a1 <WHILEM>
7272 <CURLYX cnt=2><WHILEM> a1 <WHILEM> a2 <WHILEM>
7273 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM>
7274 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM> b
7276 (Contrast this with something like CURLYM, which maintains only a single
7280 a1 <CURLYM cnt=1> a2
7281 a1 a2 <CURLYM cnt=2> a3
7282 a1 a2 a3 <CURLYM cnt=3> b
7285 Each WHILEM state block marks a point to backtrack to upon partial failure
7286 of A or B, and also contains some minor state data related to that
7287 iteration. The CURLYX block, pointed to by cur_curlyx, contains the
7288 overall state, such as the count, and pointers to the A and B ops.
7290 This is complicated slightly by nested CURLYX/WHILEM's. Since cur_curlyx
7291 must always point to the *current* CURLYX block, the rules are:
7293 When executing CURLYX, save the old cur_curlyx in the CURLYX state block,
7294 and set cur_curlyx to point the new block.
7296 When popping the CURLYX block after a successful or unsuccessful match,
7297 restore the previous cur_curlyx.
7299 When WHILEM is about to execute B, save the current cur_curlyx, and set it
7300 to the outer one saved in the CURLYX block.
7302 When popping the WHILEM block after a successful or unsuccessful B match,
7303 restore the previous cur_curlyx.
7305 Here's an example for the pattern (AI* BI)*BO
7306 I and O refer to inner and outer, C and W refer to CURLYX and WHILEM:
7309 curlyx backtrack stack
7310 ------ ---------------
7312 CO <CO prev=NULL> <WO>
7313 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
7314 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
7315 NULL <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi <WO prev=CO> bo
7317 At this point the pattern succeeds, and we work back down the stack to
7318 clean up, restoring as we go:
7320 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
7321 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
7322 CO <CO prev=NULL> <WO>
7325 *******************************************************************/
7327 #define ST st->u.curlyx
7329 case CURLYX: /* start of /A*B/ (for complex A) */
7331 /* No need to save/restore up to this paren */
7332 I32 parenfloor = scan->flags;
7334 assert(next); /* keep Coverity happy */
7335 if (OP(PREVOPER(next)) == NOTHING) /* LONGJMP */
7338 /* XXXX Probably it is better to teach regpush to support
7339 parenfloor > maxopenparen ... */
7340 if (parenfloor > (I32)rex->lastparen)
7341 parenfloor = rex->lastparen; /* Pessimization... */
7343 ST.prev_curlyx= cur_curlyx;
7345 ST.cp = PL_savestack_ix;
7347 /* these fields contain the state of the current curly.
7348 * they are accessed by subsequent WHILEMs */
7349 ST.parenfloor = parenfloor;
7354 ST.count = -1; /* this will be updated by WHILEM */
7355 ST.lastloc = NULL; /* this will be updated by WHILEM */
7357 PUSH_YES_STATE_GOTO(CURLYX_end, PREVOPER(next), locinput);
7358 NOT_REACHED; /* NOTREACHED */
7361 case CURLYX_end: /* just finished matching all of A*B */
7362 cur_curlyx = ST.prev_curlyx;
7364 NOT_REACHED; /* NOTREACHED */
7366 case CURLYX_end_fail: /* just failed to match all of A*B */
7368 cur_curlyx = ST.prev_curlyx;
7370 NOT_REACHED; /* NOTREACHED */
7374 #define ST st->u.whilem
7376 case WHILEM: /* just matched an A in /A*B/ (for complex A) */
7378 /* see the discussion above about CURLYX/WHILEM */
7383 assert(cur_curlyx); /* keep Coverity happy */
7385 min = ARG1(cur_curlyx->u.curlyx.me);
7386 max = ARG2(cur_curlyx->u.curlyx.me);
7387 A = NEXTOPER(cur_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS;
7388 n = ++cur_curlyx->u.curlyx.count; /* how many A's matched */
7389 ST.save_lastloc = cur_curlyx->u.curlyx.lastloc;
7390 ST.cache_offset = 0;
7394 DEBUG_EXECUTE_r( Perl_re_exec_indentf( aTHX_ "whilem: matched %ld out of %d..%d\n",
7395 depth, (long)n, min, max)
7398 /* First just match a string of min A's. */
7401 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor, maxopenparen);
7402 cur_curlyx->u.curlyx.lastloc = locinput;
7403 REGCP_SET(ST.lastcp);
7405 PUSH_STATE_GOTO(WHILEM_A_pre, A, locinput);
7406 NOT_REACHED; /* NOTREACHED */
7409 /* If degenerate A matches "", assume A done. */
7411 if (locinput == cur_curlyx->u.curlyx.lastloc) {
7412 DEBUG_EXECUTE_r( Perl_re_exec_indentf( aTHX_ "whilem: empty match detected, trying continuation...\n",
7415 goto do_whilem_B_max;
7418 /* super-linear cache processing.
7420 * The idea here is that for certain types of CURLYX/WHILEM -
7421 * principally those whose upper bound is infinity (and
7422 * excluding regexes that have things like \1 and other very
7423 * non-regular expresssiony things), then if a pattern like
7424 * /....A*.../ fails and we backtrack to the WHILEM, then we
7425 * make a note that this particular WHILEM op was at string
7426 * position 47 (say) when the rest of pattern failed. Then, if
7427 * we ever find ourselves back at that WHILEM, and at string
7428 * position 47 again, we can just fail immediately rather than
7429 * running the rest of the pattern again.
7431 * This is very handy when patterns start to go
7432 * 'super-linear', like in (a+)*(a+)*(a+)*, where you end up
7433 * with a combinatorial explosion of backtracking.
7435 * The cache is implemented as a bit array, with one bit per
7436 * string byte position per WHILEM op (up to 16) - so its
7437 * between 0.25 and 2x the string size.
7439 * To avoid allocating a poscache buffer every time, we do an
7440 * initially countdown; only after we have executed a WHILEM
7441 * op (string-length x #WHILEMs) times do we allocate the
7444 * The top 4 bits of scan->flags byte say how many different
7445 * relevant CURLLYX/WHILEM op pairs there are, while the
7446 * bottom 4-bits is the identifying index number of this
7452 if (!reginfo->poscache_maxiter) {
7453 /* start the countdown: Postpone detection until we
7454 * know the match is not *that* much linear. */
7455 reginfo->poscache_maxiter
7456 = (reginfo->strend - reginfo->strbeg + 1)
7458 /* possible overflow for long strings and many CURLYX's */
7459 if (reginfo->poscache_maxiter < 0)
7460 reginfo->poscache_maxiter = I32_MAX;
7461 reginfo->poscache_iter = reginfo->poscache_maxiter;
7464 if (reginfo->poscache_iter-- == 0) {
7465 /* initialise cache */
7466 const SSize_t size = (reginfo->poscache_maxiter + 7)/8;
7467 regmatch_info_aux *const aux = reginfo->info_aux;
7468 if (aux->poscache) {
7469 if ((SSize_t)reginfo->poscache_size < size) {
7470 Renew(aux->poscache, size, char);
7471 reginfo->poscache_size = size;
7473 Zero(aux->poscache, size, char);
7476 reginfo->poscache_size = size;
7477 Newxz(aux->poscache, size, char);
7479 DEBUG_EXECUTE_r( Perl_re_printf( aTHX_
7480 "%swhilem: Detected a super-linear match, switching on caching%s...\n",
7481 PL_colors[4], PL_colors[5])
7485 if (reginfo->poscache_iter < 0) {
7486 /* have we already failed at this position? */
7487 SSize_t offset, mask;
7489 reginfo->poscache_iter = -1; /* stop eventual underflow */
7490 offset = (scan->flags & 0xf) - 1
7491 + (locinput - reginfo->strbeg)
7493 mask = 1 << (offset % 8);
7495 if (reginfo->info_aux->poscache[offset] & mask) {
7496 DEBUG_EXECUTE_r( Perl_re_exec_indentf( aTHX_ "whilem: (cache) already tried at this position...\n",
7499 cur_curlyx->u.curlyx.count--;
7500 sayNO; /* cache records failure */
7502 ST.cache_offset = offset;
7503 ST.cache_mask = mask;
7507 /* Prefer B over A for minimal matching. */
7509 if (cur_curlyx->u.curlyx.minmod) {
7510 ST.save_curlyx = cur_curlyx;
7511 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
7512 ST.cp = regcppush(rex, ST.save_curlyx->u.curlyx.parenfloor,
7514 REGCP_SET(ST.lastcp);
7515 PUSH_YES_STATE_GOTO(WHILEM_B_min, ST.save_curlyx->u.curlyx.B,
7517 NOT_REACHED; /* NOTREACHED */
7520 /* Prefer A over B for maximal matching. */
7522 if (n < max) { /* More greed allowed? */
7523 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
7525 cur_curlyx->u.curlyx.lastloc = locinput;
7526 REGCP_SET(ST.lastcp);
7527 PUSH_STATE_GOTO(WHILEM_A_max, A, locinput);
7528 NOT_REACHED; /* NOTREACHED */
7530 goto do_whilem_B_max;
7532 NOT_REACHED; /* NOTREACHED */
7534 case WHILEM_B_min: /* just matched B in a minimal match */
7535 case WHILEM_B_max: /* just matched B in a maximal match */
7536 cur_curlyx = ST.save_curlyx;
7538 NOT_REACHED; /* NOTREACHED */
7540 case WHILEM_B_max_fail: /* just failed to match B in a maximal match */
7541 cur_curlyx = ST.save_curlyx;
7542 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
7543 cur_curlyx->u.curlyx.count--;
7545 NOT_REACHED; /* NOTREACHED */
7547 case WHILEM_A_min_fail: /* just failed to match A in a minimal match */
7549 case WHILEM_A_pre_fail: /* just failed to match even minimal A */
7550 REGCP_UNWIND(ST.lastcp);
7551 regcppop(rex, &maxopenparen);
7552 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
7553 cur_curlyx->u.curlyx.count--;
7555 NOT_REACHED; /* NOTREACHED */
7557 case WHILEM_A_max_fail: /* just failed to match A in a maximal match */
7558 REGCP_UNWIND(ST.lastcp);
7559 regcppop(rex, &maxopenparen); /* Restore some previous $<digit>s? */
7560 DEBUG_EXECUTE_r(Perl_re_exec_indentf( aTHX_ "whilem: failed, trying continuation...\n",
7564 if (cur_curlyx->u.curlyx.count >= REG_INFTY
7565 && ckWARN(WARN_REGEXP)
7566 && !reginfo->warned)
7568 reginfo->warned = TRUE;
7569 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
7570 "Complex regular subexpression recursion limit (%d) "
7576 ST.save_curlyx = cur_curlyx;
7577 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
7578 PUSH_YES_STATE_GOTO(WHILEM_B_max, ST.save_curlyx->u.curlyx.B,
7580 NOT_REACHED; /* NOTREACHED */
7582 case WHILEM_B_min_fail: /* just failed to match B in a minimal match */
7583 cur_curlyx = ST.save_curlyx;
7584 REGCP_UNWIND(ST.lastcp);
7585 regcppop(rex, &maxopenparen);
7587 if (cur_curlyx->u.curlyx.count >= /*max*/ARG2(cur_curlyx->u.curlyx.me)) {
7588 /* Maximum greed exceeded */
7589 if (cur_curlyx->u.curlyx.count >= REG_INFTY
7590 && ckWARN(WARN_REGEXP)
7591 && !reginfo->warned)
7593 reginfo->warned = TRUE;
7594 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
7595 "Complex regular subexpression recursion "
7596 "limit (%d) exceeded",
7599 cur_curlyx->u.curlyx.count--;
7603 DEBUG_EXECUTE_r(Perl_re_exec_indentf( aTHX_ "trying longer...\n", depth)
7605 /* Try grabbing another A and see if it helps. */
7606 cur_curlyx->u.curlyx.lastloc = locinput;
7607 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
7609 REGCP_SET(ST.lastcp);
7610 PUSH_STATE_GOTO(WHILEM_A_min,
7611 /*A*/ NEXTOPER(ST.save_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS,
7613 NOT_REACHED; /* NOTREACHED */
7616 #define ST st->u.branch
7618 case BRANCHJ: /* /(...|A|...)/ with long next pointer */
7619 next = scan + ARG(scan);
7622 scan = NEXTOPER(scan);
7625 case BRANCH: /* /(...|A|...)/ */
7626 scan = NEXTOPER(scan); /* scan now points to inner node */
7627 ST.lastparen = rex->lastparen;
7628 ST.lastcloseparen = rex->lastcloseparen;
7629 ST.next_branch = next;
7632 /* Now go into the branch */
7634 PUSH_YES_STATE_GOTO(BRANCH_next, scan, locinput);
7636 PUSH_STATE_GOTO(BRANCH_next, scan, locinput);
7638 NOT_REACHED; /* NOTREACHED */
7640 case CUTGROUP: /* /(*THEN)/ */
7641 sv_yes_mark = st->u.mark.mark_name = scan->flags
7642 ? MUTABLE_SV(rexi->data->data[ ARG( scan ) ])
7644 PUSH_STATE_GOTO(CUTGROUP_next, next, locinput);
7645 NOT_REACHED; /* NOTREACHED */
7647 case CUTGROUP_next_fail:
7650 if (st->u.mark.mark_name)
7651 sv_commit = st->u.mark.mark_name;
7653 NOT_REACHED; /* NOTREACHED */
7657 NOT_REACHED; /* NOTREACHED */
7659 case BRANCH_next_fail: /* that branch failed; try the next, if any */
7664 REGCP_UNWIND(ST.cp);
7665 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7666 scan = ST.next_branch;
7667 /* no more branches? */
7668 if (!scan || (OP(scan) != BRANCH && OP(scan) != BRANCHJ)) {
7670 Perl_re_exec_indentf( aTHX_ "%sBRANCH failed...%s\n",
7677 continue; /* execute next BRANCH[J] op */
7680 case MINMOD: /* next op will be non-greedy, e.g. A*? */
7685 #define ST st->u.curlym
7687 case CURLYM: /* /A{m,n}B/ where A is fixed-length */
7689 /* This is an optimisation of CURLYX that enables us to push
7690 * only a single backtracking state, no matter how many matches
7691 * there are in {m,n}. It relies on the pattern being constant
7692 * length, with no parens to influence future backrefs
7696 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
7698 ST.lastparen = rex->lastparen;
7699 ST.lastcloseparen = rex->lastcloseparen;
7701 /* if paren positive, emulate an OPEN/CLOSE around A */
7703 U32 paren = ST.me->flags;
7704 if (paren > maxopenparen)
7705 maxopenparen = paren;
7706 scan += NEXT_OFF(scan); /* Skip former OPEN. */
7714 ST.c1 = CHRTEST_UNINIT;
7717 if (!(ST.minmod ? ARG1(ST.me) : ARG2(ST.me))) /* min/max */
7720 curlym_do_A: /* execute the A in /A{m,n}B/ */
7721 PUSH_YES_STATE_GOTO(CURLYM_A, ST.A, locinput); /* match A */
7722 NOT_REACHED; /* NOTREACHED */
7724 case CURLYM_A: /* we've just matched an A */
7726 /* after first match, determine A's length: u.curlym.alen */
7727 if (ST.count == 1) {
7728 if (reginfo->is_utf8_target) {
7729 char *s = st->locinput;
7730 while (s < locinput) {
7736 ST.alen = locinput - st->locinput;
7739 ST.count = ST.minmod ? ARG1(ST.me) : ARG2(ST.me);
7742 Perl_re_exec_indentf( aTHX_ "CURLYM now matched %" IVdf " times, len=%" IVdf "...\n",
7743 depth, (IV) ST.count, (IV)ST.alen)
7746 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.me->flags))
7750 I32 max = (ST.minmod ? ARG1(ST.me) : ARG2(ST.me));
7751 if ( max == REG_INFTY || ST.count < max )
7752 goto curlym_do_A; /* try to match another A */
7754 goto curlym_do_B; /* try to match B */
7756 case CURLYM_A_fail: /* just failed to match an A */
7757 REGCP_UNWIND(ST.cp);
7760 if (ST.minmod || ST.count < ARG1(ST.me) /* min*/
7761 || EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.me->flags))
7764 curlym_do_B: /* execute the B in /A{m,n}B/ */
7765 if (ST.c1 == CHRTEST_UNINIT) {
7766 /* calculate c1 and c2 for possible match of 1st char
7767 * following curly */
7768 ST.c1 = ST.c2 = CHRTEST_VOID;
7770 if (HAS_TEXT(ST.B) || JUMPABLE(ST.B)) {
7771 regnode *text_node = ST.B;
7772 if (! HAS_TEXT(text_node))
7773 FIND_NEXT_IMPT(text_node);
7776 (HAS_TEXT(text_node) && PL_regkind[OP(text_node)] == EXACT)
7778 But the former is redundant in light of the latter.
7780 if this changes back then the macro for
7781 IS_TEXT and friends need to change.
7783 if (PL_regkind[OP(text_node)] == EXACT) {
7784 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
7785 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
7795 Perl_re_exec_indentf( aTHX_ "CURLYM trying tail with matches=%" IVdf "...\n",
7796 depth, (IV)ST.count)
7798 if (! NEXTCHR_IS_EOS && ST.c1 != CHRTEST_VOID) {
7799 if (! UTF8_IS_INVARIANT(nextchr) && utf8_target) {
7800 if (memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
7801 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
7803 /* simulate B failing */
7805 Perl_re_exec_indentf( aTHX_ "CURLYM Fast bail next target=0x%" UVXf " c1=0x%" UVXf " c2=0x%" UVXf "\n",
7807 valid_utf8_to_uvchr((U8 *) locinput, NULL),
7808 valid_utf8_to_uvchr(ST.c1_utf8, NULL),
7809 valid_utf8_to_uvchr(ST.c2_utf8, NULL))
7811 state_num = CURLYM_B_fail;
7812 goto reenter_switch;
7815 else if (nextchr != ST.c1 && nextchr != ST.c2) {
7816 /* simulate B failing */
7818 Perl_re_exec_indentf( aTHX_ "CURLYM Fast bail next target=0x%X c1=0x%X c2=0x%X\n",
7820 (int) nextchr, ST.c1, ST.c2)
7822 state_num = CURLYM_B_fail;
7823 goto reenter_switch;
7828 /* emulate CLOSE: mark current A as captured */
7829 I32 paren = ST.me->flags;
7831 rex->offs[paren].start
7832 = HOPc(locinput, -ST.alen) - reginfo->strbeg;
7833 rex->offs[paren].end = locinput - reginfo->strbeg;
7834 if ((U32)paren > rex->lastparen)
7835 rex->lastparen = paren;
7836 rex->lastcloseparen = paren;
7839 rex->offs[paren].end = -1;
7841 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.me->flags))
7850 PUSH_STATE_GOTO(CURLYM_B, ST.B, locinput); /* match B */
7851 NOT_REACHED; /* NOTREACHED */
7853 case CURLYM_B_fail: /* just failed to match a B */
7854 REGCP_UNWIND(ST.cp);
7855 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7857 I32 max = ARG2(ST.me);
7858 if (max != REG_INFTY && ST.count == max)
7860 goto curlym_do_A; /* try to match a further A */
7862 /* backtrack one A */
7863 if (ST.count == ARG1(ST.me) /* min */)
7866 SET_locinput(HOPc(locinput, -ST.alen));
7867 goto curlym_do_B; /* try to match B */
7870 #define ST st->u.curly
7872 #define CURLY_SETPAREN(paren, success) \
7875 rex->offs[paren].start = HOPc(locinput, -1) - reginfo->strbeg; \
7876 rex->offs[paren].end = locinput - reginfo->strbeg; \
7877 if (paren > rex->lastparen) \
7878 rex->lastparen = paren; \
7879 rex->lastcloseparen = paren; \
7882 rex->offs[paren].end = -1; \
7883 rex->lastparen = ST.lastparen; \
7884 rex->lastcloseparen = ST.lastcloseparen; \
7888 case STAR: /* /A*B/ where A is width 1 char */
7892 scan = NEXTOPER(scan);
7895 case PLUS: /* /A+B/ where A is width 1 char */
7899 scan = NEXTOPER(scan);
7902 case CURLYN: /* /(A){m,n}B/ where A is width 1 char */
7903 ST.paren = scan->flags; /* Which paren to set */
7904 ST.lastparen = rex->lastparen;
7905 ST.lastcloseparen = rex->lastcloseparen;
7906 if (ST.paren > maxopenparen)
7907 maxopenparen = ST.paren;
7908 ST.min = ARG1(scan); /* min to match */
7909 ST.max = ARG2(scan); /* max to match */
7910 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.paren))
7915 scan = regnext(NEXTOPER(scan) + NODE_STEP_REGNODE);
7918 case CURLY: /* /A{m,n}B/ where A is width 1 char */
7920 ST.min = ARG1(scan); /* min to match */
7921 ST.max = ARG2(scan); /* max to match */
7922 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
7925 * Lookahead to avoid useless match attempts
7926 * when we know what character comes next.
7928 * Used to only do .*x and .*?x, but now it allows
7929 * for )'s, ('s and (?{ ... })'s to be in the way
7930 * of the quantifier and the EXACT-like node. -- japhy
7933 assert(ST.min <= ST.max);
7934 if (! HAS_TEXT(next) && ! JUMPABLE(next)) {
7935 ST.c1 = ST.c2 = CHRTEST_VOID;
7938 regnode *text_node = next;
7940 if (! HAS_TEXT(text_node))
7941 FIND_NEXT_IMPT(text_node);
7943 if (! HAS_TEXT(text_node))
7944 ST.c1 = ST.c2 = CHRTEST_VOID;
7946 if ( PL_regkind[OP(text_node)] != EXACT ) {
7947 ST.c1 = ST.c2 = CHRTEST_VOID;
7951 /* Currently we only get here when
7953 PL_rekind[OP(text_node)] == EXACT
7955 if this changes back then the macro for IS_TEXT and
7956 friends need to change. */
7957 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
7958 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
7970 char *li = locinput;
7973 regrepeat(rex, &li, ST.A, reginfo, ST.min)
7979 if (ST.c1 == CHRTEST_VOID)
7980 goto curly_try_B_min;
7982 ST.oldloc = locinput;
7984 /* set ST.maxpos to the furthest point along the
7985 * string that could possibly match */
7986 if (ST.max == REG_INFTY) {
7987 ST.maxpos = reginfo->strend - 1;
7989 while (UTF8_IS_CONTINUATION(*(U8*)ST.maxpos))
7992 else if (utf8_target) {
7993 int m = ST.max - ST.min;
7994 for (ST.maxpos = locinput;
7995 m >0 && ST.maxpos < reginfo->strend; m--)
7996 ST.maxpos += UTF8SKIP(ST.maxpos);
7999 ST.maxpos = locinput + ST.max - ST.min;
8000 if (ST.maxpos >= reginfo->strend)
8001 ST.maxpos = reginfo->strend - 1;
8003 goto curly_try_B_min_known;
8007 /* avoid taking address of locinput, so it can remain
8009 char *li = locinput;
8010 ST.count = regrepeat(rex, &li, ST.A, reginfo, ST.max);
8011 if (ST.count < ST.min)
8014 if ((ST.count > ST.min)
8015 && (PL_regkind[OP(ST.B)] == EOL) && (OP(ST.B) != MEOL))
8017 /* A{m,n} must come at the end of the string, there's
8018 * no point in backing off ... */
8020 /* ...except that $ and \Z can match before *and* after
8021 newline at the end. Consider "\n\n" =~ /\n+\Z\n/.
8022 We may back off by one in this case. */
8023 if (UCHARAT(locinput - 1) == '\n' && OP(ST.B) != EOS)
8027 goto curly_try_B_max;
8029 NOT_REACHED; /* NOTREACHED */
8031 case CURLY_B_min_known_fail:
8032 /* failed to find B in a non-greedy match where c1,c2 valid */
8034 REGCP_UNWIND(ST.cp);
8036 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
8038 /* Couldn't or didn't -- move forward. */
8039 ST.oldloc = locinput;
8041 locinput += UTF8SKIP(locinput);
8045 curly_try_B_min_known:
8046 /* find the next place where 'B' could work, then call B */
8050 n = (ST.oldloc == locinput) ? 0 : 1;
8051 if (ST.c1 == ST.c2) {
8052 /* set n to utf8_distance(oldloc, locinput) */
8053 while (locinput <= ST.maxpos
8054 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput)))
8056 locinput += UTF8SKIP(locinput);
8061 /* set n to utf8_distance(oldloc, locinput) */
8062 while (locinput <= ST.maxpos
8063 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
8064 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
8066 locinput += UTF8SKIP(locinput);
8071 else { /* Not utf8_target */
8072 if (ST.c1 == ST.c2) {
8073 while (locinput <= ST.maxpos &&
8074 UCHARAT(locinput) != ST.c1)
8078 while (locinput <= ST.maxpos
8079 && UCHARAT(locinput) != ST.c1
8080 && UCHARAT(locinput) != ST.c2)
8083 n = locinput - ST.oldloc;
8085 if (locinput > ST.maxpos)
8088 /* In /a{m,n}b/, ST.oldloc is at "a" x m, locinput is
8089 * at b; check that everything between oldloc and
8090 * locinput matches */
8091 char *li = ST.oldloc;
8093 if (regrepeat(rex, &li, ST.A, reginfo, n) < n)
8095 assert(n == REG_INFTY || locinput == li);
8097 CURLY_SETPAREN(ST.paren, ST.count);
8098 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.paren))
8100 PUSH_STATE_GOTO(CURLY_B_min_known, ST.B, locinput);
8102 NOT_REACHED; /* NOTREACHED */
8104 case CURLY_B_min_fail:
8105 /* failed to find B in a non-greedy match where c1,c2 invalid */
8107 REGCP_UNWIND(ST.cp);
8109 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
8111 /* failed -- move forward one */
8113 char *li = locinput;
8114 if (!regrepeat(rex, &li, ST.A, reginfo, 1)) {
8121 if (ST.count <= ST.max || (ST.max == REG_INFTY &&
8122 ST.count > 0)) /* count overflow ? */
8125 CURLY_SETPAREN(ST.paren, ST.count);
8126 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.paren))
8128 PUSH_STATE_GOTO(CURLY_B_min, ST.B, locinput);
8132 NOT_REACHED; /* NOTREACHED */
8135 /* a successful greedy match: now try to match B */
8136 if (EVAL_CLOSE_PAREN_IS_TRUE(cur_eval,(U32)ST.paren))
8139 bool could_match = locinput < reginfo->strend;
8141 /* If it could work, try it. */
8142 if (ST.c1 != CHRTEST_VOID && could_match) {
8143 if (! UTF8_IS_INVARIANT(UCHARAT(locinput)) && utf8_target)
8145 could_match = memEQ(locinput,
8150 UTF8SKIP(locinput));
8153 could_match = UCHARAT(locinput) == ST.c1
8154 || UCHARAT(locinput) == ST.c2;
8157 if (ST.c1 == CHRTEST_VOID || could_match) {
8158 CURLY_SETPAREN(ST.paren, ST.count);
8159 PUSH_STATE_GOTO(CURLY_B_max, ST.B, locinput);
8160 NOT_REACHED; /* NOTREACHED */
8165 case CURLY_B_max_fail:
8166 /* failed to find B in a greedy match */
8168 REGCP_UNWIND(ST.cp);
8170 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
8173 if (--ST.count < ST.min)
8175 locinput = HOPc(locinput, -1);
8176 goto curly_try_B_max;
8180 case END: /* last op of main pattern */
8183 /* we've just finished A in /(??{A})B/; now continue with B */
8184 SET_RECURSE_LOCINPUT("FAKE-END[before]", CUR_EVAL.prev_recurse_locinput);
8185 st->u.eval.prev_rex = rex_sv; /* inner */
8187 /* Save *all* the positions. */
8188 st->u.eval.cp = regcppush(rex, 0, maxopenparen);
8189 rex_sv = CUR_EVAL.prev_rex;
8190 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
8191 SET_reg_curpm(rex_sv);
8192 rex = ReANY(rex_sv);
8193 rexi = RXi_GET(rex);
8195 st->u.eval.prev_curlyx = cur_curlyx;
8196 cur_curlyx = CUR_EVAL.prev_curlyx;
8198 REGCP_SET(st->u.eval.lastcp);
8200 /* Restore parens of the outer rex without popping the
8202 regcp_restore(rex, CUR_EVAL.lastcp, &maxopenparen);
8204 st->u.eval.prev_eval = cur_eval;
8205 cur_eval = CUR_EVAL.prev_eval;
8207 Perl_re_exec_indentf( aTHX_ "EVAL trying tail ... (cur_eval=%p)\n",
8209 if ( nochange_depth )
8212 SET_RECURSE_LOCINPUT("FAKE-END[after]", cur_eval->locinput);
8214 PUSH_YES_STATE_GOTO(EVAL_AB, st->u.eval.prev_eval->u.eval.B,
8215 locinput); /* match B */
8218 if (locinput < reginfo->till) {
8219 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_
8220 "%sMatch possible, but length=%ld is smaller than requested=%ld, failing!%s\n",
8222 (long)(locinput - startpos),
8223 (long)(reginfo->till - startpos),
8226 sayNO_SILENT; /* Cannot match: too short. */
8228 sayYES; /* Success! */
8230 case SUCCEED: /* successful SUSPEND/UNLESSM/IFMATCH/CURLYM */
8232 Perl_re_exec_indentf( aTHX_ "%ssubpattern success...%s\n",
8233 depth, PL_colors[4], PL_colors[5]));
8234 sayYES; /* Success! */
8237 #define ST st->u.ifmatch
8242 case SUSPEND: /* (?>A) */
8244 newstart = locinput;
8247 case UNLESSM: /* -ve lookaround: (?!A), or with flags, (?<!A) */
8249 goto ifmatch_trivial_fail_test;
8251 case IFMATCH: /* +ve lookaround: (?=A), or with flags, (?<=A) */
8253 ifmatch_trivial_fail_test:
8255 char * const s = HOPBACKc(locinput, scan->flags);
8260 sw = 1 - cBOOL(ST.wanted);
8264 next = scan + ARG(scan);
8272 newstart = locinput;
8276 ST.logical = logical;
8277 logical = 0; /* XXX: reset state of logical once it has been saved into ST */
8279 /* execute body of (?...A) */
8280 PUSH_YES_STATE_GOTO(IFMATCH_A, NEXTOPER(NEXTOPER(scan)), newstart);
8281 NOT_REACHED; /* NOTREACHED */
8284 case IFMATCH_A_fail: /* body of (?...A) failed */
8285 ST.wanted = !ST.wanted;
8288 case IFMATCH_A: /* body of (?...A) succeeded */
8290 sw = cBOOL(ST.wanted);
8292 else if (!ST.wanted)
8295 if (OP(ST.me) != SUSPEND) {
8296 /* restore old position except for (?>...) */
8297 locinput = st->locinput;
8299 scan = ST.me + ARG(ST.me);
8302 continue; /* execute B */
8306 case LONGJMP: /* alternative with many branches compiles to
8307 * (BRANCHJ; EXACT ...; LONGJMP ) x N */
8308 next = scan + ARG(scan);
8313 case COMMIT: /* (*COMMIT) */
8314 reginfo->cutpoint = reginfo->strend;
8317 case PRUNE: /* (*PRUNE) */
8319 sv_yes_mark = sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8320 PUSH_STATE_GOTO(COMMIT_next, next, locinput);
8321 NOT_REACHED; /* NOTREACHED */
8323 case COMMIT_next_fail:
8327 NOT_REACHED; /* NOTREACHED */
8329 case OPFAIL: /* (*FAIL) */
8331 sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8333 /* deal with (?(?!)X|Y) properly,
8334 * make sure we trigger the no branch
8335 * of the trailing IFTHEN structure*/
8341 NOT_REACHED; /* NOTREACHED */
8343 #define ST st->u.mark
8344 case MARKPOINT: /* (*MARK:foo) */
8345 ST.prev_mark = mark_state;
8346 ST.mark_name = sv_commit = sv_yes_mark
8347 = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8349 ST.mark_loc = locinput;
8350 PUSH_YES_STATE_GOTO(MARKPOINT_next, next, locinput);
8351 NOT_REACHED; /* NOTREACHED */
8353 case MARKPOINT_next:
8354 mark_state = ST.prev_mark;
8356 NOT_REACHED; /* NOTREACHED */
8358 case MARKPOINT_next_fail:
8359 if (popmark && sv_eq(ST.mark_name,popmark))
8361 if (ST.mark_loc > startpoint)
8362 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
8363 popmark = NULL; /* we found our mark */
8364 sv_commit = ST.mark_name;
8367 Perl_re_exec_indentf( aTHX_ "%ssetting cutpoint to mark:%" SVf "...%s\n",
8369 PL_colors[4], SVfARG(sv_commit), PL_colors[5]);
8372 mark_state = ST.prev_mark;
8373 sv_yes_mark = mark_state ?
8374 mark_state->u.mark.mark_name : NULL;
8376 NOT_REACHED; /* NOTREACHED */
8378 case SKIP: /* (*SKIP) */
8380 /* (*SKIP) : if we fail we cut here*/
8381 ST.mark_name = NULL;
8382 ST.mark_loc = locinput;
8383 PUSH_STATE_GOTO(SKIP_next,next, locinput);
8385 /* (*SKIP:NAME) : if there is a (*MARK:NAME) fail where it was,
8386 otherwise do nothing. Meaning we need to scan
8388 regmatch_state *cur = mark_state;
8389 SV *find = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8392 if ( sv_eq( cur->u.mark.mark_name,
8395 ST.mark_name = find;
8396 PUSH_STATE_GOTO( SKIP_next, next, locinput);
8398 cur = cur->u.mark.prev_mark;
8401 /* Didn't find our (*MARK:NAME) so ignore this (*SKIP:NAME) */
8404 case SKIP_next_fail:
8406 /* (*CUT:NAME) - Set up to search for the name as we
8407 collapse the stack*/
8408 popmark = ST.mark_name;
8410 /* (*CUT) - No name, we cut here.*/
8411 if (ST.mark_loc > startpoint)
8412 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
8413 /* but we set sv_commit to latest mark_name if there
8414 is one so they can test to see how things lead to this
8417 sv_commit=mark_state->u.mark.mark_name;
8421 NOT_REACHED; /* NOTREACHED */
8424 case LNBREAK: /* \R */
8425 if ((n=is_LNBREAK_safe(locinput, reginfo->strend, utf8_target))) {
8432 PerlIO_printf(Perl_error_log, "%" UVxf " %d\n",
8433 PTR2UV(scan), OP(scan));
8434 Perl_croak(aTHX_ "regexp memory corruption");
8436 /* this is a point to jump to in order to increment
8437 * locinput by one character */
8439 assert(!NEXTCHR_IS_EOS);
8441 locinput += PL_utf8skip[nextchr];
8442 /* locinput is allowed to go 1 char off the end, but not 2+ */
8443 if (locinput > reginfo->strend)
8452 /* switch break jumps here */
8453 scan = next; /* prepare to execute the next op and ... */
8454 continue; /* ... jump back to the top, reusing st */
8458 /* push a state that backtracks on success */
8459 st->u.yes.prev_yes_state = yes_state;
8463 /* push a new regex state, then continue at scan */
8465 regmatch_state *newst;
8468 regmatch_state *cur = st;
8469 regmatch_state *curyes = yes_state;
8471 regmatch_slab *slab = PL_regmatch_slab;
8472 for (;curd > -1 && (depth-curd < 3);cur--,curd--) {
8473 if (cur < SLAB_FIRST(slab)) {
8475 cur = SLAB_LAST(slab);
8477 Perl_re_exec_indentf( aTHX_ "#%-3d %-10s %s\n",
8479 curd, PL_reg_name[cur->resume_state],
8480 (curyes == cur) ? "yes" : ""
8483 curyes = cur->u.yes.prev_yes_state;
8486 DEBUG_STATE_pp("push")
8489 st->locinput = locinput;
8491 if (newst > SLAB_LAST(PL_regmatch_slab))
8492 newst = S_push_slab(aTHX);
8493 PL_regmatch_state = newst;
8495 locinput = pushinput;
8501 #ifdef SOLARIS_BAD_OPTIMIZER
8502 # undef PL_charclass
8506 * We get here only if there's trouble -- normally "case END" is
8507 * the terminating point.
8509 Perl_croak(aTHX_ "corrupted regexp pointers");
8510 NOT_REACHED; /* NOTREACHED */
8514 /* we have successfully completed a subexpression, but we must now
8515 * pop to the state marked by yes_state and continue from there */
8516 assert(st != yes_state);
8518 while (st != yes_state) {
8520 if (st < SLAB_FIRST(PL_regmatch_slab)) {
8521 PL_regmatch_slab = PL_regmatch_slab->prev;
8522 st = SLAB_LAST(PL_regmatch_slab);
8526 DEBUG_STATE_pp("pop (no final)");
8528 DEBUG_STATE_pp("pop (yes)");
8534 while (yes_state < SLAB_FIRST(PL_regmatch_slab)
8535 || yes_state > SLAB_LAST(PL_regmatch_slab))
8537 /* not in this slab, pop slab */
8538 depth -= (st - SLAB_FIRST(PL_regmatch_slab) + 1);
8539 PL_regmatch_slab = PL_regmatch_slab->prev;
8540 st = SLAB_LAST(PL_regmatch_slab);
8542 depth -= (st - yes_state);
8545 yes_state = st->u.yes.prev_yes_state;
8546 PL_regmatch_state = st;
8549 locinput= st->locinput;
8550 state_num = st->resume_state + no_final;
8551 goto reenter_switch;
8554 DEBUG_EXECUTE_r(Perl_re_printf( aTHX_ "%sMatch successful!%s\n",
8555 PL_colors[4], PL_colors[5]));
8557 if (reginfo->info_aux_eval) {
8558 /* each successfully executed (?{...}) block does the equivalent of
8559 * local $^R = do {...}
8560 * When popping the save stack, all these locals would be undone;
8561 * bypass this by setting the outermost saved $^R to the latest
8563 /* I dont know if this is needed or works properly now.
8564 * see code related to PL_replgv elsewhere in this file.
8567 if (oreplsv != GvSV(PL_replgv))
8568 sv_setsv(oreplsv, GvSV(PL_replgv));
8575 Perl_re_exec_indentf( aTHX_ "%sfailed...%s\n",
8577 PL_colors[4], PL_colors[5])
8589 /* there's a previous state to backtrack to */
8591 if (st < SLAB_FIRST(PL_regmatch_slab)) {
8592 PL_regmatch_slab = PL_regmatch_slab->prev;
8593 st = SLAB_LAST(PL_regmatch_slab);
8595 PL_regmatch_state = st;
8596 locinput= st->locinput;
8598 DEBUG_STATE_pp("pop");
8600 if (yes_state == st)
8601 yes_state = st->u.yes.prev_yes_state;
8603 state_num = st->resume_state + 1; /* failure = success + 1 */
8605 goto reenter_switch;
8610 if (rex->intflags & PREGf_VERBARG_SEEN) {
8611 SV *sv_err = get_sv("REGERROR", 1);
8612 SV *sv_mrk = get_sv("REGMARK", 1);
8614 sv_commit = &PL_sv_no;
8616 sv_yes_mark = &PL_sv_yes;
8619 sv_commit = &PL_sv_yes;
8620 sv_yes_mark = &PL_sv_no;
8624 sv_setsv(sv_err, sv_commit);
8625 sv_setsv(sv_mrk, sv_yes_mark);
8629 if (last_pushed_cv) {
8632 PERL_UNUSED_VAR(SP);
8635 assert(!result || locinput - reginfo->strbeg >= 0);
8636 return result ? locinput - reginfo->strbeg : -1;
8640 - regrepeat - repeatedly match something simple, report how many
8642 * What 'simple' means is a node which can be the operand of a quantifier like
8645 * startposp - pointer a pointer to the start position. This is updated
8646 * to point to the byte following the highest successful
8648 * p - the regnode to be repeatedly matched against.
8649 * reginfo - struct holding match state, such as strend
8650 * max - maximum number of things to match.
8651 * depth - (for debugging) backtracking depth.
8654 S_regrepeat(pTHX_ regexp *prog, char **startposp, const regnode *p,
8655 regmatch_info *const reginfo, I32 max _pDEPTH)
8657 char *scan; /* Pointer to current position in target string */
8659 char *loceol = reginfo->strend; /* local version */
8660 I32 hardcount = 0; /* How many matches so far */
8661 bool utf8_target = reginfo->is_utf8_target;
8662 unsigned int to_complement = 0; /* Invert the result? */
8664 _char_class_number classnum;
8666 PERL_ARGS_ASSERT_REGREPEAT;
8669 if (max == REG_INFTY)
8671 else if (! utf8_target && loceol - scan > max)
8672 loceol = scan + max;
8674 /* Here, for the case of a non-UTF-8 target we have adjusted <loceol> down
8675 * to the maximum of how far we should go in it (leaving it set to the real
8676 * end, if the maximum permissible would take us beyond that). This allows
8677 * us to make the loop exit condition that we haven't gone past <loceol> to
8678 * also mean that we haven't exceeded the max permissible count, saving a
8679 * test each time through the loop. But it assumes that the OP matches a
8680 * single byte, which is true for most of the OPs below when applied to a
8681 * non-UTF-8 target. Those relatively few OPs that don't have this
8682 * characteristic will have to compensate.
8684 * There is no adjustment for UTF-8 targets, as the number of bytes per
8685 * character varies. OPs will have to test both that the count is less
8686 * than the max permissible (using <hardcount> to keep track), and that we
8687 * are still within the bounds of the string (using <loceol>. A few OPs
8688 * match a single byte no matter what the encoding. They can omit the max
8689 * test if, for the UTF-8 case, they do the adjustment that was skipped
8692 * Thus, the code above sets things up for the common case; and exceptional
8693 * cases need extra work; the common case is to make sure <scan> doesn't
8694 * go past <loceol>, and for UTF-8 to also use <hardcount> to make sure the
8695 * count doesn't exceed the maximum permissible */
8700 while (scan < loceol && hardcount < max && *scan != '\n') {
8701 scan += UTF8SKIP(scan);
8705 while (scan < loceol && *scan != '\n')
8711 while (scan < loceol && hardcount < max) {
8712 scan += UTF8SKIP(scan);
8720 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8721 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*scan)) {
8722 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(scan, loceol);
8726 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
8730 /* Can use a simple loop if the pattern char to match on is invariant
8731 * under UTF-8, or both target and pattern aren't UTF-8. Note that we
8732 * can use UTF8_IS_INVARIANT() even if the pattern isn't UTF-8, as it's
8733 * true iff it doesn't matter if the argument is in UTF-8 or not */
8734 if (UTF8_IS_INVARIANT(c) || (! utf8_target && ! reginfo->is_utf8_pat)) {
8735 if (utf8_target && loceol - scan > max) {
8736 /* We didn't adjust <loceol> because is UTF-8, but ok to do so,
8737 * since here, to match at all, 1 char == 1 byte */
8738 loceol = scan + max;
8740 while (scan < loceol && UCHARAT(scan) == c) {
8744 else if (reginfo->is_utf8_pat) {
8746 STRLEN scan_char_len;
8748 /* When both target and pattern are UTF-8, we have to do
8750 while (hardcount < max
8752 && (scan_char_len = UTF8SKIP(scan)) <= STR_LEN(p)
8753 && memEQ(scan, STRING(p), scan_char_len))
8755 scan += scan_char_len;
8759 else if (! UTF8_IS_ABOVE_LATIN1(c)) {
8761 /* Target isn't utf8; convert the character in the UTF-8
8762 * pattern to non-UTF8, and do a simple loop */
8763 c = EIGHT_BIT_UTF8_TO_NATIVE(c, *(STRING(p) + 1));
8764 while (scan < loceol && UCHARAT(scan) == c) {
8767 } /* else pattern char is above Latin1, can't possibly match the
8772 /* Here, the string must be utf8; pattern isn't, and <c> is
8773 * different in utf8 than not, so can't compare them directly.
8774 * Outside the loop, find the two utf8 bytes that represent c, and
8775 * then look for those in sequence in the utf8 string */
8776 U8 high = UTF8_TWO_BYTE_HI(c);
8777 U8 low = UTF8_TWO_BYTE_LO(c);
8779 while (hardcount < max
8780 && scan + 1 < loceol
8781 && UCHARAT(scan) == high
8782 && UCHARAT(scan + 1) == low)
8790 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
8791 assert(! reginfo->is_utf8_pat);
8794 utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
8798 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8799 utf8_flags = FOLDEQ_LOCALE;
8802 case EXACTF: /* This node only generated for non-utf8 patterns */
8803 assert(! reginfo->is_utf8_pat);
8808 if (! utf8_target) {
8811 utf8_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
8812 | FOLDEQ_S2_FOLDS_SANE;
8817 utf8_flags = reginfo->is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
8821 U8 c1_utf8[UTF8_MAXBYTES+1], c2_utf8[UTF8_MAXBYTES+1];
8823 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
8825 if (S_setup_EXACTISH_ST_c1_c2(aTHX_ p, &c1, c1_utf8, &c2, c2_utf8,
8828 if (c1 == CHRTEST_VOID) {
8829 /* Use full Unicode fold matching */
8830 char *tmpeol = reginfo->strend;
8831 STRLEN pat_len = reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1;
8832 while (hardcount < max
8833 && foldEQ_utf8_flags(scan, &tmpeol, 0, utf8_target,
8834 STRING(p), NULL, pat_len,
8835 reginfo->is_utf8_pat, utf8_flags))
8838 tmpeol = reginfo->strend;
8842 else if (utf8_target) {
8844 while (scan < loceol
8846 && memEQ(scan, c1_utf8, UTF8SKIP(scan)))
8848 scan += UTF8SKIP(scan);
8853 while (scan < loceol
8855 && (memEQ(scan, c1_utf8, UTF8SKIP(scan))
8856 || memEQ(scan, c2_utf8, UTF8SKIP(scan))))
8858 scan += UTF8SKIP(scan);
8863 else if (c1 == c2) {
8864 while (scan < loceol && UCHARAT(scan) == c1) {
8869 while (scan < loceol &&
8870 (UCHARAT(scan) == c1 || UCHARAT(scan) == c2))
8879 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8881 if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(p)) && ! IN_UTF8_CTYPE_LOCALE) {
8882 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
8888 while (hardcount < max
8890 && reginclass(prog, p, (U8*)scan, (U8*) loceol, utf8_target))
8892 scan += UTF8SKIP(scan);
8896 while (scan < loceol && REGINCLASS(prog, p, (U8*)scan, 0))
8901 /* The argument (FLAGS) to all the POSIX node types is the class number */
8908 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8909 if (! utf8_target) {
8910 while (scan < loceol && to_complement ^ cBOOL(isFOO_lc(FLAGS(p),
8916 while (hardcount < max && scan < loceol
8917 && to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(p),
8920 scan += UTF8SKIP(scan);
8933 if (utf8_target && loceol - scan > max) {
8935 /* We didn't adjust <loceol> at the beginning of this routine
8936 * because is UTF-8, but it is actually ok to do so, since here, to
8937 * match, 1 char == 1 byte. */
8938 loceol = scan + max;
8940 while (scan < loceol && _generic_isCC_A((U8) *scan, FLAGS(p))) {
8953 if (! utf8_target) {
8954 while (scan < loceol && ! _generic_isCC_A((U8) *scan, FLAGS(p))) {
8960 /* The complement of something that matches only ASCII matches all
8961 * non-ASCII, plus everything in ASCII that isn't in the class. */
8962 while (hardcount < max && scan < loceol
8963 && (! isASCII_utf8(scan)
8964 || ! _generic_isCC_A((U8) *scan, FLAGS(p))))
8966 scan += UTF8SKIP(scan);
8977 if (! utf8_target) {
8978 while (scan < loceol && to_complement
8979 ^ cBOOL(_generic_isCC((U8) *scan, FLAGS(p))))
8986 classnum = (_char_class_number) FLAGS(p);
8987 if (classnum < _FIRST_NON_SWASH_CC) {
8989 /* Here, a swash is needed for above-Latin1 code points.
8990 * Process as many Latin1 code points using the built-in rules.
8991 * Go to another loop to finish processing upon encountering
8992 * the first Latin1 code point. We could do that in this loop
8993 * as well, but the other way saves having to test if the swash
8994 * has been loaded every time through the loop: extra space to
8996 while (hardcount < max && scan < loceol) {
8997 if (UTF8_IS_INVARIANT(*scan)) {
8998 if (! (to_complement ^ cBOOL(_generic_isCC((U8) *scan,
9005 else if (UTF8_IS_DOWNGRADEABLE_START(*scan)) {
9006 if (! (to_complement
9007 ^ cBOOL(_generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(*scan,
9016 goto found_above_latin1;
9023 /* For these character classes, the knowledge of how to handle
9024 * every code point is compiled in to Perl via a macro. This
9025 * code is written for making the loops as tight as possible.
9026 * It could be refactored to save space instead */
9028 case _CC_ENUM_SPACE:
9029 while (hardcount < max
9031 && (to_complement ^ cBOOL(isSPACE_utf8(scan))))
9033 scan += UTF8SKIP(scan);
9037 case _CC_ENUM_BLANK:
9038 while (hardcount < max
9040 && (to_complement ^ cBOOL(isBLANK_utf8(scan))))
9042 scan += UTF8SKIP(scan);
9046 case _CC_ENUM_XDIGIT:
9047 while (hardcount < max
9049 && (to_complement ^ cBOOL(isXDIGIT_utf8(scan))))
9051 scan += UTF8SKIP(scan);
9055 case _CC_ENUM_VERTSPACE:
9056 while (hardcount < max
9058 && (to_complement ^ cBOOL(isVERTWS_utf8(scan))))
9060 scan += UTF8SKIP(scan);
9064 case _CC_ENUM_CNTRL:
9065 while (hardcount < max
9067 && (to_complement ^ cBOOL(isCNTRL_utf8(scan))))
9069 scan += UTF8SKIP(scan);
9074 Perl_croak(aTHX_ "panic: regrepeat() node %d='%s' has an unexpected character class '%d'", OP(p), PL_reg_name[OP(p)], classnum);
9080 found_above_latin1: /* Continuation of POSIXU and NPOSIXU */
9082 /* Load the swash if not already present */
9083 if (! PL_utf8_swash_ptrs[classnum]) {
9084 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
9085 PL_utf8_swash_ptrs[classnum] = _core_swash_init(
9089 PL_XPosix_ptrs[classnum], &flags);
9092 while (hardcount < max && scan < loceol
9093 && to_complement ^ cBOOL(_generic_utf8(
9096 swash_fetch(PL_utf8_swash_ptrs[classnum],
9100 scan += UTF8SKIP(scan);
9107 while (hardcount < max && scan < loceol &&
9108 (c=is_LNBREAK_utf8_safe(scan, loceol))) {
9113 /* LNBREAK can match one or two latin chars, which is ok, but we
9114 * have to use hardcount in this situation, and throw away the
9115 * adjustment to <loceol> done before the switch statement */
9116 loceol = reginfo->strend;
9117 while (scan < loceol && (c=is_LNBREAK_latin1_safe(scan, loceol))) {
9126 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
9140 /* These are all 0 width, so match right here or not at all. */
9144 Perl_croak(aTHX_ "panic: regrepeat() called with unrecognized node type %d='%s'", OP(p), PL_reg_name[OP(p)]);
9145 NOT_REACHED; /* NOTREACHED */
9152 c = scan - *startposp;
9156 GET_RE_DEBUG_FLAGS_DECL;
9158 SV * const prop = sv_newmortal();
9159 regprop(prog, prop, p, reginfo, NULL);
9160 Perl_re_exec_indentf( aTHX_ "%s can match %" IVdf " times out of %" IVdf "...\n",
9161 depth, SvPVX_const(prop),(IV)c,(IV)max);
9169 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
9171 - regclass_swash - prepare the utf8 swash. Wraps the shared core version to
9172 create a copy so that changes the caller makes won't change the shared one.
9173 If <altsvp> is non-null, will return NULL in it, for back-compat.
9176 Perl_regclass_swash(pTHX_ const regexp *prog, const regnode* node, bool doinit, SV** listsvp, SV **altsvp)
9178 PERL_ARGS_ASSERT_REGCLASS_SWASH;
9184 return newSVsv(_get_regclass_nonbitmap_data(prog, node, doinit, listsvp, NULL, NULL));
9187 #endif /* !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION) */
9190 - reginclass - determine if a character falls into a character class
9192 n is the ANYOF-type regnode
9193 p is the target string
9194 p_end points to one byte beyond the end of the target string
9195 utf8_target tells whether p is in UTF-8.
9197 Returns true if matched; false otherwise.
9199 Note that this can be a synthetic start class, a combination of various
9200 nodes, so things you think might be mutually exclusive, such as locale,
9201 aren't. It can match both locale and non-locale
9206 S_reginclass(pTHX_ regexp * const prog, const regnode * const n, const U8* const p, const U8* const p_end, const bool utf8_target)
9209 const char flags = ANYOF_FLAGS(n);
9213 PERL_ARGS_ASSERT_REGINCLASS;
9215 /* If c is not already the code point, get it. Note that
9216 * UTF8_IS_INVARIANT() works even if not in UTF-8 */
9217 if (! UTF8_IS_INVARIANT(c) && utf8_target) {
9219 c = utf8n_to_uvchr(p, p_end - p, &c_len, ( UTF8_ALLOW_DEFAULT
9220 | UTF8_CHECK_ONLY));
9221 if (c_len == (STRLEN)-1)
9222 Perl_croak(aTHX_ "Malformed UTF-8 character (fatal)");
9223 if (c > 255 && OP(n) == ANYOFL && ! ANYOFL_UTF8_LOCALE_REQD(flags)) {
9224 _CHECK_AND_OUTPUT_WIDE_LOCALE_CP_MSG(c);
9228 /* If this character is potentially in the bitmap, check it */
9229 if (c < NUM_ANYOF_CODE_POINTS) {
9230 if (ANYOF_BITMAP_TEST(n, c))
9233 & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
9240 else if (flags & ANYOF_LOCALE_FLAGS) {
9241 if ((flags & ANYOFL_FOLD)
9243 && ANYOF_BITMAP_TEST(n, PL_fold_locale[c]))
9247 else if (ANYOF_POSIXL_TEST_ANY_SET(n)
9251 /* The data structure is arranged so bits 0, 2, 4, ... are set
9252 * if the class includes the Posix character class given by
9253 * bit/2; and 1, 3, 5, ... are set if the class includes the
9254 * complemented Posix class given by int(bit/2). So we loop
9255 * through the bits, each time changing whether we complement
9256 * the result or not. Suppose for the sake of illustration
9257 * that bits 0-3 mean respectively, \w, \W, \s, \S. If bit 0
9258 * is set, it means there is a match for this ANYOF node if the
9259 * character is in the class given by the expression (0 / 2 = 0
9260 * = \w). If it is in that class, isFOO_lc() will return 1,
9261 * and since 'to_complement' is 0, the result will stay TRUE,
9262 * and we exit the loop. Suppose instead that bit 0 is 0, but
9263 * bit 1 is 1. That means there is a match if the character
9264 * matches \W. We won't bother to call isFOO_lc() on bit 0,
9265 * but will on bit 1. On the second iteration 'to_complement'
9266 * will be 1, so the exclusive or will reverse things, so we
9267 * are testing for \W. On the third iteration, 'to_complement'
9268 * will be 0, and we would be testing for \s; the fourth
9269 * iteration would test for \S, etc.
9271 * Note that this code assumes that all the classes are closed
9272 * under folding. For example, if a character matches \w, then
9273 * its fold does too; and vice versa. This should be true for
9274 * any well-behaved locale for all the currently defined Posix
9275 * classes, except for :lower: and :upper:, which are handled
9276 * by the pseudo-class :cased: which matches if either of the
9277 * other two does. To get rid of this assumption, an outer
9278 * loop could be used below to iterate over both the source
9279 * character, and its fold (if different) */
9282 int to_complement = 0;
9284 while (count < ANYOF_MAX) {
9285 if (ANYOF_POSIXL_TEST(n, count)
9286 && to_complement ^ cBOOL(isFOO_lc(count/2, (U8) c)))
9299 /* If the bitmap didn't (or couldn't) match, and something outside the
9300 * bitmap could match, try that. */
9302 if (c >= NUM_ANYOF_CODE_POINTS
9303 && (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP))
9305 match = TRUE; /* Everything above the bitmap matches */
9307 /* Here doesn't match everything above the bitmap. If there is
9308 * some information available beyond the bitmap, we may find a
9309 * match in it. If so, this is most likely because the code point
9310 * is outside the bitmap range. But rarely, it could be because of
9311 * some other reason. If so, various flags are set to indicate
9312 * this possibility. On ANYOFD nodes, there may be matches that
9313 * happen only when the target string is UTF-8; or for other node
9314 * types, because runtime lookup is needed, regardless of the
9315 * UTF-8ness of the target string. Finally, under /il, there may
9316 * be some matches only possible if the locale is a UTF-8 one. */
9317 else if ( ARG(n) != ANYOF_ONLY_HAS_BITMAP
9318 && ( c >= NUM_ANYOF_CODE_POINTS
9319 || ( (flags & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)
9320 && ( UNLIKELY(OP(n) != ANYOFD)
9321 || (utf8_target && ! isASCII_uni(c)
9322 # if NUM_ANYOF_CODE_POINTS > 256
9326 || ( ANYOFL_SOME_FOLDS_ONLY_IN_UTF8_LOCALE(flags)
9327 && IN_UTF8_CTYPE_LOCALE)))
9329 SV* only_utf8_locale = NULL;
9330 SV * const sw = _get_regclass_nonbitmap_data(prog, n, TRUE, 0,
9331 &only_utf8_locale, NULL);
9337 } else { /* Convert to utf8 */
9338 utf8_p = utf8_buffer;
9339 append_utf8_from_native_byte(*p, &utf8_p);
9340 utf8_p = utf8_buffer;
9343 if (swash_fetch(sw, utf8_p, TRUE)) {
9347 if (! match && only_utf8_locale && IN_UTF8_CTYPE_LOCALE) {
9348 match = _invlist_contains_cp(only_utf8_locale, c);
9352 if (UNICODE_IS_SUPER(c)
9354 & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
9356 && ckWARN_d(WARN_NON_UNICODE))
9358 Perl_warner(aTHX_ packWARN(WARN_NON_UNICODE),
9359 "Matched non-Unicode code point 0x%04" UVXf " against Unicode property; may not be portable", c);
9363 #if ANYOF_INVERT != 1
9364 /* Depending on compiler optimization cBOOL takes time, so if don't have to
9366 # error ANYOF_INVERT needs to be set to 1, or guarded with cBOOL below,
9369 /* The xor complements the return if to invert: 1^1 = 0, 1^0 = 1 */
9370 return (flags & ANYOF_INVERT) ^ match;
9374 S_reghop3(U8 *s, SSize_t off, const U8* lim)
9376 /* return the position 'off' UTF-8 characters away from 's', forward if
9377 * 'off' >= 0, backwards if negative. But don't go outside of position
9378 * 'lim', which better be < s if off < 0 */
9380 PERL_ARGS_ASSERT_REGHOP3;
9383 while (off-- && s < lim) {
9384 /* XXX could check well-formedness here */
9389 while (off++ && s > lim) {
9391 if (UTF8_IS_CONTINUED(*s)) {
9392 while (s > lim && UTF8_IS_CONTINUATION(*s))
9394 if (! UTF8_IS_START(*s)) {
9395 Perl_croak_nocontext("Malformed UTF-8 character (fatal)");
9398 /* XXX could check well-formedness here */
9405 S_reghop4(U8 *s, SSize_t off, const U8* llim, const U8* rlim)
9407 PERL_ARGS_ASSERT_REGHOP4;
9410 while (off-- && s < rlim) {
9411 /* XXX could check well-formedness here */
9416 while (off++ && s > llim) {
9418 if (UTF8_IS_CONTINUED(*s)) {
9419 while (s > llim && UTF8_IS_CONTINUATION(*s))
9421 if (! UTF8_IS_START(*s)) {
9422 Perl_croak_nocontext("Malformed UTF-8 character (fatal)");
9425 /* XXX could check well-formedness here */
9431 /* like reghop3, but returns NULL on overrun, rather than returning last
9435 S_reghopmaybe3(U8* s, SSize_t off, const U8* const lim)
9437 PERL_ARGS_ASSERT_REGHOPMAYBE3;
9440 while (off-- && s < lim) {
9441 /* XXX could check well-formedness here */
9448 while (off++ && s > lim) {
9450 if (UTF8_IS_CONTINUED(*s)) {
9451 while (s > lim && UTF8_IS_CONTINUATION(*s))
9453 if (! UTF8_IS_START(*s)) {
9454 Perl_croak_nocontext("Malformed UTF-8 character (fatal)");
9457 /* XXX could check well-formedness here */
9466 /* when executing a regex that may have (?{}), extra stuff needs setting
9467 up that will be visible to the called code, even before the current
9468 match has finished. In particular:
9470 * $_ is localised to the SV currently being matched;
9471 * pos($_) is created if necessary, ready to be updated on each call-out
9473 * a fake PMOP is created that can be set to PL_curpm (normally PL_curpm
9474 isn't set until the current pattern is successfully finished), so that
9475 $1 etc of the match-so-far can be seen;
9476 * save the old values of subbeg etc of the current regex, and set then
9477 to the current string (again, this is normally only done at the end
9482 S_setup_eval_state(pTHX_ regmatch_info *const reginfo)
9485 regexp *const rex = ReANY(reginfo->prog);
9486 regmatch_info_aux_eval *eval_state = reginfo->info_aux_eval;
9488 eval_state->rex = rex;
9491 /* Make $_ available to executed code. */
9492 if (reginfo->sv != DEFSV) {
9494 DEFSV_set(reginfo->sv);
9497 if (!(mg = mg_find_mglob(reginfo->sv))) {
9498 /* prepare for quick setting of pos */
9499 mg = sv_magicext_mglob(reginfo->sv);
9502 eval_state->pos_magic = mg;
9503 eval_state->pos = mg->mg_len;
9504 eval_state->pos_flags = mg->mg_flags;
9507 eval_state->pos_magic = NULL;
9509 if (!PL_reg_curpm) {
9510 /* PL_reg_curpm is a fake PMOP that we can attach the current
9511 * regex to and point PL_curpm at, so that $1 et al are visible
9512 * within a /(?{})/. It's just allocated once per interpreter the
9513 * first time its needed */
9514 Newxz(PL_reg_curpm, 1, PMOP);
9517 SV* const repointer = &PL_sv_undef;
9518 /* this regexp is also owned by the new PL_reg_curpm, which
9519 will try to free it. */
9520 av_push(PL_regex_padav, repointer);
9521 PL_reg_curpm->op_pmoffset = av_tindex(PL_regex_padav);
9522 PL_regex_pad = AvARRAY(PL_regex_padav);
9526 SET_reg_curpm(reginfo->prog);
9527 eval_state->curpm = PL_curpm;
9528 PL_curpm_under = PL_curpm;
9529 PL_curpm = PL_reg_curpm;
9530 if (RXp_MATCH_COPIED(rex)) {
9531 /* Here is a serious problem: we cannot rewrite subbeg,
9532 since it may be needed if this match fails. Thus
9533 $` inside (?{}) could fail... */
9534 eval_state->subbeg = rex->subbeg;
9535 eval_state->sublen = rex->sublen;
9536 eval_state->suboffset = rex->suboffset;
9537 eval_state->subcoffset = rex->subcoffset;
9539 eval_state->saved_copy = rex->saved_copy;
9541 RXp_MATCH_COPIED_off(rex);
9544 eval_state->subbeg = NULL;
9545 rex->subbeg = (char *)reginfo->strbeg;
9547 rex->subcoffset = 0;
9548 rex->sublen = reginfo->strend - reginfo->strbeg;
9552 /* destructor to clear up regmatch_info_aux and regmatch_info_aux_eval */
9555 S_cleanup_regmatch_info_aux(pTHX_ void *arg)
9557 regmatch_info_aux *aux = (regmatch_info_aux *) arg;
9558 regmatch_info_aux_eval *eval_state = aux->info_aux_eval;
9561 Safefree(aux->poscache);
9565 /* undo the effects of S_setup_eval_state() */
9567 if (eval_state->subbeg) {
9568 regexp * const rex = eval_state->rex;
9569 rex->subbeg = eval_state->subbeg;
9570 rex->sublen = eval_state->sublen;
9571 rex->suboffset = eval_state->suboffset;
9572 rex->subcoffset = eval_state->subcoffset;
9574 rex->saved_copy = eval_state->saved_copy;
9576 RXp_MATCH_COPIED_on(rex);
9578 if (eval_state->pos_magic)
9580 eval_state->pos_magic->mg_len = eval_state->pos;
9581 eval_state->pos_magic->mg_flags =
9582 (eval_state->pos_magic->mg_flags & ~MGf_BYTES)
9583 | (eval_state->pos_flags & MGf_BYTES);
9586 PL_curpm = eval_state->curpm;
9589 PL_regmatch_state = aux->old_regmatch_state;
9590 PL_regmatch_slab = aux->old_regmatch_slab;
9592 /* free all slabs above current one - this must be the last action
9593 * of this function, as aux and eval_state are allocated within
9594 * slabs and may be freed here */
9596 s = PL_regmatch_slab->next;
9598 PL_regmatch_slab->next = NULL;
9600 regmatch_slab * const osl = s;
9609 S_to_utf8_substr(pTHX_ regexp *prog)
9611 /* Converts substr fields in prog from bytes to UTF-8, calling fbm_compile
9612 * on the converted value */
9616 PERL_ARGS_ASSERT_TO_UTF8_SUBSTR;
9619 if (prog->substrs->data[i].substr
9620 && !prog->substrs->data[i].utf8_substr) {
9621 SV* const sv = newSVsv(prog->substrs->data[i].substr);
9622 prog->substrs->data[i].utf8_substr = sv;
9623 sv_utf8_upgrade(sv);
9624 if (SvVALID(prog->substrs->data[i].substr)) {
9625 if (SvTAIL(prog->substrs->data[i].substr)) {
9626 /* Trim the trailing \n that fbm_compile added last
9628 SvCUR_set(sv, SvCUR(sv) - 1);
9629 /* Whilst this makes the SV technically "invalid" (as its
9630 buffer is no longer followed by "\0") when fbm_compile()
9631 adds the "\n" back, a "\0" is restored. */
9632 fbm_compile(sv, FBMcf_TAIL);
9636 if (prog->substrs->data[i].substr == prog->check_substr)
9637 prog->check_utf8 = sv;
9643 S_to_byte_substr(pTHX_ regexp *prog)
9645 /* Converts substr fields in prog from UTF-8 to bytes, calling fbm_compile
9646 * on the converted value; returns FALSE if can't be converted. */
9650 PERL_ARGS_ASSERT_TO_BYTE_SUBSTR;
9653 if (prog->substrs->data[i].utf8_substr
9654 && !prog->substrs->data[i].substr) {
9655 SV* sv = newSVsv(prog->substrs->data[i].utf8_substr);
9656 if (! sv_utf8_downgrade(sv, TRUE)) {
9659 if (SvVALID(prog->substrs->data[i].utf8_substr)) {
9660 if (SvTAIL(prog->substrs->data[i].utf8_substr)) {
9661 /* Trim the trailing \n that fbm_compile added last
9663 SvCUR_set(sv, SvCUR(sv) - 1);
9664 fbm_compile(sv, FBMcf_TAIL);
9668 prog->substrs->data[i].substr = sv;
9669 if (prog->substrs->data[i].utf8_substr == prog->check_utf8)
9670 prog->check_substr = sv;
9678 * ex: set ts=8 sts=4 sw=4 et: