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(PerlIO_printf(Perl_debug_log, "%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 for non-utf8 strings: avoids the reginclass
111 * call if there are no complications: i.e., if everything matchable is
112 * straight forward in the bitmap */
113 #define REGINCLASS(prog,p,c) (ANYOF_FLAGS(p) ? reginclass(prog,p,c,c+1,0) \
114 : ANYOF_BITMAP_TEST(p,*(c)))
120 #define CHR_SVLEN(sv) (utf8_target ? sv_len_utf8(sv) : SvCUR(sv))
121 #define CHR_DIST(a,b) (reginfo->is_utf8_target ? utf8_distance(a,b) : a - b)
123 #define HOPc(pos,off) \
124 (char *)(reginfo->is_utf8_target \
125 ? reghop3((U8*)pos, off, \
126 (U8*)(off >= 0 ? reginfo->strend : reginfo->strbeg)) \
129 #define HOPBACKc(pos, off) \
130 (char*)(reginfo->is_utf8_target \
131 ? reghopmaybe3((U8*)pos, -off, (U8*)(reginfo->strbeg)) \
132 : (pos - off >= reginfo->strbeg) \
136 #define HOP3(pos,off,lim) (reginfo->is_utf8_target ? reghop3((U8*)(pos), off, (U8*)(lim)) : (U8*)(pos + off))
137 #define HOP3c(pos,off,lim) ((char*)HOP3(pos,off,lim))
139 /* lim must be +ve. Returns NULL on overshoot */
140 #define HOPMAYBE3(pos,off,lim) \
141 (reginfo->is_utf8_target \
142 ? reghopmaybe3((U8*)pos, off, (U8*)(lim)) \
143 : ((U8*)pos + off <= lim) \
147 /* like HOP3, but limits the result to <= lim even for the non-utf8 case.
148 * off must be >=0; args should be vars rather than expressions */
149 #define HOP3lim(pos,off,lim) (reginfo->is_utf8_target \
150 ? reghop3((U8*)(pos), off, (U8*)(lim)) \
151 : (U8*)((pos + off) > lim ? lim : (pos + off)))
153 #define HOP4(pos,off,llim, rlim) (reginfo->is_utf8_target \
154 ? reghop4((U8*)(pos), off, (U8*)(llim), (U8*)(rlim)) \
156 #define HOP4c(pos,off,llim, rlim) ((char*)HOP4(pos,off,llim, rlim))
158 #define NEXTCHR_EOS -10 /* nextchr has fallen off the end */
159 #define NEXTCHR_IS_EOS (nextchr < 0)
161 #define SET_nextchr \
162 nextchr = ((locinput < reginfo->strend) ? UCHARAT(locinput) : NEXTCHR_EOS)
164 #define SET_locinput(p) \
169 #define LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist) STMT_START { \
171 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST; \
172 swash_ptr = _core_swash_init("utf8", property_name, &PL_sv_undef, \
173 1, 0, invlist, &flags); \
178 /* If in debug mode, we test that a known character properly matches */
180 # define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
183 utf8_char_in_property) \
184 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist); \
185 assert(swash_fetch(swash_ptr, (U8 *) utf8_char_in_property, TRUE));
187 # define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
190 utf8_char_in_property) \
191 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist)
194 #define LOAD_UTF8_CHARCLASS_ALNUM() LOAD_UTF8_CHARCLASS_DEBUG_TEST( \
195 PL_utf8_swash_ptrs[_CC_WORDCHAR], \
197 PL_XPosix_ptrs[_CC_WORDCHAR], \
198 LATIN_SMALL_LIGATURE_LONG_S_T_UTF8);
200 #define PLACEHOLDER /* Something for the preprocessor to grab onto */
201 /* TODO: Combine JUMPABLE and HAS_TEXT to cache OP(rn) */
203 /* for use after a quantifier and before an EXACT-like node -- japhy */
204 /* it would be nice to rework regcomp.sym to generate this stuff. sigh
206 * NOTE that *nothing* that affects backtracking should be in here, specifically
207 * VERBS must NOT be included. JUMPABLE is used to determine if we can ignore a
208 * node that is in between two EXACT like nodes when ascertaining what the required
209 * "follow" character is. This should probably be moved to regex compile time
210 * although it may be done at run time beause of the REF possibility - more
211 * investigation required. -- demerphq
213 #define JUMPABLE(rn) ( \
215 (OP(rn) == CLOSE && (!cur_eval || cur_eval->u.eval.close_paren != ARG(rn))) || \
217 OP(rn) == SUSPEND || OP(rn) == IFMATCH || \
218 OP(rn) == PLUS || OP(rn) == MINMOD || \
220 (PL_regkind[OP(rn)] == CURLY && ARG1(rn) > 0) \
222 #define IS_EXACT(rn) (PL_regkind[OP(rn)] == EXACT)
224 #define HAS_TEXT(rn) ( IS_EXACT(rn) || PL_regkind[OP(rn)] == REF )
227 /* Currently these are only used when PL_regkind[OP(rn)] == EXACT so
228 we don't need this definition. XXX These are now out-of-sync*/
229 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==REF || OP(rn)==NREF )
230 #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 )
231 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL || OP(rn)==REFFL || OP(rn)==NREFFL )
234 /* ... so we use this as its faster. */
235 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==EXACTL )
236 #define IS_TEXTFU(rn) ( OP(rn)==EXACTFU || OP(rn)==EXACTFLU8 || OP(rn)==EXACTFU_SS || OP(rn) == EXACTFA || OP(rn) == EXACTFA_NO_TRIE)
237 #define IS_TEXTF(rn) ( OP(rn)==EXACTF )
238 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL )
243 Search for mandatory following text node; for lookahead, the text must
244 follow but for lookbehind (rn->flags != 0) we skip to the next step.
246 #define FIND_NEXT_IMPT(rn) STMT_START { \
247 while (JUMPABLE(rn)) { \
248 const OPCODE type = OP(rn); \
249 if (type == SUSPEND || PL_regkind[type] == CURLY) \
250 rn = NEXTOPER(NEXTOPER(rn)); \
251 else if (type == PLUS) \
253 else if (type == IFMATCH) \
254 rn = (rn->flags == 0) ? NEXTOPER(NEXTOPER(rn)) : rn + ARG(rn); \
255 else rn += NEXT_OFF(rn); \
259 #define SLAB_FIRST(s) (&(s)->states[0])
260 #define SLAB_LAST(s) (&(s)->states[PERL_REGMATCH_SLAB_SLOTS-1])
262 static void S_setup_eval_state(pTHX_ regmatch_info *const reginfo);
263 static void S_cleanup_regmatch_info_aux(pTHX_ void *arg);
264 static regmatch_state * S_push_slab(pTHX);
266 #define REGCP_PAREN_ELEMS 3
267 #define REGCP_OTHER_ELEMS 3
268 #define REGCP_FRAME_ELEMS 1
269 /* REGCP_FRAME_ELEMS are not part of the REGCP_OTHER_ELEMS and
270 * are needed for the regexp context stack bookkeeping. */
273 S_regcppush(pTHX_ const regexp *rex, I32 parenfloor, U32 maxopenparen)
275 const int retval = PL_savestack_ix;
276 const int paren_elems_to_push =
277 (maxopenparen - parenfloor) * REGCP_PAREN_ELEMS;
278 const UV total_elems = paren_elems_to_push + REGCP_OTHER_ELEMS;
279 const UV elems_shifted = total_elems << SAVE_TIGHT_SHIFT;
281 GET_RE_DEBUG_FLAGS_DECL;
283 PERL_ARGS_ASSERT_REGCPPUSH;
285 if (paren_elems_to_push < 0)
286 Perl_croak(aTHX_ "panic: paren_elems_to_push, %i < 0, maxopenparen: %i parenfloor: %i REGCP_PAREN_ELEMS: %u",
287 (int)paren_elems_to_push, (int)maxopenparen,
288 (int)parenfloor, (unsigned)REGCP_PAREN_ELEMS);
290 if ((elems_shifted >> SAVE_TIGHT_SHIFT) != total_elems)
291 Perl_croak(aTHX_ "panic: paren_elems_to_push offset %"UVuf
292 " out of range (%lu-%ld)",
294 (unsigned long)maxopenparen,
297 SSGROW(total_elems + REGCP_FRAME_ELEMS);
300 if ((int)maxopenparen > (int)parenfloor)
301 PerlIO_printf(Perl_debug_log,
302 "rex=0x%"UVxf" offs=0x%"UVxf": saving capture indices:\n",
307 for (p = parenfloor+1; p <= (I32)maxopenparen; p++) {
308 /* REGCP_PARENS_ELEMS are pushed per pairs of parentheses. */
309 SSPUSHIV(rex->offs[p].end);
310 SSPUSHIV(rex->offs[p].start);
311 SSPUSHINT(rex->offs[p].start_tmp);
312 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
313 " \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"\n",
315 (IV)rex->offs[p].start,
316 (IV)rex->offs[p].start_tmp,
320 /* REGCP_OTHER_ELEMS are pushed in any case, parentheses or no. */
321 SSPUSHINT(maxopenparen);
322 SSPUSHINT(rex->lastparen);
323 SSPUSHINT(rex->lastcloseparen);
324 SSPUSHUV(SAVEt_REGCONTEXT | elems_shifted); /* Magic cookie. */
329 /* These are needed since we do not localize EVAL nodes: */
330 #define REGCP_SET(cp) \
332 PerlIO_printf(Perl_debug_log, \
333 " Setting an EVAL scope, savestack=%"IVdf"\n", \
334 (IV)PL_savestack_ix)); \
337 #define REGCP_UNWIND(cp) \
339 if (cp != PL_savestack_ix) \
340 PerlIO_printf(Perl_debug_log, \
341 " Clearing an EVAL scope, savestack=%"IVdf"..%"IVdf"\n", \
342 (IV)(cp), (IV)PL_savestack_ix)); \
345 #define UNWIND_PAREN(lp, lcp) \
346 for (n = rex->lastparen; n > lp; n--) \
347 rex->offs[n].end = -1; \
348 rex->lastparen = n; \
349 rex->lastcloseparen = lcp;
353 S_regcppop(pTHX_ regexp *rex, U32 *maxopenparen_p)
357 GET_RE_DEBUG_FLAGS_DECL;
359 PERL_ARGS_ASSERT_REGCPPOP;
361 /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
363 assert((i & SAVE_MASK) == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
364 i >>= SAVE_TIGHT_SHIFT; /* Parentheses elements to pop. */
365 rex->lastcloseparen = SSPOPINT;
366 rex->lastparen = SSPOPINT;
367 *maxopenparen_p = SSPOPINT;
369 i -= REGCP_OTHER_ELEMS;
370 /* Now restore the parentheses context. */
372 if (i || rex->lastparen + 1 <= rex->nparens)
373 PerlIO_printf(Perl_debug_log,
374 "rex=0x%"UVxf" offs=0x%"UVxf": restoring capture indices to:\n",
379 paren = *maxopenparen_p;
380 for ( ; i > 0; i -= REGCP_PAREN_ELEMS) {
382 rex->offs[paren].start_tmp = SSPOPINT;
383 rex->offs[paren].start = SSPOPIV;
385 if (paren <= rex->lastparen)
386 rex->offs[paren].end = tmps;
387 DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
388 " \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"%s\n",
390 (IV)rex->offs[paren].start,
391 (IV)rex->offs[paren].start_tmp,
392 (IV)rex->offs[paren].end,
393 (paren > rex->lastparen ? "(skipped)" : ""));
398 /* It would seem that the similar code in regtry()
399 * already takes care of this, and in fact it is in
400 * a better location to since this code can #if 0-ed out
401 * but the code in regtry() is needed or otherwise tests
402 * requiring null fields (pat.t#187 and split.t#{13,14}
403 * (as of patchlevel 7877) will fail. Then again,
404 * this code seems to be necessary or otherwise
405 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
406 * --jhi updated by dapm */
407 for (i = rex->lastparen + 1; i <= rex->nparens; i++) {
408 if (i > *maxopenparen_p)
409 rex->offs[i].start = -1;
410 rex->offs[i].end = -1;
411 DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
412 " \\%"UVuf": %s ..-1 undeffing\n",
414 (i > *maxopenparen_p) ? "-1" : " "
420 /* restore the parens and associated vars at savestack position ix,
421 * but without popping the stack */
424 S_regcp_restore(pTHX_ regexp *rex, I32 ix, U32 *maxopenparen_p)
426 I32 tmpix = PL_savestack_ix;
427 PL_savestack_ix = ix;
428 regcppop(rex, maxopenparen_p);
429 PL_savestack_ix = tmpix;
432 #define regcpblow(cp) LEAVE_SCOPE(cp) /* Ignores regcppush()ed data. */
435 S_isFOO_lc(pTHX_ const U8 classnum, const U8 character)
437 /* Returns a boolean as to whether or not 'character' is a member of the
438 * Posix character class given by 'classnum' that should be equivalent to a
439 * value in the typedef '_char_class_number'.
441 * Ideally this could be replaced by a just an array of function pointers
442 * to the C library functions that implement the macros this calls.
443 * However, to compile, the precise function signatures are required, and
444 * these may vary from platform to to platform. To avoid having to figure
445 * out what those all are on each platform, I (khw) am using this method,
446 * which adds an extra layer of function call overhead (unless the C
447 * optimizer strips it away). But we don't particularly care about
448 * performance with locales anyway. */
450 switch ((_char_class_number) classnum) {
451 case _CC_ENUM_ALPHANUMERIC: return isALPHANUMERIC_LC(character);
452 case _CC_ENUM_ALPHA: return isALPHA_LC(character);
453 case _CC_ENUM_ASCII: return isASCII_LC(character);
454 case _CC_ENUM_BLANK: return isBLANK_LC(character);
455 case _CC_ENUM_CASED: return isLOWER_LC(character)
456 || isUPPER_LC(character);
457 case _CC_ENUM_CNTRL: return isCNTRL_LC(character);
458 case _CC_ENUM_DIGIT: return isDIGIT_LC(character);
459 case _CC_ENUM_GRAPH: return isGRAPH_LC(character);
460 case _CC_ENUM_LOWER: return isLOWER_LC(character);
461 case _CC_ENUM_PRINT: return isPRINT_LC(character);
462 case _CC_ENUM_PUNCT: return isPUNCT_LC(character);
463 case _CC_ENUM_SPACE: return isSPACE_LC(character);
464 case _CC_ENUM_UPPER: return isUPPER_LC(character);
465 case _CC_ENUM_WORDCHAR: return isWORDCHAR_LC(character);
466 case _CC_ENUM_XDIGIT: return isXDIGIT_LC(character);
467 default: /* VERTSPACE should never occur in locales */
468 Perl_croak(aTHX_ "panic: isFOO_lc() has an unexpected character class '%d'", classnum);
471 NOT_REACHED; /* NOTREACHED */
476 S_isFOO_utf8_lc(pTHX_ const U8 classnum, const U8* character)
478 /* Returns a boolean as to whether or not the (well-formed) UTF-8-encoded
479 * 'character' is a member of the Posix character class given by 'classnum'
480 * that should be equivalent to a value in the typedef
481 * '_char_class_number'.
483 * This just calls isFOO_lc on the code point for the character if it is in
484 * the range 0-255. Outside that range, all characters use Unicode
485 * rules, ignoring any locale. So use the Unicode function if this class
486 * requires a swash, and use the Unicode macro otherwise. */
488 PERL_ARGS_ASSERT_ISFOO_UTF8_LC;
490 if (UTF8_IS_INVARIANT(*character)) {
491 return isFOO_lc(classnum, *character);
493 else if (UTF8_IS_DOWNGRADEABLE_START(*character)) {
494 return isFOO_lc(classnum,
495 EIGHT_BIT_UTF8_TO_NATIVE(*character, *(character + 1)));
498 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(character, character + UTF8SKIP(character));
500 if (classnum < _FIRST_NON_SWASH_CC) {
502 /* Initialize the swash unless done already */
503 if (! PL_utf8_swash_ptrs[classnum]) {
504 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
505 PL_utf8_swash_ptrs[classnum] =
506 _core_swash_init("utf8",
509 PL_XPosix_ptrs[classnum], &flags);
512 return cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum], (U8 *)
514 TRUE /* is UTF */ ));
517 switch ((_char_class_number) classnum) {
518 case _CC_ENUM_SPACE: return is_XPERLSPACE_high(character);
519 case _CC_ENUM_BLANK: return is_HORIZWS_high(character);
520 case _CC_ENUM_XDIGIT: return is_XDIGIT_high(character);
521 case _CC_ENUM_VERTSPACE: return is_VERTWS_high(character);
525 return FALSE; /* Things like CNTRL are always below 256 */
529 * pregexec and friends
532 #ifndef PERL_IN_XSUB_RE
534 - pregexec - match a regexp against a string
537 Perl_pregexec(pTHX_ REGEXP * const prog, char* stringarg, char *strend,
538 char *strbeg, SSize_t minend, SV *screamer, U32 nosave)
539 /* stringarg: the point in the string at which to begin matching */
540 /* strend: pointer to null at end of string */
541 /* strbeg: real beginning of string */
542 /* minend: end of match must be >= minend bytes after stringarg. */
543 /* screamer: SV being matched: only used for utf8 flag, pos() etc; string
544 * itself is accessed via the pointers above */
545 /* nosave: For optimizations. */
547 PERL_ARGS_ASSERT_PREGEXEC;
550 regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
551 nosave ? 0 : REXEC_COPY_STR);
557 /* re_intuit_start():
559 * Based on some optimiser hints, try to find the earliest position in the
560 * string where the regex could match.
562 * rx: the regex to match against
563 * sv: the SV being matched: only used for utf8 flag; the string
564 * itself is accessed via the pointers below. Note that on
565 * something like an overloaded SV, SvPOK(sv) may be false
566 * and the string pointers may point to something unrelated to
568 * strbeg: real beginning of string
569 * strpos: the point in the string at which to begin matching
570 * strend: pointer to the byte following the last char of the string
571 * flags currently unused; set to 0
572 * data: currently unused; set to NULL
574 * The basic idea of re_intuit_start() is to use some known information
575 * about the pattern, namely:
577 * a) the longest known anchored substring (i.e. one that's at a
578 * constant offset from the beginning of the pattern; but not
579 * necessarily at a fixed offset from the beginning of the
581 * b) the longest floating substring (i.e. one that's not at a constant
582 * offset from the beginning of the pattern);
583 * c) Whether the pattern is anchored to the string; either
584 * an absolute anchor: /^../, or anchored to \n: /^.../m,
585 * or anchored to pos(): /\G/;
586 * d) A start class: a real or synthetic character class which
587 * represents which characters are legal at the start of the pattern;
589 * to either quickly reject the match, or to find the earliest position
590 * within the string at which the pattern might match, thus avoiding
591 * running the full NFA engine at those earlier locations, only to
592 * eventually fail and retry further along.
594 * Returns NULL if the pattern can't match, or returns the address within
595 * the string which is the earliest place the match could occur.
597 * The longest of the anchored and floating substrings is called 'check'
598 * and is checked first. The other is called 'other' and is checked
599 * second. The 'other' substring may not be present. For example,
601 * /(abc|xyz)ABC\d{0,3}DEFG/
605 * check substr (float) = "DEFG", offset 6..9 chars
606 * other substr (anchored) = "ABC", offset 3..3 chars
609 * Be aware that during the course of this function, sometimes 'anchored'
610 * refers to a substring being anchored relative to the start of the
611 * pattern, and sometimes to the pattern itself being anchored relative to
612 * the string. For example:
614 * /\dabc/: "abc" is anchored to the pattern;
615 * /^\dabc/: "abc" is anchored to the pattern and the string;
616 * /\d+abc/: "abc" is anchored to neither the pattern nor the string;
617 * /^\d+abc/: "abc" is anchored to neither the pattern nor the string,
618 * but the pattern is anchored to the string.
622 Perl_re_intuit_start(pTHX_
625 const char * const strbeg,
629 re_scream_pos_data *data)
631 struct regexp *const prog = ReANY(rx);
632 SSize_t start_shift = prog->check_offset_min;
633 /* Should be nonnegative! */
634 SSize_t end_shift = 0;
635 /* current lowest pos in string where the regex can start matching */
636 char *rx_origin = strpos;
638 const bool utf8_target = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
639 U8 other_ix = 1 - prog->substrs->check_ix;
641 char *other_last = strpos;/* latest pos 'other' substr already checked to */
642 char *check_at = NULL; /* check substr found at this pos */
643 const I32 multiline = prog->extflags & RXf_PMf_MULTILINE;
644 RXi_GET_DECL(prog,progi);
645 regmatch_info reginfo_buf; /* create some info to pass to find_byclass */
646 regmatch_info *const reginfo = ®info_buf;
647 GET_RE_DEBUG_FLAGS_DECL;
649 PERL_ARGS_ASSERT_RE_INTUIT_START;
650 PERL_UNUSED_ARG(flags);
651 PERL_UNUSED_ARG(data);
653 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
654 "Intuit: trying to determine minimum start position...\n"));
656 /* for now, assume that all substr offsets are positive. If at some point
657 * in the future someone wants to do clever things with lookbehind and
658 * -ve offsets, they'll need to fix up any code in this function
659 * which uses these offsets. See the thread beginning
660 * <20140113145929.GF27210@iabyn.com>
662 assert(prog->substrs->data[0].min_offset >= 0);
663 assert(prog->substrs->data[0].max_offset >= 0);
664 assert(prog->substrs->data[1].min_offset >= 0);
665 assert(prog->substrs->data[1].max_offset >= 0);
666 assert(prog->substrs->data[2].min_offset >= 0);
667 assert(prog->substrs->data[2].max_offset >= 0);
669 /* for now, assume that if both present, that the floating substring
670 * doesn't start before the anchored substring.
671 * If you break this assumption (e.g. doing better optimisations
672 * with lookahead/behind), then you'll need to audit the code in this
673 * function carefully first
676 ! ( (prog->anchored_utf8 || prog->anchored_substr)
677 && (prog->float_utf8 || prog->float_substr))
678 || (prog->float_min_offset >= prog->anchored_offset));
680 /* byte rather than char calculation for efficiency. It fails
681 * to quickly reject some cases that can't match, but will reject
682 * them later after doing full char arithmetic */
683 if (prog->minlen > strend - strpos) {
684 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
685 " String too short...\n"));
689 RX_MATCH_UTF8_set(rx,utf8_target);
690 reginfo->is_utf8_target = cBOOL(utf8_target);
691 reginfo->info_aux = NULL;
692 reginfo->strbeg = strbeg;
693 reginfo->strend = strend;
694 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
696 /* not actually used within intuit, but zero for safety anyway */
697 reginfo->poscache_maxiter = 0;
700 if (!prog->check_utf8 && prog->check_substr)
701 to_utf8_substr(prog);
702 check = prog->check_utf8;
704 if (!prog->check_substr && prog->check_utf8) {
705 if (! to_byte_substr(prog)) {
706 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(fail);
709 check = prog->check_substr;
712 /* dump the various substring data */
713 DEBUG_OPTIMISE_MORE_r({
715 for (i=0; i<=2; i++) {
716 SV *sv = (utf8_target ? prog->substrs->data[i].utf8_substr
717 : prog->substrs->data[i].substr);
721 PerlIO_printf(Perl_debug_log,
722 " substrs[%d]: min=%"IVdf" max=%"IVdf" end shift=%"IVdf
723 " useful=%"IVdf" utf8=%d [%s]\n",
725 (IV)prog->substrs->data[i].min_offset,
726 (IV)prog->substrs->data[i].max_offset,
727 (IV)prog->substrs->data[i].end_shift,
734 if (prog->intflags & PREGf_ANCH) { /* Match at \G, beg-of-str or after \n */
736 /* ml_anch: check after \n?
738 * A note about PREGf_IMPLICIT: on an un-anchored pattern beginning
739 * with /.*.../, these flags will have been added by the
741 * /.*abc/, /.*abc/m: PREGf_IMPLICIT | PREGf_ANCH_MBOL
742 * /.*abc/s: PREGf_IMPLICIT | PREGf_ANCH_SBOL
744 ml_anch = (prog->intflags & PREGf_ANCH_MBOL)
745 && !(prog->intflags & PREGf_IMPLICIT);
747 if (!ml_anch && !(prog->intflags & PREGf_IMPLICIT)) {
748 /* we are only allowed to match at BOS or \G */
750 /* trivially reject if there's a BOS anchor and we're not at BOS.
752 * Note that we don't try to do a similar quick reject for
753 * \G, since generally the caller will have calculated strpos
754 * based on pos() and gofs, so the string is already correctly
755 * anchored by definition; and handling the exceptions would
756 * be too fiddly (e.g. REXEC_IGNOREPOS).
758 if ( strpos != strbeg
759 && (prog->intflags & PREGf_ANCH_SBOL))
761 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
762 " Not at start...\n"));
766 /* in the presence of an anchor, the anchored (relative to the
767 * start of the regex) substr must also be anchored relative
768 * to strpos. So quickly reject if substr isn't found there.
769 * This works for \G too, because the caller will already have
770 * subtracted gofs from pos, and gofs is the offset from the
771 * \G to the start of the regex. For example, in /.abc\Gdef/,
772 * where substr="abcdef", pos()=3, gofs=4, offset_min=1:
773 * caller will have set strpos=pos()-4; we look for the substr
774 * at position pos()-4+1, which lines up with the "a" */
776 if (prog->check_offset_min == prog->check_offset_max) {
777 /* Substring at constant offset from beg-of-str... */
778 SSize_t slen = SvCUR(check);
779 char *s = HOP3c(strpos, prog->check_offset_min, strend);
781 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
782 " Looking for check substr at fixed offset %"IVdf"...\n",
783 (IV)prog->check_offset_min));
786 /* In this case, the regex is anchored at the end too.
787 * Unless it's a multiline match, the lengths must match
788 * exactly, give or take a \n. NB: slen >= 1 since
789 * the last char of check is \n */
791 && ( strend - s > slen
792 || strend - s < slen - 1
793 || (strend - s == slen && strend[-1] != '\n')))
795 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
796 " String too long...\n"));
799 /* Now should match s[0..slen-2] */
802 if (slen && (*SvPVX_const(check) != *s
803 || (slen > 1 && memNE(SvPVX_const(check), s, slen))))
805 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
806 " String not equal...\n"));
811 goto success_at_start;
816 end_shift = prog->check_end_shift;
818 #ifdef DEBUGGING /* 7/99: reports of failure (with the older version) */
820 Perl_croak(aTHX_ "panic: end_shift: %"IVdf" pattern:\n%s\n ",
821 (IV)end_shift, RX_PRECOMP(prog));
826 /* This is the (re)entry point of the main loop in this function.
827 * The goal of this loop is to:
828 * 1) find the "check" substring in the region rx_origin..strend
829 * (adjusted by start_shift / end_shift). If not found, reject
831 * 2) If it exists, look for the "other" substr too if defined; for
832 * example, if the check substr maps to the anchored substr, then
833 * check the floating substr, and vice-versa. If not found, go
834 * back to (1) with rx_origin suitably incremented.
835 * 3) If we find an rx_origin position that doesn't contradict
836 * either of the substrings, then check the possible additional
837 * constraints on rx_origin of /^.../m or a known start class.
838 * If these fail, then depending on which constraints fail, jump
839 * back to here, or to various other re-entry points further along
840 * that skip some of the first steps.
841 * 4) If we pass all those tests, update the BmUSEFUL() count on the
842 * substring. If the start position was determined to be at the
843 * beginning of the string - so, not rejected, but not optimised,
844 * since we have to run regmatch from position 0 - decrement the
845 * BmUSEFUL() count. Otherwise increment it.
849 /* first, look for the 'check' substring */
855 DEBUG_OPTIMISE_MORE_r({
856 PerlIO_printf(Perl_debug_log,
857 " At restart: rx_origin=%"IVdf" Check offset min: %"IVdf
858 " Start shift: %"IVdf" End shift %"IVdf
859 " Real end Shift: %"IVdf"\n",
860 (IV)(rx_origin - strbeg),
861 (IV)prog->check_offset_min,
864 (IV)prog->check_end_shift);
867 end_point = HOP3(strend, -end_shift, strbeg);
868 start_point = HOPMAYBE3(rx_origin, start_shift, end_point);
873 /* If the regex is absolutely anchored to either the start of the
874 * string (SBOL) or to pos() (ANCH_GPOS), then
875 * check_offset_max represents an upper bound on the string where
876 * the substr could start. For the ANCH_GPOS case, we assume that
877 * the caller of intuit will have already set strpos to
878 * pos()-gofs, so in this case strpos + offset_max will still be
879 * an upper bound on the substr.
882 && prog->intflags & PREGf_ANCH
883 && prog->check_offset_max != SSize_t_MAX)
885 SSize_t len = SvCUR(check) - !!SvTAIL(check);
886 const char * const anchor =
887 (prog->intflags & PREGf_ANCH_GPOS ? strpos : strbeg);
889 /* do a bytes rather than chars comparison. It's conservative;
890 * so it skips doing the HOP if the result can't possibly end
891 * up earlier than the old value of end_point.
893 if ((char*)end_point - anchor > prog->check_offset_max) {
894 end_point = HOP3lim((U8*)anchor,
895 prog->check_offset_max,
901 check_at = fbm_instr( start_point, end_point,
902 check, multiline ? FBMrf_MULTILINE : 0);
904 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
905 " doing 'check' fbm scan, [%"IVdf"..%"IVdf"] gave %"IVdf"\n",
906 (IV)((char*)start_point - strbeg),
907 (IV)((char*)end_point - strbeg),
908 (IV)(check_at ? check_at - strbeg : -1)
911 /* Update the count-of-usability, remove useless subpatterns,
915 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
916 SvPVX_const(check), RE_SV_DUMPLEN(check), 30);
917 PerlIO_printf(Perl_debug_log, " %s %s substr %s%s%s",
918 (check_at ? "Found" : "Did not find"),
919 (check == (utf8_target ? prog->anchored_utf8 : prog->anchored_substr)
920 ? "anchored" : "floating"),
923 (check_at ? " at offset " : "...\n") );
928 /* set rx_origin to the minimum position where the regex could start
929 * matching, given the constraint of the just-matched check substring.
930 * But don't set it lower than previously.
933 if (check_at - rx_origin > prog->check_offset_max)
934 rx_origin = HOP3c(check_at, -prog->check_offset_max, rx_origin);
935 /* Finish the diagnostic message */
936 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
937 "%ld (rx_origin now %"IVdf")...\n",
938 (long)(check_at - strbeg),
939 (IV)(rx_origin - strbeg)
944 /* now look for the 'other' substring if defined */
946 if (utf8_target ? prog->substrs->data[other_ix].utf8_substr
947 : prog->substrs->data[other_ix].substr)
949 /* Take into account the "other" substring. */
953 struct reg_substr_datum *other;
956 other = &prog->substrs->data[other_ix];
958 /* if "other" is anchored:
959 * we've previously found a floating substr starting at check_at.
960 * This means that the regex origin must lie somewhere
961 * between min (rx_origin): HOP3(check_at, -check_offset_max)
962 * and max: HOP3(check_at, -check_offset_min)
963 * (except that min will be >= strpos)
964 * So the fixed substr must lie somewhere between
965 * HOP3(min, anchored_offset)
966 * HOP3(max, anchored_offset) + SvCUR(substr)
969 /* if "other" is floating
970 * Calculate last1, the absolute latest point where the
971 * floating substr could start in the string, ignoring any
972 * constraints from the earlier fixed match. It is calculated
975 * strend - prog->minlen (in chars) is the absolute latest
976 * position within the string where the origin of the regex
977 * could appear. The latest start point for the floating
978 * substr is float_min_offset(*) on from the start of the
979 * regex. last1 simply combines thee two offsets.
981 * (*) You might think the latest start point should be
982 * float_max_offset from the regex origin, and technically
983 * you'd be correct. However, consider
985 * Here, float min, max are 3,5 and minlen is 7.
986 * This can match either
990 * In the first case, the regex matches minlen chars; in the
991 * second, minlen+1, in the third, minlen+2.
992 * In the first case, the floating offset is 3 (which equals
993 * float_min), in the second, 4, and in the third, 5 (which
994 * equals float_max). In all cases, the floating string bcd
995 * can never start more than 4 chars from the end of the
996 * string, which equals minlen - float_min. As the substring
997 * starts to match more than float_min from the start of the
998 * regex, it makes the regex match more than minlen chars,
999 * and the two cancel each other out. So we can always use
1000 * float_min - minlen, rather than float_max - minlen for the
1001 * latest position in the string.
1003 * Note that -minlen + float_min_offset is equivalent (AFAIKT)
1004 * to CHR_SVLEN(must) - !!SvTAIL(must) + prog->float_end_shift
1007 assert(prog->minlen >= other->min_offset);
1008 last1 = HOP3c(strend,
1009 other->min_offset - prog->minlen, strbeg);
1011 if (other_ix) {/* i.e. if (other-is-float) */
1012 /* last is the latest point where the floating substr could
1013 * start, *given* any constraints from the earlier fixed
1014 * match. This constraint is that the floating string starts
1015 * <= float_max_offset chars from the regex origin (rx_origin).
1016 * If this value is less than last1, use it instead.
1018 assert(rx_origin <= last1);
1020 /* this condition handles the offset==infinity case, and
1021 * is a short-cut otherwise. Although it's comparing a
1022 * byte offset to a char length, it does so in a safe way,
1023 * since 1 char always occupies 1 or more bytes,
1024 * so if a string range is (last1 - rx_origin) bytes,
1025 * it will be less than or equal to (last1 - rx_origin)
1026 * chars; meaning it errs towards doing the accurate HOP3
1027 * rather than just using last1 as a short-cut */
1028 (last1 - rx_origin) < other->max_offset
1030 : (char*)HOP3lim(rx_origin, other->max_offset, last1);
1033 assert(strpos + start_shift <= check_at);
1034 last = HOP4c(check_at, other->min_offset - start_shift,
1038 s = HOP3c(rx_origin, other->min_offset, strend);
1039 if (s < other_last) /* These positions already checked */
1042 must = utf8_target ? other->utf8_substr : other->substr;
1043 assert(SvPOK(must));
1046 char *to = last + SvCUR(must) - (SvTAIL(must)!=0);
1050 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1051 " skipping 'other' fbm scan: %"IVdf" > %"IVdf"\n",
1052 (IV)(from - strbeg),
1058 (unsigned char*)from,
1061 multiline ? FBMrf_MULTILINE : 0
1063 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1064 " doing 'other' fbm scan, [%"IVdf"..%"IVdf"] gave %"IVdf"\n",
1065 (IV)(from - strbeg),
1067 (IV)(s ? s - strbeg : -1)
1073 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
1074 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
1075 PerlIO_printf(Perl_debug_log, " %s %s substr %s%s",
1076 s ? "Found" : "Contradicts",
1077 other_ix ? "floating" : "anchored",
1078 quoted, RE_SV_TAIL(must));
1083 /* last1 is latest possible substr location. If we didn't
1084 * find it before there, we never will */
1085 if (last >= last1) {
1086 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1087 "; giving up...\n"));
1091 /* try to find the check substr again at a later
1092 * position. Maybe next time we'll find the "other" substr
1094 other_last = HOP3c(last, 1, strend) /* highest failure */;
1096 other_ix /* i.e. if other-is-float */
1097 ? HOP3c(rx_origin, 1, strend)
1098 : HOP4c(last, 1 - other->min_offset, strbeg, strend);
1099 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1100 "; about to retry %s at offset %ld (rx_origin now %"IVdf")...\n",
1101 (other_ix ? "floating" : "anchored"),
1102 (long)(HOP3c(check_at, 1, strend) - strbeg),
1103 (IV)(rx_origin - strbeg)
1108 if (other_ix) { /* if (other-is-float) */
1109 /* other_last is set to s, not s+1, since its possible for
1110 * a floating substr to fail first time, then succeed
1111 * second time at the same floating position; e.g.:
1112 * "-AB--AABZ" =~ /\wAB\d*Z/
1113 * The first time round, anchored and float match at
1114 * "-(AB)--AAB(Z)" then fail on the initial \w character
1115 * class. Second time round, they match at "-AB--A(AB)(Z)".
1120 rx_origin = HOP3c(s, -other->min_offset, strbeg);
1121 other_last = HOP3c(s, 1, strend);
1123 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1124 " at offset %ld (rx_origin now %"IVdf")...\n",
1126 (IV)(rx_origin - strbeg)
1132 DEBUG_OPTIMISE_MORE_r(
1133 PerlIO_printf(Perl_debug_log,
1134 " Check-only match: offset min:%"IVdf" max:%"IVdf
1135 " check_at:%"IVdf" rx_origin:%"IVdf" rx_origin-check_at:%"IVdf
1136 " strend:%"IVdf"\n",
1137 (IV)prog->check_offset_min,
1138 (IV)prog->check_offset_max,
1139 (IV)(check_at-strbeg),
1140 (IV)(rx_origin-strbeg),
1141 (IV)(rx_origin-check_at),
1147 postprocess_substr_matches:
1149 /* handle the extra constraint of /^.../m if present */
1151 if (ml_anch && rx_origin != strbeg && rx_origin[-1] != '\n') {
1154 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1155 " looking for /^/m anchor"));
1157 /* we have failed the constraint of a \n before rx_origin.
1158 * Find the next \n, if any, even if it's beyond the current
1159 * anchored and/or floating substrings. Whether we should be
1160 * scanning ahead for the next \n or the next substr is debatable.
1161 * On the one hand you'd expect rare substrings to appear less
1162 * often than \n's. On the other hand, searching for \n means
1163 * we're effectively flipping between check_substr and "\n" on each
1164 * iteration as the current "rarest" string candidate, which
1165 * means for example that we'll quickly reject the whole string if
1166 * hasn't got a \n, rather than trying every substr position
1170 s = HOP3c(strend, - prog->minlen, strpos);
1171 if (s <= rx_origin ||
1172 ! ( rx_origin = (char *)memchr(rx_origin, '\n', s - rx_origin)))
1174 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1175 " Did not find /%s^%s/m...\n",
1176 PL_colors[0], PL_colors[1]));
1180 /* earliest possible origin is 1 char after the \n.
1181 * (since *rx_origin == '\n', it's safe to ++ here rather than
1182 * HOP(rx_origin, 1)) */
1185 if (prog->substrs->check_ix == 0 /* check is anchored */
1186 || rx_origin >= HOP3c(check_at, - prog->check_offset_min, strpos))
1188 /* Position contradicts check-string; either because
1189 * check was anchored (and thus has no wiggle room),
1190 * or check was float and rx_origin is above the float range */
1191 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1192 " Found /%s^%s/m, about to restart lookup for check-string with rx_origin %ld...\n",
1193 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1197 /* if we get here, the check substr must have been float,
1198 * is in range, and we may or may not have had an anchored
1199 * "other" substr which still contradicts */
1200 assert(prog->substrs->check_ix); /* check is float */
1202 if (utf8_target ? prog->anchored_utf8 : prog->anchored_substr) {
1203 /* whoops, the anchored "other" substr exists, so we still
1204 * contradict. On the other hand, the float "check" substr
1205 * didn't contradict, so just retry the anchored "other"
1207 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1208 " Found /%s^%s/m, rescanning for anchored from offset %"IVdf" (rx_origin now %"IVdf")...\n",
1209 PL_colors[0], PL_colors[1],
1210 (IV)(rx_origin - strbeg + prog->anchored_offset),
1211 (IV)(rx_origin - strbeg)
1213 goto do_other_substr;
1216 /* success: we don't contradict the found floating substring
1217 * (and there's no anchored substr). */
1218 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1219 " Found /%s^%s/m with rx_origin %ld...\n",
1220 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1223 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1224 " (multiline anchor test skipped)\n"));
1230 /* if we have a starting character class, then test that extra constraint.
1231 * (trie stclasses are too expensive to use here, we are better off to
1232 * leave it to regmatch itself) */
1234 if (progi->regstclass && PL_regkind[OP(progi->regstclass)]!=TRIE) {
1235 const U8* const str = (U8*)STRING(progi->regstclass);
1237 /* XXX this value could be pre-computed */
1238 const int cl_l = (PL_regkind[OP(progi->regstclass)] == EXACT
1239 ? (reginfo->is_utf8_pat
1240 ? utf8_distance(str + STR_LEN(progi->regstclass), str)
1241 : STR_LEN(progi->regstclass))
1245 /* latest pos that a matching float substr constrains rx start to */
1246 char *rx_max_float = NULL;
1248 /* if the current rx_origin is anchored, either by satisfying an
1249 * anchored substring constraint, or a /^.../m constraint, then we
1250 * can reject the current origin if the start class isn't found
1251 * at the current position. If we have a float-only match, then
1252 * rx_origin is constrained to a range; so look for the start class
1253 * in that range. if neither, then look for the start class in the
1254 * whole rest of the string */
1256 /* XXX DAPM it's not clear what the minlen test is for, and why
1257 * it's not used in the floating case. Nothing in the test suite
1258 * causes minlen == 0 here. See <20140313134639.GS12844@iabyn.com>.
1259 * Here are some old comments, which may or may not be correct:
1261 * minlen == 0 is possible if regstclass is \b or \B,
1262 * and the fixed substr is ''$.
1263 * Since minlen is already taken into account, rx_origin+1 is
1264 * before strend; accidentally, minlen >= 1 guaranties no false
1265 * positives at rx_origin + 1 even for \b or \B. But (minlen? 1 :
1266 * 0) below assumes that regstclass does not come from lookahead...
1267 * If regstclass takes bytelength more than 1: If charlength==1, OK.
1268 * This leaves EXACTF-ish only, which are dealt with in
1272 if (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
1273 endpos= HOP3c(rx_origin, (prog->minlen ? cl_l : 0), strend);
1274 else if (prog->float_substr || prog->float_utf8) {
1275 rx_max_float = HOP3c(check_at, -start_shift, strbeg);
1276 endpos= HOP3c(rx_max_float, cl_l, strend);
1281 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1282 " looking for class: start_shift: %"IVdf" check_at: %"IVdf
1283 " rx_origin: %"IVdf" endpos: %"IVdf"\n",
1284 (IV)start_shift, (IV)(check_at - strbeg),
1285 (IV)(rx_origin - strbeg), (IV)(endpos - strbeg)));
1287 s = find_byclass(prog, progi->regstclass, rx_origin, endpos,
1290 if (endpos == strend) {
1291 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1292 " Could not match STCLASS...\n") );
1295 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1296 " This position contradicts STCLASS...\n") );
1297 if ((prog->intflags & PREGf_ANCH) && !ml_anch
1298 && !(prog->intflags & PREGf_IMPLICIT))
1301 /* Contradict one of substrings */
1302 if (prog->anchored_substr || prog->anchored_utf8) {
1303 if (prog->substrs->check_ix == 1) { /* check is float */
1304 /* Have both, check_string is floating */
1305 assert(rx_origin + start_shift <= check_at);
1306 if (rx_origin + start_shift != check_at) {
1307 /* not at latest position float substr could match:
1308 * Recheck anchored substring, but not floating.
1309 * The condition above is in bytes rather than
1310 * chars for efficiency. It's conservative, in
1311 * that it errs on the side of doing 'goto
1312 * do_other_substr'. In this case, at worst,
1313 * an extra anchored search may get done, but in
1314 * practice the extra fbm_instr() is likely to
1315 * get skipped anyway. */
1316 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1317 " about to retry anchored at offset %ld (rx_origin now %"IVdf")...\n",
1318 (long)(other_last - strbeg),
1319 (IV)(rx_origin - strbeg)
1321 goto do_other_substr;
1329 /* In the presence of ml_anch, we might be able to
1330 * find another \n without breaking the current float
1333 /* strictly speaking this should be HOP3c(..., 1, ...),
1334 * but since we goto a block of code that's going to
1335 * search for the next \n if any, its safe here */
1337 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1338 " about to look for /%s^%s/m starting at rx_origin %ld...\n",
1339 PL_colors[0], PL_colors[1],
1340 (long)(rx_origin - strbeg)) );
1341 goto postprocess_substr_matches;
1344 /* strictly speaking this can never be true; but might
1345 * be if we ever allow intuit without substrings */
1346 if (!(utf8_target ? prog->float_utf8 : prog->float_substr))
1349 rx_origin = rx_max_float;
1352 /* at this point, any matching substrings have been
1353 * contradicted. Start again... */
1355 rx_origin = HOP3c(rx_origin, 1, strend);
1357 /* uses bytes rather than char calculations for efficiency.
1358 * It's conservative: it errs on the side of doing 'goto restart',
1359 * where there is code that does a proper char-based test */
1360 if (rx_origin + start_shift + end_shift > strend) {
1361 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1362 " Could not match STCLASS...\n") );
1365 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1366 " about to look for %s substr starting at offset %ld (rx_origin now %"IVdf")...\n",
1367 (prog->substrs->check_ix ? "floating" : "anchored"),
1368 (long)(rx_origin + start_shift - strbeg),
1369 (IV)(rx_origin - strbeg)
1376 if (rx_origin != s) {
1377 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1378 " By STCLASS: moving %ld --> %ld\n",
1379 (long)(rx_origin - strbeg), (long)(s - strbeg))
1383 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1384 " Does not contradict STCLASS...\n");
1389 /* Decide whether using the substrings helped */
1391 if (rx_origin != strpos) {
1392 /* Fixed substring is found far enough so that the match
1393 cannot start at strpos. */
1395 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " try at offset...\n"));
1396 ++BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr); /* hooray/5 */
1399 /* The found rx_origin position does not prohibit matching at
1400 * strpos, so calling intuit didn't gain us anything. Decrement
1401 * the BmUSEFUL() count on the check substring, and if we reach
1403 if (!(prog->intflags & PREGf_NAUGHTY)
1405 prog->check_utf8 /* Could be deleted already */
1406 && --BmUSEFUL(prog->check_utf8) < 0
1407 && (prog->check_utf8 == prog->float_utf8)
1409 prog->check_substr /* Could be deleted already */
1410 && --BmUSEFUL(prog->check_substr) < 0
1411 && (prog->check_substr == prog->float_substr)
1414 /* If flags & SOMETHING - do not do it many times on the same match */
1415 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " ... Disabling check substring...\n"));
1416 /* XXX Does the destruction order has to change with utf8_target? */
1417 SvREFCNT_dec(utf8_target ? prog->check_utf8 : prog->check_substr);
1418 SvREFCNT_dec(utf8_target ? prog->check_substr : prog->check_utf8);
1419 prog->check_substr = prog->check_utf8 = NULL; /* disable */
1420 prog->float_substr = prog->float_utf8 = NULL; /* clear */
1421 check = NULL; /* abort */
1422 /* XXXX This is a remnant of the old implementation. It
1423 looks wasteful, since now INTUIT can use many
1424 other heuristics. */
1425 prog->extflags &= ~RXf_USE_INTUIT;
1429 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1430 "Intuit: %sSuccessfully guessed:%s match at offset %ld\n",
1431 PL_colors[4], PL_colors[5], (long)(rx_origin - strbeg)) );
1435 fail_finish: /* Substring not found */
1436 if (prog->check_substr || prog->check_utf8) /* could be removed already */
1437 BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
1439 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch rejected by optimizer%s\n",
1440 PL_colors[4], PL_colors[5]));
1445 #define DECL_TRIE_TYPE(scan) \
1446 const enum { trie_plain, trie_utf8, trie_utf8_fold, trie_latin_utf8_fold, \
1447 trie_utf8_exactfa_fold, trie_latin_utf8_exactfa_fold, \
1448 trie_utf8l, trie_flu8 } \
1449 trie_type = ((scan->flags == EXACT) \
1450 ? (utf8_target ? trie_utf8 : trie_plain) \
1451 : (scan->flags == EXACTL) \
1452 ? (utf8_target ? trie_utf8l : trie_plain) \
1453 : (scan->flags == EXACTFA) \
1455 ? trie_utf8_exactfa_fold \
1456 : trie_latin_utf8_exactfa_fold) \
1457 : (scan->flags == EXACTFLU8 \
1461 : trie_latin_utf8_fold)))
1463 #define REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc, uscan, len, uvc, charid, foldlen, foldbuf, uniflags) \
1466 U8 flags = FOLD_FLAGS_FULL; \
1467 switch (trie_type) { \
1469 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1470 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1471 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1473 goto do_trie_utf8_fold; \
1474 case trie_utf8_exactfa_fold: \
1475 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1477 case trie_utf8_fold: \
1478 do_trie_utf8_fold: \
1479 if ( foldlen>0 ) { \
1480 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1485 uvc = _to_utf8_fold_flags( (const U8*) uc, foldbuf, &foldlen, flags); \
1486 len = UTF8SKIP(uc); \
1487 skiplen = UVCHR_SKIP( uvc ); \
1488 foldlen -= skiplen; \
1489 uscan = foldbuf + skiplen; \
1492 case trie_latin_utf8_exactfa_fold: \
1493 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1495 case trie_latin_utf8_fold: \
1496 if ( foldlen>0 ) { \
1497 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1503 uvc = _to_fold_latin1( (U8) *uc, foldbuf, &foldlen, flags); \
1504 skiplen = UVCHR_SKIP( uvc ); \
1505 foldlen -= skiplen; \
1506 uscan = foldbuf + skiplen; \
1510 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1511 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1512 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1516 uvc = utf8n_to_uvchr( (const U8*) uc, UTF8_MAXLEN, &len, uniflags ); \
1523 charid = trie->charmap[ uvc ]; \
1527 if (widecharmap) { \
1528 SV** const svpp = hv_fetch(widecharmap, \
1529 (char*)&uvc, sizeof(UV), 0); \
1531 charid = (U16)SvIV(*svpp); \
1536 #define DUMP_EXEC_POS(li,s,doutf8) \
1537 dump_exec_pos(li,s,(reginfo->strend),(reginfo->strbeg), \
1540 #define REXEC_FBC_EXACTISH_SCAN(COND) \
1544 && (ln == 1 || folder(s, pat_string, ln)) \
1545 && (reginfo->intuit || regtry(reginfo, &s)) )\
1551 #define REXEC_FBC_UTF8_SCAN(CODE) \
1553 while (s < strend) { \
1559 #define REXEC_FBC_SCAN(CODE) \
1561 while (s < strend) { \
1567 #define REXEC_FBC_UTF8_CLASS_SCAN(COND) \
1568 REXEC_FBC_UTF8_SCAN( /* Loops while (s < strend) */ \
1570 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1579 #define REXEC_FBC_CLASS_SCAN(COND) \
1580 REXEC_FBC_SCAN( /* Loops while (s < strend) */ \
1582 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1591 #define REXEC_FBC_CSCAN(CONDUTF8,COND) \
1592 if (utf8_target) { \
1593 REXEC_FBC_UTF8_CLASS_SCAN(CONDUTF8); \
1596 REXEC_FBC_CLASS_SCAN(COND); \
1599 /* The three macros below are slightly different versions of the same logic.
1601 * The first is for /a and /aa when the target string is UTF-8. This can only
1602 * match ascii, but it must advance based on UTF-8. The other two handle the
1603 * non-UTF-8 and the more generic UTF-8 cases. In all three, we are looking
1604 * for the boundary (or non-boundary) between a word and non-word character.
1605 * The utf8 and non-utf8 cases have the same logic, but the details must be
1606 * different. Find the "wordness" of the character just prior to this one, and
1607 * compare it with the wordness of this one. If they differ, we have a
1608 * boundary. At the beginning of the string, pretend that the previous
1609 * character was a new-line.
1611 * All these macros uncleanly have side-effects with each other and outside
1612 * variables. So far it's been too much trouble to clean-up
1614 * TEST_NON_UTF8 is the macro or function to call to test if its byte input is
1615 * a word character or not.
1616 * IF_SUCCESS is code to do if it finds that we are at a boundary between
1618 * IF_FAIL is code to do if we aren't at a boundary between word/non-word
1620 * Exactly one of the two IF_FOO parameters is a no-op, depending on whether we
1621 * are looking for a boundary or for a non-boundary. If we are looking for a
1622 * boundary, we want IF_FAIL to be the no-op, and for IF_SUCCESS to go out and
1623 * see if this tentative match actually works, and if so, to quit the loop
1624 * here. And vice-versa if we are looking for a non-boundary.
1626 * 'tmp' below in the next three macros in the REXEC_FBC_SCAN and
1627 * REXEC_FBC_UTF8_SCAN loops is a loop invariant, a bool giving the return of
1628 * TEST_NON_UTF8(s-1). To see this, note that that's what it is defined to be
1629 * at entry to the loop, and to get to the IF_FAIL branch, tmp must equal
1630 * TEST_NON_UTF8(s), and in the opposite branch, IF_SUCCESS, tmp is that
1631 * complement. But in that branch we complement tmp, meaning that at the
1632 * bottom of the loop tmp is always going to be equal to TEST_NON_UTF8(s),
1633 * which means at the top of the loop in the next iteration, it is
1634 * TEST_NON_UTF8(s-1) */
1635 #define FBC_UTF8_A(TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1636 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1637 tmp = TEST_NON_UTF8(tmp); \
1638 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1639 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1641 IF_SUCCESS; /* Is a boundary if values for s-1 and s differ */ \
1648 /* Like FBC_UTF8_A, but TEST_UV is a macro which takes a UV as its input, and
1649 * TEST_UTF8 is a macro that for the same input code points returns identically
1650 * to TEST_UV, but takes a pointer to a UTF-8 encoded string instead */
1651 #define FBC_UTF8(TEST_UV, TEST_UTF8, IF_SUCCESS, IF_FAIL) \
1652 if (s == reginfo->strbeg) { \
1655 else { /* Back-up to the start of the previous character */ \
1656 U8 * const r = reghop3((U8*)s, -1, (U8*)reginfo->strbeg); \
1657 tmp = utf8n_to_uvchr(r, (U8*) reginfo->strend - r, \
1658 0, UTF8_ALLOW_DEFAULT); \
1660 tmp = TEST_UV(tmp); \
1661 LOAD_UTF8_CHARCLASS_ALNUM(); \
1662 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1663 if (tmp == ! (TEST_UTF8((U8 *) s))) { \
1672 /* Like the above two macros. UTF8_CODE is the complete code for handling
1673 * UTF-8. Common to the BOUND and NBOUND cases, set-up by the FBC_BOUND, etc
1675 #define FBC_BOUND_COMMON(UTF8_CODE, TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1676 if (utf8_target) { \
1679 else { /* Not utf8 */ \
1680 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1681 tmp = TEST_NON_UTF8(tmp); \
1682 REXEC_FBC_SCAN( /* advances s while s < strend */ \
1683 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1692 /* Here, things have been set up by the previous code so that tmp is the \
1693 * return of TEST_NON_UTF(s-1) or TEST_UTF8(s-1) (depending on the \
1694 * utf8ness of the target). We also have to check if this matches against \
1695 * the EOS, which we treat as a \n (which is the same value in both UTF-8 \
1696 * or non-UTF8, so can use the non-utf8 test condition even for a UTF-8 \
1698 if (tmp == ! TEST_NON_UTF8('\n')) { \
1705 /* This is the macro to use when we want to see if something that looks like it
1706 * could match, actually does, and if so exits the loop */
1707 #define REXEC_FBC_TRYIT \
1708 if ((reginfo->intuit || regtry(reginfo, &s))) \
1711 /* The only difference between the BOUND and NBOUND cases is that
1712 * REXEC_FBC_TRYIT is called when matched in BOUND, and when non-matched in
1713 * NBOUND. This is accomplished by passing it as either the if or else clause,
1714 * with the other one being empty (PLACEHOLDER is defined as empty).
1716 * The TEST_FOO parameters are for operating on different forms of input, but
1717 * all should be ones that return identically for the same underlying code
1719 #define FBC_BOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1721 FBC_UTF8(TEST_UV, TEST_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1722 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1724 #define FBC_BOUND_A(TEST_NON_UTF8) \
1726 FBC_UTF8_A(TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1727 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1729 #define FBC_NBOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1731 FBC_UTF8(TEST_UV, TEST_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1732 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1734 #define FBC_NBOUND_A(TEST_NON_UTF8) \
1736 FBC_UTF8_A(TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1737 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1741 S_get_break_val_cp_checked(SV* const invlist, const UV cp_in) {
1742 IV cp_out = Perl__invlist_search(invlist, cp_in);
1743 assert(cp_out >= 0);
1746 # define _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp) \
1747 invmap[S_get_break_val_cp_checked(invlist, cp)]
1749 # define _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp) \
1750 invmap[_invlist_search(invlist, cp)]
1753 /* Takes a pointer to an inversion list, a pointer to its corresponding
1754 * inversion map, and a code point, and returns the code point's value
1755 * according to the two arrays. It assumes that all code points have a value.
1756 * This is used as the base macro for macros for particular properties */
1757 #define _generic_GET_BREAK_VAL_CP(invlist, invmap, cp) \
1758 _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp)
1760 /* Same as above, but takes begin, end ptrs to a UTF-8 encoded string instead
1761 * of a code point, returning the value for the first code point in the string.
1762 * And it takes the particular macro name that finds the desired value given a
1763 * code point. Merely convert the UTF-8 to code point and call the cp macro */
1764 #define _generic_GET_BREAK_VAL_UTF8(cp_macro, pos, strend) \
1765 (__ASSERT_(pos < strend) \
1766 /* Note assumes is valid UTF-8 */ \
1767 (cp_macro(utf8_to_uvchr_buf((pos), (strend), NULL))))
1769 /* Returns the GCB value for the input code point */
1770 #define getGCB_VAL_CP(cp) \
1771 _generic_GET_BREAK_VAL_CP( \
1776 /* Returns the GCB value for the first code point in the UTF-8 encoded string
1777 * bounded by pos and strend */
1778 #define getGCB_VAL_UTF8(pos, strend) \
1779 _generic_GET_BREAK_VAL_UTF8(getGCB_VAL_CP, pos, strend)
1781 /* Returns the LB value for the input code point */
1782 #define getLB_VAL_CP(cp) \
1783 _generic_GET_BREAK_VAL_CP( \
1788 /* Returns the LB value for the first code point in the UTF-8 encoded string
1789 * bounded by pos and strend */
1790 #define getLB_VAL_UTF8(pos, strend) \
1791 _generic_GET_BREAK_VAL_UTF8(getLB_VAL_CP, pos, strend)
1794 /* Returns the SB value for the input code point */
1795 #define getSB_VAL_CP(cp) \
1796 _generic_GET_BREAK_VAL_CP( \
1801 /* Returns the SB value for the first code point in the UTF-8 encoded string
1802 * bounded by pos and strend */
1803 #define getSB_VAL_UTF8(pos, strend) \
1804 _generic_GET_BREAK_VAL_UTF8(getSB_VAL_CP, pos, strend)
1806 /* Returns the WB value for the input code point */
1807 #define getWB_VAL_CP(cp) \
1808 _generic_GET_BREAK_VAL_CP( \
1813 /* Returns the WB value for the first code point in the UTF-8 encoded string
1814 * bounded by pos and strend */
1815 #define getWB_VAL_UTF8(pos, strend) \
1816 _generic_GET_BREAK_VAL_UTF8(getWB_VAL_CP, pos, strend)
1818 /* We know what class REx starts with. Try to find this position... */
1819 /* if reginfo->intuit, its a dryrun */
1820 /* annoyingly all the vars in this routine have different names from their counterparts
1821 in regmatch. /grrr */
1823 S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
1824 const char *strend, regmatch_info *reginfo)
1827 const I32 doevery = (prog->intflags & PREGf_SKIP) == 0;
1828 char *pat_string; /* The pattern's exactish string */
1829 char *pat_end; /* ptr to end char of pat_string */
1830 re_fold_t folder; /* Function for computing non-utf8 folds */
1831 const U8 *fold_array; /* array for folding ords < 256 */
1837 I32 tmp = 1; /* Scratch variable? */
1838 const bool utf8_target = reginfo->is_utf8_target;
1839 UV utf8_fold_flags = 0;
1840 const bool is_utf8_pat = reginfo->is_utf8_pat;
1841 bool to_complement = FALSE; /* Invert the result? Taking the xor of this
1842 with a result inverts that result, as 0^1 =
1844 _char_class_number classnum;
1846 RXi_GET_DECL(prog,progi);
1848 PERL_ARGS_ASSERT_FIND_BYCLASS;
1850 /* We know what class it must start with. */
1853 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1855 if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(c)) && ! IN_UTF8_CTYPE_LOCALE) {
1856 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
1863 REXEC_FBC_UTF8_CLASS_SCAN(
1864 reginclass(prog, c, (U8*)s, (U8*) strend, utf8_target));
1867 REXEC_FBC_CLASS_SCAN(REGINCLASS(prog, c, (U8*)s));
1871 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
1872 assert(! is_utf8_pat);
1875 if (is_utf8_pat || utf8_target) {
1876 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
1877 goto do_exactf_utf8;
1879 fold_array = PL_fold_latin1; /* Latin1 folds are not affected by */
1880 folder = foldEQ_latin1; /* /a, except the sharp s one which */
1881 goto do_exactf_non_utf8; /* isn't dealt with by these */
1883 case EXACTF: /* This node only generated for non-utf8 patterns */
1884 assert(! is_utf8_pat);
1886 utf8_fold_flags = 0;
1887 goto do_exactf_utf8;
1889 fold_array = PL_fold;
1891 goto do_exactf_non_utf8;
1894 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1895 if (is_utf8_pat || utf8_target || IN_UTF8_CTYPE_LOCALE) {
1896 utf8_fold_flags = FOLDEQ_LOCALE;
1897 goto do_exactf_utf8;
1899 fold_array = PL_fold_locale;
1900 folder = foldEQ_locale;
1901 goto do_exactf_non_utf8;
1905 utf8_fold_flags = FOLDEQ_S2_ALREADY_FOLDED;
1907 goto do_exactf_utf8;
1910 if (! utf8_target) { /* All code points in this node require
1911 UTF-8 to express. */
1914 utf8_fold_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
1915 | FOLDEQ_S2_FOLDS_SANE;
1916 goto do_exactf_utf8;
1919 if (is_utf8_pat || utf8_target) {
1920 utf8_fold_flags = is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
1921 goto do_exactf_utf8;
1924 /* Any 'ss' in the pattern should have been replaced by regcomp,
1925 * so we don't have to worry here about this single special case
1926 * in the Latin1 range */
1927 fold_array = PL_fold_latin1;
1928 folder = foldEQ_latin1;
1932 do_exactf_non_utf8: /* Neither pattern nor string are UTF8, and there
1933 are no glitches with fold-length differences
1934 between the target string and pattern */
1936 /* The idea in the non-utf8 EXACTF* cases is to first find the
1937 * first character of the EXACTF* node and then, if necessary,
1938 * case-insensitively compare the full text of the node. c1 is the
1939 * first character. c2 is its fold. This logic will not work for
1940 * Unicode semantics and the german sharp ss, which hence should
1941 * not be compiled into a node that gets here. */
1942 pat_string = STRING(c);
1943 ln = STR_LEN(c); /* length to match in octets/bytes */
1945 /* We know that we have to match at least 'ln' bytes (which is the
1946 * same as characters, since not utf8). If we have to match 3
1947 * characters, and there are only 2 availabe, we know without
1948 * trying that it will fail; so don't start a match past the
1949 * required minimum number from the far end */
1950 e = HOP3c(strend, -((SSize_t)ln), s);
1952 if (reginfo->intuit && e < s) {
1953 e = s; /* Due to minlen logic of intuit() */
1957 c2 = fold_array[c1];
1958 if (c1 == c2) { /* If char and fold are the same */
1959 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1);
1962 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1 || *(U8*)s == c2);
1970 /* If one of the operands is in utf8, we can't use the simpler folding
1971 * above, due to the fact that many different characters can have the
1972 * same fold, or portion of a fold, or different- length fold */
1973 pat_string = STRING(c);
1974 ln = STR_LEN(c); /* length to match in octets/bytes */
1975 pat_end = pat_string + ln;
1976 lnc = is_utf8_pat /* length to match in characters */
1977 ? utf8_length((U8 *) pat_string, (U8 *) pat_end)
1980 /* We have 'lnc' characters to match in the pattern, but because of
1981 * multi-character folding, each character in the target can match
1982 * up to 3 characters (Unicode guarantees it will never exceed
1983 * this) if it is utf8-encoded; and up to 2 if not (based on the
1984 * fact that the Latin 1 folds are already determined, and the
1985 * only multi-char fold in that range is the sharp-s folding to
1986 * 'ss'. Thus, a pattern character can match as little as 1/3 of a
1987 * string character. Adjust lnc accordingly, rounding up, so that
1988 * if we need to match at least 4+1/3 chars, that really is 5. */
1989 expansion = (utf8_target) ? UTF8_MAX_FOLD_CHAR_EXPAND : 2;
1990 lnc = (lnc + expansion - 1) / expansion;
1992 /* As in the non-UTF8 case, if we have to match 3 characters, and
1993 * only 2 are left, it's guaranteed to fail, so don't start a
1994 * match that would require us to go beyond the end of the string
1996 e = HOP3c(strend, -((SSize_t)lnc), s);
1998 if (reginfo->intuit && e < s) {
1999 e = s; /* Due to minlen logic of intuit() */
2002 /* XXX Note that we could recalculate e to stop the loop earlier,
2003 * as the worst case expansion above will rarely be met, and as we
2004 * go along we would usually find that e moves further to the left.
2005 * This would happen only after we reached the point in the loop
2006 * where if there were no expansion we should fail. Unclear if
2007 * worth the expense */
2010 char *my_strend= (char *)strend;
2011 if (foldEQ_utf8_flags(s, &my_strend, 0, utf8_target,
2012 pat_string, NULL, ln, is_utf8_pat, utf8_fold_flags)
2013 && (reginfo->intuit || regtry(reginfo, &s)) )
2017 s += (utf8_target) ? UTF8SKIP(s) : 1;
2023 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2024 if (FLAGS(c) != TRADITIONAL_BOUND) {
2025 if (! IN_UTF8_CTYPE_LOCALE) {
2026 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2027 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2032 FBC_BOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8);
2036 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2037 if (FLAGS(c) != TRADITIONAL_BOUND) {
2038 if (! IN_UTF8_CTYPE_LOCALE) {
2039 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2040 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2045 FBC_NBOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8);
2048 case BOUND: /* regcomp.c makes sure that this only has the traditional \b
2050 assert(FLAGS(c) == TRADITIONAL_BOUND);
2052 FBC_BOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8);
2055 case BOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2057 assert(FLAGS(c) == TRADITIONAL_BOUND);
2059 FBC_BOUND_A(isWORDCHAR_A);
2062 case NBOUND: /* regcomp.c makes sure that this only has the traditional \b
2064 assert(FLAGS(c) == TRADITIONAL_BOUND);
2066 FBC_NBOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8);
2069 case NBOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2071 assert(FLAGS(c) == TRADITIONAL_BOUND);
2073 FBC_NBOUND_A(isWORDCHAR_A);
2077 if ((bound_type) FLAGS(c) == TRADITIONAL_BOUND) {
2078 FBC_NBOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8);
2089 switch((bound_type) FLAGS(c)) {
2090 case TRADITIONAL_BOUND:
2091 FBC_BOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8);
2094 if (s == reginfo->strbeg) {
2095 if (reginfo->intuit || regtry(reginfo, &s))
2100 /* Didn't match. Try at the next position (if there is one) */
2101 s += (utf8_target) ? UTF8SKIP(s) : 1;
2102 if (UNLIKELY(s >= reginfo->strend)) {
2108 GCB_enum before = getGCB_VAL_UTF8(
2110 (U8*)(reginfo->strbeg)),
2111 (U8*) reginfo->strend);
2112 while (s < strend) {
2113 GCB_enum after = getGCB_VAL_UTF8((U8*) s,
2114 (U8*) reginfo->strend);
2115 if ( (to_complement ^ isGCB(before, after))
2116 && (reginfo->intuit || regtry(reginfo, &s)))
2124 else { /* Not utf8. Everything is a GCB except between CR and
2126 while (s < strend) {
2127 if ((to_complement ^ ( UCHARAT(s - 1) != '\r'
2128 || UCHARAT(s) != '\n'))
2129 && (reginfo->intuit || regtry(reginfo, &s)))
2137 /* And, since this is a bound, it can match after the final
2138 * character in the string */
2139 if ((reginfo->intuit || regtry(reginfo, &s))) {
2145 if (s == reginfo->strbeg) {
2146 if (reginfo->intuit || regtry(reginfo, &s)) {
2149 s += (utf8_target) ? UTF8SKIP(s) : 1;
2150 if (UNLIKELY(s >= reginfo->strend)) {
2156 LB_enum before = getLB_VAL_UTF8(reghop3((U8*)s,
2158 (U8*)(reginfo->strbeg)),
2159 (U8*) reginfo->strend);
2160 while (s < strend) {
2161 LB_enum after = getLB_VAL_UTF8((U8*) s, (U8*) reginfo->strend);
2162 if (to_complement ^ isLB(before,
2164 (U8*) reginfo->strbeg,
2166 (U8*) reginfo->strend,
2168 && (reginfo->intuit || regtry(reginfo, &s)))
2176 else { /* Not utf8. */
2177 LB_enum before = getLB_VAL_CP((U8) *(s -1));
2178 while (s < strend) {
2179 LB_enum after = getLB_VAL_CP((U8) *s);
2180 if (to_complement ^ isLB(before,
2182 (U8*) reginfo->strbeg,
2184 (U8*) reginfo->strend,
2186 && (reginfo->intuit || regtry(reginfo, &s)))
2195 if (reginfo->intuit || regtry(reginfo, &s)) {
2202 if (s == reginfo->strbeg) {
2203 if (reginfo->intuit || regtry(reginfo, &s)) {
2206 s += (utf8_target) ? UTF8SKIP(s) : 1;
2207 if (UNLIKELY(s >= reginfo->strend)) {
2213 SB_enum before = getSB_VAL_UTF8(reghop3((U8*)s,
2215 (U8*)(reginfo->strbeg)),
2216 (U8*) reginfo->strend);
2217 while (s < strend) {
2218 SB_enum after = getSB_VAL_UTF8((U8*) s,
2219 (U8*) reginfo->strend);
2220 if ((to_complement ^ isSB(before,
2222 (U8*) reginfo->strbeg,
2224 (U8*) reginfo->strend,
2226 && (reginfo->intuit || regtry(reginfo, &s)))
2234 else { /* Not utf8. */
2235 SB_enum before = getSB_VAL_CP((U8) *(s -1));
2236 while (s < strend) {
2237 SB_enum after = getSB_VAL_CP((U8) *s);
2238 if ((to_complement ^ isSB(before,
2240 (U8*) reginfo->strbeg,
2242 (U8*) reginfo->strend,
2244 && (reginfo->intuit || regtry(reginfo, &s)))
2253 /* Here are at the final position in the target string. The SB
2254 * value is always true here, so matches, depending on other
2256 if (reginfo->intuit || regtry(reginfo, &s)) {
2263 if (s == reginfo->strbeg) {
2264 if (reginfo->intuit || regtry(reginfo, &s)) {
2267 s += (utf8_target) ? UTF8SKIP(s) : 1;
2268 if (UNLIKELY(s >= reginfo->strend)) {
2274 /* We are at a boundary between char_sub_0 and char_sub_1.
2275 * We also keep track of the value for char_sub_-1 as we
2276 * loop through the line. Context may be needed to make a
2277 * determination, and if so, this can save having to
2279 WB_enum previous = WB_UNKNOWN;
2280 WB_enum before = getWB_VAL_UTF8(
2283 (U8*)(reginfo->strbeg)),
2284 (U8*) reginfo->strend);
2285 while (s < strend) {
2286 WB_enum after = getWB_VAL_UTF8((U8*) s,
2287 (U8*) reginfo->strend);
2288 if ((to_complement ^ isWB(previous,
2291 (U8*) reginfo->strbeg,
2293 (U8*) reginfo->strend,
2295 && (reginfo->intuit || regtry(reginfo, &s)))
2304 else { /* Not utf8. */
2305 WB_enum previous = WB_UNKNOWN;
2306 WB_enum before = getWB_VAL_CP((U8) *(s -1));
2307 while (s < strend) {
2308 WB_enum after = getWB_VAL_CP((U8) *s);
2309 if ((to_complement ^ isWB(previous,
2312 (U8*) reginfo->strbeg,
2314 (U8*) reginfo->strend,
2316 && (reginfo->intuit || regtry(reginfo, &s)))
2326 if (reginfo->intuit || regtry(reginfo, &s)) {
2333 REXEC_FBC_CSCAN(is_LNBREAK_utf8_safe(s, strend),
2334 is_LNBREAK_latin1_safe(s, strend)
2338 /* The argument to all the POSIX node types is the class number to pass to
2339 * _generic_isCC() to build a mask for searching in PL_charclass[] */
2346 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2347 REXEC_FBC_CSCAN(to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(c), (U8 *) s)),
2348 to_complement ^ cBOOL(isFOO_lc(FLAGS(c), *s)));
2363 /* The complement of something that matches only ASCII matches all
2364 * non-ASCII, plus everything in ASCII that isn't in the class. */
2365 REXEC_FBC_UTF8_CLASS_SCAN(! isASCII_utf8(s)
2366 || ! _generic_isCC_A(*s, FLAGS(c)));
2375 /* Don't need to worry about utf8, as it can match only a single
2376 * byte invariant character. */
2377 REXEC_FBC_CLASS_SCAN(
2378 to_complement ^ cBOOL(_generic_isCC_A(*s, FLAGS(c))));
2386 if (! utf8_target) {
2387 REXEC_FBC_CLASS_SCAN(to_complement ^ cBOOL(_generic_isCC(*s,
2393 classnum = (_char_class_number) FLAGS(c);
2394 if (classnum < _FIRST_NON_SWASH_CC) {
2395 while (s < strend) {
2397 /* We avoid loading in the swash as long as possible, but
2398 * should we have to, we jump to a separate loop. This
2399 * extra 'if' statement is what keeps this code from being
2400 * just a call to REXEC_FBC_UTF8_CLASS_SCAN() */
2401 if (UTF8_IS_ABOVE_LATIN1(*s)) {
2402 goto found_above_latin1;
2404 if ((UTF8_IS_INVARIANT(*s)
2405 && to_complement ^ cBOOL(_generic_isCC((U8) *s,
2407 || (UTF8_IS_DOWNGRADEABLE_START(*s)
2408 && to_complement ^ cBOOL(
2409 _generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(*s,
2413 if (tmp && (reginfo->intuit || regtry(reginfo, &s)))
2425 else switch (classnum) { /* These classes are implemented as
2427 case _CC_ENUM_SPACE:
2428 REXEC_FBC_UTF8_CLASS_SCAN(
2429 to_complement ^ cBOOL(isSPACE_utf8(s)));
2432 case _CC_ENUM_BLANK:
2433 REXEC_FBC_UTF8_CLASS_SCAN(
2434 to_complement ^ cBOOL(isBLANK_utf8(s)));
2437 case _CC_ENUM_XDIGIT:
2438 REXEC_FBC_UTF8_CLASS_SCAN(
2439 to_complement ^ cBOOL(isXDIGIT_utf8(s)));
2442 case _CC_ENUM_VERTSPACE:
2443 REXEC_FBC_UTF8_CLASS_SCAN(
2444 to_complement ^ cBOOL(isVERTWS_utf8(s)));
2447 case _CC_ENUM_CNTRL:
2448 REXEC_FBC_UTF8_CLASS_SCAN(
2449 to_complement ^ cBOOL(isCNTRL_utf8(s)));
2453 Perl_croak(aTHX_ "panic: find_byclass() node %d='%s' has an unexpected character class '%d'", OP(c), PL_reg_name[OP(c)], classnum);
2454 NOT_REACHED; /* NOTREACHED */
2459 found_above_latin1: /* Here we have to load a swash to get the result
2460 for the current code point */
2461 if (! PL_utf8_swash_ptrs[classnum]) {
2462 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
2463 PL_utf8_swash_ptrs[classnum] =
2464 _core_swash_init("utf8",
2467 PL_XPosix_ptrs[classnum], &flags);
2470 /* This is a copy of the loop above for swash classes, though using the
2471 * FBC macro instead of being expanded out. Since we've loaded the
2472 * swash, we don't have to check for that each time through the loop */
2473 REXEC_FBC_UTF8_CLASS_SCAN(
2474 to_complement ^ cBOOL(_generic_utf8(
2477 swash_fetch(PL_utf8_swash_ptrs[classnum],
2485 /* what trie are we using right now */
2486 reg_ac_data *aho = (reg_ac_data*)progi->data->data[ ARG( c ) ];
2487 reg_trie_data *trie = (reg_trie_data*)progi->data->data[ aho->trie ];
2488 HV *widecharmap = MUTABLE_HV(progi->data->data[ aho->trie + 1 ]);
2490 const char *last_start = strend - trie->minlen;
2492 const char *real_start = s;
2494 STRLEN maxlen = trie->maxlen;
2496 U8 **points; /* map of where we were in the input string
2497 when reading a given char. For ASCII this
2498 is unnecessary overhead as the relationship
2499 is always 1:1, but for Unicode, especially
2500 case folded Unicode this is not true. */
2501 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
2505 GET_RE_DEBUG_FLAGS_DECL;
2507 /* We can't just allocate points here. We need to wrap it in
2508 * an SV so it gets freed properly if there is a croak while
2509 * running the match */
2512 sv_points=newSV(maxlen * sizeof(U8 *));
2513 SvCUR_set(sv_points,
2514 maxlen * sizeof(U8 *));
2515 SvPOK_on(sv_points);
2516 sv_2mortal(sv_points);
2517 points=(U8**)SvPV_nolen(sv_points );
2518 if ( trie_type != trie_utf8_fold
2519 && (trie->bitmap || OP(c)==AHOCORASICKC) )
2522 bitmap=(U8*)trie->bitmap;
2524 bitmap=(U8*)ANYOF_BITMAP(c);
2526 /* this is the Aho-Corasick algorithm modified a touch
2527 to include special handling for long "unknown char" sequences.
2528 The basic idea being that we use AC as long as we are dealing
2529 with a possible matching char, when we encounter an unknown char
2530 (and we have not encountered an accepting state) we scan forward
2531 until we find a legal starting char.
2532 AC matching is basically that of trie matching, except that when
2533 we encounter a failing transition, we fall back to the current
2534 states "fail state", and try the current char again, a process
2535 we repeat until we reach the root state, state 1, or a legal
2536 transition. If we fail on the root state then we can either
2537 terminate if we have reached an accepting state previously, or
2538 restart the entire process from the beginning if we have not.
2541 while (s <= last_start) {
2542 const U32 uniflags = UTF8_ALLOW_DEFAULT;
2550 U8 *uscan = (U8*)NULL;
2551 U8 *leftmost = NULL;
2553 U32 accepted_word= 0;
2557 while ( state && uc <= (U8*)strend ) {
2559 U32 word = aho->states[ state ].wordnum;
2563 DEBUG_TRIE_EXECUTE_r(
2564 if ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2565 dump_exec_pos( (char *)uc, c, strend, real_start,
2566 (char *)uc, utf8_target );
2567 PerlIO_printf( Perl_debug_log,
2568 " Scanning for legal start char...\n");
2572 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2576 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2582 if (uc >(U8*)last_start) break;
2586 U8 *lpos= points[ (pointpos - trie->wordinfo[word].len) % maxlen ];
2587 if (!leftmost || lpos < leftmost) {
2588 DEBUG_r(accepted_word=word);
2594 points[pointpos++ % maxlen]= uc;
2595 if (foldlen || uc < (U8*)strend) {
2596 REXEC_TRIE_READ_CHAR(trie_type, trie,
2598 uscan, len, uvc, charid, foldlen,
2600 DEBUG_TRIE_EXECUTE_r({
2601 dump_exec_pos( (char *)uc, c, strend,
2602 real_start, s, utf8_target);
2603 PerlIO_printf(Perl_debug_log,
2604 " Charid:%3u CP:%4"UVxf" ",
2616 word = aho->states[ state ].wordnum;
2618 base = aho->states[ state ].trans.base;
2620 DEBUG_TRIE_EXECUTE_r({
2622 dump_exec_pos( (char *)uc, c, strend, real_start,
2624 PerlIO_printf( Perl_debug_log,
2625 "%sState: %4"UVxf", word=%"UVxf,
2626 failed ? " Fail transition to " : "",
2627 (UV)state, (UV)word);
2633 ( ((offset = base + charid
2634 - 1 - trie->uniquecharcount)) >= 0)
2635 && ((U32)offset < trie->lasttrans)
2636 && trie->trans[offset].check == state
2637 && (tmp=trie->trans[offset].next))
2639 DEBUG_TRIE_EXECUTE_r(
2640 PerlIO_printf( Perl_debug_log," - legal\n"));
2645 DEBUG_TRIE_EXECUTE_r(
2646 PerlIO_printf( Perl_debug_log," - fail\n"));
2648 state = aho->fail[state];
2652 /* we must be accepting here */
2653 DEBUG_TRIE_EXECUTE_r(
2654 PerlIO_printf( Perl_debug_log," - accepting\n"));
2663 if (!state) state = 1;
2666 if ( aho->states[ state ].wordnum ) {
2667 U8 *lpos = points[ (pointpos - trie->wordinfo[aho->states[ state ].wordnum].len) % maxlen ];
2668 if (!leftmost || lpos < leftmost) {
2669 DEBUG_r(accepted_word=aho->states[ state ].wordnum);
2674 s = (char*)leftmost;
2675 DEBUG_TRIE_EXECUTE_r({
2677 Perl_debug_log,"Matches word #%"UVxf" at position %"IVdf". Trying full pattern...\n",
2678 (UV)accepted_word, (IV)(s - real_start)
2681 if (reginfo->intuit || regtry(reginfo, &s)) {
2687 DEBUG_TRIE_EXECUTE_r({
2688 PerlIO_printf( Perl_debug_log,"Pattern failed. Looking for new start point...\n");
2691 DEBUG_TRIE_EXECUTE_r(
2692 PerlIO_printf( Perl_debug_log,"No match.\n"));
2701 Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
2708 /* set RX_SAVED_COPY, RX_SUBBEG etc.
2709 * flags have same meanings as with regexec_flags() */
2712 S_reg_set_capture_string(pTHX_ REGEXP * const rx,
2719 struct regexp *const prog = ReANY(rx);
2721 if (flags & REXEC_COPY_STR) {
2725 PerlIO_printf(Perl_debug_log,
2726 "Copy on write: regexp capture, type %d\n",
2729 /* Create a new COW SV to share the match string and store
2730 * in saved_copy, unless the current COW SV in saved_copy
2731 * is valid and suitable for our purpose */
2732 if (( prog->saved_copy
2733 && SvIsCOW(prog->saved_copy)
2734 && SvPOKp(prog->saved_copy)
2737 && SvPVX(sv) == SvPVX(prog->saved_copy)))
2739 /* just reuse saved_copy SV */
2740 if (RXp_MATCH_COPIED(prog)) {
2741 Safefree(prog->subbeg);
2742 RXp_MATCH_COPIED_off(prog);
2746 /* create new COW SV to share string */
2747 RX_MATCH_COPY_FREE(rx);
2748 prog->saved_copy = sv_setsv_cow(prog->saved_copy, sv);
2750 prog->subbeg = (char *)SvPVX_const(prog->saved_copy);
2751 assert (SvPOKp(prog->saved_copy));
2752 prog->sublen = strend - strbeg;
2753 prog->suboffset = 0;
2754 prog->subcoffset = 0;
2759 SSize_t max = strend - strbeg;
2762 if ( (flags & REXEC_COPY_SKIP_POST)
2763 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2764 && !(PL_sawampersand & SAWAMPERSAND_RIGHT)
2765 ) { /* don't copy $' part of string */
2768 /* calculate the right-most part of the string covered
2769 * by a capture. Due to lookahead, this may be to
2770 * the right of $&, so we have to scan all captures */
2771 while (n <= prog->lastparen) {
2772 if (prog->offs[n].end > max)
2773 max = prog->offs[n].end;
2777 max = (PL_sawampersand & SAWAMPERSAND_LEFT)
2778 ? prog->offs[0].start
2780 assert(max >= 0 && max <= strend - strbeg);
2783 if ( (flags & REXEC_COPY_SKIP_PRE)
2784 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2785 && !(PL_sawampersand & SAWAMPERSAND_LEFT)
2786 ) { /* don't copy $` part of string */
2789 /* calculate the left-most part of the string covered
2790 * by a capture. Due to lookbehind, this may be to
2791 * the left of $&, so we have to scan all captures */
2792 while (min && n <= prog->lastparen) {
2793 if ( prog->offs[n].start != -1
2794 && prog->offs[n].start < min)
2796 min = prog->offs[n].start;
2800 if ((PL_sawampersand & SAWAMPERSAND_RIGHT)
2801 && min > prog->offs[0].end
2803 min = prog->offs[0].end;
2807 assert(min >= 0 && min <= max && min <= strend - strbeg);
2810 if (RX_MATCH_COPIED(rx)) {
2811 if (sublen > prog->sublen)
2813 (char*)saferealloc(prog->subbeg, sublen+1);
2816 prog->subbeg = (char*)safemalloc(sublen+1);
2817 Copy(strbeg + min, prog->subbeg, sublen, char);
2818 prog->subbeg[sublen] = '\0';
2819 prog->suboffset = min;
2820 prog->sublen = sublen;
2821 RX_MATCH_COPIED_on(rx);
2823 prog->subcoffset = prog->suboffset;
2824 if (prog->suboffset && utf8_target) {
2825 /* Convert byte offset to chars.
2826 * XXX ideally should only compute this if @-/@+
2827 * has been seen, a la PL_sawampersand ??? */
2829 /* If there's a direct correspondence between the
2830 * string which we're matching and the original SV,
2831 * then we can use the utf8 len cache associated with
2832 * the SV. In particular, it means that under //g,
2833 * sv_pos_b2u() will use the previously cached
2834 * position to speed up working out the new length of
2835 * subcoffset, rather than counting from the start of
2836 * the string each time. This stops
2837 * $x = "\x{100}" x 1E6; 1 while $x =~ /(.)/g;
2838 * from going quadratic */
2839 if (SvPOKp(sv) && SvPVX(sv) == strbeg)
2840 prog->subcoffset = sv_pos_b2u_flags(sv, prog->subcoffset,
2841 SV_GMAGIC|SV_CONST_RETURN);
2843 prog->subcoffset = utf8_length((U8*)strbeg,
2844 (U8*)(strbeg+prog->suboffset));
2848 RX_MATCH_COPY_FREE(rx);
2849 prog->subbeg = strbeg;
2850 prog->suboffset = 0;
2851 prog->subcoffset = 0;
2852 prog->sublen = strend - strbeg;
2860 - regexec_flags - match a regexp against a string
2863 Perl_regexec_flags(pTHX_ REGEXP * const rx, char *stringarg, char *strend,
2864 char *strbeg, SSize_t minend, SV *sv, void *data, U32 flags)
2865 /* stringarg: the point in the string at which to begin matching */
2866 /* strend: pointer to null at end of string */
2867 /* strbeg: real beginning of string */
2868 /* minend: end of match must be >= minend bytes after stringarg. */
2869 /* sv: SV being matched: only used for utf8 flag, pos() etc; string
2870 * itself is accessed via the pointers above */
2871 /* data: May be used for some additional optimizations.
2872 Currently unused. */
2873 /* flags: For optimizations. See REXEC_* in regexp.h */
2876 struct regexp *const prog = ReANY(rx);
2880 SSize_t minlen; /* must match at least this many chars */
2881 SSize_t dontbother = 0; /* how many characters not to try at end */
2882 const bool utf8_target = cBOOL(DO_UTF8(sv));
2884 RXi_GET_DECL(prog,progi);
2885 regmatch_info reginfo_buf; /* create some info to pass to regtry etc */
2886 regmatch_info *const reginfo = ®info_buf;
2887 regexp_paren_pair *swap = NULL;
2889 GET_RE_DEBUG_FLAGS_DECL;
2891 PERL_ARGS_ASSERT_REGEXEC_FLAGS;
2892 PERL_UNUSED_ARG(data);
2894 /* Be paranoid... */
2896 Perl_croak(aTHX_ "NULL regexp parameter");
2900 debug_start_match(rx, utf8_target, stringarg, strend,
2904 startpos = stringarg;
2906 /* set these early as they may be used by the HOP macros below */
2907 reginfo->strbeg = strbeg;
2908 reginfo->strend = strend;
2909 reginfo->is_utf8_target = cBOOL(utf8_target);
2911 if (prog->intflags & PREGf_GPOS_SEEN) {
2914 /* set reginfo->ganch, the position where \G can match */
2917 (flags & REXEC_IGNOREPOS)
2918 ? stringarg /* use start pos rather than pos() */
2919 : ((mg = mg_find_mglob(sv)) && mg->mg_len >= 0)
2920 /* Defined pos(): */
2921 ? strbeg + MgBYTEPOS(mg, sv, strbeg, strend-strbeg)
2922 : strbeg; /* pos() not defined; use start of string */
2924 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
2925 "GPOS ganch set to strbeg[%"IVdf"]\n", (IV)(reginfo->ganch - strbeg)));
2927 /* in the presence of \G, we may need to start looking earlier in
2928 * the string than the suggested start point of stringarg:
2929 * if prog->gofs is set, then that's a known, fixed minimum
2932 * /ab|c\G/: gofs = 1
2933 * or if the minimum offset isn't known, then we have to go back
2934 * to the start of the string, e.g. /w+\G/
2937 if (prog->intflags & PREGf_ANCH_GPOS) {
2939 startpos = HOPBACKc(reginfo->ganch, prog->gofs);
2941 ((flags & REXEC_FAIL_ON_UNDERFLOW) && startpos < stringarg))
2943 DEBUG_r(PerlIO_printf(Perl_debug_log,
2944 "fail: ganch-gofs before earliest possible start\n"));
2949 startpos = reginfo->ganch;
2951 else if (prog->gofs) {
2952 startpos = HOPBACKc(startpos, prog->gofs);
2956 else if (prog->intflags & PREGf_GPOS_FLOAT)
2960 minlen = prog->minlen;
2961 if ((startpos + minlen) > strend || startpos < strbeg) {
2962 DEBUG_r(PerlIO_printf(Perl_debug_log,
2963 "Regex match can't succeed, so not even tried\n"));
2967 /* at the end of this function, we'll do a LEAVE_SCOPE(oldsave),
2968 * which will call destuctors to reset PL_regmatch_state, free higher
2969 * PL_regmatch_slabs, and clean up regmatch_info_aux and
2970 * regmatch_info_aux_eval */
2972 oldsave = PL_savestack_ix;
2976 if ((prog->extflags & RXf_USE_INTUIT)
2977 && !(flags & REXEC_CHECKED))
2979 s = re_intuit_start(rx, sv, strbeg, startpos, strend,
2984 if (prog->extflags & RXf_CHECK_ALL) {
2985 /* we can match based purely on the result of INTUIT.
2986 * Set up captures etc just for $& and $-[0]
2987 * (an intuit-only match wont have $1,$2,..) */
2988 assert(!prog->nparens);
2990 /* s/// doesn't like it if $& is earlier than where we asked it to
2991 * start searching (which can happen on something like /.\G/) */
2992 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
2995 /* this should only be possible under \G */
2996 assert(prog->intflags & PREGf_GPOS_SEEN);
2997 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
2998 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3002 /* match via INTUIT shouldn't have any captures.
3003 * Let @-, @+, $^N know */
3004 prog->lastparen = prog->lastcloseparen = 0;
3005 RX_MATCH_UTF8_set(rx, utf8_target);
3006 prog->offs[0].start = s - strbeg;
3007 prog->offs[0].end = utf8_target
3008 ? (char*)utf8_hop((U8*)s, prog->minlenret) - strbeg
3009 : s - strbeg + prog->minlenret;
3010 if ( !(flags & REXEC_NOT_FIRST) )
3011 S_reg_set_capture_string(aTHX_ rx,
3013 sv, flags, utf8_target);
3019 multiline = prog->extflags & RXf_PMf_MULTILINE;
3021 if (strend - s < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
3022 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
3023 "String too short [regexec_flags]...\n"));
3027 /* Check validity of program. */
3028 if (UCHARAT(progi->program) != REG_MAGIC) {
3029 Perl_croak(aTHX_ "corrupted regexp program");
3032 RX_MATCH_TAINTED_off(rx);
3033 RX_MATCH_UTF8_set(rx, utf8_target);
3035 reginfo->prog = rx; /* Yes, sorry that this is confusing. */
3036 reginfo->intuit = 0;
3037 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
3038 reginfo->warned = FALSE;
3040 reginfo->poscache_maxiter = 0; /* not yet started a countdown */
3041 /* see how far we have to get to not match where we matched before */
3042 reginfo->till = stringarg + minend;
3044 if (prog->extflags & RXf_EVAL_SEEN && SvPADTMP(sv)) {
3045 /* SAVEFREESV, not sv_mortalcopy, as this SV must last until after
3046 S_cleanup_regmatch_info_aux has executed (registered by
3047 SAVEDESTRUCTOR_X below). S_cleanup_regmatch_info_aux modifies
3048 magic belonging to this SV.
3049 Not newSVsv, either, as it does not COW.
3051 reginfo->sv = newSV(0);
3052 SvSetSV_nosteal(reginfo->sv, sv);
3053 SAVEFREESV(reginfo->sv);
3056 /* reserve next 2 or 3 slots in PL_regmatch_state:
3057 * slot N+0: may currently be in use: skip it
3058 * slot N+1: use for regmatch_info_aux struct
3059 * slot N+2: use for regmatch_info_aux_eval struct if we have (?{})'s
3060 * slot N+3: ready for use by regmatch()
3064 regmatch_state *old_regmatch_state;
3065 regmatch_slab *old_regmatch_slab;
3066 int i, max = (prog->extflags & RXf_EVAL_SEEN) ? 2 : 1;
3068 /* on first ever match, allocate first slab */
3069 if (!PL_regmatch_slab) {
3070 Newx(PL_regmatch_slab, 1, regmatch_slab);
3071 PL_regmatch_slab->prev = NULL;
3072 PL_regmatch_slab->next = NULL;
3073 PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
3076 old_regmatch_state = PL_regmatch_state;
3077 old_regmatch_slab = PL_regmatch_slab;
3079 for (i=0; i <= max; i++) {
3081 reginfo->info_aux = &(PL_regmatch_state->u.info_aux);
3083 reginfo->info_aux_eval =
3084 reginfo->info_aux->info_aux_eval =
3085 &(PL_regmatch_state->u.info_aux_eval);
3087 if (++PL_regmatch_state > SLAB_LAST(PL_regmatch_slab))
3088 PL_regmatch_state = S_push_slab(aTHX);
3091 /* note initial PL_regmatch_state position; at end of match we'll
3092 * pop back to there and free any higher slabs */
3094 reginfo->info_aux->old_regmatch_state = old_regmatch_state;
3095 reginfo->info_aux->old_regmatch_slab = old_regmatch_slab;
3096 reginfo->info_aux->poscache = NULL;
3098 SAVEDESTRUCTOR_X(S_cleanup_regmatch_info_aux, reginfo->info_aux);
3100 if ((prog->extflags & RXf_EVAL_SEEN))
3101 S_setup_eval_state(aTHX_ reginfo);
3103 reginfo->info_aux_eval = reginfo->info_aux->info_aux_eval = NULL;
3106 /* If there is a "must appear" string, look for it. */
3108 if (PL_curpm && (PM_GETRE(PL_curpm) == rx)) {
3109 /* We have to be careful. If the previous successful match
3110 was from this regex we don't want a subsequent partially
3111 successful match to clobber the old results.
3112 So when we detect this possibility we add a swap buffer
3113 to the re, and switch the buffer each match. If we fail,
3114 we switch it back; otherwise we leave it swapped.
3117 /* do we need a save destructor here for eval dies? */
3118 Newxz(prog->offs, (prog->nparens + 1), regexp_paren_pair);
3119 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
3120 "rex=0x%"UVxf" saving offs: orig=0x%"UVxf" new=0x%"UVxf"\n",
3127 /* Simplest case: anchored match need be tried only once, or with
3128 * MBOL, only at the beginning of each line.
3130 * Note that /.*.../ sets PREGf_IMPLICIT|MBOL, while /.*.../s sets
3131 * PREGf_IMPLICIT|SBOL. The idea is that with /.*.../s, if it doesn't
3132 * match at the start of the string then it won't match anywhere else
3133 * either; while with /.*.../, if it doesn't match at the beginning,
3134 * the earliest it could match is at the start of the next line */
3136 if (prog->intflags & (PREGf_ANCH & ~PREGf_ANCH_GPOS)) {
3139 if (regtry(reginfo, &s))
3142 if (!(prog->intflags & PREGf_ANCH_MBOL))
3145 /* didn't match at start, try at other newline positions */
3148 dontbother = minlen - 1;
3149 end = HOP3c(strend, -dontbother, strbeg) - 1;
3151 /* skip to next newline */
3153 while (s <= end) { /* note it could be possible to match at the end of the string */
3154 /* NB: newlines are the same in unicode as they are in latin */
3157 if (prog->check_substr || prog->check_utf8) {
3158 /* note that with PREGf_IMPLICIT, intuit can only fail
3159 * or return the start position, so it's of limited utility.
3160 * Nevertheless, I made the decision that the potential for
3161 * quick fail was still worth it - DAPM */
3162 s = re_intuit_start(rx, sv, strbeg, s, strend, flags, NULL);
3166 if (regtry(reginfo, &s))
3170 } /* end anchored search */
3172 if (prog->intflags & PREGf_ANCH_GPOS)
3174 /* PREGf_ANCH_GPOS should never be true if PREGf_GPOS_SEEN is not true */
3175 assert(prog->intflags & PREGf_GPOS_SEEN);
3176 /* For anchored \G, the only position it can match from is
3177 * (ganch-gofs); we already set startpos to this above; if intuit
3178 * moved us on from there, we can't possibly succeed */
3179 assert(startpos == HOPBACKc(reginfo->ganch, prog->gofs));
3180 if (s == startpos && regtry(reginfo, &s))
3185 /* Messy cases: unanchored match. */
3186 if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
3187 /* we have /x+whatever/ */
3188 /* it must be a one character string (XXXX Except is_utf8_pat?) */
3194 if (! prog->anchored_utf8) {
3195 to_utf8_substr(prog);
3197 ch = SvPVX_const(prog->anchored_utf8)[0];
3200 DEBUG_EXECUTE_r( did_match = 1 );
3201 if (regtry(reginfo, &s)) goto got_it;
3203 while (s < strend && *s == ch)
3210 if (! prog->anchored_substr) {
3211 if (! to_byte_substr(prog)) {
3212 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3215 ch = SvPVX_const(prog->anchored_substr)[0];
3218 DEBUG_EXECUTE_r( did_match = 1 );
3219 if (regtry(reginfo, &s)) goto got_it;
3221 while (s < strend && *s == ch)
3226 DEBUG_EXECUTE_r(if (!did_match)
3227 PerlIO_printf(Perl_debug_log,
3228 "Did not find anchored character...\n")
3231 else if (prog->anchored_substr != NULL
3232 || prog->anchored_utf8 != NULL
3233 || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
3234 && prog->float_max_offset < strend - s)) {
3239 char *last1; /* Last position checked before */
3243 if (prog->anchored_substr || prog->anchored_utf8) {
3245 if (! prog->anchored_utf8) {
3246 to_utf8_substr(prog);
3248 must = prog->anchored_utf8;
3251 if (! prog->anchored_substr) {
3252 if (! to_byte_substr(prog)) {
3253 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3256 must = prog->anchored_substr;
3258 back_max = back_min = prog->anchored_offset;
3261 if (! prog->float_utf8) {
3262 to_utf8_substr(prog);
3264 must = prog->float_utf8;
3267 if (! prog->float_substr) {
3268 if (! to_byte_substr(prog)) {
3269 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3272 must = prog->float_substr;
3274 back_max = prog->float_max_offset;
3275 back_min = prog->float_min_offset;
3281 last = HOP3c(strend, /* Cannot start after this */
3282 -(SSize_t)(CHR_SVLEN(must)
3283 - (SvTAIL(must) != 0) + back_min), strbeg);
3285 if (s > reginfo->strbeg)
3286 last1 = HOPc(s, -1);
3288 last1 = s - 1; /* bogus */
3290 /* XXXX check_substr already used to find "s", can optimize if
3291 check_substr==must. */
3293 strend = HOPc(strend, -dontbother);
3294 while ( (s <= last) &&
3295 (s = fbm_instr((unsigned char*)HOP4c(s, back_min, strbeg, strend),
3296 (unsigned char*)strend, must,
3297 multiline ? FBMrf_MULTILINE : 0)) ) {
3298 DEBUG_EXECUTE_r( did_match = 1 );
3299 if (HOPc(s, -back_max) > last1) {
3300 last1 = HOPc(s, -back_min);
3301 s = HOPc(s, -back_max);
3304 char * const t = (last1 >= reginfo->strbeg)
3305 ? HOPc(last1, 1) : last1 + 1;
3307 last1 = HOPc(s, -back_min);
3311 while (s <= last1) {
3312 if (regtry(reginfo, &s))
3315 s++; /* to break out of outer loop */
3322 while (s <= last1) {
3323 if (regtry(reginfo, &s))
3329 DEBUG_EXECUTE_r(if (!did_match) {
3330 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
3331 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
3332 PerlIO_printf(Perl_debug_log, "Did not find %s substr %s%s...\n",
3333 ((must == prog->anchored_substr || must == prog->anchored_utf8)
3334 ? "anchored" : "floating"),
3335 quoted, RE_SV_TAIL(must));
3339 else if ( (c = progi->regstclass) ) {
3341 const OPCODE op = OP(progi->regstclass);
3342 /* don't bother with what can't match */
3343 if (PL_regkind[op] != EXACT && PL_regkind[op] != TRIE)
3344 strend = HOPc(strend, -(minlen - 1));
3347 SV * const prop = sv_newmortal();
3348 regprop(prog, prop, c, reginfo, NULL);
3350 RE_PV_QUOTED_DECL(quoted,utf8_target,PERL_DEBUG_PAD_ZERO(1),
3352 PerlIO_printf(Perl_debug_log,
3353 "Matching stclass %.*s against %s (%d bytes)\n",
3354 (int)SvCUR(prop), SvPVX_const(prop),
3355 quoted, (int)(strend - s));
3358 if (find_byclass(prog, c, s, strend, reginfo))
3360 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Contradicts stclass... [regexec_flags]\n"));
3364 if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
3372 if (! prog->float_utf8) {
3373 to_utf8_substr(prog);
3375 float_real = prog->float_utf8;
3378 if (! prog->float_substr) {
3379 if (! to_byte_substr(prog)) {
3380 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3383 float_real = prog->float_substr;
3386 little = SvPV_const(float_real, len);
3387 if (SvTAIL(float_real)) {
3388 /* This means that float_real contains an artificial \n on
3389 * the end due to the presence of something like this:
3390 * /foo$/ where we can match both "foo" and "foo\n" at the
3391 * end of the string. So we have to compare the end of the
3392 * string first against the float_real without the \n and
3393 * then against the full float_real with the string. We
3394 * have to watch out for cases where the string might be
3395 * smaller than the float_real or the float_real without
3397 char *checkpos= strend - len;
3399 PerlIO_printf(Perl_debug_log,
3400 "%sChecking for float_real.%s\n",
3401 PL_colors[4], PL_colors[5]));
3402 if (checkpos + 1 < strbeg) {
3403 /* can't match, even if we remove the trailing \n
3404 * string is too short to match */
3406 PerlIO_printf(Perl_debug_log,
3407 "%sString shorter than required trailing substring, cannot match.%s\n",
3408 PL_colors[4], PL_colors[5]));
3410 } else if (memEQ(checkpos + 1, little, len - 1)) {
3411 /* can match, the end of the string matches without the
3413 last = checkpos + 1;
3414 } else if (checkpos < strbeg) {
3415 /* cant match, string is too short when the "\n" is
3418 PerlIO_printf(Perl_debug_log,
3419 "%sString does not contain required trailing substring, cannot match.%s\n",
3420 PL_colors[4], PL_colors[5]));
3422 } else if (!multiline) {
3423 /* non multiline match, so compare with the "\n" at the
3424 * end of the string */
3425 if (memEQ(checkpos, little, len)) {
3429 PerlIO_printf(Perl_debug_log,
3430 "%sString does not contain required trailing substring, cannot match.%s\n",
3431 PL_colors[4], PL_colors[5]));
3435 /* multiline match, so we have to search for a place
3436 * where the full string is located */
3442 last = rninstr(s, strend, little, little + len);
3444 last = strend; /* matching "$" */
3447 /* at one point this block contained a comment which was
3448 * probably incorrect, which said that this was a "should not
3449 * happen" case. Even if it was true when it was written I am
3450 * pretty sure it is not anymore, so I have removed the comment
3451 * and replaced it with this one. Yves */
3453 PerlIO_printf(Perl_debug_log,
3454 "%sString does not contain required substring, cannot match.%s\n",
3455 PL_colors[4], PL_colors[5]
3459 dontbother = strend - last + prog->float_min_offset;
3461 if (minlen && (dontbother < minlen))
3462 dontbother = minlen - 1;
3463 strend -= dontbother; /* this one's always in bytes! */
3464 /* We don't know much -- general case. */
3467 if (regtry(reginfo, &s))
3476 if (regtry(reginfo, &s))
3478 } while (s++ < strend);
3486 /* s/// doesn't like it if $& is earlier than where we asked it to
3487 * start searching (which can happen on something like /.\G/) */
3488 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
3489 && (prog->offs[0].start < stringarg - strbeg))
3491 /* this should only be possible under \G */
3492 assert(prog->intflags & PREGf_GPOS_SEEN);
3493 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
3494 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3500 PerlIO_printf(Perl_debug_log,
3501 "rex=0x%"UVxf" freeing offs: 0x%"UVxf"\n",
3508 /* clean up; this will trigger destructors that will free all slabs
3509 * above the current one, and cleanup the regmatch_info_aux
3510 * and regmatch_info_aux_eval sructs */
3512 LEAVE_SCOPE(oldsave);
3514 if (RXp_PAREN_NAMES(prog))
3515 (void)hv_iterinit(RXp_PAREN_NAMES(prog));
3517 /* make sure $`, $&, $', and $digit will work later */
3518 if ( !(flags & REXEC_NOT_FIRST) )
3519 S_reg_set_capture_string(aTHX_ rx,
3520 strbeg, reginfo->strend,
3521 sv, flags, utf8_target);
3526 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch failed%s\n",
3527 PL_colors[4], PL_colors[5]));
3529 /* clean up; this will trigger destructors that will free all slabs
3530 * above the current one, and cleanup the regmatch_info_aux
3531 * and regmatch_info_aux_eval sructs */
3533 LEAVE_SCOPE(oldsave);
3536 /* we failed :-( roll it back */
3537 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
3538 "rex=0x%"UVxf" rolling back offs: freeing=0x%"UVxf" restoring=0x%"UVxf"\n",
3543 Safefree(prog->offs);
3550 /* Set which rex is pointed to by PL_reg_curpm, handling ref counting.
3551 * Do inc before dec, in case old and new rex are the same */
3552 #define SET_reg_curpm(Re2) \
3553 if (reginfo->info_aux_eval) { \
3554 (void)ReREFCNT_inc(Re2); \
3555 ReREFCNT_dec(PM_GETRE(PL_reg_curpm)); \
3556 PM_SETRE((PL_reg_curpm), (Re2)); \
3561 - regtry - try match at specific point
3563 STATIC bool /* 0 failure, 1 success */
3564 S_regtry(pTHX_ regmatch_info *reginfo, char **startposp)
3567 REGEXP *const rx = reginfo->prog;
3568 regexp *const prog = ReANY(rx);
3570 RXi_GET_DECL(prog,progi);
3571 GET_RE_DEBUG_FLAGS_DECL;
3573 PERL_ARGS_ASSERT_REGTRY;
3575 reginfo->cutpoint=NULL;
3577 prog->offs[0].start = *startposp - reginfo->strbeg;
3578 prog->lastparen = 0;
3579 prog->lastcloseparen = 0;
3581 /* XXXX What this code is doing here?!!! There should be no need
3582 to do this again and again, prog->lastparen should take care of
3585 /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
3586 * Actually, the code in regcppop() (which Ilya may be meaning by
3587 * prog->lastparen), is not needed at all by the test suite
3588 * (op/regexp, op/pat, op/split), but that code is needed otherwise
3589 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
3590 * Meanwhile, this code *is* needed for the
3591 * above-mentioned test suite tests to succeed. The common theme
3592 * on those tests seems to be returning null fields from matches.
3593 * --jhi updated by dapm */
3595 if (prog->nparens) {
3596 regexp_paren_pair *pp = prog->offs;
3598 for (i = prog->nparens; i > (I32)prog->lastparen; i--) {
3606 result = regmatch(reginfo, *startposp, progi->program + 1);
3608 prog->offs[0].end = result;
3611 if (reginfo->cutpoint)
3612 *startposp= reginfo->cutpoint;
3613 REGCP_UNWIND(lastcp);
3618 #define sayYES goto yes
3619 #define sayNO goto no
3620 #define sayNO_SILENT goto no_silent
3622 /* we dont use STMT_START/END here because it leads to
3623 "unreachable code" warnings, which are bogus, but distracting. */
3624 #define CACHEsayNO \
3625 if (ST.cache_mask) \
3626 reginfo->info_aux->poscache[ST.cache_offset] |= ST.cache_mask; \
3629 /* this is used to determine how far from the left messages like
3630 'failed...' are printed. It should be set such that messages
3631 are inline with the regop output that created them.
3633 #define REPORT_CODE_OFF 32
3636 #define CHRTEST_UNINIT -1001 /* c1/c2 haven't been calculated yet */
3637 #define CHRTEST_VOID -1000 /* the c1/c2 "next char" test should be skipped */
3638 #define CHRTEST_NOT_A_CP_1 -999
3639 #define CHRTEST_NOT_A_CP_2 -998
3641 /* grab a new slab and return the first slot in it */
3643 STATIC regmatch_state *
3646 #if PERL_VERSION < 9 && !defined(PERL_CORE)
3649 regmatch_slab *s = PL_regmatch_slab->next;
3651 Newx(s, 1, regmatch_slab);
3652 s->prev = PL_regmatch_slab;
3654 PL_regmatch_slab->next = s;
3656 PL_regmatch_slab = s;
3657 return SLAB_FIRST(s);
3661 /* push a new state then goto it */
3663 #define PUSH_STATE_GOTO(state, node, input) \
3664 pushinput = input; \
3666 st->resume_state = state; \
3669 /* push a new state with success backtracking, then goto it */
3671 #define PUSH_YES_STATE_GOTO(state, node, input) \
3672 pushinput = input; \
3674 st->resume_state = state; \
3675 goto push_yes_state;
3682 regmatch() - main matching routine
3684 This is basically one big switch statement in a loop. We execute an op,
3685 set 'next' to point the next op, and continue. If we come to a point which
3686 we may need to backtrack to on failure such as (A|B|C), we push a
3687 backtrack state onto the backtrack stack. On failure, we pop the top
3688 state, and re-enter the loop at the state indicated. If there are no more
3689 states to pop, we return failure.
3691 Sometimes we also need to backtrack on success; for example /A+/, where
3692 after successfully matching one A, we need to go back and try to
3693 match another one; similarly for lookahead assertions: if the assertion
3694 completes successfully, we backtrack to the state just before the assertion
3695 and then carry on. In these cases, the pushed state is marked as
3696 'backtrack on success too'. This marking is in fact done by a chain of
3697 pointers, each pointing to the previous 'yes' state. On success, we pop to
3698 the nearest yes state, discarding any intermediate failure-only states.
3699 Sometimes a yes state is pushed just to force some cleanup code to be
3700 called at the end of a successful match or submatch; e.g. (??{$re}) uses
3701 it to free the inner regex.
3703 Note that failure backtracking rewinds the cursor position, while
3704 success backtracking leaves it alone.
3706 A pattern is complete when the END op is executed, while a subpattern
3707 such as (?=foo) is complete when the SUCCESS op is executed. Both of these
3708 ops trigger the "pop to last yes state if any, otherwise return true"
3711 A common convention in this function is to use A and B to refer to the two
3712 subpatterns (or to the first nodes thereof) in patterns like /A*B/: so A is
3713 the subpattern to be matched possibly multiple times, while B is the entire
3714 rest of the pattern. Variable and state names reflect this convention.
3716 The states in the main switch are the union of ops and failure/success of
3717 substates associated with with that op. For example, IFMATCH is the op
3718 that does lookahead assertions /(?=A)B/ and so the IFMATCH state means
3719 'execute IFMATCH'; while IFMATCH_A is a state saying that we have just
3720 successfully matched A and IFMATCH_A_fail is a state saying that we have
3721 just failed to match A. Resume states always come in pairs. The backtrack
3722 state we push is marked as 'IFMATCH_A', but when that is popped, we resume
3723 at IFMATCH_A or IFMATCH_A_fail, depending on whether we are backtracking
3724 on success or failure.
3726 The struct that holds a backtracking state is actually a big union, with
3727 one variant for each major type of op. The variable st points to the
3728 top-most backtrack struct. To make the code clearer, within each
3729 block of code we #define ST to alias the relevant union.
3731 Here's a concrete example of a (vastly oversimplified) IFMATCH
3737 #define ST st->u.ifmatch
3739 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3740 ST.foo = ...; // some state we wish to save
3742 // push a yes backtrack state with a resume value of
3743 // IFMATCH_A/IFMATCH_A_fail, then continue execution at the
3745 PUSH_YES_STATE_GOTO(IFMATCH_A, A, newinput);
3748 case IFMATCH_A: // we have successfully executed A; now continue with B
3750 bar = ST.foo; // do something with the preserved value
3753 case IFMATCH_A_fail: // A failed, so the assertion failed
3754 ...; // do some housekeeping, then ...
3755 sayNO; // propagate the failure
3762 For any old-timers reading this who are familiar with the old recursive
3763 approach, the code above is equivalent to:
3765 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3774 ...; // do some housekeeping, then ...
3775 sayNO; // propagate the failure
3778 The topmost backtrack state, pointed to by st, is usually free. If you
3779 want to claim it, populate any ST.foo fields in it with values you wish to
3780 save, then do one of
3782 PUSH_STATE_GOTO(resume_state, node, newinput);
3783 PUSH_YES_STATE_GOTO(resume_state, node, newinput);
3785 which sets that backtrack state's resume value to 'resume_state', pushes a
3786 new free entry to the top of the backtrack stack, then goes to 'node'.
3787 On backtracking, the free slot is popped, and the saved state becomes the
3788 new free state. An ST.foo field in this new top state can be temporarily
3789 accessed to retrieve values, but once the main loop is re-entered, it
3790 becomes available for reuse.
3792 Note that the depth of the backtrack stack constantly increases during the
3793 left-to-right execution of the pattern, rather than going up and down with
3794 the pattern nesting. For example the stack is at its maximum at Z at the
3795 end of the pattern, rather than at X in the following:
3797 /(((X)+)+)+....(Y)+....Z/
3799 The only exceptions to this are lookahead/behind assertions and the cut,
3800 (?>A), which pop all the backtrack states associated with A before
3803 Backtrack state structs are allocated in slabs of about 4K in size.
3804 PL_regmatch_state and st always point to the currently active state,
3805 and PL_regmatch_slab points to the slab currently containing
3806 PL_regmatch_state. The first time regmatch() is called, the first slab is
3807 allocated, and is never freed until interpreter destruction. When the slab
3808 is full, a new one is allocated and chained to the end. At exit from
3809 regmatch(), slabs allocated since entry are freed.
3814 #define DEBUG_STATE_pp(pp) \
3816 DUMP_EXEC_POS(locinput, scan, utf8_target); \
3817 PerlIO_printf(Perl_debug_log, \
3818 " %*s"pp" %s%s%s%s%s\n", \
3820 PL_reg_name[st->resume_state], \
3821 ((st==yes_state||st==mark_state) ? "[" : ""), \
3822 ((st==yes_state) ? "Y" : ""), \
3823 ((st==mark_state) ? "M" : ""), \
3824 ((st==yes_state||st==mark_state) ? "]" : "") \
3829 #define REG_NODE_NUM(x) ((x) ? (int)((x)-prog) : -1)
3834 S_debug_start_match(pTHX_ const REGEXP *prog, const bool utf8_target,
3835 const char *start, const char *end, const char *blurb)
3837 const bool utf8_pat = RX_UTF8(prog) ? 1 : 0;
3839 PERL_ARGS_ASSERT_DEBUG_START_MATCH;
3844 RE_PV_QUOTED_DECL(s0, utf8_pat, PERL_DEBUG_PAD_ZERO(0),
3845 RX_PRECOMP_const(prog), RX_PRELEN(prog), 60);
3847 RE_PV_QUOTED_DECL(s1, utf8_target, PERL_DEBUG_PAD_ZERO(1),
3848 start, end - start, 60);
3850 PerlIO_printf(Perl_debug_log,
3851 "%s%s REx%s %s against %s\n",
3852 PL_colors[4], blurb, PL_colors[5], s0, s1);
3854 if (utf8_target||utf8_pat)
3855 PerlIO_printf(Perl_debug_log, "UTF-8 %s%s%s...\n",
3856 utf8_pat ? "pattern" : "",
3857 utf8_pat && utf8_target ? " and " : "",
3858 utf8_target ? "string" : ""
3864 S_dump_exec_pos(pTHX_ const char *locinput,
3865 const regnode *scan,
3866 const char *loc_regeol,
3867 const char *loc_bostr,
3868 const char *loc_reg_starttry,
3869 const bool utf8_target)
3871 const int docolor = *PL_colors[0] || *PL_colors[2] || *PL_colors[4];
3872 const int taill = (docolor ? 10 : 7); /* 3 chars for "> <" */
3873 int l = (loc_regeol - locinput) > taill ? taill : (loc_regeol - locinput);
3874 /* The part of the string before starttry has one color
3875 (pref0_len chars), between starttry and current
3876 position another one (pref_len - pref0_len chars),
3877 after the current position the third one.
3878 We assume that pref0_len <= pref_len, otherwise we
3879 decrease pref0_len. */
3880 int pref_len = (locinput - loc_bostr) > (5 + taill) - l
3881 ? (5 + taill) - l : locinput - loc_bostr;
3884 PERL_ARGS_ASSERT_DUMP_EXEC_POS;
3886 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput - pref_len)))
3888 pref0_len = pref_len - (locinput - loc_reg_starttry);
3889 if (l + pref_len < (5 + taill) && l < loc_regeol - locinput)
3890 l = ( loc_regeol - locinput > (5 + taill) - pref_len
3891 ? (5 + taill) - pref_len : loc_regeol - locinput);
3892 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput + l)))
3896 if (pref0_len > pref_len)
3897 pref0_len = pref_len;
3899 const int is_uni = utf8_target ? 1 : 0;
3901 RE_PV_COLOR_DECL(s0,len0,is_uni,PERL_DEBUG_PAD(0),
3902 (locinput - pref_len),pref0_len, 60, 4, 5);
3904 RE_PV_COLOR_DECL(s1,len1,is_uni,PERL_DEBUG_PAD(1),
3905 (locinput - pref_len + pref0_len),
3906 pref_len - pref0_len, 60, 2, 3);
3908 RE_PV_COLOR_DECL(s2,len2,is_uni,PERL_DEBUG_PAD(2),
3909 locinput, loc_regeol - locinput, 10, 0, 1);
3911 const STRLEN tlen=len0+len1+len2;
3912 PerlIO_printf(Perl_debug_log,
3913 "%4"IVdf" <%.*s%.*s%s%.*s>%*s|",
3914 (IV)(locinput - loc_bostr),
3917 (docolor ? "" : "> <"),
3919 (int)(tlen > 19 ? 0 : 19 - tlen),
3926 /* reg_check_named_buff_matched()
3927 * Checks to see if a named buffer has matched. The data array of
3928 * buffer numbers corresponding to the buffer is expected to reside
3929 * in the regexp->data->data array in the slot stored in the ARG() of
3930 * node involved. Note that this routine doesn't actually care about the
3931 * name, that information is not preserved from compilation to execution.
3932 * Returns the index of the leftmost defined buffer with the given name
3933 * or 0 if non of the buffers matched.
3936 S_reg_check_named_buff_matched(const regexp *rex, const regnode *scan)
3939 RXi_GET_DECL(rex,rexi);
3940 SV *sv_dat= MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
3941 I32 *nums=(I32*)SvPVX(sv_dat);
3943 PERL_ARGS_ASSERT_REG_CHECK_NAMED_BUFF_MATCHED;
3945 for ( n=0; n<SvIVX(sv_dat); n++ ) {
3946 if ((I32)rex->lastparen >= nums[n] &&
3947 rex->offs[nums[n]].end != -1)
3957 S_setup_EXACTISH_ST_c1_c2(pTHX_ const regnode * const text_node, int *c1p,
3958 U8* c1_utf8, int *c2p, U8* c2_utf8, regmatch_info *reginfo)
3960 /* This function determines if there are one or two characters that match
3961 * the first character of the passed-in EXACTish node <text_node>, and if
3962 * so, returns them in the passed-in pointers.
3964 * If it determines that no possible character in the target string can
3965 * match, it returns FALSE; otherwise TRUE. (The FALSE situation occurs if
3966 * the first character in <text_node> requires UTF-8 to represent, and the
3967 * target string isn't in UTF-8.)
3969 * If there are more than two characters that could match the beginning of
3970 * <text_node>, or if more context is required to determine a match or not,
3971 * it sets both *<c1p> and *<c2p> to CHRTEST_VOID.
3973 * The motiviation behind this function is to allow the caller to set up
3974 * tight loops for matching. If <text_node> is of type EXACT, there is
3975 * only one possible character that can match its first character, and so
3976 * the situation is quite simple. But things get much more complicated if
3977 * folding is involved. It may be that the first character of an EXACTFish
3978 * node doesn't participate in any possible fold, e.g., punctuation, so it
3979 * can be matched only by itself. The vast majority of characters that are
3980 * in folds match just two things, their lower and upper-case equivalents.
3981 * But not all are like that; some have multiple possible matches, or match
3982 * sequences of more than one character. This function sorts all that out.
3984 * Consider the patterns A*B or A*?B where A and B are arbitrary. In a
3985 * loop of trying to match A*, we know we can't exit where the thing
3986 * following it isn't a B. And something can't be a B unless it is the
3987 * beginning of B. By putting a quick test for that beginning in a tight
3988 * loop, we can rule out things that can't possibly be B without having to
3989 * break out of the loop, thus avoiding work. Similarly, if A is a single
3990 * character, we can make a tight loop matching A*, using the outputs of
3993 * If the target string to match isn't in UTF-8, and there aren't
3994 * complications which require CHRTEST_VOID, *<c1p> and *<c2p> are set to
3995 * the one or two possible octets (which are characters in this situation)
3996 * that can match. In all cases, if there is only one character that can
3997 * match, *<c1p> and *<c2p> will be identical.
3999 * If the target string is in UTF-8, the buffers pointed to by <c1_utf8>
4000 * and <c2_utf8> will contain the one or two UTF-8 sequences of bytes that
4001 * can match the beginning of <text_node>. They should be declared with at
4002 * least length UTF8_MAXBYTES+1. (If the target string isn't in UTF-8, it is
4003 * undefined what these contain.) If one or both of the buffers are
4004 * invariant under UTF-8, *<c1p>, and *<c2p> will also be set to the
4005 * corresponding invariant. If variant, the corresponding *<c1p> and/or
4006 * *<c2p> will be set to a negative number(s) that shouldn't match any code
4007 * point (unless inappropriately coerced to unsigned). *<c1p> will equal
4008 * *<c2p> if and only if <c1_utf8> and <c2_utf8> are the same. */
4010 const bool utf8_target = reginfo->is_utf8_target;
4012 UV c1 = (UV)CHRTEST_NOT_A_CP_1;
4013 UV c2 = (UV)CHRTEST_NOT_A_CP_2;
4014 bool use_chrtest_void = FALSE;
4015 const bool is_utf8_pat = reginfo->is_utf8_pat;
4017 /* Used when we have both utf8 input and utf8 output, to avoid converting
4018 * to/from code points */
4019 bool utf8_has_been_setup = FALSE;
4023 U8 *pat = (U8*)STRING(text_node);
4024 U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' };
4026 if (OP(text_node) == EXACT || OP(text_node) == EXACTL) {
4028 /* In an exact node, only one thing can be matched, that first
4029 * character. If both the pat and the target are UTF-8, we can just
4030 * copy the input to the output, avoiding finding the code point of
4035 else if (utf8_target) {
4036 Copy(pat, c1_utf8, UTF8SKIP(pat), U8);
4037 Copy(pat, c2_utf8, UTF8SKIP(pat), U8);
4038 utf8_has_been_setup = TRUE;
4041 c2 = c1 = valid_utf8_to_uvchr(pat, NULL);
4044 else { /* an EXACTFish node */
4045 U8 *pat_end = pat + STR_LEN(text_node);
4047 /* An EXACTFL node has at least some characters unfolded, because what
4048 * they match is not known until now. So, now is the time to fold
4049 * the first few of them, as many as are needed to determine 'c1' and
4050 * 'c2' later in the routine. If the pattern isn't UTF-8, we only need
4051 * to fold if in a UTF-8 locale, and then only the Sharp S; everything
4052 * else is 1-1 and isn't assumed to be folded. In a UTF-8 pattern, we
4053 * need to fold as many characters as a single character can fold to,
4054 * so that later we can check if the first ones are such a multi-char
4055 * fold. But, in such a pattern only locale-problematic characters
4056 * aren't folded, so we can skip this completely if the first character
4057 * in the node isn't one of the tricky ones */
4058 if (OP(text_node) == EXACTFL) {
4060 if (! is_utf8_pat) {
4061 if (IN_UTF8_CTYPE_LOCALE && *pat == LATIN_SMALL_LETTER_SHARP_S)
4063 folded[0] = folded[1] = 's';
4065 pat_end = folded + 2;
4068 else if (is_PROBLEMATIC_LOCALE_FOLDEDS_START_utf8(pat)) {
4073 for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < pat_end; i++) {
4075 *(d++) = (U8) toFOLD_LC(*s);
4080 _to_utf8_fold_flags(s,
4083 FOLD_FLAGS_FULL | FOLD_FLAGS_LOCALE);
4094 if ((is_utf8_pat && is_MULTI_CHAR_FOLD_utf8_safe(pat, pat_end))
4095 || (!is_utf8_pat && is_MULTI_CHAR_FOLD_latin1_safe(pat, pat_end)))
4097 /* Multi-character folds require more context to sort out. Also
4098 * PL_utf8_foldclosures used below doesn't handle them, so have to
4099 * be handled outside this routine */
4100 use_chrtest_void = TRUE;
4102 else { /* an EXACTFish node which doesn't begin with a multi-char fold */
4103 c1 = is_utf8_pat ? valid_utf8_to_uvchr(pat, NULL) : *pat;
4105 /* Load the folds hash, if not already done */
4107 if (! PL_utf8_foldclosures) {
4108 _load_PL_utf8_foldclosures();
4111 /* The fold closures data structure is a hash with the keys
4112 * being the UTF-8 of every character that is folded to, like
4113 * 'k', and the values each an array of all code points that
4114 * fold to its key. e.g. [ 'k', 'K', KELVIN_SIGN ].
4115 * Multi-character folds are not included */
4116 if ((! (listp = hv_fetch(PL_utf8_foldclosures,
4121 /* Not found in the hash, therefore there are no folds
4122 * containing it, so there is only a single character that
4126 else { /* Does participate in folds */
4127 AV* list = (AV*) *listp;
4128 if (av_tindex(list) != 1) {
4130 /* If there aren't exactly two folds to this, it is
4131 * outside the scope of this function */
4132 use_chrtest_void = TRUE;
4134 else { /* There are two. Get them */
4135 SV** c_p = av_fetch(list, 0, FALSE);
4137 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
4141 c_p = av_fetch(list, 1, FALSE);
4143 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
4147 /* Folds that cross the 255/256 boundary are forbidden
4148 * if EXACTFL (and isnt a UTF8 locale), or EXACTFA and
4149 * one is ASCIII. Since the pattern character is above
4150 * 255, and its only other match is below 256, the only
4151 * legal match will be to itself. We have thrown away
4152 * the original, so have to compute which is the one
4154 if ((c1 < 256) != (c2 < 256)) {
4155 if ((OP(text_node) == EXACTFL
4156 && ! IN_UTF8_CTYPE_LOCALE)
4157 || ((OP(text_node) == EXACTFA
4158 || OP(text_node) == EXACTFA_NO_TRIE)
4159 && (isASCII(c1) || isASCII(c2))))
4172 else /* Here, c1 is <= 255 */
4174 && HAS_NONLATIN1_FOLD_CLOSURE(c1)
4175 && ( ! (OP(text_node) == EXACTFL && ! IN_UTF8_CTYPE_LOCALE))
4176 && ((OP(text_node) != EXACTFA
4177 && OP(text_node) != EXACTFA_NO_TRIE)
4180 /* Here, there could be something above Latin1 in the target
4181 * which folds to this character in the pattern. All such
4182 * cases except LATIN SMALL LETTER Y WITH DIAERESIS have more
4183 * than two characters involved in their folds, so are outside
4184 * the scope of this function */
4185 if (UNLIKELY(c1 == LATIN_SMALL_LETTER_Y_WITH_DIAERESIS)) {
4186 c2 = LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS;
4189 use_chrtest_void = TRUE;
4192 else { /* Here nothing above Latin1 can fold to the pattern
4194 switch (OP(text_node)) {
4196 case EXACTFL: /* /l rules */
4197 c2 = PL_fold_locale[c1];
4200 case EXACTF: /* This node only generated for non-utf8
4202 assert(! is_utf8_pat);
4203 if (! utf8_target) { /* /d rules */
4208 /* /u rules for all these. This happens to work for
4209 * EXACTFA as nothing in Latin1 folds to ASCII */
4210 case EXACTFA_NO_TRIE: /* This node only generated for
4211 non-utf8 patterns */
4212 assert(! is_utf8_pat);
4217 c2 = PL_fold_latin1[c1];
4221 Perl_croak(aTHX_ "panic: Unexpected op %u", OP(text_node));
4222 NOT_REACHED; /* NOTREACHED */
4228 /* Here have figured things out. Set up the returns */
4229 if (use_chrtest_void) {
4230 *c2p = *c1p = CHRTEST_VOID;
4232 else if (utf8_target) {
4233 if (! utf8_has_been_setup) { /* Don't have the utf8; must get it */
4234 uvchr_to_utf8(c1_utf8, c1);
4235 uvchr_to_utf8(c2_utf8, c2);
4238 /* Invariants are stored in both the utf8 and byte outputs; Use
4239 * negative numbers otherwise for the byte ones. Make sure that the
4240 * byte ones are the same iff the utf8 ones are the same */
4241 *c1p = (UTF8_IS_INVARIANT(*c1_utf8)) ? *c1_utf8 : CHRTEST_NOT_A_CP_1;
4242 *c2p = (UTF8_IS_INVARIANT(*c2_utf8))
4245 ? CHRTEST_NOT_A_CP_1
4246 : CHRTEST_NOT_A_CP_2;
4248 else if (c1 > 255) {
4249 if (c2 > 255) { /* both possibilities are above what a non-utf8 string
4254 *c1p = *c2p = c2; /* c2 is the only representable value */
4256 else { /* c1 is representable; see about c2 */
4258 *c2p = (c2 < 256) ? c2 : c1;
4264 PERL_STATIC_INLINE bool
4265 S_isGCB(const GCB_enum before, const GCB_enum after)
4267 /* returns a boolean indicating if there is a Grapheme Cluster Boundary
4268 * between the inputs. See http://www.unicode.org/reports/tr29/ */
4270 return GCB_table[before][after];
4273 /* Combining marks attach to most classes that precede them, but this defines
4274 * the exceptions (from TR14) */
4275 #define LB_CM_ATTACHES_TO(prev) ( ! ( prev == LB_EDGE \
4276 || prev == LB_Mandatory_Break \
4277 || prev == LB_Carriage_Return \
4278 || prev == LB_Line_Feed \
4279 || prev == LB_Next_Line \
4280 || prev == LB_Space \
4281 || prev == LB_ZWSpace))
4284 S_isLB(pTHX_ LB_enum before,
4286 const U8 * const strbeg,
4287 const U8 * const curpos,
4288 const U8 * const strend,
4289 const bool utf8_target)
4291 U8 * temp_pos = (U8 *) curpos;
4292 LB_enum prev = before;
4294 /* Is the boundary between 'before' and 'after' line-breakable?
4295 * Most of this is just a table lookup of a generated table from Unicode
4296 * rules. But some rules require context to decide, and so have to be
4297 * implemented in code */
4299 PERL_ARGS_ASSERT_ISLB;
4301 /* Rule numbers in the comments below are as of Unicode 8.0 */
4305 switch (LB_table[before][after]) {
4310 case LB_NOBREAK_EVEN_WITH_SP_BETWEEN:
4313 case LB_SP_foo + LB_BREAKABLE:
4314 case LB_SP_foo + LB_NOBREAK:
4315 case LB_SP_foo + LB_NOBREAK_EVEN_WITH_SP_BETWEEN:
4317 /* When we have something following a SP, we have to look at the
4318 * context in order to know what to do.
4320 * SP SP should not reach here because LB7: Do not break before
4321 * spaces. (For two spaces in a row there is nothing that
4322 * overrides that) */
4323 assert(after != LB_Space);
4325 /* Here we have a space followed by a non-space. Mostly this is a
4326 * case of LB18: "Break after spaces". But there are complications
4327 * as the handling of spaces is somewhat tricky. They are in a
4328 * number of rules, which have to be applied in priority order, but
4329 * something earlier in the string can cause a rule to be skipped
4330 * and a lower priority rule invoked. A prime example is LB7 which
4331 * says don't break before a space. But rule LB8 (lower priority)
4332 * says that the first break opportunity after a ZW is after any
4333 * span of spaces immediately after it. If a ZW comes before a SP
4334 * in the input, rule LB8 applies, and not LB7. Other such rules
4335 * involve combining marks which are rules 9 and 10, but they may
4336 * override higher priority rules if they come earlier in the
4337 * string. Since we're doing random access into the middle of the
4338 * string, we have to look for rules that should get applied based
4339 * on both string position and priority. Combining marks do not
4340 * attach to either ZW nor SP, so we don't have to consider them
4343 * To check for LB8, we have to find the first non-space character
4344 * before this span of spaces */
4346 prev = backup_one_LB(strbeg, &temp_pos, utf8_target);
4348 while (prev == LB_Space);
4350 /* LB8 Break before any character following a zero-width space,
4351 * even if one or more spaces intervene.
4353 * So if we have a ZW just before this span, and to get here this
4354 * is the final space in the span. */
4355 if (prev == LB_ZWSpace) {
4359 /* Here, not ZW SP+. There are several rules that have higher
4360 * priority than LB18 and can be resolved now, as they don't depend
4361 * on anything earlier in the string (except ZW, which we have
4362 * already handled). One of these rules is LB11 Do not break
4363 * before Word joiner, but we have specially encoded that in the
4364 * lookup table so it is caught by the single test below which
4365 * catches the other ones. */
4366 if (LB_table[LB_Space][after] - LB_SP_foo
4367 == LB_NOBREAK_EVEN_WITH_SP_BETWEEN)
4372 /* If we get here, we have to XXX consider combining marks. */
4373 if (prev == LB_Combining_Mark) {
4375 /* What happens with these depends on the character they
4378 prev = backup_one_LB(strbeg, &temp_pos, utf8_target);
4380 while (prev == LB_Combining_Mark);
4382 /* Most times these attach to and inherit the characteristics
4383 * of that character, but not always, and when not, they are to
4384 * be treated as AL by rule LB10. */
4385 if (! LB_CM_ATTACHES_TO(prev)) {
4386 prev = LB_Alphabetic;
4390 /* Here, we have the character preceding the span of spaces all set
4391 * up. We follow LB18: "Break after spaces" unless the table shows
4392 * that is overriden */
4393 return LB_table[prev][after] != LB_NOBREAK_EVEN_WITH_SP_BETWEEN;
4397 /* We don't know how to treat the CM except by looking at the first
4398 * non-CM character preceding it */
4400 prev = backup_one_LB(strbeg, &temp_pos, utf8_target);
4402 while (prev == LB_Combining_Mark);
4404 /* Here, 'prev' is that first earlier non-CM character. If the CM
4405 * attatches to it, then it inherits the behavior of 'prev'. If it
4406 * doesn't attach, it is to be treated as an AL */
4407 if (! LB_CM_ATTACHES_TO(prev)) {
4408 prev = LB_Alphabetic;
4413 case LB_HY_or_BA_then_foo + LB_BREAKABLE:
4414 case LB_HY_or_BA_then_foo + LB_NOBREAK:
4416 /* LB21a Don't break after Hebrew + Hyphen.
4417 * HL (HY | BA) × */
4419 if (backup_one_LB(strbeg, &temp_pos, utf8_target)
4420 == LB_Hebrew_Letter)
4425 return LB_table[prev][after] - LB_HY_or_BA_then_foo == LB_BREAKABLE;
4427 case LB_PR_or_PO_then_OP_or_HY + LB_BREAKABLE:
4428 case LB_PR_or_PO_then_OP_or_HY + LB_NOBREAK:
4430 /* LB25a (PR | PO) × ( OP | HY )? NU */
4431 if (advance_one_LB(&temp_pos, strend, utf8_target) == LB_Numeric) {
4435 return LB_table[prev][after] - LB_PR_or_PO_then_OP_or_HY
4438 case LB_SY_or_IS_then_various + LB_BREAKABLE:
4439 case LB_SY_or_IS_then_various + LB_NOBREAK:
4441 /* LB25d NU (SY | IS)* × (NU | SY | IS | CL | CP ) */
4443 LB_enum temp = prev;
4445 temp = backup_one_LB(strbeg, &temp_pos, utf8_target);
4447 while (temp == LB_Break_Symbols || temp == LB_Infix_Numeric);
4448 if (temp == LB_Numeric) {
4452 return LB_table[prev][after] - LB_SY_or_IS_then_various
4456 case LB_various_then_PO_or_PR + LB_BREAKABLE:
4457 case LB_various_then_PO_or_PR + LB_NOBREAK:
4459 /* LB25e NU (SY | IS)* (CL | CP)? × (PO | PR) */
4461 LB_enum temp = prev;
4462 if (temp == LB_Close_Punctuation || temp == LB_Close_Parenthesis)
4464 temp = backup_one_LB(strbeg, &temp_pos, utf8_target);
4466 while (temp == LB_Break_Symbols || temp == LB_Infix_Numeric) {
4467 temp = backup_one_LB(strbeg, &temp_pos, utf8_target);
4469 if (temp == LB_Numeric) {
4472 return LB_various_then_PO_or_PR;
4480 PerlIO_printf(Perl_error_log, "Unhandled LB pair: LB_table[%d, %d] = %d\n",
4481 before, after, LB_table[before][after]);
4488 S_advance_one_LB(pTHX_ U8 ** curpos, const U8 * const strend, const bool utf8_target)
4492 PERL_ARGS_ASSERT_ADVANCE_ONE_LB;
4494 if (*curpos >= strend) {
4499 *curpos += UTF8SKIP(*curpos);
4500 if (*curpos >= strend) {
4503 lb = getLB_VAL_UTF8(*curpos, strend);
4507 if (*curpos >= strend) {
4510 lb = getLB_VAL_CP(**curpos);
4517 S_backup_one_LB(pTHX_ const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
4521 PERL_ARGS_ASSERT_BACKUP_ONE_LB;
4523 if (*curpos < strbeg) {
4528 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
4529 U8 * prev_prev_char_pos;
4531 if (! prev_char_pos) {
4535 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos, -1, strbeg))) {
4536 lb = getLB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
4537 *curpos = prev_char_pos;
4538 prev_char_pos = prev_prev_char_pos;
4541 *curpos = (U8 *) strbeg;
4546 if (*curpos - 2 < strbeg) {
4547 *curpos = (U8 *) strbeg;
4551 lb = getLB_VAL_CP(*(*curpos - 1));
4558 S_isSB(pTHX_ SB_enum before,
4560 const U8 * const strbeg,
4561 const U8 * const curpos,
4562 const U8 * const strend,
4563 const bool utf8_target)
4565 /* returns a boolean indicating if there is a Sentence Boundary Break
4566 * between the inputs. See http://www.unicode.org/reports/tr29/ */
4568 U8 * lpos = (U8 *) curpos;
4569 bool has_para_sep = FALSE;
4570 bool has_sp = FALSE;
4572 PERL_ARGS_ASSERT_ISSB;
4574 /* Break at the start and end of text.
4577 But unstated in Unicode is don't break if the text is empty */
4578 if (before == SB_EDGE || after == SB_EDGE) {
4579 return before != after;
4582 /* SB 3: Do not break within CRLF. */
4583 if (before == SB_CR && after == SB_LF) {
4587 /* Break after paragraph separators. CR and LF are considered
4588 * so because Unicode views text as like word processing text where there
4589 * are no newlines except between paragraphs, and the word processor takes
4590 * care of wrapping without there being hard line-breaks in the text *./
4591 SB4. Sep | CR | LF ÷ */
4592 if (before == SB_Sep || before == SB_CR || before == SB_LF) {
4596 /* Ignore Format and Extend characters, except after sot, Sep, CR, or LF.
4597 * (See Section 6.2, Replacing Ignore Rules.)
4598 SB5. X (Extend | Format)* → X */
4599 if (after == SB_Extend || after == SB_Format) {
4601 /* Implied is that the these characters attach to everything
4602 * immediately prior to them except for those separator-type
4603 * characters. And the rules earlier have already handled the case
4604 * when one of those immediately precedes the extend char */
4608 if (before == SB_Extend || before == SB_Format) {
4609 U8 * temp_pos = lpos;
4610 const SB_enum backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4611 if ( backup != SB_EDGE
4620 /* Here, both 'before' and 'backup' are these types; implied is that we
4621 * don't break between them */
4622 if (backup == SB_Extend || backup == SB_Format) {
4627 /* Do not break after ambiguous terminators like period, if they are
4628 * immediately followed by a number or lowercase letter, if they are
4629 * between uppercase letters, if the first following letter (optionally
4630 * after certain punctuation) is lowercase, or if they are followed by
4631 * "continuation" punctuation such as comma, colon, or semicolon. For
4632 * example, a period may be an abbreviation or numeric period, and thus may
4633 * not mark the end of a sentence.
4635 * SB6. ATerm × Numeric */
4636 if (before == SB_ATerm && after == SB_Numeric) {
4640 /* SB7. (Upper | Lower) ATerm × Upper */
4641 if (before == SB_ATerm && after == SB_Upper) {
4642 U8 * temp_pos = lpos;
4643 SB_enum backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4644 if (backup == SB_Upper || backup == SB_Lower) {
4649 /* The remaining rules that aren't the final one, all require an STerm or
4650 * an ATerm after having backed up over some Close* Sp*, and in one case an
4651 * optional Paragraph separator, although one rule doesn't have any Sp's in it.
4652 * So do that backup now, setting flags if either Sp or a paragraph
4653 * separator are found */
4655 if (before == SB_Sep || before == SB_CR || before == SB_LF) {
4656 has_para_sep = TRUE;
4657 before = backup_one_SB(strbeg, &lpos, utf8_target);
4660 if (before == SB_Sp) {
4663 before = backup_one_SB(strbeg, &lpos, utf8_target);
4665 while (before == SB_Sp);
4668 while (before == SB_Close) {
4669 before = backup_one_SB(strbeg, &lpos, utf8_target);
4672 /* The next few rules apply only when the backed-up-to is an ATerm, and in
4673 * most cases an STerm */
4674 if (before == SB_STerm || before == SB_ATerm) {
4676 /* So, here the lhs matches
4677 * (STerm | ATerm) Close* Sp* (Sep | CR | LF)?
4678 * and we have set flags if we found an Sp, or the optional Sep,CR,LF.
4679 * The rules that apply here are:
4681 * SB8 ATerm Close* Sp* × ( ¬(OLetter | Upper | Lower | Sep | CR
4682 | LF | STerm | ATerm) )* Lower
4683 SB8a (STerm | ATerm) Close* Sp* × (SContinue | STerm | ATerm)
4684 SB9 (STerm | ATerm) Close* × (Close | Sp | Sep | CR | LF)
4685 SB10 (STerm | ATerm) Close* Sp* × (Sp | Sep | CR | LF)
4686 SB11 (STerm | ATerm) Close* Sp* (Sep | CR | LF)? ÷
4689 /* And all but SB11 forbid having seen a paragraph separator */
4690 if (! has_para_sep) {
4691 if (before == SB_ATerm) { /* SB8 */
4692 U8 * rpos = (U8 *) curpos;
4693 SB_enum later = after;
4695 while ( later != SB_OLetter
4696 && later != SB_Upper
4697 && later != SB_Lower
4701 && later != SB_STerm
4702 && later != SB_ATerm
4703 && later != SB_EDGE)
4705 later = advance_one_SB(&rpos, strend, utf8_target);
4707 if (later == SB_Lower) {
4712 if ( after == SB_SContinue /* SB8a */
4713 || after == SB_STerm
4714 || after == SB_ATerm)
4719 if (! has_sp) { /* SB9 applies only if there was no Sp* */
4720 if ( after == SB_Close
4730 /* SB10. This and SB9 could probably be combined some way, but khw
4731 * has decided to follow the Unicode rule book precisely for
4732 * simplified maintenance */
4746 /* Otherwise, do not break.
4753 S_advance_one_SB(pTHX_ U8 ** curpos, const U8 * const strend, const bool utf8_target)
4757 PERL_ARGS_ASSERT_ADVANCE_ONE_SB;
4759 if (*curpos >= strend) {
4765 *curpos += UTF8SKIP(*curpos);
4766 if (*curpos >= strend) {
4769 sb = getSB_VAL_UTF8(*curpos, strend);
4770 } while (sb == SB_Extend || sb == SB_Format);
4775 if (*curpos >= strend) {
4778 sb = getSB_VAL_CP(**curpos);
4779 } while (sb == SB_Extend || sb == SB_Format);
4786 S_backup_one_SB(pTHX_ const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
4790 PERL_ARGS_ASSERT_BACKUP_ONE_SB;
4792 if (*curpos < strbeg) {
4797 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
4798 if (! prev_char_pos) {
4802 /* Back up over Extend and Format. curpos is always just to the right
4803 * of the characater whose value we are getting */
4805 U8 * prev_prev_char_pos;
4806 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos, -1,
4809 sb = getSB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
4810 *curpos = prev_char_pos;
4811 prev_char_pos = prev_prev_char_pos;
4814 *curpos = (U8 *) strbeg;
4817 } while (sb == SB_Extend || sb == SB_Format);
4821 if (*curpos - 2 < strbeg) {
4822 *curpos = (U8 *) strbeg;
4826 sb = getSB_VAL_CP(*(*curpos - 1));
4827 } while (sb == SB_Extend || sb == SB_Format);
4834 S_isWB(pTHX_ WB_enum previous,
4837 const U8 * const strbeg,
4838 const U8 * const curpos,
4839 const U8 * const strend,
4840 const bool utf8_target)
4842 /* Return a boolean as to if the boundary between 'before' and 'after' is
4843 * a Unicode word break, using their published algorithm, but tailored for
4844 * Perl by treating spans of white space as one unit. Context may be
4845 * needed to make this determination. If the value for the character
4846 * before 'before' is known, it is passed as 'previous'; otherwise that
4847 * should be set to WB_UNKNOWN. The other input parameters give the
4848 * boundaries and current position in the matching of the string. That
4849 * is, 'curpos' marks the position where the character whose wb value is
4850 * 'after' begins. See http://www.unicode.org/reports/tr29/ */
4852 U8 * before_pos = (U8 *) curpos;
4853 U8 * after_pos = (U8 *) curpos;
4854 WB_enum prev = before;
4857 PERL_ARGS_ASSERT_ISWB;
4859 /* Rule numbers in the comments below are as of Unicode 8.0 */
4863 switch (WB_table[before][after]) {
4870 case WB_hs_then_hs: /* 2 horizontal spaces in a row */
4871 next = advance_one_WB(&after_pos, strend, utf8_target,
4872 FALSE /* Don't skip Extend nor Format */ );
4873 /* A space immediately preceeding an Extend or Format is attached
4874 * to by them, and hence gets separated from previous spaces.
4875 * Otherwise don't break between horizontal white space */
4876 return next == WB_Extend || next == WB_Format;
4878 /* WB4 Ignore Format and Extend characters, except when they appear at
4879 * the beginning of a region of text. This code currently isn't
4880 * general purpose, but it works as the rules are currently and likely
4881 * to be laid out. The reason it works is that when 'they appear at
4882 * the beginning of a region of text', the rule is to break before
4883 * them, just like any other character. Therefore, the default rule
4884 * applies and we don't have to look in more depth. Should this ever
4885 * change, we would have to have 2 'case' statements, like in the
4886 * rules below, and backup a single character (not spacing over the
4887 * extend ones) and then see if that is one of the region-end
4888 * characters and go from there */
4889 case WB_Ex_or_FO_then_foo:
4890 prev = backup_one_WB(&previous, strbeg, &before_pos, utf8_target);
4893 case WB_DQ_then_HL + WB_BREAKABLE:
4894 case WB_DQ_then_HL + WB_NOBREAK:
4896 /* WB7c Hebrew_Letter Double_Quote × Hebrew_Letter */
4898 if (backup_one_WB(&previous, strbeg, &before_pos, utf8_target)
4899 == WB_Hebrew_Letter)
4904 return WB_table[before][after] - WB_DQ_then_HL == WB_BREAKABLE;
4906 case WB_HL_then_DQ + WB_BREAKABLE:
4907 case WB_HL_then_DQ + WB_NOBREAK:
4909 /* WB7b Hebrew_Letter × Double_Quote Hebrew_Letter */
4911 if (advance_one_WB(&after_pos, strend, utf8_target,
4912 TRUE /* Do skip Extend and Format */ )
4913 == WB_Hebrew_Letter)
4918 return WB_table[before][after] - WB_HL_then_DQ == WB_BREAKABLE;
4920 case WB_LE_or_HL_then_MB_or_ML_or_SQ + WB_NOBREAK:
4921 case WB_LE_or_HL_then_MB_or_ML_or_SQ + WB_BREAKABLE:
4923 /* WB6 (ALetter | Hebrew_Letter) × (MidLetter | MidNumLet
4924 * | Single_Quote) (ALetter | Hebrew_Letter) */
4926 next = advance_one_WB(&after_pos, strend, utf8_target,
4927 TRUE /* Do skip Extend and Format */ );
4929 if (next == WB_ALetter || next == WB_Hebrew_Letter)
4934 return WB_table[before][after]
4935 - WB_LE_or_HL_then_MB_or_ML_or_SQ == WB_BREAKABLE;
4937 case WB_MB_or_ML_or_SQ_then_LE_or_HL + WB_NOBREAK:
4938 case WB_MB_or_ML_or_SQ_then_LE_or_HL + WB_BREAKABLE:
4940 /* WB7 (ALetter | Hebrew_Letter) (MidLetter | MidNumLet
4941 * | Single_Quote) × (ALetter | Hebrew_Letter) */
4943 prev = backup_one_WB(&previous, strbeg, &before_pos, utf8_target);
4944 if (prev == WB_ALetter || prev == WB_Hebrew_Letter)
4949 return WB_table[before][after]
4950 - WB_MB_or_ML_or_SQ_then_LE_or_HL == WB_BREAKABLE;
4952 case WB_MB_or_MN_or_SQ_then_NU + WB_NOBREAK:
4953 case WB_MB_or_MN_or_SQ_then_NU + WB_BREAKABLE:
4955 /* WB11 Numeric (MidNum | (MidNumLet | Single_Quote)) × Numeric
4958 if (backup_one_WB(&previous, strbeg, &before_pos, utf8_target)
4964 return WB_table[before][after]
4965 - WB_MB_or_MN_or_SQ_then_NU == WB_BREAKABLE;
4967 case WB_NU_then_MB_or_MN_or_SQ + WB_NOBREAK:
4968 case WB_NU_then_MB_or_MN_or_SQ + WB_BREAKABLE:
4970 /* WB12 Numeric × (MidNum | MidNumLet | Single_Quote) Numeric */
4972 if (advance_one_WB(&after_pos, strend, utf8_target,
4973 TRUE /* Do skip Extend and Format */ )
4979 return WB_table[before][after]
4980 - WB_NU_then_MB_or_MN_or_SQ == WB_BREAKABLE;
4987 PerlIO_printf(Perl_error_log, "Unhandled WB pair: WB_table[%d, %d] = %d\n",
4988 before, after, WB_table[before][after]);
4995 S_advance_one_WB(pTHX_ U8 ** curpos,
4996 const U8 * const strend,
4997 const bool utf8_target,
4998 const bool skip_Extend_Format)
5002 PERL_ARGS_ASSERT_ADVANCE_ONE_WB;
5004 if (*curpos >= strend) {
5010 /* Advance over Extend and Format */
5012 *curpos += UTF8SKIP(*curpos);
5013 if (*curpos >= strend) {
5016 wb = getWB_VAL_UTF8(*curpos, strend);
5017 } while ( skip_Extend_Format
5018 && (wb == WB_Extend || wb == WB_Format));
5023 if (*curpos >= strend) {
5026 wb = getWB_VAL_CP(**curpos);
5027 } while ( skip_Extend_Format
5028 && (wb == WB_Extend || wb == WB_Format));
5035 S_backup_one_WB(pTHX_ WB_enum * previous, const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
5039 PERL_ARGS_ASSERT_BACKUP_ONE_WB;
5041 /* If we know what the previous character's break value is, don't have
5043 if (*previous != WB_UNKNOWN) {
5046 /* But we need to move backwards by one */
5048 *curpos = reghopmaybe3(*curpos, -1, strbeg);
5050 *previous = WB_EDGE;
5051 *curpos = (U8 *) strbeg;
5054 *previous = WB_UNKNOWN;
5059 *previous = (*curpos <= strbeg) ? WB_EDGE : WB_UNKNOWN;
5062 /* And we always back up over these two types */
5063 if (wb != WB_Extend && wb != WB_Format) {
5068 if (*curpos < strbeg) {
5073 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
5074 if (! prev_char_pos) {
5078 /* Back up over Extend and Format. curpos is always just to the right
5079 * of the characater whose value we are getting */
5081 U8 * prev_prev_char_pos;
5082 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos,
5086 wb = getWB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
5087 *curpos = prev_char_pos;
5088 prev_char_pos = prev_prev_char_pos;
5091 *curpos = (U8 *) strbeg;
5094 } while (wb == WB_Extend || wb == WB_Format);
5098 if (*curpos - 2 < strbeg) {
5099 *curpos = (U8 *) strbeg;
5103 wb = getWB_VAL_CP(*(*curpos - 1));
5104 } while (wb == WB_Extend || wb == WB_Format);
5110 /* returns -1 on failure, $+[0] on success */
5112 S_regmatch(pTHX_ regmatch_info *reginfo, char *startpos, regnode *prog)
5115 #if PERL_VERSION < 9 && !defined(PERL_CORE)
5119 const bool utf8_target = reginfo->is_utf8_target;
5120 const U32 uniflags = UTF8_ALLOW_DEFAULT;
5121 REGEXP *rex_sv = reginfo->prog;
5122 regexp *rex = ReANY(rex_sv);
5123 RXi_GET_DECL(rex,rexi);
5124 /* the current state. This is a cached copy of PL_regmatch_state */
5126 /* cache heavy used fields of st in registers */
5129 U32 n = 0; /* general value; init to avoid compiler warning */
5130 SSize_t ln = 0; /* len or last; init to avoid compiler warning */
5131 char *locinput = startpos;
5132 char *pushinput; /* where to continue after a PUSH */
5133 I32 nextchr; /* is always set to UCHARAT(locinput) */
5135 bool result = 0; /* return value of S_regmatch */
5136 int depth = 0; /* depth of backtrack stack */
5137 U32 nochange_depth = 0; /* depth of GOSUB recursion with nochange */
5138 const U32 max_nochange_depth =
5139 (3 * rex->nparens > MAX_RECURSE_EVAL_NOCHANGE_DEPTH) ?
5140 3 * rex->nparens : MAX_RECURSE_EVAL_NOCHANGE_DEPTH;
5141 regmatch_state *yes_state = NULL; /* state to pop to on success of
5143 /* mark_state piggy backs on the yes_state logic so that when we unwind
5144 the stack on success we can update the mark_state as we go */
5145 regmatch_state *mark_state = NULL; /* last mark state we have seen */
5146 regmatch_state *cur_eval = NULL; /* most recent EVAL_AB state */
5147 struct regmatch_state *cur_curlyx = NULL; /* most recent curlyx */
5149 bool no_final = 0; /* prevent failure from backtracking? */
5150 bool do_cutgroup = 0; /* no_final only until next branch/trie entry */
5151 char *startpoint = locinput;
5152 SV *popmark = NULL; /* are we looking for a mark? */
5153 SV *sv_commit = NULL; /* last mark name seen in failure */
5154 SV *sv_yes_mark = NULL; /* last mark name we have seen
5155 during a successful match */
5156 U32 lastopen = 0; /* last open we saw */
5157 bool has_cutgroup = RX_HAS_CUTGROUP(rex) ? 1 : 0;
5158 SV* const oreplsv = GvSVn(PL_replgv);
5159 /* these three flags are set by various ops to signal information to
5160 * the very next op. They have a useful lifetime of exactly one loop
5161 * iteration, and are not preserved or restored by state pushes/pops
5163 bool sw = 0; /* the condition value in (?(cond)a|b) */
5164 bool minmod = 0; /* the next "{n,m}" is a "{n,m}?" */
5165 int logical = 0; /* the following EVAL is:
5169 or the following IFMATCH/UNLESSM is:
5170 false: plain (?=foo)
5171 true: used as a condition: (?(?=foo))
5173 PAD* last_pad = NULL;
5175 U8 gimme = G_SCALAR;
5176 CV *caller_cv = NULL; /* who called us */
5177 CV *last_pushed_cv = NULL; /* most recently called (?{}) CV */
5178 CHECKPOINT runops_cp; /* savestack position before executing EVAL */
5179 U32 maxopenparen = 0; /* max '(' index seen so far */
5180 int to_complement; /* Invert the result? */
5181 _char_class_number classnum;
5182 bool is_utf8_pat = reginfo->is_utf8_pat;
5187 GET_RE_DEBUG_FLAGS_DECL;
5190 /* protect against undef(*^R) */
5191 SAVEFREESV(SvREFCNT_inc_simple_NN(oreplsv));
5193 /* shut up 'may be used uninitialized' compiler warnings for dMULTICALL */
5194 multicall_oldcatch = 0;
5195 PERL_UNUSED_VAR(multicall_cop);
5197 PERL_ARGS_ASSERT_REGMATCH;
5199 DEBUG_OPTIMISE_r( DEBUG_EXECUTE_r({
5200 PerlIO_printf(Perl_debug_log,"regmatch start\n");
5203 st = PL_regmatch_state;
5205 /* Note that nextchr is a byte even in UTF */
5208 while (scan != NULL) {
5211 SV * const prop = sv_newmortal();
5212 regnode *rnext=regnext(scan);
5213 DUMP_EXEC_POS( locinput, scan, utf8_target );
5214 regprop(rex, prop, scan, reginfo, NULL);
5216 PerlIO_printf(Perl_debug_log,
5217 "%3"IVdf":%*s%s(%"IVdf")\n",
5218 (IV)(scan - rexi->program), depth*2, "",
5220 (PL_regkind[OP(scan)] == END || !rnext) ?
5221 0 : (IV)(rnext - rexi->program));
5224 next = scan + NEXT_OFF(scan);
5227 state_num = OP(scan);
5233 assert(nextchr < 256 && (nextchr >= 0 || nextchr == NEXTCHR_EOS));
5235 switch (state_num) {
5236 case SBOL: /* /^../ and /\A../ */
5237 if (locinput == reginfo->strbeg)
5241 case MBOL: /* /^../m */
5242 if (locinput == reginfo->strbeg ||
5243 (!NEXTCHR_IS_EOS && locinput[-1] == '\n'))
5250 if (locinput == reginfo->ganch)
5254 case KEEPS: /* \K */
5255 /* update the startpoint */
5256 st->u.keeper.val = rex->offs[0].start;
5257 rex->offs[0].start = locinput - reginfo->strbeg;
5258 PUSH_STATE_GOTO(KEEPS_next, next, locinput);
5260 NOT_REACHED; /* NOTREACHED */
5262 case KEEPS_next_fail:
5263 /* rollback the start point change */
5264 rex->offs[0].start = st->u.keeper.val;
5267 NOT_REACHED; /* NOTREACHED */
5269 case MEOL: /* /..$/m */
5270 if (!NEXTCHR_IS_EOS && nextchr != '\n')
5274 case SEOL: /* /..$/ */
5275 if (!NEXTCHR_IS_EOS && nextchr != '\n')
5277 if (reginfo->strend - locinput > 1)
5282 if (!NEXTCHR_IS_EOS)
5286 case SANY: /* /./s */
5289 goto increment_locinput;
5291 case REG_ANY: /* /./ */
5292 if ((NEXTCHR_IS_EOS) || nextchr == '\n')
5294 goto increment_locinput;
5298 #define ST st->u.trie
5299 case TRIEC: /* (ab|cd) with known charclass */
5300 /* In this case the charclass data is available inline so
5301 we can fail fast without a lot of extra overhead.
5303 if(!NEXTCHR_IS_EOS && !ANYOF_BITMAP_TEST(scan, nextchr)) {
5305 PerlIO_printf(Perl_debug_log,
5306 "%*s %sfailed to match trie start class...%s\n",
5307 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
5311 NOT_REACHED; /* NOTREACHED */
5314 case TRIE: /* (ab|cd) */
5315 /* the basic plan of execution of the trie is:
5316 * At the beginning, run though all the states, and
5317 * find the longest-matching word. Also remember the position
5318 * of the shortest matching word. For example, this pattern:
5321 * when matched against the string "abcde", will generate
5322 * accept states for all words except 3, with the longest
5323 * matching word being 4, and the shortest being 2 (with
5324 * the position being after char 1 of the string).
5326 * Then for each matching word, in word order (i.e. 1,2,4,5),
5327 * we run the remainder of the pattern; on each try setting
5328 * the current position to the character following the word,
5329 * returning to try the next word on failure.
5331 * We avoid having to build a list of words at runtime by
5332 * using a compile-time structure, wordinfo[].prev, which
5333 * gives, for each word, the previous accepting word (if any).
5334 * In the case above it would contain the mappings 1->2, 2->0,
5335 * 3->0, 4->5, 5->1. We can use this table to generate, from
5336 * the longest word (4 above), a list of all words, by
5337 * following the list of prev pointers; this gives us the
5338 * unordered list 4,5,1,2. Then given the current word we have
5339 * just tried, we can go through the list and find the
5340 * next-biggest word to try (so if we just failed on word 2,
5341 * the next in the list is 4).
5343 * Since at runtime we don't record the matching position in
5344 * the string for each word, we have to work that out for
5345 * each word we're about to process. The wordinfo table holds
5346 * the character length of each word; given that we recorded
5347 * at the start: the position of the shortest word and its
5348 * length in chars, we just need to move the pointer the
5349 * difference between the two char lengths. Depending on
5350 * Unicode status and folding, that's cheap or expensive.
5352 * This algorithm is optimised for the case where are only a
5353 * small number of accept states, i.e. 0,1, or maybe 2.
5354 * With lots of accepts states, and having to try all of them,
5355 * it becomes quadratic on number of accept states to find all
5360 /* what type of TRIE am I? (utf8 makes this contextual) */
5361 DECL_TRIE_TYPE(scan);
5363 /* what trie are we using right now */
5364 reg_trie_data * const trie
5365 = (reg_trie_data*)rexi->data->data[ ARG( scan ) ];
5366 HV * widecharmap = MUTABLE_HV(rexi->data->data[ ARG( scan ) + 1 ]);
5367 U32 state = trie->startstate;
5369 if (scan->flags == EXACTL || scan->flags == EXACTFLU8) {
5370 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5372 && UTF8_IS_ABOVE_LATIN1(nextchr)
5373 && scan->flags == EXACTL)
5375 /* We only output for EXACTL, as we let the folder
5376 * output this message for EXACTFLU8 to avoid
5378 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput,
5383 && (NEXTCHR_IS_EOS || !TRIE_BITMAP_TEST(trie, nextchr)))
5385 if (trie->states[ state ].wordnum) {
5387 PerlIO_printf(Perl_debug_log,
5388 "%*s %smatched empty string...%s\n",
5389 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
5395 PerlIO_printf(Perl_debug_log,
5396 "%*s %sfailed to match trie start class...%s\n",
5397 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
5404 U8 *uc = ( U8* )locinput;
5408 U8 *uscan = (U8*)NULL;
5409 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
5410 U32 charcount = 0; /* how many input chars we have matched */
5411 U32 accepted = 0; /* have we seen any accepting states? */
5413 ST.jump = trie->jump;
5416 ST.longfold = FALSE; /* char longer if folded => it's harder */
5419 /* fully traverse the TRIE; note the position of the
5420 shortest accept state and the wordnum of the longest
5423 while ( state && uc <= (U8*)(reginfo->strend) ) {
5424 U32 base = trie->states[ state ].trans.base;
5428 wordnum = trie->states[ state ].wordnum;
5430 if (wordnum) { /* it's an accept state */
5433 /* record first match position */
5435 ST.firstpos = (U8*)locinput;
5440 ST.firstchars = charcount;
5443 if (!ST.nextword || wordnum < ST.nextword)
5444 ST.nextword = wordnum;
5445 ST.topword = wordnum;
5448 DEBUG_TRIE_EXECUTE_r({
5449 DUMP_EXEC_POS( (char *)uc, scan, utf8_target );
5450 PerlIO_printf( Perl_debug_log,
5451 "%*s %sState: %4"UVxf" Accepted: %c ",
5452 2+depth * 2, "", PL_colors[4],
5453 (UV)state, (accepted ? 'Y' : 'N'));
5456 /* read a char and goto next state */
5457 if ( base && (foldlen || uc < (U8*)(reginfo->strend))) {
5459 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
5460 uscan, len, uvc, charid, foldlen,
5467 base + charid - 1 - trie->uniquecharcount)) >= 0)
5469 && ((U32)offset < trie->lasttrans)
5470 && trie->trans[offset].check == state)
5472 state = trie->trans[offset].next;
5483 DEBUG_TRIE_EXECUTE_r(
5484 PerlIO_printf( Perl_debug_log,
5485 "Charid:%3x CP:%4"UVxf" After State: %4"UVxf"%s\n",
5486 charid, uvc, (UV)state, PL_colors[5] );
5492 /* calculate total number of accept states */
5497 w = trie->wordinfo[w].prev;
5500 ST.accepted = accepted;
5504 PerlIO_printf( Perl_debug_log,
5505 "%*s %sgot %"IVdf" possible matches%s\n",
5506 REPORT_CODE_OFF + depth * 2, "",
5507 PL_colors[4], (IV)ST.accepted, PL_colors[5] );
5509 goto trie_first_try; /* jump into the fail handler */
5512 NOT_REACHED; /* NOTREACHED */
5514 case TRIE_next_fail: /* we failed - try next alternative */
5518 REGCP_UNWIND(ST.cp);
5519 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
5521 if (!--ST.accepted) {
5523 PerlIO_printf( Perl_debug_log,
5524 "%*s %sTRIE failed...%s\n",
5525 REPORT_CODE_OFF+depth*2, "",
5532 /* Find next-highest word to process. Note that this code
5533 * is O(N^2) per trie run (O(N) per branch), so keep tight */
5536 U16 const nextword = ST.nextword;
5537 reg_trie_wordinfo * const wordinfo
5538 = ((reg_trie_data*)rexi->data->data[ARG(ST.me)])->wordinfo;
5539 for (word=ST.topword; word; word=wordinfo[word].prev) {
5540 if (word > nextword && (!min || word < min))
5553 ST.lastparen = rex->lastparen;
5554 ST.lastcloseparen = rex->lastcloseparen;
5558 /* find start char of end of current word */
5560 U32 chars; /* how many chars to skip */
5561 reg_trie_data * const trie
5562 = (reg_trie_data*)rexi->data->data[ARG(ST.me)];
5564 assert((trie->wordinfo[ST.nextword].len - trie->prefixlen)
5566 chars = (trie->wordinfo[ST.nextword].len - trie->prefixlen)
5571 /* the hard option - fold each char in turn and find
5572 * its folded length (which may be different */
5573 U8 foldbuf[UTF8_MAXBYTES_CASE + 1];
5581 uvc = utf8n_to_uvchr((U8*)uc, UTF8_MAXLEN, &len,
5589 uvc = to_uni_fold(uvc, foldbuf, &foldlen);
5594 uvc = utf8n_to_uvchr(uscan, UTF8_MAXLEN, &len,
5610 scan = ST.me + ((ST.jump && ST.jump[ST.nextword])
5611 ? ST.jump[ST.nextword]
5615 PerlIO_printf( Perl_debug_log,
5616 "%*s %sTRIE matched word #%d, continuing%s\n",
5617 REPORT_CODE_OFF+depth*2, "",
5624 if (ST.accepted > 1 || has_cutgroup) {
5625 PUSH_STATE_GOTO(TRIE_next, scan, (char*)uc);
5627 NOT_REACHED; /* NOTREACHED */
5629 /* only one choice left - just continue */
5631 AV *const trie_words
5632 = MUTABLE_AV(rexi->data->data[ARG(ST.me)+TRIE_WORDS_OFFSET]);
5633 SV ** const tmp = trie_words
5634 ? av_fetch(trie_words, ST.nextword - 1, 0) : NULL;
5635 SV *sv= tmp ? sv_newmortal() : NULL;
5637 PerlIO_printf( Perl_debug_log,
5638 "%*s %sonly one match left, short-circuiting: #%d <%s>%s\n",
5639 REPORT_CODE_OFF+depth*2, "", PL_colors[4],
5641 tmp ? pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 0,
5642 PL_colors[0], PL_colors[1],
5643 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)|PERL_PV_ESCAPE_NONASCII
5645 : "not compiled under -Dr",
5649 locinput = (char*)uc;
5650 continue; /* execute rest of RE */
5655 case EXACTL: /* /abc/l */
5656 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5658 /* Complete checking would involve going through every character
5659 * matched by the string to see if any is above latin1. But the
5660 * comparision otherwise might very well be a fast assembly
5661 * language routine, and I (khw) don't think slowing things down
5662 * just to check for this warning is worth it. So this just checks
5663 * the first character */
5664 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*locinput)) {
5665 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput, reginfo->strend);
5668 case EXACT: { /* /abc/ */
5669 char *s = STRING(scan);
5671 if (utf8_target != is_utf8_pat) {
5672 /* The target and the pattern have differing utf8ness. */
5674 const char * const e = s + ln;
5677 /* The target is utf8, the pattern is not utf8.
5678 * Above-Latin1 code points can't match the pattern;
5679 * invariants match exactly, and the other Latin1 ones need
5680 * to be downgraded to a single byte in order to do the
5681 * comparison. (If we could be confident that the target
5682 * is not malformed, this could be refactored to have fewer
5683 * tests by just assuming that if the first bytes match, it
5684 * is an invariant, but there are tests in the test suite
5685 * dealing with (??{...}) which violate this) */
5687 if (l >= reginfo->strend
5688 || UTF8_IS_ABOVE_LATIN1(* (U8*) l))
5692 if (UTF8_IS_INVARIANT(*(U8*)l)) {
5699 if (EIGHT_BIT_UTF8_TO_NATIVE(*l, *(l+1)) != * (U8*) s)
5709 /* The target is not utf8, the pattern is utf8. */
5711 if (l >= reginfo->strend
5712 || UTF8_IS_ABOVE_LATIN1(* (U8*) s))
5716 if (UTF8_IS_INVARIANT(*(U8*)s)) {
5723 if (EIGHT_BIT_UTF8_TO_NATIVE(*s, *(s+1)) != * (U8*) l)
5735 /* The target and the pattern have the same utf8ness. */
5736 /* Inline the first character, for speed. */
5737 if (reginfo->strend - locinput < ln
5738 || UCHARAT(s) != nextchr
5739 || (ln > 1 && memNE(s, locinput, ln)))
5748 case EXACTFL: { /* /abc/il */
5750 const U8 * fold_array;
5752 U32 fold_utf8_flags;
5754 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5755 folder = foldEQ_locale;
5756 fold_array = PL_fold_locale;
5757 fold_utf8_flags = FOLDEQ_LOCALE;
5760 case EXACTFLU8: /* /abc/il; but all 'abc' are above 255, so
5761 is effectively /u; hence to match, target
5763 if (! utf8_target) {
5766 fold_utf8_flags = FOLDEQ_LOCALE | FOLDEQ_S1_ALREADY_FOLDED
5767 | FOLDEQ_S1_FOLDS_SANE;
5768 folder = foldEQ_latin1;
5769 fold_array = PL_fold_latin1;
5772 case EXACTFU_SS: /* /\x{df}/iu */
5773 case EXACTFU: /* /abc/iu */
5774 folder = foldEQ_latin1;
5775 fold_array = PL_fold_latin1;
5776 fold_utf8_flags = is_utf8_pat ? FOLDEQ_S1_ALREADY_FOLDED : 0;
5779 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8
5781 assert(! is_utf8_pat);
5783 case EXACTFA: /* /abc/iaa */
5784 folder = foldEQ_latin1;
5785 fold_array = PL_fold_latin1;
5786 fold_utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
5789 case EXACTF: /* /abc/i This node only generated for
5790 non-utf8 patterns */
5791 assert(! is_utf8_pat);
5793 fold_array = PL_fold;
5794 fold_utf8_flags = 0;
5802 || state_num == EXACTFU_SS
5803 || (state_num == EXACTFL && IN_UTF8_CTYPE_LOCALE))
5805 /* Either target or the pattern are utf8, or has the issue where
5806 * the fold lengths may differ. */
5807 const char * const l = locinput;
5808 char *e = reginfo->strend;
5810 if (! foldEQ_utf8_flags(s, 0, ln, is_utf8_pat,
5811 l, &e, 0, utf8_target, fold_utf8_flags))
5819 /* Neither the target nor the pattern are utf8 */
5820 if (UCHARAT(s) != nextchr
5822 && UCHARAT(s) != fold_array[nextchr])
5826 if (reginfo->strend - locinput < ln)
5828 if (ln > 1 && ! folder(s, locinput, ln))
5834 case NBOUNDL: /* /\B/l */
5838 case BOUNDL: /* /\b/l */
5841 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5843 if (FLAGS(scan) != TRADITIONAL_BOUND) {
5844 if (! IN_UTF8_CTYPE_LOCALE) {
5845 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
5846 B_ON_NON_UTF8_LOCALE_IS_WRONG);
5852 if (locinput == reginfo->strbeg)
5853 b1 = isWORDCHAR_LC('\n');
5855 b1 = isWORDCHAR_LC_utf8(reghop3((U8*)locinput, -1,
5856 (U8*)(reginfo->strbeg)));
5858 b2 = (NEXTCHR_IS_EOS)
5859 ? isWORDCHAR_LC('\n')
5860 : isWORDCHAR_LC_utf8((U8*)locinput);
5862 else { /* Here the string isn't utf8 */
5863 b1 = (locinput == reginfo->strbeg)
5864 ? isWORDCHAR_LC('\n')
5865 : isWORDCHAR_LC(UCHARAT(locinput - 1));
5866 b2 = (NEXTCHR_IS_EOS)
5867 ? isWORDCHAR_LC('\n')
5868 : isWORDCHAR_LC(nextchr);
5870 if (to_complement ^ (b1 == b2)) {
5876 case NBOUND: /* /\B/ */
5880 case BOUND: /* /\b/ */
5884 goto bound_ascii_match_only;
5886 case NBOUNDA: /* /\B/a */
5890 case BOUNDA: /* /\b/a */
5894 bound_ascii_match_only:
5895 /* Here the string isn't utf8, or is utf8 and only ascii characters
5896 * are to match \w. In the latter case looking at the byte just
5897 * prior to the current one may be just the final byte of a
5898 * multi-byte character. This is ok. There are two cases:
5899 * 1) it is a single byte character, and then the test is doing
5900 * just what it's supposed to.
5901 * 2) it is a multi-byte character, in which case the final byte is
5902 * never mistakable for ASCII, and so the test will say it is
5903 * not a word character, which is the correct answer. */
5904 b1 = (locinput == reginfo->strbeg)
5905 ? isWORDCHAR_A('\n')
5906 : isWORDCHAR_A(UCHARAT(locinput - 1));
5907 b2 = (NEXTCHR_IS_EOS)
5908 ? isWORDCHAR_A('\n')
5909 : isWORDCHAR_A(nextchr);
5910 if (to_complement ^ (b1 == b2)) {
5916 case NBOUNDU: /* /\B/u */
5920 case BOUNDU: /* /\b/u */
5923 if (UNLIKELY(reginfo->strbeg >= reginfo->strend)) {
5926 else if (utf8_target) {
5928 switch((bound_type) FLAGS(scan)) {
5929 case TRADITIONAL_BOUND:
5932 b1 = (locinput == reginfo->strbeg)
5933 ? 0 /* isWORDCHAR_L1('\n') */
5934 : isWORDCHAR_utf8(reghop3((U8*)locinput, -1,
5935 (U8*)(reginfo->strbeg)));
5936 b2 = (NEXTCHR_IS_EOS)
5937 ? 0 /* isWORDCHAR_L1('\n') */
5938 : isWORDCHAR_utf8((U8*)locinput);
5939 match = cBOOL(b1 != b2);
5943 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
5944 match = TRUE; /* GCB always matches at begin and
5948 /* Find the gcb values of previous and current
5949 * chars, then see if is a break point */
5950 match = isGCB(getGCB_VAL_UTF8(
5951 reghop3((U8*)locinput,
5953 (U8*)(reginfo->strbeg)),
5954 (U8*) reginfo->strend),
5955 getGCB_VAL_UTF8((U8*) locinput,
5956 (U8*) reginfo->strend));
5961 if (locinput == reginfo->strbeg) {
5964 else if (NEXTCHR_IS_EOS) {
5968 match = isLB(getLB_VAL_UTF8(
5969 reghop3((U8*)locinput,
5971 (U8*)(reginfo->strbeg)),
5972 (U8*) reginfo->strend),
5973 getLB_VAL_UTF8((U8*) locinput,
5974 (U8*) reginfo->strend),
5975 (U8*) reginfo->strbeg,
5977 (U8*) reginfo->strend,
5982 case SB_BOUND: /* Always matches at begin and end */
5983 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
5987 match = isSB(getSB_VAL_UTF8(
5988 reghop3((U8*)locinput,
5990 (U8*)(reginfo->strbeg)),
5991 (U8*) reginfo->strend),
5992 getSB_VAL_UTF8((U8*) locinput,
5993 (U8*) reginfo->strend),
5994 (U8*) reginfo->strbeg,
5996 (U8*) reginfo->strend,
6002 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6006 match = isWB(WB_UNKNOWN,
6008 reghop3((U8*)locinput,
6010 (U8*)(reginfo->strbeg)),
6011 (U8*) reginfo->strend),
6012 getWB_VAL_UTF8((U8*) locinput,
6013 (U8*) reginfo->strend),
6014 (U8*) reginfo->strbeg,
6016 (U8*) reginfo->strend,
6022 else { /* Not utf8 target */
6023 switch((bound_type) FLAGS(scan)) {
6024 case TRADITIONAL_BOUND:
6027 b1 = (locinput == reginfo->strbeg)
6028 ? 0 /* isWORDCHAR_L1('\n') */
6029 : isWORDCHAR_L1(UCHARAT(locinput - 1));
6030 b2 = (NEXTCHR_IS_EOS)
6031 ? 0 /* isWORDCHAR_L1('\n') */
6032 : isWORDCHAR_L1(nextchr);
6033 match = cBOOL(b1 != b2);
6038 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6039 match = TRUE; /* GCB always matches at begin and
6042 else { /* Only CR-LF combo isn't a GCB in 0-255
6044 match = UCHARAT(locinput - 1) != '\r'
6045 || UCHARAT(locinput) != '\n';
6050 if (locinput == reginfo->strbeg) {
6053 else if (NEXTCHR_IS_EOS) {
6057 match = isLB(getLB_VAL_CP(UCHARAT(locinput -1)),
6058 getLB_VAL_CP(UCHARAT(locinput)),
6059 (U8*) reginfo->strbeg,
6061 (U8*) reginfo->strend,
6066 case SB_BOUND: /* Always matches at begin and end */
6067 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6071 match = isSB(getSB_VAL_CP(UCHARAT(locinput -1)),
6072 getSB_VAL_CP(UCHARAT(locinput)),
6073 (U8*) reginfo->strbeg,
6075 (U8*) reginfo->strend,
6081 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6085 match = isWB(WB_UNKNOWN,
6086 getWB_VAL_CP(UCHARAT(locinput -1)),
6087 getWB_VAL_CP(UCHARAT(locinput)),
6088 (U8*) reginfo->strbeg,
6090 (U8*) reginfo->strend,
6097 if (to_complement ^ ! match) {
6102 case ANYOFL: /* /[abc]/l */
6103 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6105 if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(scan)) && ! IN_UTF8_CTYPE_LOCALE)
6107 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
6110 case ANYOFD: /* /[abc]/d */
6111 case ANYOF: /* /[abc]/ */
6114 if (utf8_target && ! UTF8_IS_INVARIANT(*locinput)) {
6115 if (!reginclass(rex, scan, (U8*)locinput, (U8*)reginfo->strend,
6118 locinput += UTF8SKIP(locinput);
6121 if (!REGINCLASS(rex, scan, (U8*)locinput))
6127 /* The argument (FLAGS) to all the POSIX node types is the class number
6130 case NPOSIXL: /* \W or [:^punct:] etc. under /l */
6134 case POSIXL: /* \w or [:punct:] etc. under /l */
6135 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6139 /* Use isFOO_lc() for characters within Latin1. (Note that
6140 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
6141 * wouldn't be invariant) */
6142 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
6143 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan), (U8) nextchr)))) {
6147 else if (UTF8_IS_DOWNGRADEABLE_START(nextchr)) {
6148 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan),
6149 EIGHT_BIT_UTF8_TO_NATIVE(nextchr,
6150 *(locinput + 1))))))
6155 else { /* Here, must be an above Latin-1 code point */
6156 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput, reginfo->strend);
6157 goto utf8_posix_above_latin1;
6160 /* Here, must be utf8 */
6161 locinput += UTF8SKIP(locinput);
6164 case NPOSIXD: /* \W or [:^punct:] etc. under /d */
6168 case POSIXD: /* \w or [:punct:] etc. under /d */
6174 case NPOSIXA: /* \W or [:^punct:] etc. under /a */
6176 if (NEXTCHR_IS_EOS) {
6180 /* All UTF-8 variants match */
6181 if (! UTF8_IS_INVARIANT(nextchr)) {
6182 goto increment_locinput;
6188 case POSIXA: /* \w or [:punct:] etc. under /a */
6191 /* We get here through POSIXD, NPOSIXD, and NPOSIXA when not in
6192 * UTF-8, and also from NPOSIXA even in UTF-8 when the current
6193 * character is a single byte */
6196 || ! (to_complement ^ cBOOL(_generic_isCC_A(nextchr,
6202 /* Here we are either not in utf8, or we matched a utf8-invariant,
6203 * so the next char is the next byte */
6207 case NPOSIXU: /* \W or [:^punct:] etc. under /u */
6211 case POSIXU: /* \w or [:punct:] etc. under /u */
6213 if (NEXTCHR_IS_EOS) {
6217 /* Use _generic_isCC() for characters within Latin1. (Note that
6218 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
6219 * wouldn't be invariant) */
6220 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
6221 if (! (to_complement ^ cBOOL(_generic_isCC(nextchr,
6228 else if (UTF8_IS_DOWNGRADEABLE_START(nextchr)) {
6229 if (! (to_complement
6230 ^ cBOOL(_generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(nextchr,
6238 else { /* Handle above Latin-1 code points */
6239 utf8_posix_above_latin1:
6240 classnum = (_char_class_number) FLAGS(scan);
6241 if (classnum < _FIRST_NON_SWASH_CC) {
6243 /* Here, uses a swash to find such code points. Load if if
6244 * not done already */
6245 if (! PL_utf8_swash_ptrs[classnum]) {
6246 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
6247 PL_utf8_swash_ptrs[classnum]
6248 = _core_swash_init("utf8",
6251 PL_XPosix_ptrs[classnum], &flags);
6253 if (! (to_complement
6254 ^ cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum],
6255 (U8 *) locinput, TRUE))))
6260 else { /* Here, uses macros to find above Latin-1 code points */
6262 case _CC_ENUM_SPACE:
6263 if (! (to_complement
6264 ^ cBOOL(is_XPERLSPACE_high(locinput))))
6269 case _CC_ENUM_BLANK:
6270 if (! (to_complement
6271 ^ cBOOL(is_HORIZWS_high(locinput))))
6276 case _CC_ENUM_XDIGIT:
6277 if (! (to_complement
6278 ^ cBOOL(is_XDIGIT_high(locinput))))
6283 case _CC_ENUM_VERTSPACE:
6284 if (! (to_complement
6285 ^ cBOOL(is_VERTWS_high(locinput))))
6290 default: /* The rest, e.g. [:cntrl:], can't match
6292 if (! to_complement) {
6298 locinput += UTF8SKIP(locinput);
6302 case CLUMP: /* Match \X: logical Unicode character. This is defined as
6303 a Unicode extended Grapheme Cluster */
6306 if (! utf8_target) {
6308 /* Match either CR LF or '.', as all the other possibilities
6310 locinput++; /* Match the . or CR */
6311 if (nextchr == '\r' /* And if it was CR, and the next is LF,
6313 && locinput < reginfo->strend
6314 && UCHARAT(locinput) == '\n')
6321 /* Get the gcb type for the current character */
6322 GCB_enum prev_gcb = getGCB_VAL_UTF8((U8*) locinput,
6323 (U8*) reginfo->strend);
6325 /* Then scan through the input until we get to the first
6326 * character whose type is supposed to be a gcb with the
6327 * current character. (There is always a break at the
6329 locinput += UTF8SKIP(locinput);
6330 while (locinput < reginfo->strend) {
6331 GCB_enum cur_gcb = getGCB_VAL_UTF8((U8*) locinput,
6332 (U8*) reginfo->strend);
6333 if (isGCB(prev_gcb, cur_gcb)) {
6338 locinput += UTF8SKIP(locinput);
6345 case NREFFL: /* /\g{name}/il */
6346 { /* The capture buffer cases. The ones beginning with N for the
6347 named buffers just convert to the equivalent numbered and
6348 pretend they were called as the corresponding numbered buffer
6350 /* don't initialize these in the declaration, it makes C++
6355 const U8 *fold_array;
6358 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6359 folder = foldEQ_locale;
6360 fold_array = PL_fold_locale;
6362 utf8_fold_flags = FOLDEQ_LOCALE;
6365 case NREFFA: /* /\g{name}/iaa */
6366 folder = foldEQ_latin1;
6367 fold_array = PL_fold_latin1;
6369 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
6372 case NREFFU: /* /\g{name}/iu */
6373 folder = foldEQ_latin1;
6374 fold_array = PL_fold_latin1;
6376 utf8_fold_flags = 0;
6379 case NREFF: /* /\g{name}/i */
6381 fold_array = PL_fold;
6383 utf8_fold_flags = 0;
6386 case NREF: /* /\g{name}/ */
6390 utf8_fold_flags = 0;
6393 /* For the named back references, find the corresponding buffer
6395 n = reg_check_named_buff_matched(rex,scan);
6400 goto do_nref_ref_common;
6402 case REFFL: /* /\1/il */
6403 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6404 folder = foldEQ_locale;
6405 fold_array = PL_fold_locale;
6406 utf8_fold_flags = FOLDEQ_LOCALE;
6409 case REFFA: /* /\1/iaa */
6410 folder = foldEQ_latin1;
6411 fold_array = PL_fold_latin1;
6412 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
6415 case REFFU: /* /\1/iu */
6416 folder = foldEQ_latin1;
6417 fold_array = PL_fold_latin1;
6418 utf8_fold_flags = 0;
6421 case REFF: /* /\1/i */
6423 fold_array = PL_fold;
6424 utf8_fold_flags = 0;
6427 case REF: /* /\1/ */
6430 utf8_fold_flags = 0;
6434 n = ARG(scan); /* which paren pair */
6437 ln = rex->offs[n].start;
6438 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
6439 if (rex->lastparen < n || ln == -1)
6440 sayNO; /* Do not match unless seen CLOSEn. */
6441 if (ln == rex->offs[n].end)
6444 s = reginfo->strbeg + ln;
6445 if (type != REF /* REF can do byte comparison */
6446 && (utf8_target || type == REFFU || type == REFFL))
6448 char * limit = reginfo->strend;
6450 /* This call case insensitively compares the entire buffer
6451 * at s, with the current input starting at locinput, but
6452 * not going off the end given by reginfo->strend, and
6453 * returns in <limit> upon success, how much of the
6454 * current input was matched */
6455 if (! foldEQ_utf8_flags(s, NULL, rex->offs[n].end - ln, utf8_target,
6456 locinput, &limit, 0, utf8_target, utf8_fold_flags))
6464 /* Not utf8: Inline the first character, for speed. */
6465 if (!NEXTCHR_IS_EOS &&
6466 UCHARAT(s) != nextchr &&
6468 UCHARAT(s) != fold_array[nextchr]))
6470 ln = rex->offs[n].end - ln;
6471 if (locinput + ln > reginfo->strend)
6473 if (ln > 1 && (type == REF
6474 ? memNE(s, locinput, ln)
6475 : ! folder(s, locinput, ln)))
6481 case NOTHING: /* null op; e.g. the 'nothing' following
6482 * the '*' in m{(a+|b)*}' */
6484 case TAIL: /* placeholder while compiling (A|B|C) */
6488 #define ST st->u.eval
6493 regexp_internal *rei;
6494 regnode *startpoint;
6496 case GOSTART: /* (?R) */
6497 case GOSUB: /* /(...(?1))/ /(...(?&foo))/ */
6498 if (cur_eval && cur_eval->locinput==locinput) {
6499 if (cur_eval->u.eval.close_paren == (U32)ARG(scan))
6500 Perl_croak(aTHX_ "Infinite recursion in regex");
6501 if ( ++nochange_depth > max_nochange_depth )
6503 "Pattern subroutine nesting without pos change"
6504 " exceeded limit in regex");
6511 if (OP(scan)==GOSUB) {
6512 startpoint = scan + ARG2L(scan);
6513 ST.close_paren = ARG(scan);
6515 startpoint = rei->program+1;
6519 /* Save all the positions seen so far. */
6520 ST.cp = regcppush(rex, 0, maxopenparen);
6521 REGCP_SET(ST.lastcp);
6523 /* and then jump to the code we share with EVAL */
6524 goto eval_recurse_doit;
6527 case EVAL: /* /(?{A})B/ /(??{A})B/ and /(?(?{A})X|Y)B/ */
6528 if (cur_eval && cur_eval->locinput==locinput) {
6529 if ( ++nochange_depth > max_nochange_depth )
6530 Perl_croak(aTHX_ "EVAL without pos change exceeded limit in regex");
6535 /* execute the code in the {...} */
6539 OP * const oop = PL_op;
6540 COP * const ocurcop = PL_curcop;
6544 /* save *all* paren positions */
6545 regcppush(rex, 0, maxopenparen);
6546 REGCP_SET(runops_cp);
6549 caller_cv = find_runcv(NULL);
6553 if (rexi->data->what[n] == 'r') { /* code from an external qr */
6555 (REGEXP*)(rexi->data->data[n])
6558 nop = (OP*)rexi->data->data[n+1];
6560 else if (rexi->data->what[n] == 'l') { /* literal code */
6562 nop = (OP*)rexi->data->data[n];
6563 assert(CvDEPTH(newcv));
6566 /* literal with own CV */
6567 assert(rexi->data->what[n] == 'L');
6568 newcv = rex->qr_anoncv;
6569 nop = (OP*)rexi->data->data[n];
6572 /* normally if we're about to execute code from the same
6573 * CV that we used previously, we just use the existing
6574 * CX stack entry. However, its possible that in the
6575 * meantime we may have backtracked, popped from the save
6576 * stack, and undone the SAVECOMPPAD(s) associated with
6577 * PUSH_MULTICALL; in which case PL_comppad no longer
6578 * points to newcv's pad. */
6579 if (newcv != last_pushed_cv || PL_comppad != last_pad)
6581 U8 flags = (CXp_SUB_RE |
6582 ((newcv == caller_cv) ? CXp_SUB_RE_FAKE : 0));
6583 if (last_pushed_cv) {
6584 /* PUSH/POP_MULTICALL save and restore the
6585 * caller's PL_comppad; if we call multiple subs
6586 * using the same CX block, we have to save and
6587 * unwind the varying PL_comppad's ourselves,
6588 * especially restoring the right PL_comppad on
6589 * backtrack - so save it on the save stack */
6591 CHANGE_MULTICALL_FLAGS(newcv, flags);
6594 PUSH_MULTICALL_FLAGS(newcv, flags);
6596 last_pushed_cv = newcv;
6599 /* these assignments are just to silence compiler
6601 multicall_cop = NULL;
6603 last_pad = PL_comppad;
6605 /* the initial nextstate you would normally execute
6606 * at the start of an eval (which would cause error
6607 * messages to come from the eval), may be optimised
6608 * away from the execution path in the regex code blocks;
6609 * so manually set PL_curcop to it initially */
6611 OP *o = cUNOPx(nop)->op_first;
6612 assert(o->op_type == OP_NULL);
6613 if (o->op_targ == OP_SCOPE) {
6614 o = cUNOPo->op_first;
6617 assert(o->op_targ == OP_LEAVE);
6618 o = cUNOPo->op_first;
6619 assert(o->op_type == OP_ENTER);
6623 if (o->op_type != OP_STUB) {
6624 assert( o->op_type == OP_NEXTSTATE
6625 || o->op_type == OP_DBSTATE
6626 || (o->op_type == OP_NULL
6627 && ( o->op_targ == OP_NEXTSTATE
6628 || o->op_targ == OP_DBSTATE
6632 PL_curcop = (COP*)o;
6637 DEBUG_STATE_r( PerlIO_printf(Perl_debug_log,
6638 " re EVAL PL_op=0x%"UVxf"\n", PTR2UV(nop)) );
6640 rex->offs[0].end = locinput - reginfo->strbeg;
6641 if (reginfo->info_aux_eval->pos_magic)
6642 MgBYTEPOS_set(reginfo->info_aux_eval->pos_magic,
6643 reginfo->sv, reginfo->strbeg,
6644 locinput - reginfo->strbeg);
6647 SV *sv_mrk = get_sv("REGMARK", 1);
6648 sv_setsv(sv_mrk, sv_yes_mark);
6651 /* we don't use MULTICALL here as we want to call the
6652 * first op of the block of interest, rather than the
6653 * first op of the sub. Also, we don't want to free
6654 * the savestack frame */
6655 before = (IV)(SP-PL_stack_base);
6657 CALLRUNOPS(aTHX); /* Scalar context. */
6659 if ((IV)(SP-PL_stack_base) == before)
6660 ret = &PL_sv_undef; /* protect against empty (?{}) blocks. */
6666 /* before restoring everything, evaluate the returned
6667 * value, so that 'uninit' warnings don't use the wrong
6668 * PL_op or pad. Also need to process any magic vars
6669 * (e.g. $1) *before* parentheses are restored */
6674 if (logical == 0) /* (?{})/ */
6675 sv_setsv(save_scalar(PL_replgv), ret); /* $^R */
6676 else if (logical == 1) { /* /(?(?{...})X|Y)/ */
6677 sw = cBOOL(SvTRUE(ret));
6680 else { /* /(??{}) */
6681 /* if its overloaded, let the regex compiler handle
6682 * it; otherwise extract regex, or stringify */
6683 if (SvGMAGICAL(ret))
6684 ret = sv_mortalcopy(ret);
6685 if (!SvAMAGIC(ret)) {
6689 if (SvTYPE(sv) == SVt_REGEXP)
6690 re_sv = (REGEXP*) sv;
6691 else if (SvSMAGICAL(ret)) {
6692 MAGIC *mg = mg_find(ret, PERL_MAGIC_qr);
6694 re_sv = (REGEXP *) mg->mg_obj;
6697 /* force any undef warnings here */
6698 if (!re_sv && !SvPOK(ret) && !SvNIOK(ret)) {
6699 ret = sv_mortalcopy(ret);
6700 (void) SvPV_force_nolen(ret);
6706 /* *** Note that at this point we don't restore
6707 * PL_comppad, (or pop the CxSUB) on the assumption it may
6708 * be used again soon. This is safe as long as nothing
6709 * in the regexp code uses the pad ! */
6711 PL_curcop = ocurcop;
6712 S_regcp_restore(aTHX_ rex, runops_cp, &maxopenparen);
6713 PL_curpm = PL_reg_curpm;
6719 /* only /(??{})/ from now on */
6722 /* extract RE object from returned value; compiling if
6726 re_sv = reg_temp_copy(NULL, re_sv);
6731 if (SvUTF8(ret) && IN_BYTES) {
6732 /* In use 'bytes': make a copy of the octet
6733 * sequence, but without the flag on */
6735 const char *const p = SvPV(ret, len);
6736 ret = newSVpvn_flags(p, len, SVs_TEMP);
6738 if (rex->intflags & PREGf_USE_RE_EVAL)
6739 pm_flags |= PMf_USE_RE_EVAL;
6741 /* if we got here, it should be an engine which
6742 * supports compiling code blocks and stuff */
6743 assert(rex->engine && rex->engine->op_comp);
6744 assert(!(scan->flags & ~RXf_PMf_COMPILETIME));
6745 re_sv = rex->engine->op_comp(aTHX_ &ret, 1, NULL,
6746 rex->engine, NULL, NULL,
6747 /* copy /msixn etc to inner pattern */
6752 & (SVs_TEMP | SVs_GMG | SVf_ROK))
6753 && (!SvPADTMP(ret) || SvREADONLY(ret))) {
6754 /* This isn't a first class regexp. Instead, it's
6755 caching a regexp onto an existing, Perl visible
6757 sv_magic(ret, MUTABLE_SV(re_sv), PERL_MAGIC_qr, 0, 0);
6763 RXp_MATCH_COPIED_off(re);
6764 re->subbeg = rex->subbeg;
6765 re->sublen = rex->sublen;
6766 re->suboffset = rex->suboffset;
6767 re->subcoffset = rex->subcoffset;
6769 re->lastcloseparen = 0;
6772 debug_start_match(re_sv, utf8_target, locinput,
6773 reginfo->strend, "Matching embedded");
6775 startpoint = rei->program + 1;
6776 ST.close_paren = 0; /* only used for GOSUB */
6777 /* Save all the seen positions so far. */
6778 ST.cp = regcppush(rex, 0, maxopenparen);
6779 REGCP_SET(ST.lastcp);
6780 /* and set maxopenparen to 0, since we are starting a "fresh" match */
6782 /* run the pattern returned from (??{...}) */
6784 eval_recurse_doit: /* Share code with GOSUB below this line
6785 * At this point we expect the stack context to be
6786 * set up correctly */
6788 /* invalidate the S-L poscache. We're now executing a
6789 * different set of WHILEM ops (and their associated
6790 * indexes) against the same string, so the bits in the
6791 * cache are meaningless. Setting maxiter to zero forces
6792 * the cache to be invalidated and zeroed before reuse.
6793 * XXX This is too dramatic a measure. Ideally we should
6794 * save the old cache and restore when running the outer
6796 reginfo->poscache_maxiter = 0;
6798 /* the new regexp might have a different is_utf8_pat than we do */
6799 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(re_sv));
6801 ST.prev_rex = rex_sv;
6802 ST.prev_curlyx = cur_curlyx;
6804 SET_reg_curpm(rex_sv);
6809 ST.prev_eval = cur_eval;
6811 /* now continue from first node in postoned RE */
6812 PUSH_YES_STATE_GOTO(EVAL_AB, startpoint, locinput);
6814 NOT_REACHED; /* NOTREACHED */
6817 case EVAL_AB: /* cleanup after a successful (??{A})B */
6818 /* note: this is called twice; first after popping B, then A */
6819 rex_sv = ST.prev_rex;
6820 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
6821 SET_reg_curpm(rex_sv);
6822 rex = ReANY(rex_sv);
6823 rexi = RXi_GET(rex);
6825 /* preserve $^R across LEAVE's. See Bug 121070. */
6826 SV *save_sv= GvSV(PL_replgv);
6827 SvREFCNT_inc(save_sv);
6828 regcpblow(ST.cp); /* LEAVE in disguise */
6829 sv_setsv(GvSV(PL_replgv), save_sv);
6830 SvREFCNT_dec(save_sv);
6832 cur_eval = ST.prev_eval;
6833 cur_curlyx = ST.prev_curlyx;
6835 /* Invalidate cache. See "invalidate" comment above. */
6836 reginfo->poscache_maxiter = 0;
6837 if ( nochange_depth )
6842 case EVAL_AB_fail: /* unsuccessfully ran A or B in (??{A})B */
6843 /* note: this is called twice; first after popping B, then A */
6844 rex_sv = ST.prev_rex;
6845 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
6846 SET_reg_curpm(rex_sv);
6847 rex = ReANY(rex_sv);
6848 rexi = RXi_GET(rex);
6850 REGCP_UNWIND(ST.lastcp);
6851 regcppop(rex, &maxopenparen);
6852 cur_eval = ST.prev_eval;
6853 cur_curlyx = ST.prev_curlyx;
6854 /* Invalidate cache. See "invalidate" comment above. */
6855 reginfo->poscache_maxiter = 0;
6856 if ( nochange_depth )
6862 n = ARG(scan); /* which paren pair */
6863 rex->offs[n].start_tmp = locinput - reginfo->strbeg;
6864 if (n > maxopenparen)
6866 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
6867 "rex=0x%"UVxf" offs=0x%"UVxf": \\%"UVuf": set %"IVdf" tmp; maxopenparen=%"UVuf"\n",
6871 (IV)rex->offs[n].start_tmp,
6877 /* XXX really need to log other places start/end are set too */
6878 #define CLOSE_CAPTURE \
6879 rex->offs[n].start = rex->offs[n].start_tmp; \
6880 rex->offs[n].end = locinput - reginfo->strbeg; \
6881 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log, \
6882 "rex=0x%"UVxf" offs=0x%"UVxf": \\%"UVuf": set %"IVdf"..%"IVdf"\n", \
6884 PTR2UV(rex->offs), \
6886 (IV)rex->offs[n].start, \
6887 (IV)rex->offs[n].end \
6891 n = ARG(scan); /* which paren pair */
6893 if (n > rex->lastparen)
6895 rex->lastcloseparen = n;
6896 if (cur_eval && cur_eval->u.eval.close_paren == n) {
6901 case ACCEPT: /* (*ACCEPT) */
6903 sv_yes_mark = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
6907 cursor && OP(cursor)!=END;
6908 cursor=regnext(cursor))
6910 if ( OP(cursor)==CLOSE ){
6912 if ( n <= lastopen ) {
6914 if (n > rex->lastparen)
6916 rex->lastcloseparen = n;
6917 if ( n == ARG(scan) || (cur_eval &&
6918 cur_eval->u.eval.close_paren == n))
6927 case GROUPP: /* (?(1)) */
6928 n = ARG(scan); /* which paren pair */
6929 sw = cBOOL(rex->lastparen >= n && rex->offs[n].end != -1);
6932 case NGROUPP: /* (?(<name>)) */
6933 /* reg_check_named_buff_matched returns 0 for no match */
6934 sw = cBOOL(0 < reg_check_named_buff_matched(rex,scan));
6937 case INSUBP: /* (?(R)) */
6939 sw = (cur_eval && (!n || cur_eval->u.eval.close_paren == n));
6942 case DEFINEP: /* (?(DEFINE)) */
6946 case IFTHEN: /* (?(cond)A|B) */
6947 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
6949 next = NEXTOPER(NEXTOPER(scan));
6951 next = scan + ARG(scan);
6952 if (OP(next) == IFTHEN) /* Fake one. */
6953 next = NEXTOPER(NEXTOPER(next));
6957 case LOGICAL: /* modifier for EVAL and IFMATCH */
6958 logical = scan->flags;
6961 /*******************************************************************
6963 The CURLYX/WHILEM pair of ops handle the most generic case of the /A*B/
6964 pattern, where A and B are subpatterns. (For simple A, CURLYM or
6965 STAR/PLUS/CURLY/CURLYN are used instead.)
6967 A*B is compiled as <CURLYX><A><WHILEM><B>
6969 On entry to the subpattern, CURLYX is called. This pushes a CURLYX
6970 state, which contains the current count, initialised to -1. It also sets
6971 cur_curlyx to point to this state, with any previous value saved in the
6974 CURLYX then jumps straight to the WHILEM op, rather than executing A,
6975 since the pattern may possibly match zero times (i.e. it's a while {} loop
6976 rather than a do {} while loop).
6978 Each entry to WHILEM represents a successful match of A. The count in the
6979 CURLYX block is incremented, another WHILEM state is pushed, and execution
6980 passes to A or B depending on greediness and the current count.
6982 For example, if matching against the string a1a2a3b (where the aN are
6983 substrings that match /A/), then the match progresses as follows: (the
6984 pushed states are interspersed with the bits of strings matched so far):
6987 <CURLYX cnt=0><WHILEM>
6988 <CURLYX cnt=1><WHILEM> a1 <WHILEM>
6989 <CURLYX cnt=2><WHILEM> a1 <WHILEM> a2 <WHILEM>
6990 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM>
6991 <CURLYX cnt=3><WHILEM> a1 <WHILEM> a2 <WHILEM> a3 <WHILEM> b
6993 (Contrast this with something like CURLYM, which maintains only a single
6997 a1 <CURLYM cnt=1> a2
6998 a1 a2 <CURLYM cnt=2> a3
6999 a1 a2 a3 <CURLYM cnt=3> b
7002 Each WHILEM state block marks a point to backtrack to upon partial failure
7003 of A or B, and also contains some minor state data related to that
7004 iteration. The CURLYX block, pointed to by cur_curlyx, contains the
7005 overall state, such as the count, and pointers to the A and B ops.
7007 This is complicated slightly by nested CURLYX/WHILEM's. Since cur_curlyx
7008 must always point to the *current* CURLYX block, the rules are:
7010 When executing CURLYX, save the old cur_curlyx in the CURLYX state block,
7011 and set cur_curlyx to point the new block.
7013 When popping the CURLYX block after a successful or unsuccessful match,
7014 restore the previous cur_curlyx.
7016 When WHILEM is about to execute B, save the current cur_curlyx, and set it
7017 to the outer one saved in the CURLYX block.
7019 When popping the WHILEM block after a successful or unsuccessful B match,
7020 restore the previous cur_curlyx.
7022 Here's an example for the pattern (AI* BI)*BO
7023 I and O refer to inner and outer, C and W refer to CURLYX and WHILEM:
7026 curlyx backtrack stack
7027 ------ ---------------
7029 CO <CO prev=NULL> <WO>
7030 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
7031 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
7032 NULL <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi <WO prev=CO> bo
7034 At this point the pattern succeeds, and we work back down the stack to
7035 clean up, restoring as we go:
7037 CO <CO prev=NULL> <WO> <CI prev=CO> <WI> ai <WI prev=CI> bi
7038 CI <CO prev=NULL> <WO> <CI prev=CO> <WI> ai
7039 CO <CO prev=NULL> <WO>
7042 *******************************************************************/
7044 #define ST st->u.curlyx
7046 case CURLYX: /* start of /A*B/ (for complex A) */
7048 /* No need to save/restore up to this paren */
7049 I32 parenfloor = scan->flags;
7051 assert(next); /* keep Coverity happy */
7052 if (OP(PREVOPER(next)) == NOTHING) /* LONGJMP */
7055 /* XXXX Probably it is better to teach regpush to support
7056 parenfloor > maxopenparen ... */
7057 if (parenfloor > (I32)rex->lastparen)
7058 parenfloor = rex->lastparen; /* Pessimization... */
7060 ST.prev_curlyx= cur_curlyx;
7062 ST.cp = PL_savestack_ix;
7064 /* these fields contain the state of the current curly.
7065 * they are accessed by subsequent WHILEMs */
7066 ST.parenfloor = parenfloor;
7071 ST.count = -1; /* this will be updated by WHILEM */
7072 ST.lastloc = NULL; /* this will be updated by WHILEM */
7074 PUSH_YES_STATE_GOTO(CURLYX_end, PREVOPER(next), locinput);
7076 NOT_REACHED; /* NOTREACHED */
7079 case CURLYX_end: /* just finished matching all of A*B */
7080 cur_curlyx = ST.prev_curlyx;
7083 NOT_REACHED; /* NOTREACHED */
7085 case CURLYX_end_fail: /* just failed to match all of A*B */
7087 cur_curlyx = ST.prev_curlyx;
7090 NOT_REACHED; /* NOTREACHED */
7094 #define ST st->u.whilem
7096 case WHILEM: /* just matched an A in /A*B/ (for complex A) */
7098 /* see the discussion above about CURLYX/WHILEM */
7103 assert(cur_curlyx); /* keep Coverity happy */
7105 min = ARG1(cur_curlyx->u.curlyx.me);
7106 max = ARG2(cur_curlyx->u.curlyx.me);
7107 A = NEXTOPER(cur_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS;
7108 n = ++cur_curlyx->u.curlyx.count; /* how many A's matched */
7109 ST.save_lastloc = cur_curlyx->u.curlyx.lastloc;
7110 ST.cache_offset = 0;
7114 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
7115 "%*s whilem: matched %ld out of %d..%d\n",
7116 REPORT_CODE_OFF+depth*2, "", (long)n, min, max)
7119 /* First just match a string of min A's. */
7122 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
7124 cur_curlyx->u.curlyx.lastloc = locinput;
7125 REGCP_SET(ST.lastcp);
7127 PUSH_STATE_GOTO(WHILEM_A_pre, A, locinput);
7129 NOT_REACHED; /* NOTREACHED */
7132 /* If degenerate A matches "", assume A done. */
7134 if (locinput == cur_curlyx->u.curlyx.lastloc) {
7135 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
7136 "%*s whilem: empty match detected, trying continuation...\n",
7137 REPORT_CODE_OFF+depth*2, "")
7139 goto do_whilem_B_max;
7142 /* super-linear cache processing.
7144 * The idea here is that for certain types of CURLYX/WHILEM -
7145 * principally those whose upper bound is infinity (and
7146 * excluding regexes that have things like \1 and other very
7147 * non-regular expresssiony things), then if a pattern like
7148 * /....A*.../ fails and we backtrack to the WHILEM, then we
7149 * make a note that this particular WHILEM op was at string
7150 * position 47 (say) when the rest of pattern failed. Then, if
7151 * we ever find ourselves back at that WHILEM, and at string
7152 * position 47 again, we can just fail immediately rather than
7153 * running the rest of the pattern again.
7155 * This is very handy when patterns start to go
7156 * 'super-linear', like in (a+)*(a+)*(a+)*, where you end up
7157 * with a combinatorial explosion of backtracking.
7159 * The cache is implemented as a bit array, with one bit per
7160 * string byte position per WHILEM op (up to 16) - so its
7161 * between 0.25 and 2x the string size.
7163 * To avoid allocating a poscache buffer every time, we do an
7164 * initially countdown; only after we have executed a WHILEM
7165 * op (string-length x #WHILEMs) times do we allocate the
7168 * The top 4 bits of scan->flags byte say how many different
7169 * relevant CURLLYX/WHILEM op pairs there are, while the
7170 * bottom 4-bits is the identifying index number of this
7176 if (!reginfo->poscache_maxiter) {
7177 /* start the countdown: Postpone detection until we
7178 * know the match is not *that* much linear. */
7179 reginfo->poscache_maxiter
7180 = (reginfo->strend - reginfo->strbeg + 1)
7182 /* possible overflow for long strings and many CURLYX's */
7183 if (reginfo->poscache_maxiter < 0)
7184 reginfo->poscache_maxiter = I32_MAX;
7185 reginfo->poscache_iter = reginfo->poscache_maxiter;
7188 if (reginfo->poscache_iter-- == 0) {
7189 /* initialise cache */
7190 const SSize_t size = (reginfo->poscache_maxiter + 7)/8;
7191 regmatch_info_aux *const aux = reginfo->info_aux;
7192 if (aux->poscache) {
7193 if ((SSize_t)reginfo->poscache_size < size) {
7194 Renew(aux->poscache, size, char);
7195 reginfo->poscache_size = size;
7197 Zero(aux->poscache, size, char);
7200 reginfo->poscache_size = size;
7201 Newxz(aux->poscache, size, char);
7203 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
7204 "%swhilem: Detected a super-linear match, switching on caching%s...\n",
7205 PL_colors[4], PL_colors[5])
7209 if (reginfo->poscache_iter < 0) {
7210 /* have we already failed at this position? */
7211 SSize_t offset, mask;
7213 reginfo->poscache_iter = -1; /* stop eventual underflow */
7214 offset = (scan->flags & 0xf) - 1
7215 + (locinput - reginfo->strbeg)
7217 mask = 1 << (offset % 8);
7219 if (reginfo->info_aux->poscache[offset] & mask) {
7220 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
7221 "%*s whilem: (cache) already tried at this position...\n",
7222 REPORT_CODE_OFF+depth*2, "")
7224 sayNO; /* cache records failure */
7226 ST.cache_offset = offset;
7227 ST.cache_mask = mask;
7231 /* Prefer B over A for minimal matching. */
7233 if (cur_curlyx->u.curlyx.minmod) {
7234 ST.save_curlyx = cur_curlyx;
7235 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
7236 ST.cp = regcppush(rex, ST.save_curlyx->u.curlyx.parenfloor,
7238 REGCP_SET(ST.lastcp);
7239 PUSH_YES_STATE_GOTO(WHILEM_B_min, ST.save_curlyx->u.curlyx.B,
7242 NOT_REACHED; /* NOTREACHED */
7245 /* Prefer A over B for maximal matching. */
7247 if (n < max) { /* More greed allowed? */
7248 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
7250 cur_curlyx->u.curlyx.lastloc = locinput;
7251 REGCP_SET(ST.lastcp);
7252 PUSH_STATE_GOTO(WHILEM_A_max, A, locinput);
7254 NOT_REACHED; /* NOTREACHED */
7256 goto do_whilem_B_max;
7259 NOT_REACHED; /* NOTREACHED */
7261 case WHILEM_B_min: /* just matched B in a minimal match */
7262 case WHILEM_B_max: /* just matched B in a maximal match */
7263 cur_curlyx = ST.save_curlyx;
7266 NOT_REACHED; /* NOTREACHED */
7268 case WHILEM_B_max_fail: /* just failed to match B in a maximal match */
7269 cur_curlyx = ST.save_curlyx;
7270 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
7271 cur_curlyx->u.curlyx.count--;
7274 NOT_REACHED; /* NOTREACHED */
7276 case WHILEM_A_min_fail: /* just failed to match A in a minimal match */
7278 case WHILEM_A_pre_fail: /* just failed to match even minimal A */
7279 REGCP_UNWIND(ST.lastcp);
7280 regcppop(rex, &maxopenparen);
7281 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
7282 cur_curlyx->u.curlyx.count--;
7285 NOT_REACHED; /* NOTREACHED */
7287 case WHILEM_A_max_fail: /* just failed to match A in a maximal match */
7288 REGCP_UNWIND(ST.lastcp);
7289 regcppop(rex, &maxopenparen); /* Restore some previous $<digit>s? */
7290 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
7291 "%*s whilem: failed, trying continuation...\n",
7292 REPORT_CODE_OFF+depth*2, "")
7295 if (cur_curlyx->u.curlyx.count >= REG_INFTY
7296 && ckWARN(WARN_REGEXP)
7297 && !reginfo->warned)
7299 reginfo->warned = TRUE;
7300 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
7301 "Complex regular subexpression recursion limit (%d) "
7307 ST.save_curlyx = cur_curlyx;
7308 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
7309 PUSH_YES_STATE_GOTO(WHILEM_B_max, ST.save_curlyx->u.curlyx.B,
7312 NOT_REACHED; /* NOTREACHED */
7314 case WHILEM_B_min_fail: /* just failed to match B in a minimal match */
7315 cur_curlyx = ST.save_curlyx;
7316 REGCP_UNWIND(ST.lastcp);
7317 regcppop(rex, &maxopenparen);
7319 if (cur_curlyx->u.curlyx.count >= /*max*/ARG2(cur_curlyx->u.curlyx.me)) {
7320 /* Maximum greed exceeded */
7321 if (cur_curlyx->u.curlyx.count >= REG_INFTY
7322 && ckWARN(WARN_REGEXP)
7323 && !reginfo->warned)
7325 reginfo->warned = TRUE;
7326 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
7327 "Complex regular subexpression recursion "
7328 "limit (%d) exceeded",
7331 cur_curlyx->u.curlyx.count--;
7335 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
7336 "%*s trying longer...\n", REPORT_CODE_OFF+depth*2, "")
7338 /* Try grabbing another A and see if it helps. */
7339 cur_curlyx->u.curlyx.lastloc = locinput;
7340 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
7342 REGCP_SET(ST.lastcp);
7343 PUSH_STATE_GOTO(WHILEM_A_min,
7344 /*A*/ NEXTOPER(ST.save_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS,
7347 NOT_REACHED; /* NOTREACHED */
7350 #define ST st->u.branch
7352 case BRANCHJ: /* /(...|A|...)/ with long next pointer */
7353 next = scan + ARG(scan);
7356 scan = NEXTOPER(scan);
7359 case BRANCH: /* /(...|A|...)/ */
7360 scan = NEXTOPER(scan); /* scan now points to inner node */
7361 ST.lastparen = rex->lastparen;
7362 ST.lastcloseparen = rex->lastcloseparen;
7363 ST.next_branch = next;
7366 /* Now go into the branch */
7368 PUSH_YES_STATE_GOTO(BRANCH_next, scan, locinput);
7370 PUSH_STATE_GOTO(BRANCH_next, scan, locinput);
7373 NOT_REACHED; /* NOTREACHED */
7375 case CUTGROUP: /* /(*THEN)/ */
7376 sv_yes_mark = st->u.mark.mark_name = scan->flags
7377 ? MUTABLE_SV(rexi->data->data[ ARG( scan ) ])
7379 PUSH_STATE_GOTO(CUTGROUP_next, next, locinput);
7381 NOT_REACHED; /* NOTREACHED */
7383 case CUTGROUP_next_fail:
7386 if (st->u.mark.mark_name)
7387 sv_commit = st->u.mark.mark_name;
7390 NOT_REACHED; /* NOTREACHED */
7395 NOT_REACHED; /* NOTREACHED */
7397 case BRANCH_next_fail: /* that branch failed; try the next, if any */
7402 REGCP_UNWIND(ST.cp);
7403 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7404 scan = ST.next_branch;
7405 /* no more branches? */
7406 if (!scan || (OP(scan) != BRANCH && OP(scan) != BRANCHJ)) {
7408 PerlIO_printf( Perl_debug_log,
7409 "%*s %sBRANCH failed...%s\n",
7410 REPORT_CODE_OFF+depth*2, "",
7416 continue; /* execute next BRANCH[J] op */
7419 case MINMOD: /* next op will be non-greedy, e.g. A*? */
7424 #define ST st->u.curlym
7426 case CURLYM: /* /A{m,n}B/ where A is fixed-length */
7428 /* This is an optimisation of CURLYX that enables us to push
7429 * only a single backtracking state, no matter how many matches
7430 * there are in {m,n}. It relies on the pattern being constant
7431 * length, with no parens to influence future backrefs
7435 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
7437 ST.lastparen = rex->lastparen;
7438 ST.lastcloseparen = rex->lastcloseparen;
7440 /* if paren positive, emulate an OPEN/CLOSE around A */
7442 U32 paren = ST.me->flags;
7443 if (paren > maxopenparen)
7444 maxopenparen = paren;
7445 scan += NEXT_OFF(scan); /* Skip former OPEN. */
7453 ST.c1 = CHRTEST_UNINIT;
7456 if (!(ST.minmod ? ARG1(ST.me) : ARG2(ST.me))) /* min/max */
7459 curlym_do_A: /* execute the A in /A{m,n}B/ */
7460 PUSH_YES_STATE_GOTO(CURLYM_A, ST.A, locinput); /* match A */
7462 NOT_REACHED; /* NOTREACHED */
7464 case CURLYM_A: /* we've just matched an A */
7466 /* after first match, determine A's length: u.curlym.alen */
7467 if (ST.count == 1) {
7468 if (reginfo->is_utf8_target) {
7469 char *s = st->locinput;
7470 while (s < locinput) {
7476 ST.alen = locinput - st->locinput;
7479 ST.count = ST.minmod ? ARG1(ST.me) : ARG2(ST.me);
7482 PerlIO_printf(Perl_debug_log,
7483 "%*s CURLYM now matched %"IVdf" times, len=%"IVdf"...\n",
7484 (int)(REPORT_CODE_OFF+(depth*2)), "",
7485 (IV) ST.count, (IV)ST.alen)
7488 if (cur_eval && cur_eval->u.eval.close_paren &&
7489 cur_eval->u.eval.close_paren == (U32)ST.me->flags)
7493 I32 max = (ST.minmod ? ARG1(ST.me) : ARG2(ST.me));
7494 if ( max == REG_INFTY || ST.count < max )
7495 goto curlym_do_A; /* try to match another A */
7497 goto curlym_do_B; /* try to match B */
7499 case CURLYM_A_fail: /* just failed to match an A */
7500 REGCP_UNWIND(ST.cp);
7502 if (ST.minmod || ST.count < ARG1(ST.me) /* min*/
7503 || (cur_eval && cur_eval->u.eval.close_paren &&
7504 cur_eval->u.eval.close_paren == (U32)ST.me->flags))
7507 curlym_do_B: /* execute the B in /A{m,n}B/ */
7508 if (ST.c1 == CHRTEST_UNINIT) {
7509 /* calculate c1 and c2 for possible match of 1st char
7510 * following curly */
7511 ST.c1 = ST.c2 = CHRTEST_VOID;
7513 if (HAS_TEXT(ST.B) || JUMPABLE(ST.B)) {
7514 regnode *text_node = ST.B;
7515 if (! HAS_TEXT(text_node))
7516 FIND_NEXT_IMPT(text_node);
7519 (HAS_TEXT(text_node) && PL_regkind[OP(text_node)] == EXACT)
7521 But the former is redundant in light of the latter.
7523 if this changes back then the macro for
7524 IS_TEXT and friends need to change.
7526 if (PL_regkind[OP(text_node)] == EXACT) {
7527 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
7528 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
7538 PerlIO_printf(Perl_debug_log,
7539 "%*s CURLYM trying tail with matches=%"IVdf"...\n",
7540 (int)(REPORT_CODE_OFF+(depth*2)),
7543 if (! NEXTCHR_IS_EOS && ST.c1 != CHRTEST_VOID) {
7544 if (! UTF8_IS_INVARIANT(nextchr) && utf8_target) {
7545 if (memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
7546 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
7548 /* simulate B failing */
7550 PerlIO_printf(Perl_debug_log,
7551 "%*s CURLYM Fast bail next target=0x%"UVXf" c1=0x%"UVXf" c2=0x%"UVXf"\n",
7552 (int)(REPORT_CODE_OFF+(depth*2)),"",
7553 valid_utf8_to_uvchr((U8 *) locinput, NULL),
7554 valid_utf8_to_uvchr(ST.c1_utf8, NULL),
7555 valid_utf8_to_uvchr(ST.c2_utf8, NULL))
7557 state_num = CURLYM_B_fail;
7558 goto reenter_switch;
7561 else if (nextchr != ST.c1 && nextchr != ST.c2) {
7562 /* simulate B failing */
7564 PerlIO_printf(Perl_debug_log,
7565 "%*s CURLYM Fast bail next target=0x%X c1=0x%X c2=0x%X\n",
7566 (int)(REPORT_CODE_OFF+(depth*2)),"",
7567 (int) nextchr, ST.c1, ST.c2)
7569 state_num = CURLYM_B_fail;
7570 goto reenter_switch;
7575 /* emulate CLOSE: mark current A as captured */
7576 I32 paren = ST.me->flags;
7578 rex->offs[paren].start
7579 = HOPc(locinput, -ST.alen) - reginfo->strbeg;
7580 rex->offs[paren].end = locinput - reginfo->strbeg;
7581 if ((U32)paren > rex->lastparen)
7582 rex->lastparen = paren;
7583 rex->lastcloseparen = paren;
7586 rex->offs[paren].end = -1;
7587 if (cur_eval && cur_eval->u.eval.close_paren &&
7588 cur_eval->u.eval.close_paren == (U32)ST.me->flags)
7597 PUSH_STATE_GOTO(CURLYM_B, ST.B, locinput); /* match B */
7599 NOT_REACHED; /* NOTREACHED */
7601 case CURLYM_B_fail: /* just failed to match a B */
7602 REGCP_UNWIND(ST.cp);
7603 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7605 I32 max = ARG2(ST.me);
7606 if (max != REG_INFTY && ST.count == max)
7608 goto curlym_do_A; /* try to match a further A */
7610 /* backtrack one A */
7611 if (ST.count == ARG1(ST.me) /* min */)
7614 SET_locinput(HOPc(locinput, -ST.alen));
7615 goto curlym_do_B; /* try to match B */
7618 #define ST st->u.curly
7620 #define CURLY_SETPAREN(paren, success) \
7623 rex->offs[paren].start = HOPc(locinput, -1) - reginfo->strbeg; \
7624 rex->offs[paren].end = locinput - reginfo->strbeg; \
7625 if (paren > rex->lastparen) \
7626 rex->lastparen = paren; \
7627 rex->lastcloseparen = paren; \
7630 rex->offs[paren].end = -1; \
7631 rex->lastparen = ST.lastparen; \
7632 rex->lastcloseparen = ST.lastcloseparen; \
7636 case STAR: /* /A*B/ where A is width 1 char */
7640 scan = NEXTOPER(scan);
7643 case PLUS: /* /A+B/ where A is width 1 char */
7647 scan = NEXTOPER(scan);
7650 case CURLYN: /* /(A){m,n}B/ where A is width 1 char */
7651 ST.paren = scan->flags; /* Which paren to set */
7652 ST.lastparen = rex->lastparen;
7653 ST.lastcloseparen = rex->lastcloseparen;
7654 if (ST.paren > maxopenparen)
7655 maxopenparen = ST.paren;
7656 ST.min = ARG1(scan); /* min to match */
7657 ST.max = ARG2(scan); /* max to match */
7658 if (cur_eval && cur_eval->u.eval.close_paren &&
7659 cur_eval->u.eval.close_paren == (U32)ST.paren) {
7663 scan = regnext(NEXTOPER(scan) + NODE_STEP_REGNODE);
7666 case CURLY: /* /A{m,n}B/ where A is width 1 char */
7668 ST.min = ARG1(scan); /* min to match */
7669 ST.max = ARG2(scan); /* max to match */
7670 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
7673 * Lookahead to avoid useless match attempts
7674 * when we know what character comes next.
7676 * Used to only do .*x and .*?x, but now it allows
7677 * for )'s, ('s and (?{ ... })'s to be in the way
7678 * of the quantifier and the EXACT-like node. -- japhy
7681 assert(ST.min <= ST.max);
7682 if (! HAS_TEXT(next) && ! JUMPABLE(next)) {
7683 ST.c1 = ST.c2 = CHRTEST_VOID;
7686 regnode *text_node = next;
7688 if (! HAS_TEXT(text_node))
7689 FIND_NEXT_IMPT(text_node);
7691 if (! HAS_TEXT(text_node))
7692 ST.c1 = ST.c2 = CHRTEST_VOID;
7694 if ( PL_regkind[OP(text_node)] != EXACT ) {
7695 ST.c1 = ST.c2 = CHRTEST_VOID;
7699 /* Currently we only get here when
7701 PL_rekind[OP(text_node)] == EXACT
7703 if this changes back then the macro for IS_TEXT and
7704 friends need to change. */
7705 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
7706 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
7718 char *li = locinput;
7721 regrepeat(rex, &li, ST.A, reginfo, ST.min, depth)
7727 if (ST.c1 == CHRTEST_VOID)
7728 goto curly_try_B_min;
7730 ST.oldloc = locinput;
7732 /* set ST.maxpos to the furthest point along the
7733 * string that could possibly match */
7734 if (ST.max == REG_INFTY) {
7735 ST.maxpos = reginfo->strend - 1;
7737 while (UTF8_IS_CONTINUATION(*(U8*)ST.maxpos))
7740 else if (utf8_target) {
7741 int m = ST.max - ST.min;
7742 for (ST.maxpos = locinput;
7743 m >0 && ST.maxpos < reginfo->strend; m--)
7744 ST.maxpos += UTF8SKIP(ST.maxpos);
7747 ST.maxpos = locinput + ST.max - ST.min;
7748 if (ST.maxpos >= reginfo->strend)
7749 ST.maxpos = reginfo->strend - 1;
7751 goto curly_try_B_min_known;
7755 /* avoid taking address of locinput, so it can remain
7757 char *li = locinput;
7758 ST.count = regrepeat(rex, &li, ST.A, reginfo, ST.max, depth);
7759 if (ST.count < ST.min)
7762 if ((ST.count > ST.min)
7763 && (PL_regkind[OP(ST.B)] == EOL) && (OP(ST.B) != MEOL))
7765 /* A{m,n} must come at the end of the string, there's
7766 * no point in backing off ... */
7768 /* ...except that $ and \Z can match before *and* after
7769 newline at the end. Consider "\n\n" =~ /\n+\Z\n/.
7770 We may back off by one in this case. */
7771 if (UCHARAT(locinput - 1) == '\n' && OP(ST.B) != EOS)
7775 goto curly_try_B_max;
7778 NOT_REACHED; /* NOTREACHED */
7780 case CURLY_B_min_known_fail:
7781 /* failed to find B in a non-greedy match where c1,c2 valid */
7783 REGCP_UNWIND(ST.cp);
7785 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7787 /* Couldn't or didn't -- move forward. */
7788 ST.oldloc = locinput;
7790 locinput += UTF8SKIP(locinput);
7794 curly_try_B_min_known:
7795 /* find the next place where 'B' could work, then call B */
7799 n = (ST.oldloc == locinput) ? 0 : 1;
7800 if (ST.c1 == ST.c2) {
7801 /* set n to utf8_distance(oldloc, locinput) */
7802 while (locinput <= ST.maxpos
7803 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput)))
7805 locinput += UTF8SKIP(locinput);
7810 /* set n to utf8_distance(oldloc, locinput) */
7811 while (locinput <= ST.maxpos
7812 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
7813 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
7815 locinput += UTF8SKIP(locinput);
7820 else { /* Not utf8_target */
7821 if (ST.c1 == ST.c2) {
7822 while (locinput <= ST.maxpos &&
7823 UCHARAT(locinput) != ST.c1)
7827 while (locinput <= ST.maxpos
7828 && UCHARAT(locinput) != ST.c1
7829 && UCHARAT(locinput) != ST.c2)
7832 n = locinput - ST.oldloc;
7834 if (locinput > ST.maxpos)
7837 /* In /a{m,n}b/, ST.oldloc is at "a" x m, locinput is
7838 * at b; check that everything between oldloc and
7839 * locinput matches */
7840 char *li = ST.oldloc;
7842 if (regrepeat(rex, &li, ST.A, reginfo, n, depth) < n)
7844 assert(n == REG_INFTY || locinput == li);
7846 CURLY_SETPAREN(ST.paren, ST.count);
7847 if (cur_eval && cur_eval->u.eval.close_paren &&
7848 cur_eval->u.eval.close_paren == (U32)ST.paren) {
7851 PUSH_STATE_GOTO(CURLY_B_min_known, ST.B, locinput);
7854 NOT_REACHED; /* NOTREACHED */
7856 case CURLY_B_min_fail:
7857 /* failed to find B in a non-greedy match where c1,c2 invalid */
7859 REGCP_UNWIND(ST.cp);
7861 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7863 /* failed -- move forward one */
7865 char *li = locinput;
7866 if (!regrepeat(rex, &li, ST.A, reginfo, 1, depth)) {
7873 if (ST.count <= ST.max || (ST.max == REG_INFTY &&
7874 ST.count > 0)) /* count overflow ? */
7877 CURLY_SETPAREN(ST.paren, ST.count);
7878 if (cur_eval && cur_eval->u.eval.close_paren &&
7879 cur_eval->u.eval.close_paren == (U32)ST.paren) {
7882 PUSH_STATE_GOTO(CURLY_B_min, ST.B, locinput);
7887 NOT_REACHED; /* NOTREACHED */
7890 /* a successful greedy match: now try to match B */
7891 if (cur_eval && cur_eval->u.eval.close_paren &&
7892 cur_eval->u.eval.close_paren == (U32)ST.paren) {
7896 bool could_match = locinput < reginfo->strend;
7898 /* If it could work, try it. */
7899 if (ST.c1 != CHRTEST_VOID && could_match) {
7900 if (! UTF8_IS_INVARIANT(UCHARAT(locinput)) && utf8_target)
7902 could_match = memEQ(locinput,
7907 UTF8SKIP(locinput));
7910 could_match = UCHARAT(locinput) == ST.c1
7911 || UCHARAT(locinput) == ST.c2;
7914 if (ST.c1 == CHRTEST_VOID || could_match) {
7915 CURLY_SETPAREN(ST.paren, ST.count);
7916 PUSH_STATE_GOTO(CURLY_B_max, ST.B, locinput);
7918 NOT_REACHED; /* NOTREACHED */
7923 case CURLY_B_max_fail:
7924 /* failed to find B in a greedy match */
7926 REGCP_UNWIND(ST.cp);
7928 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7931 if (--ST.count < ST.min)
7933 locinput = HOPc(locinput, -1);
7934 goto curly_try_B_max;
7938 case END: /* last op of main pattern */
7941 /* we've just finished A in /(??{A})B/; now continue with B */
7943 st->u.eval.prev_rex = rex_sv; /* inner */
7945 /* Save *all* the positions. */
7946 st->u.eval.cp = regcppush(rex, 0, maxopenparen);
7947 rex_sv = cur_eval->u.eval.prev_rex;
7948 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
7949 SET_reg_curpm(rex_sv);
7950 rex = ReANY(rex_sv);
7951 rexi = RXi_GET(rex);
7952 cur_curlyx = cur_eval->u.eval.prev_curlyx;
7954 REGCP_SET(st->u.eval.lastcp);
7956 /* Restore parens of the outer rex without popping the
7958 S_regcp_restore(aTHX_ rex, cur_eval->u.eval.lastcp,
7961 st->u.eval.prev_eval = cur_eval;
7962 cur_eval = cur_eval->u.eval.prev_eval;
7964 PerlIO_printf(Perl_debug_log, "%*s EVAL trying tail ... %"UVxf"\n",
7965 REPORT_CODE_OFF+depth*2, "",PTR2UV(cur_eval)););
7966 if ( nochange_depth )
7969 PUSH_YES_STATE_GOTO(EVAL_AB, st->u.eval.prev_eval->u.eval.B,
7970 locinput); /* match B */
7973 if (locinput < reginfo->till) {
7974 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
7975 "%sMatch possible, but length=%ld is smaller than requested=%ld, failing!%s\n",
7977 (long)(locinput - startpos),
7978 (long)(reginfo->till - startpos),
7981 sayNO_SILENT; /* Cannot match: too short. */
7983 sayYES; /* Success! */
7985 case SUCCEED: /* successful SUSPEND/UNLESSM/IFMATCH/CURLYM */
7987 PerlIO_printf(Perl_debug_log,
7988 "%*s %ssubpattern success...%s\n",
7989 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5]));
7990 sayYES; /* Success! */
7993 #define ST st->u.ifmatch
7998 case SUSPEND: /* (?>A) */
8000 newstart = locinput;
8003 case UNLESSM: /* -ve lookaround: (?!A), or with flags, (?<!A) */
8005 goto ifmatch_trivial_fail_test;
8007 case IFMATCH: /* +ve lookaround: (?=A), or with flags, (?<=A) */
8009 ifmatch_trivial_fail_test:
8011 char * const s = HOPBACKc(locinput, scan->flags);
8016 sw = 1 - cBOOL(ST.wanted);
8020 next = scan + ARG(scan);
8028 newstart = locinput;
8032 ST.logical = logical;
8033 logical = 0; /* XXX: reset state of logical once it has been saved into ST */
8035 /* execute body of (?...A) */
8036 PUSH_YES_STATE_GOTO(IFMATCH_A, NEXTOPER(NEXTOPER(scan)), newstart);
8038 NOT_REACHED; /* NOTREACHED */
8041 case IFMATCH_A_fail: /* body of (?...A) failed */
8042 ST.wanted = !ST.wanted;
8045 case IFMATCH_A: /* body of (?...A) succeeded */
8047 sw = cBOOL(ST.wanted);
8049 else if (!ST.wanted)
8052 if (OP(ST.me) != SUSPEND) {
8053 /* restore old position except for (?>...) */
8054 locinput = st->locinput;
8056 scan = ST.me + ARG(ST.me);
8059 continue; /* execute B */
8063 case LONGJMP: /* alternative with many branches compiles to
8064 * (BRANCHJ; EXACT ...; LONGJMP ) x N */
8065 next = scan + ARG(scan);
8070 case COMMIT: /* (*COMMIT) */
8071 reginfo->cutpoint = reginfo->strend;
8074 case PRUNE: /* (*PRUNE) */
8076 sv_yes_mark = sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8077 PUSH_STATE_GOTO(COMMIT_next, next, locinput);
8079 NOT_REACHED; /* NOTREACHED */
8081 case COMMIT_next_fail:
8085 NOT_REACHED; /* NOTREACHED */
8087 case OPFAIL: /* (*FAIL) */
8089 sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8091 /* deal with (?(?!)X|Y) properly,
8092 * make sure we trigger the no branch
8093 * of the trailing IFTHEN structure*/
8100 NOT_REACHED; /* NOTREACHED */
8102 #define ST st->u.mark
8103 case MARKPOINT: /* (*MARK:foo) */
8104 ST.prev_mark = mark_state;
8105 ST.mark_name = sv_commit = sv_yes_mark
8106 = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8108 ST.mark_loc = locinput;
8109 PUSH_YES_STATE_GOTO(MARKPOINT_next, next, locinput);
8111 NOT_REACHED; /* NOTREACHED */
8113 case MARKPOINT_next:
8114 mark_state = ST.prev_mark;
8117 NOT_REACHED; /* NOTREACHED */
8119 case MARKPOINT_next_fail:
8120 if (popmark && sv_eq(ST.mark_name,popmark))
8122 if (ST.mark_loc > startpoint)
8123 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
8124 popmark = NULL; /* we found our mark */
8125 sv_commit = ST.mark_name;
8128 PerlIO_printf(Perl_debug_log,
8129 "%*s %ssetting cutpoint to mark:%"SVf"...%s\n",
8130 REPORT_CODE_OFF+depth*2, "",
8131 PL_colors[4], SVfARG(sv_commit), PL_colors[5]);
8134 mark_state = ST.prev_mark;
8135 sv_yes_mark = mark_state ?
8136 mark_state->u.mark.mark_name : NULL;
8139 NOT_REACHED; /* NOTREACHED */
8141 case SKIP: /* (*SKIP) */
8143 /* (*SKIP) : if we fail we cut here*/
8144 ST.mark_name = NULL;
8145 ST.mark_loc = locinput;
8146 PUSH_STATE_GOTO(SKIP_next,next, locinput);
8148 /* (*SKIP:NAME) : if there is a (*MARK:NAME) fail where it was,
8149 otherwise do nothing. Meaning we need to scan
8151 regmatch_state *cur = mark_state;
8152 SV *find = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8155 if ( sv_eq( cur->u.mark.mark_name,
8158 ST.mark_name = find;
8159 PUSH_STATE_GOTO( SKIP_next, next, locinput);
8161 cur = cur->u.mark.prev_mark;
8164 /* Didn't find our (*MARK:NAME) so ignore this (*SKIP:NAME) */
8167 case SKIP_next_fail:
8169 /* (*CUT:NAME) - Set up to search for the name as we
8170 collapse the stack*/
8171 popmark = ST.mark_name;
8173 /* (*CUT) - No name, we cut here.*/
8174 if (ST.mark_loc > startpoint)
8175 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
8176 /* but we set sv_commit to latest mark_name if there
8177 is one so they can test to see how things lead to this
8180 sv_commit=mark_state->u.mark.mark_name;
8185 NOT_REACHED; /* NOTREACHED */
8188 case LNBREAK: /* \R */
8189 if ((n=is_LNBREAK_safe(locinput, reginfo->strend, utf8_target))) {
8196 PerlIO_printf(Perl_error_log, "%"UVxf" %d\n",
8197 PTR2UV(scan), OP(scan));
8198 Perl_croak(aTHX_ "regexp memory corruption");
8200 /* this is a point to jump to in order to increment
8201 * locinput by one character */
8203 assert(!NEXTCHR_IS_EOS);
8205 locinput += PL_utf8skip[nextchr];
8206 /* locinput is allowed to go 1 char off the end, but not 2+ */
8207 if (locinput > reginfo->strend)
8216 /* switch break jumps here */
8217 scan = next; /* prepare to execute the next op and ... */
8218 continue; /* ... jump back to the top, reusing st */
8222 /* push a state that backtracks on success */
8223 st->u.yes.prev_yes_state = yes_state;
8227 /* push a new regex state, then continue at scan */
8229 regmatch_state *newst;
8232 regmatch_state *cur = st;
8233 regmatch_state *curyes = yes_state;
8235 regmatch_slab *slab = PL_regmatch_slab;
8236 for (;curd > -1;cur--,curd--) {
8237 if (cur < SLAB_FIRST(slab)) {
8239 cur = SLAB_LAST(slab);
8241 PerlIO_printf(Perl_error_log, "%*s#%-3d %-10s %s\n",
8242 REPORT_CODE_OFF + 2 + depth * 2,"",
8243 curd, PL_reg_name[cur->resume_state],
8244 (curyes == cur) ? "yes" : ""
8247 curyes = cur->u.yes.prev_yes_state;
8250 DEBUG_STATE_pp("push")
8253 st->locinput = locinput;
8255 if (newst > SLAB_LAST(PL_regmatch_slab))
8256 newst = S_push_slab(aTHX);
8257 PL_regmatch_state = newst;
8259 locinput = pushinput;
8267 * We get here only if there's trouble -- normally "case END" is
8268 * the terminating point.
8270 Perl_croak(aTHX_ "corrupted regexp pointers");
8273 NOT_REACHED; /* NOTREACHED */
8277 /* we have successfully completed a subexpression, but we must now
8278 * pop to the state marked by yes_state and continue from there */
8279 assert(st != yes_state);
8281 while (st != yes_state) {
8283 if (st < SLAB_FIRST(PL_regmatch_slab)) {
8284 PL_regmatch_slab = PL_regmatch_slab->prev;
8285 st = SLAB_LAST(PL_regmatch_slab);
8289 DEBUG_STATE_pp("pop (no final)");
8291 DEBUG_STATE_pp("pop (yes)");
8297 while (yes_state < SLAB_FIRST(PL_regmatch_slab)
8298 || yes_state > SLAB_LAST(PL_regmatch_slab))
8300 /* not in this slab, pop slab */
8301 depth -= (st - SLAB_FIRST(PL_regmatch_slab) + 1);
8302 PL_regmatch_slab = PL_regmatch_slab->prev;
8303 st = SLAB_LAST(PL_regmatch_slab);
8305 depth -= (st - yes_state);
8308 yes_state = st->u.yes.prev_yes_state;
8309 PL_regmatch_state = st;
8312 locinput= st->locinput;
8313 state_num = st->resume_state + no_final;
8314 goto reenter_switch;
8317 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch successful!%s\n",
8318 PL_colors[4], PL_colors[5]));
8320 if (reginfo->info_aux_eval) {
8321 /* each successfully executed (?{...}) block does the equivalent of
8322 * local $^R = do {...}
8323 * When popping the save stack, all these locals would be undone;
8324 * bypass this by setting the outermost saved $^R to the latest
8326 /* I dont know if this is needed or works properly now.
8327 * see code related to PL_replgv elsewhere in this file.
8330 if (oreplsv != GvSV(PL_replgv))
8331 sv_setsv(oreplsv, GvSV(PL_replgv));
8338 PerlIO_printf(Perl_debug_log,
8339 "%*s %sfailed...%s\n",
8340 REPORT_CODE_OFF+depth*2, "",
8341 PL_colors[4], PL_colors[5])
8353 /* there's a previous state to backtrack to */
8355 if (st < SLAB_FIRST(PL_regmatch_slab)) {
8356 PL_regmatch_slab = PL_regmatch_slab->prev;
8357 st = SLAB_LAST(PL_regmatch_slab);
8359 PL_regmatch_state = st;
8360 locinput= st->locinput;
8362 DEBUG_STATE_pp("pop");
8364 if (yes_state == st)
8365 yes_state = st->u.yes.prev_yes_state;
8367 state_num = st->resume_state + 1; /* failure = success + 1 */
8368 goto reenter_switch;
8373 if (rex->intflags & PREGf_VERBARG_SEEN) {
8374 SV *sv_err = get_sv("REGERROR", 1);
8375 SV *sv_mrk = get_sv("REGMARK", 1);
8377 sv_commit = &PL_sv_no;
8379 sv_yes_mark = &PL_sv_yes;
8382 sv_commit = &PL_sv_yes;
8383 sv_yes_mark = &PL_sv_no;
8387 sv_setsv(sv_err, sv_commit);
8388 sv_setsv(sv_mrk, sv_yes_mark);
8392 if (last_pushed_cv) {
8395 PERL_UNUSED_VAR(SP);
8398 assert(!result || locinput - reginfo->strbeg >= 0);
8399 return result ? locinput - reginfo->strbeg : -1;
8403 - regrepeat - repeatedly match something simple, report how many
8405 * What 'simple' means is a node which can be the operand of a quantifier like
8408 * startposp - pointer a pointer to the start position. This is updated
8409 * to point to the byte following the highest successful
8411 * p - the regnode to be repeatedly matched against.
8412 * reginfo - struct holding match state, such as strend
8413 * max - maximum number of things to match.
8414 * depth - (for debugging) backtracking depth.
8417 S_regrepeat(pTHX_ regexp *prog, char **startposp, const regnode *p,
8418 regmatch_info *const reginfo, I32 max, int depth)
8420 char *scan; /* Pointer to current position in target string */
8422 char *loceol = reginfo->strend; /* local version */
8423 I32 hardcount = 0; /* How many matches so far */
8424 bool utf8_target = reginfo->is_utf8_target;
8425 unsigned int to_complement = 0; /* Invert the result? */
8427 _char_class_number classnum;
8429 PERL_UNUSED_ARG(depth);
8432 PERL_ARGS_ASSERT_REGREPEAT;
8435 if (max == REG_INFTY)
8437 else if (! utf8_target && loceol - scan > max)
8438 loceol = scan + max;
8440 /* Here, for the case of a non-UTF-8 target we have adjusted <loceol> down
8441 * to the maximum of how far we should go in it (leaving it set to the real
8442 * end, if the maximum permissible would take us beyond that). This allows
8443 * us to make the loop exit condition that we haven't gone past <loceol> to
8444 * also mean that we haven't exceeded the max permissible count, saving a
8445 * test each time through the loop. But it assumes that the OP matches a
8446 * single byte, which is true for most of the OPs below when applied to a
8447 * non-UTF-8 target. Those relatively few OPs that don't have this
8448 * characteristic will have to compensate.
8450 * There is no adjustment for UTF-8 targets, as the number of bytes per
8451 * character varies. OPs will have to test both that the count is less
8452 * than the max permissible (using <hardcount> to keep track), and that we
8453 * are still within the bounds of the string (using <loceol>. A few OPs
8454 * match a single byte no matter what the encoding. They can omit the max
8455 * test if, for the UTF-8 case, they do the adjustment that was skipped
8458 * Thus, the code above sets things up for the common case; and exceptional
8459 * cases need extra work; the common case is to make sure <scan> doesn't
8460 * go past <loceol>, and for UTF-8 to also use <hardcount> to make sure the
8461 * count doesn't exceed the maximum permissible */
8466 while (scan < loceol && hardcount < max && *scan != '\n') {
8467 scan += UTF8SKIP(scan);
8471 while (scan < loceol && *scan != '\n')
8477 while (scan < loceol && hardcount < max) {
8478 scan += UTF8SKIP(scan);
8486 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8487 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*scan)) {
8488 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(scan, loceol);
8492 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
8496 /* Can use a simple loop if the pattern char to match on is invariant
8497 * under UTF-8, or both target and pattern aren't UTF-8. Note that we
8498 * can use UTF8_IS_INVARIANT() even if the pattern isn't UTF-8, as it's
8499 * true iff it doesn't matter if the argument is in UTF-8 or not */
8500 if (UTF8_IS_INVARIANT(c) || (! utf8_target && ! reginfo->is_utf8_pat)) {
8501 if (utf8_target && loceol - scan > max) {
8502 /* We didn't adjust <loceol> because is UTF-8, but ok to do so,
8503 * since here, to match at all, 1 char == 1 byte */
8504 loceol = scan + max;
8506 while (scan < loceol && UCHARAT(scan) == c) {
8510 else if (reginfo->is_utf8_pat) {
8512 STRLEN scan_char_len;
8514 /* When both target and pattern are UTF-8, we have to do
8516 while (hardcount < max
8518 && (scan_char_len = UTF8SKIP(scan)) <= STR_LEN(p)
8519 && memEQ(scan, STRING(p), scan_char_len))
8521 scan += scan_char_len;
8525 else if (! UTF8_IS_ABOVE_LATIN1(c)) {
8527 /* Target isn't utf8; convert the character in the UTF-8
8528 * pattern to non-UTF8, and do a simple loop */
8529 c = EIGHT_BIT_UTF8_TO_NATIVE(c, *(STRING(p) + 1));
8530 while (scan < loceol && UCHARAT(scan) == c) {
8533 } /* else pattern char is above Latin1, can't possibly match the
8538 /* Here, the string must be utf8; pattern isn't, and <c> is
8539 * different in utf8 than not, so can't compare them directly.
8540 * Outside the loop, find the two utf8 bytes that represent c, and
8541 * then look for those in sequence in the utf8 string */
8542 U8 high = UTF8_TWO_BYTE_HI(c);
8543 U8 low = UTF8_TWO_BYTE_LO(c);
8545 while (hardcount < max
8546 && scan + 1 < loceol
8547 && UCHARAT(scan) == high
8548 && UCHARAT(scan + 1) == low)
8556 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
8557 assert(! reginfo->is_utf8_pat);
8560 utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
8564 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8565 utf8_flags = FOLDEQ_LOCALE;
8568 case EXACTF: /* This node only generated for non-utf8 patterns */
8569 assert(! reginfo->is_utf8_pat);
8574 if (! utf8_target) {
8577 utf8_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
8578 | FOLDEQ_S2_FOLDS_SANE;
8583 utf8_flags = reginfo->is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
8587 U8 c1_utf8[UTF8_MAXBYTES+1], c2_utf8[UTF8_MAXBYTES+1];
8589 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
8591 if (S_setup_EXACTISH_ST_c1_c2(aTHX_ p, &c1, c1_utf8, &c2, c2_utf8,
8594 if (c1 == CHRTEST_VOID) {
8595 /* Use full Unicode fold matching */
8596 char *tmpeol = reginfo->strend;
8597 STRLEN pat_len = reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1;
8598 while (hardcount < max
8599 && foldEQ_utf8_flags(scan, &tmpeol, 0, utf8_target,
8600 STRING(p), NULL, pat_len,
8601 reginfo->is_utf8_pat, utf8_flags))
8604 tmpeol = reginfo->strend;
8608 else if (utf8_target) {
8610 while (scan < loceol
8612 && memEQ(scan, c1_utf8, UTF8SKIP(scan)))
8614 scan += UTF8SKIP(scan);
8619 while (scan < loceol
8621 && (memEQ(scan, c1_utf8, UTF8SKIP(scan))
8622 || memEQ(scan, c2_utf8, UTF8SKIP(scan))))
8624 scan += UTF8SKIP(scan);
8629 else if (c1 == c2) {
8630 while (scan < loceol && UCHARAT(scan) == c1) {
8635 while (scan < loceol &&
8636 (UCHARAT(scan) == c1 || UCHARAT(scan) == c2))
8645 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8647 if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(p)) && ! IN_UTF8_CTYPE_LOCALE) {
8648 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
8654 while (hardcount < max
8656 && reginclass(prog, p, (U8*)scan, (U8*) loceol, utf8_target))
8658 scan += UTF8SKIP(scan);
8662 while (scan < loceol && REGINCLASS(prog, p, (U8*)scan))
8667 /* The argument (FLAGS) to all the POSIX node types is the class number */
8674 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8675 if (! utf8_target) {
8676 while (scan < loceol && to_complement ^ cBOOL(isFOO_lc(FLAGS(p),
8682 while (hardcount < max && scan < loceol
8683 && to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(p),
8686 scan += UTF8SKIP(scan);
8699 if (utf8_target && loceol - scan > max) {
8701 /* We didn't adjust <loceol> at the beginning of this routine
8702 * because is UTF-8, but it is actually ok to do so, since here, to
8703 * match, 1 char == 1 byte. */
8704 loceol = scan + max;
8706 while (scan < loceol && _generic_isCC_A((U8) *scan, FLAGS(p))) {
8719 if (! utf8_target) {
8720 while (scan < loceol && ! _generic_isCC_A((U8) *scan, FLAGS(p))) {
8726 /* The complement of something that matches only ASCII matches all
8727 * non-ASCII, plus everything in ASCII that isn't in the class. */
8728 while (hardcount < max && scan < loceol
8729 && (! isASCII_utf8(scan)
8730 || ! _generic_isCC_A((U8) *scan, FLAGS(p))))
8732 scan += UTF8SKIP(scan);
8743 if (! utf8_target) {
8744 while (scan < loceol && to_complement
8745 ^ cBOOL(_generic_isCC((U8) *scan, FLAGS(p))))
8752 classnum = (_char_class_number) FLAGS(p);
8753 if (classnum < _FIRST_NON_SWASH_CC) {
8755 /* Here, a swash is needed for above-Latin1 code points.
8756 * Process as many Latin1 code points using the built-in rules.
8757 * Go to another loop to finish processing upon encountering
8758 * the first Latin1 code point. We could do that in this loop
8759 * as well, but the other way saves having to test if the swash
8760 * has been loaded every time through the loop: extra space to
8762 while (hardcount < max && scan < loceol) {
8763 if (UTF8_IS_INVARIANT(*scan)) {
8764 if (! (to_complement ^ cBOOL(_generic_isCC((U8) *scan,
8771 else if (UTF8_IS_DOWNGRADEABLE_START(*scan)) {
8772 if (! (to_complement
8773 ^ cBOOL(_generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(*scan,
8782 goto found_above_latin1;
8789 /* For these character classes, the knowledge of how to handle
8790 * every code point is compiled in to Perl via a macro. This
8791 * code is written for making the loops as tight as possible.
8792 * It could be refactored to save space instead */
8794 case _CC_ENUM_SPACE:
8795 while (hardcount < max
8797 && (to_complement ^ cBOOL(isSPACE_utf8(scan))))
8799 scan += UTF8SKIP(scan);
8803 case _CC_ENUM_BLANK:
8804 while (hardcount < max
8806 && (to_complement ^ cBOOL(isBLANK_utf8(scan))))
8808 scan += UTF8SKIP(scan);
8812 case _CC_ENUM_XDIGIT:
8813 while (hardcount < max
8815 && (to_complement ^ cBOOL(isXDIGIT_utf8(scan))))
8817 scan += UTF8SKIP(scan);
8821 case _CC_ENUM_VERTSPACE:
8822 while (hardcount < max
8824 && (to_complement ^ cBOOL(isVERTWS_utf8(scan))))
8826 scan += UTF8SKIP(scan);
8830 case _CC_ENUM_CNTRL:
8831 while (hardcount < max
8833 && (to_complement ^ cBOOL(isCNTRL_utf8(scan))))
8835 scan += UTF8SKIP(scan);
8840 Perl_croak(aTHX_ "panic: regrepeat() node %d='%s' has an unexpected character class '%d'", OP(p), PL_reg_name[OP(p)], classnum);
8846 found_above_latin1: /* Continuation of POSIXU and NPOSIXU */
8848 /* Load the swash if not already present */
8849 if (! PL_utf8_swash_ptrs[classnum]) {
8850 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
8851 PL_utf8_swash_ptrs[classnum] = _core_swash_init(
8855 PL_XPosix_ptrs[classnum], &flags);
8858 while (hardcount < max && scan < loceol
8859 && to_complement ^ cBOOL(_generic_utf8(
8862 swash_fetch(PL_utf8_swash_ptrs[classnum],
8866 scan += UTF8SKIP(scan);
8873 while (hardcount < max && scan < loceol &&
8874 (c=is_LNBREAK_utf8_safe(scan, loceol))) {
8879 /* LNBREAK can match one or two latin chars, which is ok, but we
8880 * have to use hardcount in this situation, and throw away the
8881 * adjustment to <loceol> done before the switch statement */
8882 loceol = reginfo->strend;
8883 while (scan < loceol && (c=is_LNBREAK_latin1_safe(scan, loceol))) {
8892 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8906 /* These are all 0 width, so match right here or not at all. */
8910 Perl_croak(aTHX_ "panic: regrepeat() called with unrecognized node type %d='%s'", OP(p), PL_reg_name[OP(p)]);
8912 NOT_REACHED; /* NOTREACHED */
8919 c = scan - *startposp;
8923 GET_RE_DEBUG_FLAGS_DECL;
8925 SV * const prop = sv_newmortal();
8926 regprop(prog, prop, p, reginfo, NULL);
8927 PerlIO_printf(Perl_debug_log,
8928 "%*s %s can match %"IVdf" times out of %"IVdf"...\n",
8929 REPORT_CODE_OFF + depth*2, "", SvPVX_const(prop),(IV)c,(IV)max);
8937 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
8939 - regclass_swash - prepare the utf8 swash. Wraps the shared core version to
8940 create a copy so that changes the caller makes won't change the shared one.
8941 If <altsvp> is non-null, will return NULL in it, for back-compat.
8944 Perl_regclass_swash(pTHX_ const regexp *prog, const regnode* node, bool doinit, SV** listsvp, SV **altsvp)
8946 PERL_ARGS_ASSERT_REGCLASS_SWASH;
8952 return newSVsv(_get_regclass_nonbitmap_data(prog, node, doinit, listsvp, NULL, NULL));
8955 #endif /* !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION) */
8958 - reginclass - determine if a character falls into a character class
8960 n is the ANYOF-type regnode
8961 p is the target string
8962 p_end points to one byte beyond the end of the target string
8963 utf8_target tells whether p is in UTF-8.
8965 Returns true if matched; false otherwise.
8967 Note that this can be a synthetic start class, a combination of various
8968 nodes, so things you think might be mutually exclusive, such as locale,
8969 aren't. It can match both locale and non-locale
8974 S_reginclass(pTHX_ regexp * const prog, const regnode * const n, const U8* const p, const U8* const p_end, const bool utf8_target)
8977 const char flags = ANYOF_FLAGS(n);
8981 PERL_ARGS_ASSERT_REGINCLASS;
8983 /* If c is not already the code point, get it. Note that
8984 * UTF8_IS_INVARIANT() works even if not in UTF-8 */
8985 if (! UTF8_IS_INVARIANT(c) && utf8_target) {
8987 c = utf8n_to_uvchr(p, p_end - p, &c_len,
8988 (UTF8_ALLOW_DEFAULT & UTF8_ALLOW_ANYUV)
8989 | UTF8_ALLOW_FFFF | UTF8_CHECK_ONLY);
8990 /* see [perl #37836] for UTF8_ALLOW_ANYUV; [perl #38293] for
8991 * UTF8_ALLOW_FFFF */
8992 if (c_len == (STRLEN)-1)
8993 Perl_croak(aTHX_ "Malformed UTF-8 character (fatal)");
8994 if (c > 255 && OP(n) == ANYOFL && ! ANYOFL_UTF8_LOCALE_REQD(flags)) {
8995 _CHECK_AND_OUTPUT_WIDE_LOCALE_CP_MSG(c);
8999 /* If this character is potentially in the bitmap, check it */
9000 if (c < NUM_ANYOF_CODE_POINTS) {
9001 if (ANYOF_BITMAP_TEST(n, c))
9004 & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
9011 else if (flags & ANYOF_LOCALE_FLAGS) {
9012 if ((flags & ANYOFL_FOLD)
9014 && ANYOF_BITMAP_TEST(n, PL_fold_locale[c]))
9018 else if (ANYOF_POSIXL_TEST_ANY_SET(n)
9022 /* The data structure is arranged so bits 0, 2, 4, ... are set
9023 * if the class includes the Posix character class given by
9024 * bit/2; and 1, 3, 5, ... are set if the class includes the
9025 * complemented Posix class given by int(bit/2). So we loop
9026 * through the bits, each time changing whether we complement
9027 * the result or not. Suppose for the sake of illustration
9028 * that bits 0-3 mean respectively, \w, \W, \s, \S. If bit 0
9029 * is set, it means there is a match for this ANYOF node if the
9030 * character is in the class given by the expression (0 / 2 = 0
9031 * = \w). If it is in that class, isFOO_lc() will return 1,
9032 * and since 'to_complement' is 0, the result will stay TRUE,
9033 * and we exit the loop. Suppose instead that bit 0 is 0, but
9034 * bit 1 is 1. That means there is a match if the character
9035 * matches \W. We won't bother to call isFOO_lc() on bit 0,
9036 * but will on bit 1. On the second iteration 'to_complement'
9037 * will be 1, so the exclusive or will reverse things, so we
9038 * are testing for \W. On the third iteration, 'to_complement'
9039 * will be 0, and we would be testing for \s; the fourth
9040 * iteration would test for \S, etc.
9042 * Note that this code assumes that all the classes are closed
9043 * under folding. For example, if a character matches \w, then
9044 * its fold does too; and vice versa. This should be true for
9045 * any well-behaved locale for all the currently defined Posix
9046 * classes, except for :lower: and :upper:, which are handled
9047 * by the pseudo-class :cased: which matches if either of the
9048 * other two does. To get rid of this assumption, an outer
9049 * loop could be used below to iterate over both the source
9050 * character, and its fold (if different) */
9053 int to_complement = 0;
9055 while (count < ANYOF_MAX) {
9056 if (ANYOF_POSIXL_TEST(n, count)
9057 && to_complement ^ cBOOL(isFOO_lc(count/2, (U8) c)))
9070 /* If the bitmap didn't (or couldn't) match, and something outside the
9071 * bitmap could match, try that. */
9073 if (c >= NUM_ANYOF_CODE_POINTS
9074 && (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP))
9076 match = TRUE; /* Everything above the bitmap matches */
9078 /* Here doesn't match everything above the bitmap. If there is
9079 * some information available beyond the bitmap, we may find a
9080 * match in it. If so, this is most likely because the code point
9081 * is outside the bitmap range. But rarely, it could be because of
9082 * some other reason. If so, various flags are set to indicate
9083 * this possibility. On ANYOFD nodes, there may be matches that
9084 * happen only when the target string is UTF-8; or for other node
9085 * types, because runtime lookup is needed, regardless of the
9086 * UTF-8ness of the target string. Finally, under /il, there may
9087 * be some matches only possible if the locale is a UTF-8 one. */
9088 else if ( ARG(n) != ANYOF_ONLY_HAS_BITMAP
9089 && ( c >= NUM_ANYOF_CODE_POINTS
9090 || ( (flags & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)
9091 && ( UNLIKELY(OP(n) != ANYOFD)
9092 || (utf8_target && ! isASCII_uni(c)
9093 # if NUM_ANYOF_CODE_POINTS > 256
9097 || ( ANYOFL_SOME_FOLDS_ONLY_IN_UTF8_LOCALE(flags)
9098 && IN_UTF8_CTYPE_LOCALE)))
9100 SV* only_utf8_locale = NULL;
9101 SV * const sw = _get_regclass_nonbitmap_data(prog, n, TRUE, 0,
9102 &only_utf8_locale, NULL);
9108 } else { /* Convert to utf8 */
9109 utf8_p = utf8_buffer;
9110 append_utf8_from_native_byte(*p, &utf8_p);
9111 utf8_p = utf8_buffer;
9114 if (swash_fetch(sw, utf8_p, TRUE)) {
9118 if (! match && only_utf8_locale && IN_UTF8_CTYPE_LOCALE) {
9119 match = _invlist_contains_cp(only_utf8_locale, c);
9123 if (UNICODE_IS_SUPER(c)
9125 & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
9127 && ckWARN_d(WARN_NON_UNICODE))
9129 Perl_warner(aTHX_ packWARN(WARN_NON_UNICODE),
9130 "Matched non-Unicode code point 0x%04"UVXf" against Unicode property; may not be portable", c);
9134 #if ANYOF_INVERT != 1
9135 /* Depending on compiler optimization cBOOL takes time, so if don't have to
9137 # error ANYOF_INVERT needs to be set to 1, or guarded with cBOOL below,
9140 /* The xor complements the return if to invert: 1^1 = 0, 1^0 = 1 */
9141 return (flags & ANYOF_INVERT) ^ match;
9145 S_reghop3(U8 *s, SSize_t off, const U8* lim)
9147 /* return the position 'off' UTF-8 characters away from 's', forward if
9148 * 'off' >= 0, backwards if negative. But don't go outside of position
9149 * 'lim', which better be < s if off < 0 */
9151 PERL_ARGS_ASSERT_REGHOP3;
9154 while (off-- && s < lim) {
9155 /* XXX could check well-formedness here */
9160 while (off++ && s > lim) {
9162 if (UTF8_IS_CONTINUED(*s)) {
9163 while (s > lim && UTF8_IS_CONTINUATION(*s))
9165 if (! UTF8_IS_START(*s)) {
9166 Perl_croak_nocontext("Malformed UTF-8 character (fatal)");
9169 /* XXX could check well-formedness here */
9176 S_reghop4(U8 *s, SSize_t off, const U8* llim, const U8* rlim)
9178 PERL_ARGS_ASSERT_REGHOP4;
9181 while (off-- && s < rlim) {
9182 /* XXX could check well-formedness here */
9187 while (off++ && s > llim) {
9189 if (UTF8_IS_CONTINUED(*s)) {
9190 while (s > llim && UTF8_IS_CONTINUATION(*s))
9192 if (! UTF8_IS_START(*s)) {
9193 Perl_croak_nocontext("Malformed UTF-8 character (fatal)");
9196 /* XXX could check well-formedness here */
9202 /* like reghop3, but returns NULL on overrun, rather than returning last
9206 S_reghopmaybe3(U8* s, SSize_t off, const U8* lim)
9208 PERL_ARGS_ASSERT_REGHOPMAYBE3;
9211 while (off-- && s < lim) {
9212 /* XXX could check well-formedness here */
9219 while (off++ && s > lim) {
9221 if (UTF8_IS_CONTINUED(*s)) {
9222 while (s > lim && UTF8_IS_CONTINUATION(*s))
9224 if (! UTF8_IS_START(*s)) {
9225 Perl_croak_nocontext("Malformed UTF-8 character (fatal)");
9228 /* XXX could check well-formedness here */
9237 /* when executing a regex that may have (?{}), extra stuff needs setting
9238 up that will be visible to the called code, even before the current
9239 match has finished. In particular:
9241 * $_ is localised to the SV currently being matched;
9242 * pos($_) is created if necessary, ready to be updated on each call-out
9244 * a fake PMOP is created that can be set to PL_curpm (normally PL_curpm
9245 isn't set until the current pattern is successfully finished), so that
9246 $1 etc of the match-so-far can be seen;
9247 * save the old values of subbeg etc of the current regex, and set then
9248 to the current string (again, this is normally only done at the end
9253 S_setup_eval_state(pTHX_ regmatch_info *const reginfo)
9256 regexp *const rex = ReANY(reginfo->prog);
9257 regmatch_info_aux_eval *eval_state = reginfo->info_aux_eval;
9259 eval_state->rex = rex;
9262 /* Make $_ available to executed code. */
9263 if (reginfo->sv != DEFSV) {
9265 DEFSV_set(reginfo->sv);
9268 if (!(mg = mg_find_mglob(reginfo->sv))) {
9269 /* prepare for quick setting of pos */
9270 mg = sv_magicext_mglob(reginfo->sv);
9273 eval_state->pos_magic = mg;
9274 eval_state->pos = mg->mg_len;
9275 eval_state->pos_flags = mg->mg_flags;
9278 eval_state->pos_magic = NULL;
9280 if (!PL_reg_curpm) {
9281 /* PL_reg_curpm is a fake PMOP that we can attach the current
9282 * regex to and point PL_curpm at, so that $1 et al are visible
9283 * within a /(?{})/. It's just allocated once per interpreter the
9284 * first time its needed */
9285 Newxz(PL_reg_curpm, 1, PMOP);
9288 SV* const repointer = &PL_sv_undef;
9289 /* this regexp is also owned by the new PL_reg_curpm, which
9290 will try to free it. */
9291 av_push(PL_regex_padav, repointer);
9292 PL_reg_curpm->op_pmoffset = av_tindex(PL_regex_padav);
9293 PL_regex_pad = AvARRAY(PL_regex_padav);
9297 SET_reg_curpm(reginfo->prog);
9298 eval_state->curpm = PL_curpm;
9299 PL_curpm = PL_reg_curpm;
9300 if (RXp_MATCH_COPIED(rex)) {
9301 /* Here is a serious problem: we cannot rewrite subbeg,
9302 since it may be needed if this match fails. Thus
9303 $` inside (?{}) could fail... */
9304 eval_state->subbeg = rex->subbeg;
9305 eval_state->sublen = rex->sublen;
9306 eval_state->suboffset = rex->suboffset;
9307 eval_state->subcoffset = rex->subcoffset;
9309 eval_state->saved_copy = rex->saved_copy;
9311 RXp_MATCH_COPIED_off(rex);
9314 eval_state->subbeg = NULL;
9315 rex->subbeg = (char *)reginfo->strbeg;
9317 rex->subcoffset = 0;
9318 rex->sublen = reginfo->strend - reginfo->strbeg;
9322 /* destructor to clear up regmatch_info_aux and regmatch_info_aux_eval */
9325 S_cleanup_regmatch_info_aux(pTHX_ void *arg)
9327 regmatch_info_aux *aux = (regmatch_info_aux *) arg;
9328 regmatch_info_aux_eval *eval_state = aux->info_aux_eval;
9331 Safefree(aux->poscache);
9335 /* undo the effects of S_setup_eval_state() */
9337 if (eval_state->subbeg) {
9338 regexp * const rex = eval_state->rex;
9339 rex->subbeg = eval_state->subbeg;
9340 rex->sublen = eval_state->sublen;
9341 rex->suboffset = eval_state->suboffset;
9342 rex->subcoffset = eval_state->subcoffset;
9344 rex->saved_copy = eval_state->saved_copy;
9346 RXp_MATCH_COPIED_on(rex);
9348 if (eval_state->pos_magic)
9350 eval_state->pos_magic->mg_len = eval_state->pos;
9351 eval_state->pos_magic->mg_flags =
9352 (eval_state->pos_magic->mg_flags & ~MGf_BYTES)
9353 | (eval_state->pos_flags & MGf_BYTES);
9356 PL_curpm = eval_state->curpm;
9359 PL_regmatch_state = aux->old_regmatch_state;
9360 PL_regmatch_slab = aux->old_regmatch_slab;
9362 /* free all slabs above current one - this must be the last action
9363 * of this function, as aux and eval_state are allocated within
9364 * slabs and may be freed here */
9366 s = PL_regmatch_slab->next;
9368 PL_regmatch_slab->next = NULL;
9370 regmatch_slab * const osl = s;
9379 S_to_utf8_substr(pTHX_ regexp *prog)
9381 /* Converts substr fields in prog from bytes to UTF-8, calling fbm_compile
9382 * on the converted value */
9386 PERL_ARGS_ASSERT_TO_UTF8_SUBSTR;
9389 if (prog->substrs->data[i].substr
9390 && !prog->substrs->data[i].utf8_substr) {
9391 SV* const sv = newSVsv(prog->substrs->data[i].substr);
9392 prog->substrs->data[i].utf8_substr = sv;
9393 sv_utf8_upgrade(sv);
9394 if (SvVALID(prog->substrs->data[i].substr)) {
9395 if (SvTAIL(prog->substrs->data[i].substr)) {
9396 /* Trim the trailing \n that fbm_compile added last
9398 SvCUR_set(sv, SvCUR(sv) - 1);
9399 /* Whilst this makes the SV technically "invalid" (as its
9400 buffer is no longer followed by "\0") when fbm_compile()
9401 adds the "\n" back, a "\0" is restored. */
9402 fbm_compile(sv, FBMcf_TAIL);
9406 if (prog->substrs->data[i].substr == prog->check_substr)
9407 prog->check_utf8 = sv;
9413 S_to_byte_substr(pTHX_ regexp *prog)
9415 /* Converts substr fields in prog from UTF-8 to bytes, calling fbm_compile
9416 * on the converted value; returns FALSE if can't be converted. */
9420 PERL_ARGS_ASSERT_TO_BYTE_SUBSTR;
9423 if (prog->substrs->data[i].utf8_substr
9424 && !prog->substrs->data[i].substr) {
9425 SV* sv = newSVsv(prog->substrs->data[i].utf8_substr);
9426 if (! sv_utf8_downgrade(sv, TRUE)) {
9429 if (SvVALID(prog->substrs->data[i].utf8_substr)) {
9430 if (SvTAIL(prog->substrs->data[i].utf8_substr)) {
9431 /* Trim the trailing \n that fbm_compile added last
9433 SvCUR_set(sv, SvCUR(sv) - 1);
9434 fbm_compile(sv, FBMcf_TAIL);
9438 prog->substrs->data[i].substr = sv;
9439 if (prog->substrs->data[i].utf8_substr == prog->check_utf8)
9440 prog->check_substr = sv;
9448 * ex: set ts=8 sts=4 sw=4 et: