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 if 'c', the character being looke-up, is an invariant under
111 * UTF-8: it avoids the reginclass call if there are no complications: i.e., if
112 * everything matchable is straight forward in the bitmap */
113 #define REGINCLASS(prog,p,c,u) (ANYOF_FLAGS(p) \
114 ? reginclass(prog,p,c,c+1,u) \
115 : ANYOF_BITMAP_TEST(p,*(c)))
121 #define CHR_SVLEN(sv) (utf8_target ? sv_len_utf8(sv) : SvCUR(sv))
122 #define CHR_DIST(a,b) (reginfo->is_utf8_target ? utf8_distance(a,b) : a - b)
124 #define HOPc(pos,off) \
125 (char *)(reginfo->is_utf8_target \
126 ? reghop3((U8*)pos, off, \
127 (U8*)(off >= 0 ? reginfo->strend : reginfo->strbeg)) \
130 #define HOPBACKc(pos, off) \
131 (char*)(reginfo->is_utf8_target \
132 ? reghopmaybe3((U8*)pos, -off, (U8*)(reginfo->strbeg)) \
133 : (pos - off >= reginfo->strbeg) \
137 #define HOP3(pos,off,lim) (reginfo->is_utf8_target ? reghop3((U8*)(pos), off, (U8*)(lim)) : (U8*)(pos + off))
138 #define HOP3c(pos,off,lim) ((char*)HOP3(pos,off,lim))
140 /* lim must be +ve. Returns NULL on overshoot */
141 #define HOPMAYBE3(pos,off,lim) \
142 (reginfo->is_utf8_target \
143 ? reghopmaybe3((U8*)pos, off, (U8*)(lim)) \
144 : ((U8*)pos + off <= lim) \
148 /* like HOP3, but limits the result to <= lim even for the non-utf8 case.
149 * off must be >=0; args should be vars rather than expressions */
150 #define HOP3lim(pos,off,lim) (reginfo->is_utf8_target \
151 ? reghop3((U8*)(pos), off, (U8*)(lim)) \
152 : (U8*)((pos + off) > lim ? lim : (pos + off)))
154 #define HOP4(pos,off,llim, rlim) (reginfo->is_utf8_target \
155 ? reghop4((U8*)(pos), off, (U8*)(llim), (U8*)(rlim)) \
157 #define HOP4c(pos,off,llim, rlim) ((char*)HOP4(pos,off,llim, rlim))
159 #define NEXTCHR_EOS -10 /* nextchr has fallen off the end */
160 #define NEXTCHR_IS_EOS (nextchr < 0)
162 #define SET_nextchr \
163 nextchr = ((locinput < reginfo->strend) ? UCHARAT(locinput) : NEXTCHR_EOS)
165 #define SET_locinput(p) \
170 #define LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist) STMT_START { \
172 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST; \
173 swash_ptr = _core_swash_init("utf8", property_name, &PL_sv_undef, \
174 1, 0, invlist, &flags); \
179 /* If in debug mode, we test that a known character properly matches */
181 # define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
184 utf8_char_in_property) \
185 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist); \
186 assert(swash_fetch(swash_ptr, (U8 *) utf8_char_in_property, TRUE));
188 # define LOAD_UTF8_CHARCLASS_DEBUG_TEST(swash_ptr, \
191 utf8_char_in_property) \
192 LOAD_UTF8_CHARCLASS(swash_ptr, property_name, invlist)
195 #define LOAD_UTF8_CHARCLASS_ALNUM() LOAD_UTF8_CHARCLASS_DEBUG_TEST( \
196 PL_utf8_swash_ptrs[_CC_WORDCHAR], \
198 PL_XPosix_ptrs[_CC_WORDCHAR], \
199 LATIN_SMALL_LIGATURE_LONG_S_T_UTF8);
201 #define PLACEHOLDER /* Something for the preprocessor to grab onto */
202 /* TODO: Combine JUMPABLE and HAS_TEXT to cache OP(rn) */
204 /* for use after a quantifier and before an EXACT-like node -- japhy */
205 /* it would be nice to rework regcomp.sym to generate this stuff. sigh
207 * NOTE that *nothing* that affects backtracking should be in here, specifically
208 * VERBS must NOT be included. JUMPABLE is used to determine if we can ignore a
209 * node that is in between two EXACT like nodes when ascertaining what the required
210 * "follow" character is. This should probably be moved to regex compile time
211 * although it may be done at run time beause of the REF possibility - more
212 * investigation required. -- demerphq
214 #define JUMPABLE(rn) ( \
216 (OP(rn) == CLOSE && (!cur_eval || cur_eval->u.eval.close_paren != ARG(rn))) || \
218 OP(rn) == SUSPEND || OP(rn) == IFMATCH || \
219 OP(rn) == PLUS || OP(rn) == MINMOD || \
221 (PL_regkind[OP(rn)] == CURLY && ARG1(rn) > 0) \
223 #define IS_EXACT(rn) (PL_regkind[OP(rn)] == EXACT)
225 #define HAS_TEXT(rn) ( IS_EXACT(rn) || PL_regkind[OP(rn)] == REF )
228 /* Currently these are only used when PL_regkind[OP(rn)] == EXACT so
229 we don't need this definition. XXX These are now out-of-sync*/
230 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==REF || OP(rn)==NREF )
231 #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 )
232 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL || OP(rn)==REFFL || OP(rn)==NREFFL )
235 /* ... so we use this as its faster. */
236 #define IS_TEXT(rn) ( OP(rn)==EXACT || OP(rn)==EXACTL )
237 #define IS_TEXTFU(rn) ( OP(rn)==EXACTFU || OP(rn)==EXACTFLU8 || OP(rn)==EXACTFU_SS || OP(rn) == EXACTFA || OP(rn) == EXACTFA_NO_TRIE)
238 #define IS_TEXTF(rn) ( OP(rn)==EXACTF )
239 #define IS_TEXTFL(rn) ( OP(rn)==EXACTFL )
244 Search for mandatory following text node; for lookahead, the text must
245 follow but for lookbehind (rn->flags != 0) we skip to the next step.
247 #define FIND_NEXT_IMPT(rn) STMT_START { \
248 while (JUMPABLE(rn)) { \
249 const OPCODE type = OP(rn); \
250 if (type == SUSPEND || PL_regkind[type] == CURLY) \
251 rn = NEXTOPER(NEXTOPER(rn)); \
252 else if (type == PLUS) \
254 else if (type == IFMATCH) \
255 rn = (rn->flags == 0) ? NEXTOPER(NEXTOPER(rn)) : rn + ARG(rn); \
256 else rn += NEXT_OFF(rn); \
260 #define SLAB_FIRST(s) (&(s)->states[0])
261 #define SLAB_LAST(s) (&(s)->states[PERL_REGMATCH_SLAB_SLOTS-1])
263 static void S_setup_eval_state(pTHX_ regmatch_info *const reginfo);
264 static void S_cleanup_regmatch_info_aux(pTHX_ void *arg);
265 static regmatch_state * S_push_slab(pTHX);
267 #define REGCP_PAREN_ELEMS 3
268 #define REGCP_OTHER_ELEMS 3
269 #define REGCP_FRAME_ELEMS 1
270 /* REGCP_FRAME_ELEMS are not part of the REGCP_OTHER_ELEMS and
271 * are needed for the regexp context stack bookkeeping. */
274 S_regcppush(pTHX_ const regexp *rex, I32 parenfloor, U32 maxopenparen)
276 const int retval = PL_savestack_ix;
277 const int paren_elems_to_push =
278 (maxopenparen - parenfloor) * REGCP_PAREN_ELEMS;
279 const UV total_elems = paren_elems_to_push + REGCP_OTHER_ELEMS;
280 const UV elems_shifted = total_elems << SAVE_TIGHT_SHIFT;
282 GET_RE_DEBUG_FLAGS_DECL;
284 PERL_ARGS_ASSERT_REGCPPUSH;
286 if (paren_elems_to_push < 0)
287 Perl_croak(aTHX_ "panic: paren_elems_to_push, %i < 0, maxopenparen: %i parenfloor: %i REGCP_PAREN_ELEMS: %u",
288 (int)paren_elems_to_push, (int)maxopenparen,
289 (int)parenfloor, (unsigned)REGCP_PAREN_ELEMS);
291 if ((elems_shifted >> SAVE_TIGHT_SHIFT) != total_elems)
292 Perl_croak(aTHX_ "panic: paren_elems_to_push offset %"UVuf
293 " out of range (%lu-%ld)",
295 (unsigned long)maxopenparen,
298 SSGROW(total_elems + REGCP_FRAME_ELEMS);
301 if ((int)maxopenparen > (int)parenfloor)
302 PerlIO_printf(Perl_debug_log,
303 "rex=0x%"UVxf" offs=0x%"UVxf": saving capture indices:\n",
308 for (p = parenfloor+1; p <= (I32)maxopenparen; p++) {
309 /* REGCP_PARENS_ELEMS are pushed per pairs of parentheses. */
310 SSPUSHIV(rex->offs[p].end);
311 SSPUSHIV(rex->offs[p].start);
312 SSPUSHINT(rex->offs[p].start_tmp);
313 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
314 " \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"\n",
316 (IV)rex->offs[p].start,
317 (IV)rex->offs[p].start_tmp,
321 /* REGCP_OTHER_ELEMS are pushed in any case, parentheses or no. */
322 SSPUSHINT(maxopenparen);
323 SSPUSHINT(rex->lastparen);
324 SSPUSHINT(rex->lastcloseparen);
325 SSPUSHUV(SAVEt_REGCONTEXT | elems_shifted); /* Magic cookie. */
330 /* These are needed since we do not localize EVAL nodes: */
331 #define REGCP_SET(cp) \
333 PerlIO_printf(Perl_debug_log, \
334 " Setting an EVAL scope, savestack=%"IVdf"\n", \
335 (IV)PL_savestack_ix)); \
338 #define REGCP_UNWIND(cp) \
340 if (cp != PL_savestack_ix) \
341 PerlIO_printf(Perl_debug_log, \
342 " Clearing an EVAL scope, savestack=%"IVdf"..%"IVdf"\n", \
343 (IV)(cp), (IV)PL_savestack_ix)); \
346 #define UNWIND_PAREN(lp, lcp) \
347 for (n = rex->lastparen; n > lp; n--) \
348 rex->offs[n].end = -1; \
349 rex->lastparen = n; \
350 rex->lastcloseparen = lcp;
354 S_regcppop(pTHX_ regexp *rex, U32 *maxopenparen_p)
358 GET_RE_DEBUG_FLAGS_DECL;
360 PERL_ARGS_ASSERT_REGCPPOP;
362 /* Pop REGCP_OTHER_ELEMS before the parentheses loop starts. */
364 assert((i & SAVE_MASK) == SAVEt_REGCONTEXT); /* Check that the magic cookie is there. */
365 i >>= SAVE_TIGHT_SHIFT; /* Parentheses elements to pop. */
366 rex->lastcloseparen = SSPOPINT;
367 rex->lastparen = SSPOPINT;
368 *maxopenparen_p = SSPOPINT;
370 i -= REGCP_OTHER_ELEMS;
371 /* Now restore the parentheses context. */
373 if (i || rex->lastparen + 1 <= rex->nparens)
374 PerlIO_printf(Perl_debug_log,
375 "rex=0x%"UVxf" offs=0x%"UVxf": restoring capture indices to:\n",
380 paren = *maxopenparen_p;
381 for ( ; i > 0; i -= REGCP_PAREN_ELEMS) {
383 rex->offs[paren].start_tmp = SSPOPINT;
384 rex->offs[paren].start = SSPOPIV;
386 if (paren <= rex->lastparen)
387 rex->offs[paren].end = tmps;
388 DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
389 " \\%"UVuf": %"IVdf"(%"IVdf")..%"IVdf"%s\n",
391 (IV)rex->offs[paren].start,
392 (IV)rex->offs[paren].start_tmp,
393 (IV)rex->offs[paren].end,
394 (paren > rex->lastparen ? "(skipped)" : ""));
399 /* It would seem that the similar code in regtry()
400 * already takes care of this, and in fact it is in
401 * a better location to since this code can #if 0-ed out
402 * but the code in regtry() is needed or otherwise tests
403 * requiring null fields (pat.t#187 and split.t#{13,14}
404 * (as of patchlevel 7877) will fail. Then again,
405 * this code seems to be necessary or otherwise
406 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
407 * --jhi updated by dapm */
408 for (i = rex->lastparen + 1; i <= rex->nparens; i++) {
409 if (i > *maxopenparen_p)
410 rex->offs[i].start = -1;
411 rex->offs[i].end = -1;
412 DEBUG_BUFFERS_r( PerlIO_printf(Perl_debug_log,
413 " \\%"UVuf": %s ..-1 undeffing\n",
415 (i > *maxopenparen_p) ? "-1" : " "
421 /* restore the parens and associated vars at savestack position ix,
422 * but without popping the stack */
425 S_regcp_restore(pTHX_ regexp *rex, I32 ix, U32 *maxopenparen_p)
427 I32 tmpix = PL_savestack_ix;
428 PL_savestack_ix = ix;
429 regcppop(rex, maxopenparen_p);
430 PL_savestack_ix = tmpix;
433 #define regcpblow(cp) LEAVE_SCOPE(cp) /* Ignores regcppush()ed data. */
436 S_isFOO_lc(pTHX_ const U8 classnum, const U8 character)
438 /* Returns a boolean as to whether or not 'character' is a member of the
439 * Posix character class given by 'classnum' that should be equivalent to a
440 * value in the typedef '_char_class_number'.
442 * Ideally this could be replaced by a just an array of function pointers
443 * to the C library functions that implement the macros this calls.
444 * However, to compile, the precise function signatures are required, and
445 * these may vary from platform to to platform. To avoid having to figure
446 * out what those all are on each platform, I (khw) am using this method,
447 * which adds an extra layer of function call overhead (unless the C
448 * optimizer strips it away). But we don't particularly care about
449 * performance with locales anyway. */
451 switch ((_char_class_number) classnum) {
452 case _CC_ENUM_ALPHANUMERIC: return isALPHANUMERIC_LC(character);
453 case _CC_ENUM_ALPHA: return isALPHA_LC(character);
454 case _CC_ENUM_ASCII: return isASCII_LC(character);
455 case _CC_ENUM_BLANK: return isBLANK_LC(character);
456 case _CC_ENUM_CASED: return isLOWER_LC(character)
457 || isUPPER_LC(character);
458 case _CC_ENUM_CNTRL: return isCNTRL_LC(character);
459 case _CC_ENUM_DIGIT: return isDIGIT_LC(character);
460 case _CC_ENUM_GRAPH: return isGRAPH_LC(character);
461 case _CC_ENUM_LOWER: return isLOWER_LC(character);
462 case _CC_ENUM_PRINT: return isPRINT_LC(character);
463 case _CC_ENUM_PUNCT: return isPUNCT_LC(character);
464 case _CC_ENUM_SPACE: return isSPACE_LC(character);
465 case _CC_ENUM_UPPER: return isUPPER_LC(character);
466 case _CC_ENUM_WORDCHAR: return isWORDCHAR_LC(character);
467 case _CC_ENUM_XDIGIT: return isXDIGIT_LC(character);
468 default: /* VERTSPACE should never occur in locales */
469 Perl_croak(aTHX_ "panic: isFOO_lc() has an unexpected character class '%d'", classnum);
472 NOT_REACHED; /* NOTREACHED */
477 S_isFOO_utf8_lc(pTHX_ const U8 classnum, const U8* character)
479 /* Returns a boolean as to whether or not the (well-formed) UTF-8-encoded
480 * 'character' is a member of the Posix character class given by 'classnum'
481 * that should be equivalent to a value in the typedef
482 * '_char_class_number'.
484 * This just calls isFOO_lc on the code point for the character if it is in
485 * the range 0-255. Outside that range, all characters use Unicode
486 * rules, ignoring any locale. So use the Unicode function if this class
487 * requires a swash, and use the Unicode macro otherwise. */
489 PERL_ARGS_ASSERT_ISFOO_UTF8_LC;
491 if (UTF8_IS_INVARIANT(*character)) {
492 return isFOO_lc(classnum, *character);
494 else if (UTF8_IS_DOWNGRADEABLE_START(*character)) {
495 return isFOO_lc(classnum,
496 EIGHT_BIT_UTF8_TO_NATIVE(*character, *(character + 1)));
499 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(character, character + UTF8SKIP(character));
501 if (classnum < _FIRST_NON_SWASH_CC) {
503 /* Initialize the swash unless done already */
504 if (! PL_utf8_swash_ptrs[classnum]) {
505 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
506 PL_utf8_swash_ptrs[classnum] =
507 _core_swash_init("utf8",
510 PL_XPosix_ptrs[classnum], &flags);
513 return cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum], (U8 *)
515 TRUE /* is UTF */ ));
518 switch ((_char_class_number) classnum) {
519 case _CC_ENUM_SPACE: return is_XPERLSPACE_high(character);
520 case _CC_ENUM_BLANK: return is_HORIZWS_high(character);
521 case _CC_ENUM_XDIGIT: return is_XDIGIT_high(character);
522 case _CC_ENUM_VERTSPACE: return is_VERTWS_high(character);
526 return FALSE; /* Things like CNTRL are always below 256 */
530 * pregexec and friends
533 #ifndef PERL_IN_XSUB_RE
535 - pregexec - match a regexp against a string
538 Perl_pregexec(pTHX_ REGEXP * const prog, char* stringarg, char *strend,
539 char *strbeg, SSize_t minend, SV *screamer, U32 nosave)
540 /* stringarg: the point in the string at which to begin matching */
541 /* strend: pointer to null at end of string */
542 /* strbeg: real beginning of string */
543 /* minend: end of match must be >= minend bytes after stringarg. */
544 /* screamer: SV being matched: only used for utf8 flag, pos() etc; string
545 * itself is accessed via the pointers above */
546 /* nosave: For optimizations. */
548 PERL_ARGS_ASSERT_PREGEXEC;
551 regexec_flags(prog, stringarg, strend, strbeg, minend, screamer, NULL,
552 nosave ? 0 : REXEC_COPY_STR);
558 /* re_intuit_start():
560 * Based on some optimiser hints, try to find the earliest position in the
561 * string where the regex could match.
563 * rx: the regex to match against
564 * sv: the SV being matched: only used for utf8 flag; the string
565 * itself is accessed via the pointers below. Note that on
566 * something like an overloaded SV, SvPOK(sv) may be false
567 * and the string pointers may point to something unrelated to
569 * strbeg: real beginning of string
570 * strpos: the point in the string at which to begin matching
571 * strend: pointer to the byte following the last char of the string
572 * flags currently unused; set to 0
573 * data: currently unused; set to NULL
575 * The basic idea of re_intuit_start() is to use some known information
576 * about the pattern, namely:
578 * a) the longest known anchored substring (i.e. one that's at a
579 * constant offset from the beginning of the pattern; but not
580 * necessarily at a fixed offset from the beginning of the
582 * b) the longest floating substring (i.e. one that's not at a constant
583 * offset from the beginning of the pattern);
584 * c) Whether the pattern is anchored to the string; either
585 * an absolute anchor: /^../, or anchored to \n: /^.../m,
586 * or anchored to pos(): /\G/;
587 * d) A start class: a real or synthetic character class which
588 * represents which characters are legal at the start of the pattern;
590 * to either quickly reject the match, or to find the earliest position
591 * within the string at which the pattern might match, thus avoiding
592 * running the full NFA engine at those earlier locations, only to
593 * eventually fail and retry further along.
595 * Returns NULL if the pattern can't match, or returns the address within
596 * the string which is the earliest place the match could occur.
598 * The longest of the anchored and floating substrings is called 'check'
599 * and is checked first. The other is called 'other' and is checked
600 * second. The 'other' substring may not be present. For example,
602 * /(abc|xyz)ABC\d{0,3}DEFG/
606 * check substr (float) = "DEFG", offset 6..9 chars
607 * other substr (anchored) = "ABC", offset 3..3 chars
610 * Be aware that during the course of this function, sometimes 'anchored'
611 * refers to a substring being anchored relative to the start of the
612 * pattern, and sometimes to the pattern itself being anchored relative to
613 * the string. For example:
615 * /\dabc/: "abc" is anchored to the pattern;
616 * /^\dabc/: "abc" is anchored to the pattern and the string;
617 * /\d+abc/: "abc" is anchored to neither the pattern nor the string;
618 * /^\d+abc/: "abc" is anchored to neither the pattern nor the string,
619 * but the pattern is anchored to the string.
623 Perl_re_intuit_start(pTHX_
626 const char * const strbeg,
630 re_scream_pos_data *data)
632 struct regexp *const prog = ReANY(rx);
633 SSize_t start_shift = prog->check_offset_min;
634 /* Should be nonnegative! */
635 SSize_t end_shift = 0;
636 /* current lowest pos in string where the regex can start matching */
637 char *rx_origin = strpos;
639 const bool utf8_target = (sv && SvUTF8(sv)) ? 1 : 0; /* if no sv we have to assume bytes */
640 U8 other_ix = 1 - prog->substrs->check_ix;
642 char *other_last = strpos;/* latest pos 'other' substr already checked to */
643 char *check_at = NULL; /* check substr found at this pos */
644 const I32 multiline = prog->extflags & RXf_PMf_MULTILINE;
645 RXi_GET_DECL(prog,progi);
646 regmatch_info reginfo_buf; /* create some info to pass to find_byclass */
647 regmatch_info *const reginfo = ®info_buf;
648 GET_RE_DEBUG_FLAGS_DECL;
650 PERL_ARGS_ASSERT_RE_INTUIT_START;
651 PERL_UNUSED_ARG(flags);
652 PERL_UNUSED_ARG(data);
654 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
655 "Intuit: trying to determine minimum start position...\n"));
657 /* for now, assume that all substr offsets are positive. If at some point
658 * in the future someone wants to do clever things with lookbehind and
659 * -ve offsets, they'll need to fix up any code in this function
660 * which uses these offsets. See the thread beginning
661 * <20140113145929.GF27210@iabyn.com>
663 assert(prog->substrs->data[0].min_offset >= 0);
664 assert(prog->substrs->data[0].max_offset >= 0);
665 assert(prog->substrs->data[1].min_offset >= 0);
666 assert(prog->substrs->data[1].max_offset >= 0);
667 assert(prog->substrs->data[2].min_offset >= 0);
668 assert(prog->substrs->data[2].max_offset >= 0);
670 /* for now, assume that if both present, that the floating substring
671 * doesn't start before the anchored substring.
672 * If you break this assumption (e.g. doing better optimisations
673 * with lookahead/behind), then you'll need to audit the code in this
674 * function carefully first
677 ! ( (prog->anchored_utf8 || prog->anchored_substr)
678 && (prog->float_utf8 || prog->float_substr))
679 || (prog->float_min_offset >= prog->anchored_offset));
681 /* byte rather than char calculation for efficiency. It fails
682 * to quickly reject some cases that can't match, but will reject
683 * them later after doing full char arithmetic */
684 if (prog->minlen > strend - strpos) {
685 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
686 " String too short...\n"));
690 RX_MATCH_UTF8_set(rx,utf8_target);
691 reginfo->is_utf8_target = cBOOL(utf8_target);
692 reginfo->info_aux = NULL;
693 reginfo->strbeg = strbeg;
694 reginfo->strend = strend;
695 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
697 /* not actually used within intuit, but zero for safety anyway */
698 reginfo->poscache_maxiter = 0;
701 if (!prog->check_utf8 && prog->check_substr)
702 to_utf8_substr(prog);
703 check = prog->check_utf8;
705 if (!prog->check_substr && prog->check_utf8) {
706 if (! to_byte_substr(prog)) {
707 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(fail);
710 check = prog->check_substr;
713 /* dump the various substring data */
714 DEBUG_OPTIMISE_MORE_r({
716 for (i=0; i<=2; i++) {
717 SV *sv = (utf8_target ? prog->substrs->data[i].utf8_substr
718 : prog->substrs->data[i].substr);
722 PerlIO_printf(Perl_debug_log,
723 " substrs[%d]: min=%"IVdf" max=%"IVdf" end shift=%"IVdf
724 " useful=%"IVdf" utf8=%d [%s]\n",
726 (IV)prog->substrs->data[i].min_offset,
727 (IV)prog->substrs->data[i].max_offset,
728 (IV)prog->substrs->data[i].end_shift,
735 if (prog->intflags & PREGf_ANCH) { /* Match at \G, beg-of-str or after \n */
737 /* ml_anch: check after \n?
739 * A note about PREGf_IMPLICIT: on an un-anchored pattern beginning
740 * with /.*.../, these flags will have been added by the
742 * /.*abc/, /.*abc/m: PREGf_IMPLICIT | PREGf_ANCH_MBOL
743 * /.*abc/s: PREGf_IMPLICIT | PREGf_ANCH_SBOL
745 ml_anch = (prog->intflags & PREGf_ANCH_MBOL)
746 && !(prog->intflags & PREGf_IMPLICIT);
748 if (!ml_anch && !(prog->intflags & PREGf_IMPLICIT)) {
749 /* we are only allowed to match at BOS or \G */
751 /* trivially reject if there's a BOS anchor and we're not at BOS.
753 * Note that we don't try to do a similar quick reject for
754 * \G, since generally the caller will have calculated strpos
755 * based on pos() and gofs, so the string is already correctly
756 * anchored by definition; and handling the exceptions would
757 * be too fiddly (e.g. REXEC_IGNOREPOS).
759 if ( strpos != strbeg
760 && (prog->intflags & PREGf_ANCH_SBOL))
762 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
763 " Not at start...\n"));
767 /* in the presence of an anchor, the anchored (relative to the
768 * start of the regex) substr must also be anchored relative
769 * to strpos. So quickly reject if substr isn't found there.
770 * This works for \G too, because the caller will already have
771 * subtracted gofs from pos, and gofs is the offset from the
772 * \G to the start of the regex. For example, in /.abc\Gdef/,
773 * where substr="abcdef", pos()=3, gofs=4, offset_min=1:
774 * caller will have set strpos=pos()-4; we look for the substr
775 * at position pos()-4+1, which lines up with the "a" */
777 if (prog->check_offset_min == prog->check_offset_max) {
778 /* Substring at constant offset from beg-of-str... */
779 SSize_t slen = SvCUR(check);
780 char *s = HOP3c(strpos, prog->check_offset_min, strend);
782 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
783 " Looking for check substr at fixed offset %"IVdf"...\n",
784 (IV)prog->check_offset_min));
787 /* In this case, the regex is anchored at the end too.
788 * Unless it's a multiline match, the lengths must match
789 * exactly, give or take a \n. NB: slen >= 1 since
790 * the last char of check is \n */
792 && ( strend - s > slen
793 || strend - s < slen - 1
794 || (strend - s == slen && strend[-1] != '\n')))
796 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
797 " String too long...\n"));
800 /* Now should match s[0..slen-2] */
803 if (slen && (*SvPVX_const(check) != *s
804 || (slen > 1 && memNE(SvPVX_const(check), s, slen))))
806 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
807 " String not equal...\n"));
812 goto success_at_start;
817 end_shift = prog->check_end_shift;
819 #ifdef DEBUGGING /* 7/99: reports of failure (with the older version) */
821 Perl_croak(aTHX_ "panic: end_shift: %"IVdf" pattern:\n%s\n ",
822 (IV)end_shift, RX_PRECOMP(prog));
827 /* This is the (re)entry point of the main loop in this function.
828 * The goal of this loop is to:
829 * 1) find the "check" substring in the region rx_origin..strend
830 * (adjusted by start_shift / end_shift). If not found, reject
832 * 2) If it exists, look for the "other" substr too if defined; for
833 * example, if the check substr maps to the anchored substr, then
834 * check the floating substr, and vice-versa. If not found, go
835 * back to (1) with rx_origin suitably incremented.
836 * 3) If we find an rx_origin position that doesn't contradict
837 * either of the substrings, then check the possible additional
838 * constraints on rx_origin of /^.../m or a known start class.
839 * If these fail, then depending on which constraints fail, jump
840 * back to here, or to various other re-entry points further along
841 * that skip some of the first steps.
842 * 4) If we pass all those tests, update the BmUSEFUL() count on the
843 * substring. If the start position was determined to be at the
844 * beginning of the string - so, not rejected, but not optimised,
845 * since we have to run regmatch from position 0 - decrement the
846 * BmUSEFUL() count. Otherwise increment it.
850 /* first, look for the 'check' substring */
856 DEBUG_OPTIMISE_MORE_r({
857 PerlIO_printf(Perl_debug_log,
858 " At restart: rx_origin=%"IVdf" Check offset min: %"IVdf
859 " Start shift: %"IVdf" End shift %"IVdf
860 " Real end Shift: %"IVdf"\n",
861 (IV)(rx_origin - strbeg),
862 (IV)prog->check_offset_min,
865 (IV)prog->check_end_shift);
868 end_point = HOP3(strend, -end_shift, strbeg);
869 start_point = HOPMAYBE3(rx_origin, start_shift, end_point);
874 /* If the regex is absolutely anchored to either the start of the
875 * string (SBOL) or to pos() (ANCH_GPOS), then
876 * check_offset_max represents an upper bound on the string where
877 * the substr could start. For the ANCH_GPOS case, we assume that
878 * the caller of intuit will have already set strpos to
879 * pos()-gofs, so in this case strpos + offset_max will still be
880 * an upper bound on the substr.
883 && prog->intflags & PREGf_ANCH
884 && prog->check_offset_max != SSize_t_MAX)
886 SSize_t len = SvCUR(check) - !!SvTAIL(check);
887 const char * const anchor =
888 (prog->intflags & PREGf_ANCH_GPOS ? strpos : strbeg);
890 /* do a bytes rather than chars comparison. It's conservative;
891 * so it skips doing the HOP if the result can't possibly end
892 * up earlier than the old value of end_point.
894 if ((char*)end_point - anchor > prog->check_offset_max) {
895 end_point = HOP3lim((U8*)anchor,
896 prog->check_offset_max,
902 check_at = fbm_instr( start_point, end_point,
903 check, multiline ? FBMrf_MULTILINE : 0);
905 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
906 " doing 'check' fbm scan, [%"IVdf"..%"IVdf"] gave %"IVdf"\n",
907 (IV)((char*)start_point - strbeg),
908 (IV)((char*)end_point - strbeg),
909 (IV)(check_at ? check_at - strbeg : -1)
912 /* Update the count-of-usability, remove useless subpatterns,
916 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
917 SvPVX_const(check), RE_SV_DUMPLEN(check), 30);
918 PerlIO_printf(Perl_debug_log, " %s %s substr %s%s%s",
919 (check_at ? "Found" : "Did not find"),
920 (check == (utf8_target ? prog->anchored_utf8 : prog->anchored_substr)
921 ? "anchored" : "floating"),
924 (check_at ? " at offset " : "...\n") );
929 /* set rx_origin to the minimum position where the regex could start
930 * matching, given the constraint of the just-matched check substring.
931 * But don't set it lower than previously.
934 if (check_at - rx_origin > prog->check_offset_max)
935 rx_origin = HOP3c(check_at, -prog->check_offset_max, rx_origin);
936 /* Finish the diagnostic message */
937 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
938 "%ld (rx_origin now %"IVdf")...\n",
939 (long)(check_at - strbeg),
940 (IV)(rx_origin - strbeg)
945 /* now look for the 'other' substring if defined */
947 if (utf8_target ? prog->substrs->data[other_ix].utf8_substr
948 : prog->substrs->data[other_ix].substr)
950 /* Take into account the "other" substring. */
954 struct reg_substr_datum *other;
957 other = &prog->substrs->data[other_ix];
959 /* if "other" is anchored:
960 * we've previously found a floating substr starting at check_at.
961 * This means that the regex origin must lie somewhere
962 * between min (rx_origin): HOP3(check_at, -check_offset_max)
963 * and max: HOP3(check_at, -check_offset_min)
964 * (except that min will be >= strpos)
965 * So the fixed substr must lie somewhere between
966 * HOP3(min, anchored_offset)
967 * HOP3(max, anchored_offset) + SvCUR(substr)
970 /* if "other" is floating
971 * Calculate last1, the absolute latest point where the
972 * floating substr could start in the string, ignoring any
973 * constraints from the earlier fixed match. It is calculated
976 * strend - prog->minlen (in chars) is the absolute latest
977 * position within the string where the origin of the regex
978 * could appear. The latest start point for the floating
979 * substr is float_min_offset(*) on from the start of the
980 * regex. last1 simply combines thee two offsets.
982 * (*) You might think the latest start point should be
983 * float_max_offset from the regex origin, and technically
984 * you'd be correct. However, consider
986 * Here, float min, max are 3,5 and minlen is 7.
987 * This can match either
991 * In the first case, the regex matches minlen chars; in the
992 * second, minlen+1, in the third, minlen+2.
993 * In the first case, the floating offset is 3 (which equals
994 * float_min), in the second, 4, and in the third, 5 (which
995 * equals float_max). In all cases, the floating string bcd
996 * can never start more than 4 chars from the end of the
997 * string, which equals minlen - float_min. As the substring
998 * starts to match more than float_min from the start of the
999 * regex, it makes the regex match more than minlen chars,
1000 * and the two cancel each other out. So we can always use
1001 * float_min - minlen, rather than float_max - minlen for the
1002 * latest position in the string.
1004 * Note that -minlen + float_min_offset is equivalent (AFAIKT)
1005 * to CHR_SVLEN(must) - !!SvTAIL(must) + prog->float_end_shift
1008 assert(prog->minlen >= other->min_offset);
1009 last1 = HOP3c(strend,
1010 other->min_offset - prog->minlen, strbeg);
1012 if (other_ix) {/* i.e. if (other-is-float) */
1013 /* last is the latest point where the floating substr could
1014 * start, *given* any constraints from the earlier fixed
1015 * match. This constraint is that the floating string starts
1016 * <= float_max_offset chars from the regex origin (rx_origin).
1017 * If this value is less than last1, use it instead.
1019 assert(rx_origin <= last1);
1021 /* this condition handles the offset==infinity case, and
1022 * is a short-cut otherwise. Although it's comparing a
1023 * byte offset to a char length, it does so in a safe way,
1024 * since 1 char always occupies 1 or more bytes,
1025 * so if a string range is (last1 - rx_origin) bytes,
1026 * it will be less than or equal to (last1 - rx_origin)
1027 * chars; meaning it errs towards doing the accurate HOP3
1028 * rather than just using last1 as a short-cut */
1029 (last1 - rx_origin) < other->max_offset
1031 : (char*)HOP3lim(rx_origin, other->max_offset, last1);
1034 assert(strpos + start_shift <= check_at);
1035 last = HOP4c(check_at, other->min_offset - start_shift,
1039 s = HOP3c(rx_origin, other->min_offset, strend);
1040 if (s < other_last) /* These positions already checked */
1043 must = utf8_target ? other->utf8_substr : other->substr;
1044 assert(SvPOK(must));
1047 char *to = last + SvCUR(must) - (SvTAIL(must)!=0);
1051 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1052 " skipping 'other' fbm scan: %"IVdf" > %"IVdf"\n",
1053 (IV)(from - strbeg),
1059 (unsigned char*)from,
1062 multiline ? FBMrf_MULTILINE : 0
1064 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1065 " doing 'other' fbm scan, [%"IVdf"..%"IVdf"] gave %"IVdf"\n",
1066 (IV)(from - strbeg),
1068 (IV)(s ? s - strbeg : -1)
1074 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
1075 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
1076 PerlIO_printf(Perl_debug_log, " %s %s substr %s%s",
1077 s ? "Found" : "Contradicts",
1078 other_ix ? "floating" : "anchored",
1079 quoted, RE_SV_TAIL(must));
1084 /* last1 is latest possible substr location. If we didn't
1085 * find it before there, we never will */
1086 if (last >= last1) {
1087 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1088 "; giving up...\n"));
1092 /* try to find the check substr again at a later
1093 * position. Maybe next time we'll find the "other" substr
1095 other_last = HOP3c(last, 1, strend) /* highest failure */;
1097 other_ix /* i.e. if other-is-float */
1098 ? HOP3c(rx_origin, 1, strend)
1099 : HOP4c(last, 1 - other->min_offset, strbeg, strend);
1100 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1101 "; about to retry %s at offset %ld (rx_origin now %"IVdf")...\n",
1102 (other_ix ? "floating" : "anchored"),
1103 (long)(HOP3c(check_at, 1, strend) - strbeg),
1104 (IV)(rx_origin - strbeg)
1109 if (other_ix) { /* if (other-is-float) */
1110 /* other_last is set to s, not s+1, since its possible for
1111 * a floating substr to fail first time, then succeed
1112 * second time at the same floating position; e.g.:
1113 * "-AB--AABZ" =~ /\wAB\d*Z/
1114 * The first time round, anchored and float match at
1115 * "-(AB)--AAB(Z)" then fail on the initial \w character
1116 * class. Second time round, they match at "-AB--A(AB)(Z)".
1121 rx_origin = HOP3c(s, -other->min_offset, strbeg);
1122 other_last = HOP3c(s, 1, strend);
1124 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1125 " at offset %ld (rx_origin now %"IVdf")...\n",
1127 (IV)(rx_origin - strbeg)
1133 DEBUG_OPTIMISE_MORE_r(
1134 PerlIO_printf(Perl_debug_log,
1135 " Check-only match: offset min:%"IVdf" max:%"IVdf
1136 " check_at:%"IVdf" rx_origin:%"IVdf" rx_origin-check_at:%"IVdf
1137 " strend:%"IVdf"\n",
1138 (IV)prog->check_offset_min,
1139 (IV)prog->check_offset_max,
1140 (IV)(check_at-strbeg),
1141 (IV)(rx_origin-strbeg),
1142 (IV)(rx_origin-check_at),
1148 postprocess_substr_matches:
1150 /* handle the extra constraint of /^.../m if present */
1152 if (ml_anch && rx_origin != strbeg && rx_origin[-1] != '\n') {
1155 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1156 " looking for /^/m anchor"));
1158 /* we have failed the constraint of a \n before rx_origin.
1159 * Find the next \n, if any, even if it's beyond the current
1160 * anchored and/or floating substrings. Whether we should be
1161 * scanning ahead for the next \n or the next substr is debatable.
1162 * On the one hand you'd expect rare substrings to appear less
1163 * often than \n's. On the other hand, searching for \n means
1164 * we're effectively flipping between check_substr and "\n" on each
1165 * iteration as the current "rarest" string candidate, which
1166 * means for example that we'll quickly reject the whole string if
1167 * hasn't got a \n, rather than trying every substr position
1171 s = HOP3c(strend, - prog->minlen, strpos);
1172 if (s <= rx_origin ||
1173 ! ( rx_origin = (char *)memchr(rx_origin, '\n', s - rx_origin)))
1175 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1176 " Did not find /%s^%s/m...\n",
1177 PL_colors[0], PL_colors[1]));
1181 /* earliest possible origin is 1 char after the \n.
1182 * (since *rx_origin == '\n', it's safe to ++ here rather than
1183 * HOP(rx_origin, 1)) */
1186 if (prog->substrs->check_ix == 0 /* check is anchored */
1187 || rx_origin >= HOP3c(check_at, - prog->check_offset_min, strpos))
1189 /* Position contradicts check-string; either because
1190 * check was anchored (and thus has no wiggle room),
1191 * or check was float and rx_origin is above the float range */
1192 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1193 " Found /%s^%s/m, about to restart lookup for check-string with rx_origin %ld...\n",
1194 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1198 /* if we get here, the check substr must have been float,
1199 * is in range, and we may or may not have had an anchored
1200 * "other" substr which still contradicts */
1201 assert(prog->substrs->check_ix); /* check is float */
1203 if (utf8_target ? prog->anchored_utf8 : prog->anchored_substr) {
1204 /* whoops, the anchored "other" substr exists, so we still
1205 * contradict. On the other hand, the float "check" substr
1206 * didn't contradict, so just retry the anchored "other"
1208 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1209 " Found /%s^%s/m, rescanning for anchored from offset %"IVdf" (rx_origin now %"IVdf")...\n",
1210 PL_colors[0], PL_colors[1],
1211 (IV)(rx_origin - strbeg + prog->anchored_offset),
1212 (IV)(rx_origin - strbeg)
1214 goto do_other_substr;
1217 /* success: we don't contradict the found floating substring
1218 * (and there's no anchored substr). */
1219 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1220 " Found /%s^%s/m with rx_origin %ld...\n",
1221 PL_colors[0], PL_colors[1], (long)(rx_origin - strbeg)));
1224 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1225 " (multiline anchor test skipped)\n"));
1231 /* if we have a starting character class, then test that extra constraint.
1232 * (trie stclasses are too expensive to use here, we are better off to
1233 * leave it to regmatch itself) */
1235 if (progi->regstclass && PL_regkind[OP(progi->regstclass)]!=TRIE) {
1236 const U8* const str = (U8*)STRING(progi->regstclass);
1238 /* XXX this value could be pre-computed */
1239 const int cl_l = (PL_regkind[OP(progi->regstclass)] == EXACT
1240 ? (reginfo->is_utf8_pat
1241 ? utf8_distance(str + STR_LEN(progi->regstclass), str)
1242 : STR_LEN(progi->regstclass))
1246 /* latest pos that a matching float substr constrains rx start to */
1247 char *rx_max_float = NULL;
1249 /* if the current rx_origin is anchored, either by satisfying an
1250 * anchored substring constraint, or a /^.../m constraint, then we
1251 * can reject the current origin if the start class isn't found
1252 * at the current position. If we have a float-only match, then
1253 * rx_origin is constrained to a range; so look for the start class
1254 * in that range. if neither, then look for the start class in the
1255 * whole rest of the string */
1257 /* XXX DAPM it's not clear what the minlen test is for, and why
1258 * it's not used in the floating case. Nothing in the test suite
1259 * causes minlen == 0 here. See <20140313134639.GS12844@iabyn.com>.
1260 * Here are some old comments, which may or may not be correct:
1262 * minlen == 0 is possible if regstclass is \b or \B,
1263 * and the fixed substr is ''$.
1264 * Since minlen is already taken into account, rx_origin+1 is
1265 * before strend; accidentally, minlen >= 1 guaranties no false
1266 * positives at rx_origin + 1 even for \b or \B. But (minlen? 1 :
1267 * 0) below assumes that regstclass does not come from lookahead...
1268 * If regstclass takes bytelength more than 1: If charlength==1, OK.
1269 * This leaves EXACTF-ish only, which are dealt with in
1273 if (prog->anchored_substr || prog->anchored_utf8 || ml_anch)
1274 endpos= HOP3c(rx_origin, (prog->minlen ? cl_l : 0), strend);
1275 else if (prog->float_substr || prog->float_utf8) {
1276 rx_max_float = HOP3c(check_at, -start_shift, strbeg);
1277 endpos= HOP3c(rx_max_float, cl_l, strend);
1282 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1283 " looking for class: start_shift: %"IVdf" check_at: %"IVdf
1284 " rx_origin: %"IVdf" endpos: %"IVdf"\n",
1285 (IV)start_shift, (IV)(check_at - strbeg),
1286 (IV)(rx_origin - strbeg), (IV)(endpos - strbeg)));
1288 s = find_byclass(prog, progi->regstclass, rx_origin, endpos,
1291 if (endpos == strend) {
1292 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1293 " Could not match STCLASS...\n") );
1296 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1297 " This position contradicts STCLASS...\n") );
1298 if ((prog->intflags & PREGf_ANCH) && !ml_anch
1299 && !(prog->intflags & PREGf_IMPLICIT))
1302 /* Contradict one of substrings */
1303 if (prog->anchored_substr || prog->anchored_utf8) {
1304 if (prog->substrs->check_ix == 1) { /* check is float */
1305 /* Have both, check_string is floating */
1306 assert(rx_origin + start_shift <= check_at);
1307 if (rx_origin + start_shift != check_at) {
1308 /* not at latest position float substr could match:
1309 * Recheck anchored substring, but not floating.
1310 * The condition above is in bytes rather than
1311 * chars for efficiency. It's conservative, in
1312 * that it errs on the side of doing 'goto
1313 * do_other_substr'. In this case, at worst,
1314 * an extra anchored search may get done, but in
1315 * practice the extra fbm_instr() is likely to
1316 * get skipped anyway. */
1317 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1318 " about to retry anchored at offset %ld (rx_origin now %"IVdf")...\n",
1319 (long)(other_last - strbeg),
1320 (IV)(rx_origin - strbeg)
1322 goto do_other_substr;
1330 /* In the presence of ml_anch, we might be able to
1331 * find another \n without breaking the current float
1334 /* strictly speaking this should be HOP3c(..., 1, ...),
1335 * but since we goto a block of code that's going to
1336 * search for the next \n if any, its safe here */
1338 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1339 " about to look for /%s^%s/m starting at rx_origin %ld...\n",
1340 PL_colors[0], PL_colors[1],
1341 (long)(rx_origin - strbeg)) );
1342 goto postprocess_substr_matches;
1345 /* strictly speaking this can never be true; but might
1346 * be if we ever allow intuit without substrings */
1347 if (!(utf8_target ? prog->float_utf8 : prog->float_substr))
1350 rx_origin = rx_max_float;
1353 /* at this point, any matching substrings have been
1354 * contradicted. Start again... */
1356 rx_origin = HOP3c(rx_origin, 1, strend);
1358 /* uses bytes rather than char calculations for efficiency.
1359 * It's conservative: it errs on the side of doing 'goto restart',
1360 * where there is code that does a proper char-based test */
1361 if (rx_origin + start_shift + end_shift > strend) {
1362 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1363 " Could not match STCLASS...\n") );
1366 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
1367 " about to look for %s substr starting at offset %ld (rx_origin now %"IVdf")...\n",
1368 (prog->substrs->check_ix ? "floating" : "anchored"),
1369 (long)(rx_origin + start_shift - strbeg),
1370 (IV)(rx_origin - strbeg)
1377 if (rx_origin != s) {
1378 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1379 " By STCLASS: moving %ld --> %ld\n",
1380 (long)(rx_origin - strbeg), (long)(s - strbeg))
1384 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1385 " Does not contradict STCLASS...\n");
1390 /* Decide whether using the substrings helped */
1392 if (rx_origin != strpos) {
1393 /* Fixed substring is found far enough so that the match
1394 cannot start at strpos. */
1396 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " try at offset...\n"));
1397 ++BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr); /* hooray/5 */
1400 /* The found rx_origin position does not prohibit matching at
1401 * strpos, so calling intuit didn't gain us anything. Decrement
1402 * the BmUSEFUL() count on the check substring, and if we reach
1404 if (!(prog->intflags & PREGf_NAUGHTY)
1406 prog->check_utf8 /* Could be deleted already */
1407 && --BmUSEFUL(prog->check_utf8) < 0
1408 && (prog->check_utf8 == prog->float_utf8)
1410 prog->check_substr /* Could be deleted already */
1411 && --BmUSEFUL(prog->check_substr) < 0
1412 && (prog->check_substr == prog->float_substr)
1415 /* If flags & SOMETHING - do not do it many times on the same match */
1416 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, " ... Disabling check substring...\n"));
1417 /* XXX Does the destruction order has to change with utf8_target? */
1418 SvREFCNT_dec(utf8_target ? prog->check_utf8 : prog->check_substr);
1419 SvREFCNT_dec(utf8_target ? prog->check_substr : prog->check_utf8);
1420 prog->check_substr = prog->check_utf8 = NULL; /* disable */
1421 prog->float_substr = prog->float_utf8 = NULL; /* clear */
1422 check = NULL; /* abort */
1423 /* XXXX This is a remnant of the old implementation. It
1424 looks wasteful, since now INTUIT can use many
1425 other heuristics. */
1426 prog->extflags &= ~RXf_USE_INTUIT;
1430 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
1431 "Intuit: %sSuccessfully guessed:%s match at offset %ld\n",
1432 PL_colors[4], PL_colors[5], (long)(rx_origin - strbeg)) );
1436 fail_finish: /* Substring not found */
1437 if (prog->check_substr || prog->check_utf8) /* could be removed already */
1438 BmUSEFUL(utf8_target ? prog->check_utf8 : prog->check_substr) += 5; /* hooray */
1440 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch rejected by optimizer%s\n",
1441 PL_colors[4], PL_colors[5]));
1446 #define DECL_TRIE_TYPE(scan) \
1447 const enum { trie_plain, trie_utf8, trie_utf8_fold, trie_latin_utf8_fold, \
1448 trie_utf8_exactfa_fold, trie_latin_utf8_exactfa_fold, \
1449 trie_utf8l, trie_flu8 } \
1450 trie_type = ((scan->flags == EXACT) \
1451 ? (utf8_target ? trie_utf8 : trie_plain) \
1452 : (scan->flags == EXACTL) \
1453 ? (utf8_target ? trie_utf8l : trie_plain) \
1454 : (scan->flags == EXACTFA) \
1456 ? trie_utf8_exactfa_fold \
1457 : trie_latin_utf8_exactfa_fold) \
1458 : (scan->flags == EXACTFLU8 \
1462 : trie_latin_utf8_fold)))
1464 #define REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc, uscan, len, uvc, charid, foldlen, foldbuf, uniflags) \
1467 U8 flags = FOLD_FLAGS_FULL; \
1468 switch (trie_type) { \
1470 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1471 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1472 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1474 goto do_trie_utf8_fold; \
1475 case trie_utf8_exactfa_fold: \
1476 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1478 case trie_utf8_fold: \
1479 do_trie_utf8_fold: \
1480 if ( foldlen>0 ) { \
1481 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1486 uvc = _to_utf8_fold_flags( (const U8*) uc, foldbuf, &foldlen, flags); \
1487 len = UTF8SKIP(uc); \
1488 skiplen = UVCHR_SKIP( uvc ); \
1489 foldlen -= skiplen; \
1490 uscan = foldbuf + skiplen; \
1493 case trie_latin_utf8_exactfa_fold: \
1494 flags |= FOLD_FLAGS_NOMIX_ASCII; \
1496 case trie_latin_utf8_fold: \
1497 if ( foldlen>0 ) { \
1498 uvc = utf8n_to_uvchr( (const U8*) uscan, UTF8_MAXLEN, &len, uniflags ); \
1504 uvc = _to_fold_latin1( (U8) *uc, foldbuf, &foldlen, flags); \
1505 skiplen = UVCHR_SKIP( uvc ); \
1506 foldlen -= skiplen; \
1507 uscan = foldbuf + skiplen; \
1511 _CHECK_AND_WARN_PROBLEMATIC_LOCALE; \
1512 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*uc)) { \
1513 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(uc, uc + UTF8SKIP(uc)); \
1517 uvc = utf8n_to_uvchr( (const U8*) uc, UTF8_MAXLEN, &len, uniflags ); \
1524 charid = trie->charmap[ uvc ]; \
1528 if (widecharmap) { \
1529 SV** const svpp = hv_fetch(widecharmap, \
1530 (char*)&uvc, sizeof(UV), 0); \
1532 charid = (U16)SvIV(*svpp); \
1537 #define DUMP_EXEC_POS(li,s,doutf8) \
1538 dump_exec_pos(li,s,(reginfo->strend),(reginfo->strbeg), \
1541 #define REXEC_FBC_EXACTISH_SCAN(COND) \
1545 && (ln == 1 || folder(s, pat_string, ln)) \
1546 && (reginfo->intuit || regtry(reginfo, &s)) )\
1552 #define REXEC_FBC_UTF8_SCAN(CODE) \
1554 while (s < strend) { \
1560 #define REXEC_FBC_SCAN(CODE) \
1562 while (s < strend) { \
1568 #define REXEC_FBC_UTF8_CLASS_SCAN(COND) \
1569 REXEC_FBC_UTF8_SCAN( /* Loops while (s < strend) */ \
1571 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1580 #define REXEC_FBC_CLASS_SCAN(COND) \
1581 REXEC_FBC_SCAN( /* Loops while (s < strend) */ \
1583 if (tmp && (reginfo->intuit || regtry(reginfo, &s))) \
1592 #define REXEC_FBC_CSCAN(CONDUTF8,COND) \
1593 if (utf8_target) { \
1594 REXEC_FBC_UTF8_CLASS_SCAN(CONDUTF8); \
1597 REXEC_FBC_CLASS_SCAN(COND); \
1600 /* The three macros below are slightly different versions of the same logic.
1602 * The first is for /a and /aa when the target string is UTF-8. This can only
1603 * match ascii, but it must advance based on UTF-8. The other two handle the
1604 * non-UTF-8 and the more generic UTF-8 cases. In all three, we are looking
1605 * for the boundary (or non-boundary) between a word and non-word character.
1606 * The utf8 and non-utf8 cases have the same logic, but the details must be
1607 * different. Find the "wordness" of the character just prior to this one, and
1608 * compare it with the wordness of this one. If they differ, we have a
1609 * boundary. At the beginning of the string, pretend that the previous
1610 * character was a new-line.
1612 * All these macros uncleanly have side-effects with each other and outside
1613 * variables. So far it's been too much trouble to clean-up
1615 * TEST_NON_UTF8 is the macro or function to call to test if its byte input is
1616 * a word character or not.
1617 * IF_SUCCESS is code to do if it finds that we are at a boundary between
1619 * IF_FAIL is code to do if we aren't at a boundary between word/non-word
1621 * Exactly one of the two IF_FOO parameters is a no-op, depending on whether we
1622 * are looking for a boundary or for a non-boundary. If we are looking for a
1623 * boundary, we want IF_FAIL to be the no-op, and for IF_SUCCESS to go out and
1624 * see if this tentative match actually works, and if so, to quit the loop
1625 * here. And vice-versa if we are looking for a non-boundary.
1627 * 'tmp' below in the next three macros in the REXEC_FBC_SCAN and
1628 * REXEC_FBC_UTF8_SCAN loops is a loop invariant, a bool giving the return of
1629 * TEST_NON_UTF8(s-1). To see this, note that that's what it is defined to be
1630 * at entry to the loop, and to get to the IF_FAIL branch, tmp must equal
1631 * TEST_NON_UTF8(s), and in the opposite branch, IF_SUCCESS, tmp is that
1632 * complement. But in that branch we complement tmp, meaning that at the
1633 * bottom of the loop tmp is always going to be equal to TEST_NON_UTF8(s),
1634 * which means at the top of the loop in the next iteration, it is
1635 * TEST_NON_UTF8(s-1) */
1636 #define FBC_UTF8_A(TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1637 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1638 tmp = TEST_NON_UTF8(tmp); \
1639 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1640 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1642 IF_SUCCESS; /* Is a boundary if values for s-1 and s differ */ \
1649 /* Like FBC_UTF8_A, but TEST_UV is a macro which takes a UV as its input, and
1650 * TEST_UTF8 is a macro that for the same input code points returns identically
1651 * to TEST_UV, but takes a pointer to a UTF-8 encoded string instead */
1652 #define FBC_UTF8(TEST_UV, TEST_UTF8, IF_SUCCESS, IF_FAIL) \
1653 if (s == reginfo->strbeg) { \
1656 else { /* Back-up to the start of the previous character */ \
1657 U8 * const r = reghop3((U8*)s, -1, (U8*)reginfo->strbeg); \
1658 tmp = utf8n_to_uvchr(r, (U8*) reginfo->strend - r, \
1659 0, UTF8_ALLOW_DEFAULT); \
1661 tmp = TEST_UV(tmp); \
1662 LOAD_UTF8_CHARCLASS_ALNUM(); \
1663 REXEC_FBC_UTF8_SCAN( /* advances s while s < strend */ \
1664 if (tmp == ! (TEST_UTF8((U8 *) s))) { \
1673 /* Like the above two macros. UTF8_CODE is the complete code for handling
1674 * UTF-8. Common to the BOUND and NBOUND cases, set-up by the FBC_BOUND, etc
1676 #define FBC_BOUND_COMMON(UTF8_CODE, TEST_NON_UTF8, IF_SUCCESS, IF_FAIL) \
1677 if (utf8_target) { \
1680 else { /* Not utf8 */ \
1681 tmp = (s != reginfo->strbeg) ? UCHARAT(s - 1) : '\n'; \
1682 tmp = TEST_NON_UTF8(tmp); \
1683 REXEC_FBC_SCAN( /* advances s while s < strend */ \
1684 if (tmp == ! TEST_NON_UTF8((U8) *s)) { \
1693 /* Here, things have been set up by the previous code so that tmp is the \
1694 * return of TEST_NON_UTF(s-1) or TEST_UTF8(s-1) (depending on the \
1695 * utf8ness of the target). We also have to check if this matches against \
1696 * the EOS, which we treat as a \n (which is the same value in both UTF-8 \
1697 * or non-UTF8, so can use the non-utf8 test condition even for a UTF-8 \
1699 if (tmp == ! TEST_NON_UTF8('\n')) { \
1706 /* This is the macro to use when we want to see if something that looks like it
1707 * could match, actually does, and if so exits the loop */
1708 #define REXEC_FBC_TRYIT \
1709 if ((reginfo->intuit || regtry(reginfo, &s))) \
1712 /* The only difference between the BOUND and NBOUND cases is that
1713 * REXEC_FBC_TRYIT is called when matched in BOUND, and when non-matched in
1714 * NBOUND. This is accomplished by passing it as either the if or else clause,
1715 * with the other one being empty (PLACEHOLDER is defined as empty).
1717 * The TEST_FOO parameters are for operating on different forms of input, but
1718 * all should be ones that return identically for the same underlying code
1720 #define FBC_BOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1722 FBC_UTF8(TEST_UV, TEST_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1723 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1725 #define FBC_BOUND_A(TEST_NON_UTF8) \
1727 FBC_UTF8_A(TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER), \
1728 TEST_NON_UTF8, REXEC_FBC_TRYIT, PLACEHOLDER)
1730 #define FBC_NBOUND(TEST_NON_UTF8, TEST_UV, TEST_UTF8) \
1732 FBC_UTF8(TEST_UV, TEST_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1733 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1735 #define FBC_NBOUND_A(TEST_NON_UTF8) \
1737 FBC_UTF8_A(TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT), \
1738 TEST_NON_UTF8, PLACEHOLDER, REXEC_FBC_TRYIT)
1742 S_get_break_val_cp_checked(SV* const invlist, const UV cp_in) {
1743 IV cp_out = Perl__invlist_search(invlist, cp_in);
1744 assert(cp_out >= 0);
1747 # define _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp) \
1748 invmap[S_get_break_val_cp_checked(invlist, cp)]
1750 # define _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp) \
1751 invmap[_invlist_search(invlist, cp)]
1754 /* Takes a pointer to an inversion list, a pointer to its corresponding
1755 * inversion map, and a code point, and returns the code point's value
1756 * according to the two arrays. It assumes that all code points have a value.
1757 * This is used as the base macro for macros for particular properties */
1758 #define _generic_GET_BREAK_VAL_CP(invlist, invmap, cp) \
1759 _generic_GET_BREAK_VAL_CP_CHECKED(invlist, invmap, cp)
1761 /* Same as above, but takes begin, end ptrs to a UTF-8 encoded string instead
1762 * of a code point, returning the value for the first code point in the string.
1763 * And it takes the particular macro name that finds the desired value given a
1764 * code point. Merely convert the UTF-8 to code point and call the cp macro */
1765 #define _generic_GET_BREAK_VAL_UTF8(cp_macro, pos, strend) \
1766 (__ASSERT_(pos < strend) \
1767 /* Note assumes is valid UTF-8 */ \
1768 (cp_macro(utf8_to_uvchr_buf((pos), (strend), NULL))))
1770 /* Returns the GCB value for the input code point */
1771 #define getGCB_VAL_CP(cp) \
1772 _generic_GET_BREAK_VAL_CP( \
1777 /* Returns the GCB value for the first code point in the UTF-8 encoded string
1778 * bounded by pos and strend */
1779 #define getGCB_VAL_UTF8(pos, strend) \
1780 _generic_GET_BREAK_VAL_UTF8(getGCB_VAL_CP, pos, strend)
1782 /* Returns the LB value for the input code point */
1783 #define getLB_VAL_CP(cp) \
1784 _generic_GET_BREAK_VAL_CP( \
1789 /* Returns the LB value for the first code point in the UTF-8 encoded string
1790 * bounded by pos and strend */
1791 #define getLB_VAL_UTF8(pos, strend) \
1792 _generic_GET_BREAK_VAL_UTF8(getLB_VAL_CP, pos, strend)
1795 /* Returns the SB value for the input code point */
1796 #define getSB_VAL_CP(cp) \
1797 _generic_GET_BREAK_VAL_CP( \
1802 /* Returns the SB value for the first code point in the UTF-8 encoded string
1803 * bounded by pos and strend */
1804 #define getSB_VAL_UTF8(pos, strend) \
1805 _generic_GET_BREAK_VAL_UTF8(getSB_VAL_CP, pos, strend)
1807 /* Returns the WB value for the input code point */
1808 #define getWB_VAL_CP(cp) \
1809 _generic_GET_BREAK_VAL_CP( \
1814 /* Returns the WB value for the first code point in the UTF-8 encoded string
1815 * bounded by pos and strend */
1816 #define getWB_VAL_UTF8(pos, strend) \
1817 _generic_GET_BREAK_VAL_UTF8(getWB_VAL_CP, pos, strend)
1819 /* We know what class REx starts with. Try to find this position... */
1820 /* if reginfo->intuit, its a dryrun */
1821 /* annoyingly all the vars in this routine have different names from their counterparts
1822 in regmatch. /grrr */
1824 S_find_byclass(pTHX_ regexp * prog, const regnode *c, char *s,
1825 const char *strend, regmatch_info *reginfo)
1828 const I32 doevery = (prog->intflags & PREGf_SKIP) == 0;
1829 char *pat_string; /* The pattern's exactish string */
1830 char *pat_end; /* ptr to end char of pat_string */
1831 re_fold_t folder; /* Function for computing non-utf8 folds */
1832 const U8 *fold_array; /* array for folding ords < 256 */
1838 I32 tmp = 1; /* Scratch variable? */
1839 const bool utf8_target = reginfo->is_utf8_target;
1840 UV utf8_fold_flags = 0;
1841 const bool is_utf8_pat = reginfo->is_utf8_pat;
1842 bool to_complement = FALSE; /* Invert the result? Taking the xor of this
1843 with a result inverts that result, as 0^1 =
1845 _char_class_number classnum;
1847 RXi_GET_DECL(prog,progi);
1849 PERL_ARGS_ASSERT_FIND_BYCLASS;
1851 /* We know what class it must start with. */
1854 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1856 if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(c)) && ! IN_UTF8_CTYPE_LOCALE) {
1857 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
1864 REXEC_FBC_UTF8_CLASS_SCAN(
1865 reginclass(prog, c, (U8*)s, (U8*) strend, utf8_target));
1868 REXEC_FBC_CLASS_SCAN(REGINCLASS(prog, c, (U8*)s, 0));
1872 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
1873 assert(! is_utf8_pat);
1876 if (is_utf8_pat || utf8_target) {
1877 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
1878 goto do_exactf_utf8;
1880 fold_array = PL_fold_latin1; /* Latin1 folds are not affected by */
1881 folder = foldEQ_latin1; /* /a, except the sharp s one which */
1882 goto do_exactf_non_utf8; /* isn't dealt with by these */
1884 case EXACTF: /* This node only generated for non-utf8 patterns */
1885 assert(! is_utf8_pat);
1887 utf8_fold_flags = 0;
1888 goto do_exactf_utf8;
1890 fold_array = PL_fold;
1892 goto do_exactf_non_utf8;
1895 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
1896 if (is_utf8_pat || utf8_target || IN_UTF8_CTYPE_LOCALE) {
1897 utf8_fold_flags = FOLDEQ_LOCALE;
1898 goto do_exactf_utf8;
1900 fold_array = PL_fold_locale;
1901 folder = foldEQ_locale;
1902 goto do_exactf_non_utf8;
1906 utf8_fold_flags = FOLDEQ_S2_ALREADY_FOLDED;
1908 goto do_exactf_utf8;
1911 if (! utf8_target) { /* All code points in this node require
1912 UTF-8 to express. */
1915 utf8_fold_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
1916 | FOLDEQ_S2_FOLDS_SANE;
1917 goto do_exactf_utf8;
1920 if (is_utf8_pat || utf8_target) {
1921 utf8_fold_flags = is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
1922 goto do_exactf_utf8;
1925 /* Any 'ss' in the pattern should have been replaced by regcomp,
1926 * so we don't have to worry here about this single special case
1927 * in the Latin1 range */
1928 fold_array = PL_fold_latin1;
1929 folder = foldEQ_latin1;
1933 do_exactf_non_utf8: /* Neither pattern nor string are UTF8, and there
1934 are no glitches with fold-length differences
1935 between the target string and pattern */
1937 /* The idea in the non-utf8 EXACTF* cases is to first find the
1938 * first character of the EXACTF* node and then, if necessary,
1939 * case-insensitively compare the full text of the node. c1 is the
1940 * first character. c2 is its fold. This logic will not work for
1941 * Unicode semantics and the german sharp ss, which hence should
1942 * not be compiled into a node that gets here. */
1943 pat_string = STRING(c);
1944 ln = STR_LEN(c); /* length to match in octets/bytes */
1946 /* We know that we have to match at least 'ln' bytes (which is the
1947 * same as characters, since not utf8). If we have to match 3
1948 * characters, and there are only 2 availabe, we know without
1949 * trying that it will fail; so don't start a match past the
1950 * required minimum number from the far end */
1951 e = HOP3c(strend, -((SSize_t)ln), s);
1953 if (reginfo->intuit && e < s) {
1954 e = s; /* Due to minlen logic of intuit() */
1958 c2 = fold_array[c1];
1959 if (c1 == c2) { /* If char and fold are the same */
1960 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1);
1963 REXEC_FBC_EXACTISH_SCAN(*(U8*)s == c1 || *(U8*)s == c2);
1971 /* If one of the operands is in utf8, we can't use the simpler folding
1972 * above, due to the fact that many different characters can have the
1973 * same fold, or portion of a fold, or different- length fold */
1974 pat_string = STRING(c);
1975 ln = STR_LEN(c); /* length to match in octets/bytes */
1976 pat_end = pat_string + ln;
1977 lnc = is_utf8_pat /* length to match in characters */
1978 ? utf8_length((U8 *) pat_string, (U8 *) pat_end)
1981 /* We have 'lnc' characters to match in the pattern, but because of
1982 * multi-character folding, each character in the target can match
1983 * up to 3 characters (Unicode guarantees it will never exceed
1984 * this) if it is utf8-encoded; and up to 2 if not (based on the
1985 * fact that the Latin 1 folds are already determined, and the
1986 * only multi-char fold in that range is the sharp-s folding to
1987 * 'ss'. Thus, a pattern character can match as little as 1/3 of a
1988 * string character. Adjust lnc accordingly, rounding up, so that
1989 * if we need to match at least 4+1/3 chars, that really is 5. */
1990 expansion = (utf8_target) ? UTF8_MAX_FOLD_CHAR_EXPAND : 2;
1991 lnc = (lnc + expansion - 1) / expansion;
1993 /* As in the non-UTF8 case, if we have to match 3 characters, and
1994 * only 2 are left, it's guaranteed to fail, so don't start a
1995 * match that would require us to go beyond the end of the string
1997 e = HOP3c(strend, -((SSize_t)lnc), s);
1999 if (reginfo->intuit && e < s) {
2000 e = s; /* Due to minlen logic of intuit() */
2003 /* XXX Note that we could recalculate e to stop the loop earlier,
2004 * as the worst case expansion above will rarely be met, and as we
2005 * go along we would usually find that e moves further to the left.
2006 * This would happen only after we reached the point in the loop
2007 * where if there were no expansion we should fail. Unclear if
2008 * worth the expense */
2011 char *my_strend= (char *)strend;
2012 if (foldEQ_utf8_flags(s, &my_strend, 0, utf8_target,
2013 pat_string, NULL, ln, is_utf8_pat, utf8_fold_flags)
2014 && (reginfo->intuit || regtry(reginfo, &s)) )
2018 s += (utf8_target) ? UTF8SKIP(s) : 1;
2024 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2025 if (FLAGS(c) != TRADITIONAL_BOUND) {
2026 if (! IN_UTF8_CTYPE_LOCALE) {
2027 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2028 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2033 FBC_BOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8);
2037 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2038 if (FLAGS(c) != TRADITIONAL_BOUND) {
2039 if (! IN_UTF8_CTYPE_LOCALE) {
2040 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2041 B_ON_NON_UTF8_LOCALE_IS_WRONG);
2046 FBC_NBOUND(isWORDCHAR_LC, isWORDCHAR_LC_uvchr, isWORDCHAR_LC_utf8);
2049 case BOUND: /* regcomp.c makes sure that this only has the traditional \b
2051 assert(FLAGS(c) == TRADITIONAL_BOUND);
2053 FBC_BOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8);
2056 case BOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2058 assert(FLAGS(c) == TRADITIONAL_BOUND);
2060 FBC_BOUND_A(isWORDCHAR_A);
2063 case NBOUND: /* regcomp.c makes sure that this only has the traditional \b
2065 assert(FLAGS(c) == TRADITIONAL_BOUND);
2067 FBC_NBOUND(isWORDCHAR, isWORDCHAR_uni, isWORDCHAR_utf8);
2070 case NBOUNDA: /* regcomp.c makes sure that this only has the traditional \b
2072 assert(FLAGS(c) == TRADITIONAL_BOUND);
2074 FBC_NBOUND_A(isWORDCHAR_A);
2078 if ((bound_type) FLAGS(c) == TRADITIONAL_BOUND) {
2079 FBC_NBOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8);
2090 switch((bound_type) FLAGS(c)) {
2091 case TRADITIONAL_BOUND:
2092 FBC_BOUND(isWORDCHAR_L1, isWORDCHAR_uni, isWORDCHAR_utf8);
2095 if (s == reginfo->strbeg) {
2096 if (reginfo->intuit || regtry(reginfo, &s))
2101 /* Didn't match. Try at the next position (if there is one) */
2102 s += (utf8_target) ? UTF8SKIP(s) : 1;
2103 if (UNLIKELY(s >= reginfo->strend)) {
2109 GCB_enum before = getGCB_VAL_UTF8(
2111 (U8*)(reginfo->strbeg)),
2112 (U8*) reginfo->strend);
2113 while (s < strend) {
2114 GCB_enum after = getGCB_VAL_UTF8((U8*) s,
2115 (U8*) reginfo->strend);
2116 if ( (to_complement ^ isGCB(before, after))
2117 && (reginfo->intuit || regtry(reginfo, &s)))
2125 else { /* Not utf8. Everything is a GCB except between CR and
2127 while (s < strend) {
2128 if ((to_complement ^ ( UCHARAT(s - 1) != '\r'
2129 || UCHARAT(s) != '\n'))
2130 && (reginfo->intuit || regtry(reginfo, &s)))
2138 /* And, since this is a bound, it can match after the final
2139 * character in the string */
2140 if ((reginfo->intuit || regtry(reginfo, &s))) {
2146 if (s == reginfo->strbeg) {
2147 if (reginfo->intuit || regtry(reginfo, &s)) {
2150 s += (utf8_target) ? UTF8SKIP(s) : 1;
2151 if (UNLIKELY(s >= reginfo->strend)) {
2157 LB_enum before = getLB_VAL_UTF8(reghop3((U8*)s,
2159 (U8*)(reginfo->strbeg)),
2160 (U8*) reginfo->strend);
2161 while (s < strend) {
2162 LB_enum after = getLB_VAL_UTF8((U8*) s, (U8*) reginfo->strend);
2163 if (to_complement ^ isLB(before,
2165 (U8*) reginfo->strbeg,
2167 (U8*) reginfo->strend,
2169 && (reginfo->intuit || regtry(reginfo, &s)))
2177 else { /* Not utf8. */
2178 LB_enum before = getLB_VAL_CP((U8) *(s -1));
2179 while (s < strend) {
2180 LB_enum after = getLB_VAL_CP((U8) *s);
2181 if (to_complement ^ isLB(before,
2183 (U8*) reginfo->strbeg,
2185 (U8*) reginfo->strend,
2187 && (reginfo->intuit || regtry(reginfo, &s)))
2196 if (reginfo->intuit || regtry(reginfo, &s)) {
2203 if (s == reginfo->strbeg) {
2204 if (reginfo->intuit || regtry(reginfo, &s)) {
2207 s += (utf8_target) ? UTF8SKIP(s) : 1;
2208 if (UNLIKELY(s >= reginfo->strend)) {
2214 SB_enum before = getSB_VAL_UTF8(reghop3((U8*)s,
2216 (U8*)(reginfo->strbeg)),
2217 (U8*) reginfo->strend);
2218 while (s < strend) {
2219 SB_enum after = getSB_VAL_UTF8((U8*) s,
2220 (U8*) reginfo->strend);
2221 if ((to_complement ^ isSB(before,
2223 (U8*) reginfo->strbeg,
2225 (U8*) reginfo->strend,
2227 && (reginfo->intuit || regtry(reginfo, &s)))
2235 else { /* Not utf8. */
2236 SB_enum before = getSB_VAL_CP((U8) *(s -1));
2237 while (s < strend) {
2238 SB_enum after = getSB_VAL_CP((U8) *s);
2239 if ((to_complement ^ isSB(before,
2241 (U8*) reginfo->strbeg,
2243 (U8*) reginfo->strend,
2245 && (reginfo->intuit || regtry(reginfo, &s)))
2254 /* Here are at the final position in the target string. The SB
2255 * value is always true here, so matches, depending on other
2257 if (reginfo->intuit || regtry(reginfo, &s)) {
2264 if (s == reginfo->strbeg) {
2265 if (reginfo->intuit || regtry(reginfo, &s)) {
2268 s += (utf8_target) ? UTF8SKIP(s) : 1;
2269 if (UNLIKELY(s >= reginfo->strend)) {
2275 /* We are at a boundary between char_sub_0 and char_sub_1.
2276 * We also keep track of the value for char_sub_-1 as we
2277 * loop through the line. Context may be needed to make a
2278 * determination, and if so, this can save having to
2280 WB_enum previous = WB_UNKNOWN;
2281 WB_enum before = getWB_VAL_UTF8(
2284 (U8*)(reginfo->strbeg)),
2285 (U8*) reginfo->strend);
2286 while (s < strend) {
2287 WB_enum after = getWB_VAL_UTF8((U8*) s,
2288 (U8*) reginfo->strend);
2289 if ((to_complement ^ isWB(previous,
2292 (U8*) reginfo->strbeg,
2294 (U8*) reginfo->strend,
2296 && (reginfo->intuit || regtry(reginfo, &s)))
2305 else { /* Not utf8. */
2306 WB_enum previous = WB_UNKNOWN;
2307 WB_enum before = getWB_VAL_CP((U8) *(s -1));
2308 while (s < strend) {
2309 WB_enum after = getWB_VAL_CP((U8) *s);
2310 if ((to_complement ^ isWB(previous,
2313 (U8*) reginfo->strbeg,
2315 (U8*) reginfo->strend,
2317 && (reginfo->intuit || regtry(reginfo, &s)))
2327 if (reginfo->intuit || regtry(reginfo, &s)) {
2334 REXEC_FBC_CSCAN(is_LNBREAK_utf8_safe(s, strend),
2335 is_LNBREAK_latin1_safe(s, strend)
2339 /* The argument to all the POSIX node types is the class number to pass to
2340 * _generic_isCC() to build a mask for searching in PL_charclass[] */
2347 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2348 REXEC_FBC_CSCAN(to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(c), (U8 *) s)),
2349 to_complement ^ cBOOL(isFOO_lc(FLAGS(c), *s)));
2364 /* The complement of something that matches only ASCII matches all
2365 * non-ASCII, plus everything in ASCII that isn't in the class. */
2366 REXEC_FBC_UTF8_CLASS_SCAN(! isASCII_utf8(s)
2367 || ! _generic_isCC_A(*s, FLAGS(c)));
2376 /* Don't need to worry about utf8, as it can match only a single
2377 * byte invariant character. */
2378 REXEC_FBC_CLASS_SCAN(
2379 to_complement ^ cBOOL(_generic_isCC_A(*s, FLAGS(c))));
2387 if (! utf8_target) {
2388 REXEC_FBC_CLASS_SCAN(to_complement ^ cBOOL(_generic_isCC(*s,
2394 classnum = (_char_class_number) FLAGS(c);
2395 if (classnum < _FIRST_NON_SWASH_CC) {
2396 while (s < strend) {
2398 /* We avoid loading in the swash as long as possible, but
2399 * should we have to, we jump to a separate loop. This
2400 * extra 'if' statement is what keeps this code from being
2401 * just a call to REXEC_FBC_UTF8_CLASS_SCAN() */
2402 if (UTF8_IS_ABOVE_LATIN1(*s)) {
2403 goto found_above_latin1;
2405 if ((UTF8_IS_INVARIANT(*s)
2406 && to_complement ^ cBOOL(_generic_isCC((U8) *s,
2408 || (UTF8_IS_DOWNGRADEABLE_START(*s)
2409 && to_complement ^ cBOOL(
2410 _generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(*s,
2414 if (tmp && (reginfo->intuit || regtry(reginfo, &s)))
2426 else switch (classnum) { /* These classes are implemented as
2428 case _CC_ENUM_SPACE:
2429 REXEC_FBC_UTF8_CLASS_SCAN(
2430 to_complement ^ cBOOL(isSPACE_utf8(s)));
2433 case _CC_ENUM_BLANK:
2434 REXEC_FBC_UTF8_CLASS_SCAN(
2435 to_complement ^ cBOOL(isBLANK_utf8(s)));
2438 case _CC_ENUM_XDIGIT:
2439 REXEC_FBC_UTF8_CLASS_SCAN(
2440 to_complement ^ cBOOL(isXDIGIT_utf8(s)));
2443 case _CC_ENUM_VERTSPACE:
2444 REXEC_FBC_UTF8_CLASS_SCAN(
2445 to_complement ^ cBOOL(isVERTWS_utf8(s)));
2448 case _CC_ENUM_CNTRL:
2449 REXEC_FBC_UTF8_CLASS_SCAN(
2450 to_complement ^ cBOOL(isCNTRL_utf8(s)));
2454 Perl_croak(aTHX_ "panic: find_byclass() node %d='%s' has an unexpected character class '%d'", OP(c), PL_reg_name[OP(c)], classnum);
2455 NOT_REACHED; /* NOTREACHED */
2460 found_above_latin1: /* Here we have to load a swash to get the result
2461 for the current code point */
2462 if (! PL_utf8_swash_ptrs[classnum]) {
2463 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
2464 PL_utf8_swash_ptrs[classnum] =
2465 _core_swash_init("utf8",
2468 PL_XPosix_ptrs[classnum], &flags);
2471 /* This is a copy of the loop above for swash classes, though using the
2472 * FBC macro instead of being expanded out. Since we've loaded the
2473 * swash, we don't have to check for that each time through the loop */
2474 REXEC_FBC_UTF8_CLASS_SCAN(
2475 to_complement ^ cBOOL(_generic_utf8(
2478 swash_fetch(PL_utf8_swash_ptrs[classnum],
2486 /* what trie are we using right now */
2487 reg_ac_data *aho = (reg_ac_data*)progi->data->data[ ARG( c ) ];
2488 reg_trie_data *trie = (reg_trie_data*)progi->data->data[ aho->trie ];
2489 HV *widecharmap = MUTABLE_HV(progi->data->data[ aho->trie + 1 ]);
2491 const char *last_start = strend - trie->minlen;
2493 const char *real_start = s;
2495 STRLEN maxlen = trie->maxlen;
2497 U8 **points; /* map of where we were in the input string
2498 when reading a given char. For ASCII this
2499 is unnecessary overhead as the relationship
2500 is always 1:1, but for Unicode, especially
2501 case folded Unicode this is not true. */
2502 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
2506 GET_RE_DEBUG_FLAGS_DECL;
2508 /* We can't just allocate points here. We need to wrap it in
2509 * an SV so it gets freed properly if there is a croak while
2510 * running the match */
2513 sv_points=newSV(maxlen * sizeof(U8 *));
2514 SvCUR_set(sv_points,
2515 maxlen * sizeof(U8 *));
2516 SvPOK_on(sv_points);
2517 sv_2mortal(sv_points);
2518 points=(U8**)SvPV_nolen(sv_points );
2519 if ( trie_type != trie_utf8_fold
2520 && (trie->bitmap || OP(c)==AHOCORASICKC) )
2523 bitmap=(U8*)trie->bitmap;
2525 bitmap=(U8*)ANYOF_BITMAP(c);
2527 /* this is the Aho-Corasick algorithm modified a touch
2528 to include special handling for long "unknown char" sequences.
2529 The basic idea being that we use AC as long as we are dealing
2530 with a possible matching char, when we encounter an unknown char
2531 (and we have not encountered an accepting state) we scan forward
2532 until we find a legal starting char.
2533 AC matching is basically that of trie matching, except that when
2534 we encounter a failing transition, we fall back to the current
2535 states "fail state", and try the current char again, a process
2536 we repeat until we reach the root state, state 1, or a legal
2537 transition. If we fail on the root state then we can either
2538 terminate if we have reached an accepting state previously, or
2539 restart the entire process from the beginning if we have not.
2542 while (s <= last_start) {
2543 const U32 uniflags = UTF8_ALLOW_DEFAULT;
2551 U8 *uscan = (U8*)NULL;
2552 U8 *leftmost = NULL;
2554 U32 accepted_word= 0;
2558 while ( state && uc <= (U8*)strend ) {
2560 U32 word = aho->states[ state ].wordnum;
2564 DEBUG_TRIE_EXECUTE_r(
2565 if ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2566 dump_exec_pos( (char *)uc, c, strend, real_start,
2567 (char *)uc, utf8_target );
2568 PerlIO_printf( Perl_debug_log,
2569 " Scanning for legal start char...\n");
2573 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2577 while ( uc <= (U8*)last_start && !BITMAP_TEST(bitmap,*uc) ) {
2583 if (uc >(U8*)last_start) break;
2587 U8 *lpos= points[ (pointpos - trie->wordinfo[word].len) % maxlen ];
2588 if (!leftmost || lpos < leftmost) {
2589 DEBUG_r(accepted_word=word);
2595 points[pointpos++ % maxlen]= uc;
2596 if (foldlen || uc < (U8*)strend) {
2597 REXEC_TRIE_READ_CHAR(trie_type, trie,
2599 uscan, len, uvc, charid, foldlen,
2601 DEBUG_TRIE_EXECUTE_r({
2602 dump_exec_pos( (char *)uc, c, strend,
2603 real_start, s, utf8_target);
2604 PerlIO_printf(Perl_debug_log,
2605 " Charid:%3u CP:%4"UVxf" ",
2617 word = aho->states[ state ].wordnum;
2619 base = aho->states[ state ].trans.base;
2621 DEBUG_TRIE_EXECUTE_r({
2623 dump_exec_pos( (char *)uc, c, strend, real_start,
2625 PerlIO_printf( Perl_debug_log,
2626 "%sState: %4"UVxf", word=%"UVxf,
2627 failed ? " Fail transition to " : "",
2628 (UV)state, (UV)word);
2634 ( ((offset = base + charid
2635 - 1 - trie->uniquecharcount)) >= 0)
2636 && ((U32)offset < trie->lasttrans)
2637 && trie->trans[offset].check == state
2638 && (tmp=trie->trans[offset].next))
2640 DEBUG_TRIE_EXECUTE_r(
2641 PerlIO_printf( Perl_debug_log," - legal\n"));
2646 DEBUG_TRIE_EXECUTE_r(
2647 PerlIO_printf( Perl_debug_log," - fail\n"));
2649 state = aho->fail[state];
2653 /* we must be accepting here */
2654 DEBUG_TRIE_EXECUTE_r(
2655 PerlIO_printf( Perl_debug_log," - accepting\n"));
2664 if (!state) state = 1;
2667 if ( aho->states[ state ].wordnum ) {
2668 U8 *lpos = points[ (pointpos - trie->wordinfo[aho->states[ state ].wordnum].len) % maxlen ];
2669 if (!leftmost || lpos < leftmost) {
2670 DEBUG_r(accepted_word=aho->states[ state ].wordnum);
2675 s = (char*)leftmost;
2676 DEBUG_TRIE_EXECUTE_r({
2678 Perl_debug_log,"Matches word #%"UVxf" at position %"IVdf". Trying full pattern...\n",
2679 (UV)accepted_word, (IV)(s - real_start)
2682 if (reginfo->intuit || regtry(reginfo, &s)) {
2688 DEBUG_TRIE_EXECUTE_r({
2689 PerlIO_printf( Perl_debug_log,"Pattern failed. Looking for new start point...\n");
2692 DEBUG_TRIE_EXECUTE_r(
2693 PerlIO_printf( Perl_debug_log,"No match.\n"));
2702 Perl_croak(aTHX_ "panic: unknown regstclass %d", (int)OP(c));
2709 /* set RX_SAVED_COPY, RX_SUBBEG etc.
2710 * flags have same meanings as with regexec_flags() */
2713 S_reg_set_capture_string(pTHX_ REGEXP * const rx,
2720 struct regexp *const prog = ReANY(rx);
2722 if (flags & REXEC_COPY_STR) {
2726 PerlIO_printf(Perl_debug_log,
2727 "Copy on write: regexp capture, type %d\n",
2730 /* Create a new COW SV to share the match string and store
2731 * in saved_copy, unless the current COW SV in saved_copy
2732 * is valid and suitable for our purpose */
2733 if (( prog->saved_copy
2734 && SvIsCOW(prog->saved_copy)
2735 && SvPOKp(prog->saved_copy)
2738 && SvPVX(sv) == SvPVX(prog->saved_copy)))
2740 /* just reuse saved_copy SV */
2741 if (RXp_MATCH_COPIED(prog)) {
2742 Safefree(prog->subbeg);
2743 RXp_MATCH_COPIED_off(prog);
2747 /* create new COW SV to share string */
2748 RX_MATCH_COPY_FREE(rx);
2749 prog->saved_copy = sv_setsv_cow(prog->saved_copy, sv);
2751 prog->subbeg = (char *)SvPVX_const(prog->saved_copy);
2752 assert (SvPOKp(prog->saved_copy));
2753 prog->sublen = strend - strbeg;
2754 prog->suboffset = 0;
2755 prog->subcoffset = 0;
2760 SSize_t max = strend - strbeg;
2763 if ( (flags & REXEC_COPY_SKIP_POST)
2764 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2765 && !(PL_sawampersand & SAWAMPERSAND_RIGHT)
2766 ) { /* don't copy $' part of string */
2769 /* calculate the right-most part of the string covered
2770 * by a capture. Due to lookahead, this may be to
2771 * the right of $&, so we have to scan all captures */
2772 while (n <= prog->lastparen) {
2773 if (prog->offs[n].end > max)
2774 max = prog->offs[n].end;
2778 max = (PL_sawampersand & SAWAMPERSAND_LEFT)
2779 ? prog->offs[0].start
2781 assert(max >= 0 && max <= strend - strbeg);
2784 if ( (flags & REXEC_COPY_SKIP_PRE)
2785 && !(prog->extflags & RXf_PMf_KEEPCOPY) /* //p */
2786 && !(PL_sawampersand & SAWAMPERSAND_LEFT)
2787 ) { /* don't copy $` part of string */
2790 /* calculate the left-most part of the string covered
2791 * by a capture. Due to lookbehind, this may be to
2792 * the left of $&, so we have to scan all captures */
2793 while (min && n <= prog->lastparen) {
2794 if ( prog->offs[n].start != -1
2795 && prog->offs[n].start < min)
2797 min = prog->offs[n].start;
2801 if ((PL_sawampersand & SAWAMPERSAND_RIGHT)
2802 && min > prog->offs[0].end
2804 min = prog->offs[0].end;
2808 assert(min >= 0 && min <= max && min <= strend - strbeg);
2811 if (RX_MATCH_COPIED(rx)) {
2812 if (sublen > prog->sublen)
2814 (char*)saferealloc(prog->subbeg, sublen+1);
2817 prog->subbeg = (char*)safemalloc(sublen+1);
2818 Copy(strbeg + min, prog->subbeg, sublen, char);
2819 prog->subbeg[sublen] = '\0';
2820 prog->suboffset = min;
2821 prog->sublen = sublen;
2822 RX_MATCH_COPIED_on(rx);
2824 prog->subcoffset = prog->suboffset;
2825 if (prog->suboffset && utf8_target) {
2826 /* Convert byte offset to chars.
2827 * XXX ideally should only compute this if @-/@+
2828 * has been seen, a la PL_sawampersand ??? */
2830 /* If there's a direct correspondence between the
2831 * string which we're matching and the original SV,
2832 * then we can use the utf8 len cache associated with
2833 * the SV. In particular, it means that under //g,
2834 * sv_pos_b2u() will use the previously cached
2835 * position to speed up working out the new length of
2836 * subcoffset, rather than counting from the start of
2837 * the string each time. This stops
2838 * $x = "\x{100}" x 1E6; 1 while $x =~ /(.)/g;
2839 * from going quadratic */
2840 if (SvPOKp(sv) && SvPVX(sv) == strbeg)
2841 prog->subcoffset = sv_pos_b2u_flags(sv, prog->subcoffset,
2842 SV_GMAGIC|SV_CONST_RETURN);
2844 prog->subcoffset = utf8_length((U8*)strbeg,
2845 (U8*)(strbeg+prog->suboffset));
2849 RX_MATCH_COPY_FREE(rx);
2850 prog->subbeg = strbeg;
2851 prog->suboffset = 0;
2852 prog->subcoffset = 0;
2853 prog->sublen = strend - strbeg;
2861 - regexec_flags - match a regexp against a string
2864 Perl_regexec_flags(pTHX_ REGEXP * const rx, char *stringarg, char *strend,
2865 char *strbeg, SSize_t minend, SV *sv, void *data, U32 flags)
2866 /* stringarg: the point in the string at which to begin matching */
2867 /* strend: pointer to null at end of string */
2868 /* strbeg: real beginning of string */
2869 /* minend: end of match must be >= minend bytes after stringarg. */
2870 /* sv: SV being matched: only used for utf8 flag, pos() etc; string
2871 * itself is accessed via the pointers above */
2872 /* data: May be used for some additional optimizations.
2873 Currently unused. */
2874 /* flags: For optimizations. See REXEC_* in regexp.h */
2877 struct regexp *const prog = ReANY(rx);
2881 SSize_t minlen; /* must match at least this many chars */
2882 SSize_t dontbother = 0; /* how many characters not to try at end */
2883 const bool utf8_target = cBOOL(DO_UTF8(sv));
2885 RXi_GET_DECL(prog,progi);
2886 regmatch_info reginfo_buf; /* create some info to pass to regtry etc */
2887 regmatch_info *const reginfo = ®info_buf;
2888 regexp_paren_pair *swap = NULL;
2890 GET_RE_DEBUG_FLAGS_DECL;
2892 PERL_ARGS_ASSERT_REGEXEC_FLAGS;
2893 PERL_UNUSED_ARG(data);
2895 /* Be paranoid... */
2897 Perl_croak(aTHX_ "NULL regexp parameter");
2901 debug_start_match(rx, utf8_target, stringarg, strend,
2905 startpos = stringarg;
2907 /* set these early as they may be used by the HOP macros below */
2908 reginfo->strbeg = strbeg;
2909 reginfo->strend = strend;
2910 reginfo->is_utf8_target = cBOOL(utf8_target);
2912 if (prog->intflags & PREGf_GPOS_SEEN) {
2915 /* set reginfo->ganch, the position where \G can match */
2918 (flags & REXEC_IGNOREPOS)
2919 ? stringarg /* use start pos rather than pos() */
2920 : ((mg = mg_find_mglob(sv)) && mg->mg_len >= 0)
2921 /* Defined pos(): */
2922 ? strbeg + MgBYTEPOS(mg, sv, strbeg, strend-strbeg)
2923 : strbeg; /* pos() not defined; use start of string */
2925 DEBUG_GPOS_r(PerlIO_printf(Perl_debug_log,
2926 "GPOS ganch set to strbeg[%"IVdf"]\n", (IV)(reginfo->ganch - strbeg)));
2928 /* in the presence of \G, we may need to start looking earlier in
2929 * the string than the suggested start point of stringarg:
2930 * if prog->gofs is set, then that's a known, fixed minimum
2933 * /ab|c\G/: gofs = 1
2934 * or if the minimum offset isn't known, then we have to go back
2935 * to the start of the string, e.g. /w+\G/
2938 if (prog->intflags & PREGf_ANCH_GPOS) {
2940 startpos = HOPBACKc(reginfo->ganch, prog->gofs);
2942 ((flags & REXEC_FAIL_ON_UNDERFLOW) && startpos < stringarg))
2944 DEBUG_r(PerlIO_printf(Perl_debug_log,
2945 "fail: ganch-gofs before earliest possible start\n"));
2950 startpos = reginfo->ganch;
2952 else if (prog->gofs) {
2953 startpos = HOPBACKc(startpos, prog->gofs);
2957 else if (prog->intflags & PREGf_GPOS_FLOAT)
2961 minlen = prog->minlen;
2962 if ((startpos + minlen) > strend || startpos < strbeg) {
2963 DEBUG_r(PerlIO_printf(Perl_debug_log,
2964 "Regex match can't succeed, so not even tried\n"));
2968 /* at the end of this function, we'll do a LEAVE_SCOPE(oldsave),
2969 * which will call destuctors to reset PL_regmatch_state, free higher
2970 * PL_regmatch_slabs, and clean up regmatch_info_aux and
2971 * regmatch_info_aux_eval */
2973 oldsave = PL_savestack_ix;
2977 if ((prog->extflags & RXf_USE_INTUIT)
2978 && !(flags & REXEC_CHECKED))
2980 s = re_intuit_start(rx, sv, strbeg, startpos, strend,
2985 if (prog->extflags & RXf_CHECK_ALL) {
2986 /* we can match based purely on the result of INTUIT.
2987 * Set up captures etc just for $& and $-[0]
2988 * (an intuit-only match wont have $1,$2,..) */
2989 assert(!prog->nparens);
2991 /* s/// doesn't like it if $& is earlier than where we asked it to
2992 * start searching (which can happen on something like /.\G/) */
2993 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
2996 /* this should only be possible under \G */
2997 assert(prog->intflags & PREGf_GPOS_SEEN);
2998 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
2999 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3003 /* match via INTUIT shouldn't have any captures.
3004 * Let @-, @+, $^N know */
3005 prog->lastparen = prog->lastcloseparen = 0;
3006 RX_MATCH_UTF8_set(rx, utf8_target);
3007 prog->offs[0].start = s - strbeg;
3008 prog->offs[0].end = utf8_target
3009 ? (char*)utf8_hop((U8*)s, prog->minlenret) - strbeg
3010 : s - strbeg + prog->minlenret;
3011 if ( !(flags & REXEC_NOT_FIRST) )
3012 S_reg_set_capture_string(aTHX_ rx,
3014 sv, flags, utf8_target);
3020 multiline = prog->extflags & RXf_PMf_MULTILINE;
3022 if (strend - s < (minlen+(prog->check_offset_min<0?prog->check_offset_min:0))) {
3023 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
3024 "String too short [regexec_flags]...\n"));
3028 /* Check validity of program. */
3029 if (UCHARAT(progi->program) != REG_MAGIC) {
3030 Perl_croak(aTHX_ "corrupted regexp program");
3033 RX_MATCH_TAINTED_off(rx);
3034 RX_MATCH_UTF8_set(rx, utf8_target);
3036 reginfo->prog = rx; /* Yes, sorry that this is confusing. */
3037 reginfo->intuit = 0;
3038 reginfo->is_utf8_pat = cBOOL(RX_UTF8(rx));
3039 reginfo->warned = FALSE;
3041 reginfo->poscache_maxiter = 0; /* not yet started a countdown */
3042 /* see how far we have to get to not match where we matched before */
3043 reginfo->till = stringarg + minend;
3045 if (prog->extflags & RXf_EVAL_SEEN && SvPADTMP(sv)) {
3046 /* SAVEFREESV, not sv_mortalcopy, as this SV must last until after
3047 S_cleanup_regmatch_info_aux has executed (registered by
3048 SAVEDESTRUCTOR_X below). S_cleanup_regmatch_info_aux modifies
3049 magic belonging to this SV.
3050 Not newSVsv, either, as it does not COW.
3052 reginfo->sv = newSV(0);
3053 SvSetSV_nosteal(reginfo->sv, sv);
3054 SAVEFREESV(reginfo->sv);
3057 /* reserve next 2 or 3 slots in PL_regmatch_state:
3058 * slot N+0: may currently be in use: skip it
3059 * slot N+1: use for regmatch_info_aux struct
3060 * slot N+2: use for regmatch_info_aux_eval struct if we have (?{})'s
3061 * slot N+3: ready for use by regmatch()
3065 regmatch_state *old_regmatch_state;
3066 regmatch_slab *old_regmatch_slab;
3067 int i, max = (prog->extflags & RXf_EVAL_SEEN) ? 2 : 1;
3069 /* on first ever match, allocate first slab */
3070 if (!PL_regmatch_slab) {
3071 Newx(PL_regmatch_slab, 1, regmatch_slab);
3072 PL_regmatch_slab->prev = NULL;
3073 PL_regmatch_slab->next = NULL;
3074 PL_regmatch_state = SLAB_FIRST(PL_regmatch_slab);
3077 old_regmatch_state = PL_regmatch_state;
3078 old_regmatch_slab = PL_regmatch_slab;
3080 for (i=0; i <= max; i++) {
3082 reginfo->info_aux = &(PL_regmatch_state->u.info_aux);
3084 reginfo->info_aux_eval =
3085 reginfo->info_aux->info_aux_eval =
3086 &(PL_regmatch_state->u.info_aux_eval);
3088 if (++PL_regmatch_state > SLAB_LAST(PL_regmatch_slab))
3089 PL_regmatch_state = S_push_slab(aTHX);
3092 /* note initial PL_regmatch_state position; at end of match we'll
3093 * pop back to there and free any higher slabs */
3095 reginfo->info_aux->old_regmatch_state = old_regmatch_state;
3096 reginfo->info_aux->old_regmatch_slab = old_regmatch_slab;
3097 reginfo->info_aux->poscache = NULL;
3099 SAVEDESTRUCTOR_X(S_cleanup_regmatch_info_aux, reginfo->info_aux);
3101 if ((prog->extflags & RXf_EVAL_SEEN))
3102 S_setup_eval_state(aTHX_ reginfo);
3104 reginfo->info_aux_eval = reginfo->info_aux->info_aux_eval = NULL;
3107 /* If there is a "must appear" string, look for it. */
3109 if (PL_curpm && (PM_GETRE(PL_curpm) == rx)) {
3110 /* We have to be careful. If the previous successful match
3111 was from this regex we don't want a subsequent partially
3112 successful match to clobber the old results.
3113 So when we detect this possibility we add a swap buffer
3114 to the re, and switch the buffer each match. If we fail,
3115 we switch it back; otherwise we leave it swapped.
3118 /* do we need a save destructor here for eval dies? */
3119 Newxz(prog->offs, (prog->nparens + 1), regexp_paren_pair);
3120 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
3121 "rex=0x%"UVxf" saving offs: orig=0x%"UVxf" new=0x%"UVxf"\n",
3128 /* Simplest case: anchored match need be tried only once, or with
3129 * MBOL, only at the beginning of each line.
3131 * Note that /.*.../ sets PREGf_IMPLICIT|MBOL, while /.*.../s sets
3132 * PREGf_IMPLICIT|SBOL. The idea is that with /.*.../s, if it doesn't
3133 * match at the start of the string then it won't match anywhere else
3134 * either; while with /.*.../, if it doesn't match at the beginning,
3135 * the earliest it could match is at the start of the next line */
3137 if (prog->intflags & (PREGf_ANCH & ~PREGf_ANCH_GPOS)) {
3140 if (regtry(reginfo, &s))
3143 if (!(prog->intflags & PREGf_ANCH_MBOL))
3146 /* didn't match at start, try at other newline positions */
3149 dontbother = minlen - 1;
3150 end = HOP3c(strend, -dontbother, strbeg) - 1;
3152 /* skip to next newline */
3154 while (s <= end) { /* note it could be possible to match at the end of the string */
3155 /* NB: newlines are the same in unicode as they are in latin */
3158 if (prog->check_substr || prog->check_utf8) {
3159 /* note that with PREGf_IMPLICIT, intuit can only fail
3160 * or return the start position, so it's of limited utility.
3161 * Nevertheless, I made the decision that the potential for
3162 * quick fail was still worth it - DAPM */
3163 s = re_intuit_start(rx, sv, strbeg, s, strend, flags, NULL);
3167 if (regtry(reginfo, &s))
3171 } /* end anchored search */
3173 if (prog->intflags & PREGf_ANCH_GPOS)
3175 /* PREGf_ANCH_GPOS should never be true if PREGf_GPOS_SEEN is not true */
3176 assert(prog->intflags & PREGf_GPOS_SEEN);
3177 /* For anchored \G, the only position it can match from is
3178 * (ganch-gofs); we already set startpos to this above; if intuit
3179 * moved us on from there, we can't possibly succeed */
3180 assert(startpos == HOPBACKc(reginfo->ganch, prog->gofs));
3181 if (s == startpos && regtry(reginfo, &s))
3186 /* Messy cases: unanchored match. */
3187 if ((prog->anchored_substr || prog->anchored_utf8) && prog->intflags & PREGf_SKIP) {
3188 /* we have /x+whatever/ */
3189 /* it must be a one character string (XXXX Except is_utf8_pat?) */
3195 if (! prog->anchored_utf8) {
3196 to_utf8_substr(prog);
3198 ch = SvPVX_const(prog->anchored_utf8)[0];
3201 DEBUG_EXECUTE_r( did_match = 1 );
3202 if (regtry(reginfo, &s)) goto got_it;
3204 while (s < strend && *s == ch)
3211 if (! prog->anchored_substr) {
3212 if (! to_byte_substr(prog)) {
3213 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3216 ch = SvPVX_const(prog->anchored_substr)[0];
3219 DEBUG_EXECUTE_r( did_match = 1 );
3220 if (regtry(reginfo, &s)) goto got_it;
3222 while (s < strend && *s == ch)
3227 DEBUG_EXECUTE_r(if (!did_match)
3228 PerlIO_printf(Perl_debug_log,
3229 "Did not find anchored character...\n")
3232 else if (prog->anchored_substr != NULL
3233 || prog->anchored_utf8 != NULL
3234 || ((prog->float_substr != NULL || prog->float_utf8 != NULL)
3235 && prog->float_max_offset < strend - s)) {
3240 char *last1; /* Last position checked before */
3244 if (prog->anchored_substr || prog->anchored_utf8) {
3246 if (! prog->anchored_utf8) {
3247 to_utf8_substr(prog);
3249 must = prog->anchored_utf8;
3252 if (! prog->anchored_substr) {
3253 if (! to_byte_substr(prog)) {
3254 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3257 must = prog->anchored_substr;
3259 back_max = back_min = prog->anchored_offset;
3262 if (! prog->float_utf8) {
3263 to_utf8_substr(prog);
3265 must = prog->float_utf8;
3268 if (! prog->float_substr) {
3269 if (! to_byte_substr(prog)) {
3270 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3273 must = prog->float_substr;
3275 back_max = prog->float_max_offset;
3276 back_min = prog->float_min_offset;
3282 last = HOP3c(strend, /* Cannot start after this */
3283 -(SSize_t)(CHR_SVLEN(must)
3284 - (SvTAIL(must) != 0) + back_min), strbeg);
3286 if (s > reginfo->strbeg)
3287 last1 = HOPc(s, -1);
3289 last1 = s - 1; /* bogus */
3291 /* XXXX check_substr already used to find "s", can optimize if
3292 check_substr==must. */
3294 strend = HOPc(strend, -dontbother);
3295 while ( (s <= last) &&
3296 (s = fbm_instr((unsigned char*)HOP4c(s, back_min, strbeg, strend),
3297 (unsigned char*)strend, must,
3298 multiline ? FBMrf_MULTILINE : 0)) ) {
3299 DEBUG_EXECUTE_r( did_match = 1 );
3300 if (HOPc(s, -back_max) > last1) {
3301 last1 = HOPc(s, -back_min);
3302 s = HOPc(s, -back_max);
3305 char * const t = (last1 >= reginfo->strbeg)
3306 ? HOPc(last1, 1) : last1 + 1;
3308 last1 = HOPc(s, -back_min);
3312 while (s <= last1) {
3313 if (regtry(reginfo, &s))
3316 s++; /* to break out of outer loop */
3323 while (s <= last1) {
3324 if (regtry(reginfo, &s))
3330 DEBUG_EXECUTE_r(if (!did_match) {
3331 RE_PV_QUOTED_DECL(quoted, utf8_target, PERL_DEBUG_PAD_ZERO(0),
3332 SvPVX_const(must), RE_SV_DUMPLEN(must), 30);
3333 PerlIO_printf(Perl_debug_log, "Did not find %s substr %s%s...\n",
3334 ((must == prog->anchored_substr || must == prog->anchored_utf8)
3335 ? "anchored" : "floating"),
3336 quoted, RE_SV_TAIL(must));
3340 else if ( (c = progi->regstclass) ) {
3342 const OPCODE op = OP(progi->regstclass);
3343 /* don't bother with what can't match */
3344 if (PL_regkind[op] != EXACT && PL_regkind[op] != TRIE)
3345 strend = HOPc(strend, -(minlen - 1));
3348 SV * const prop = sv_newmortal();
3349 regprop(prog, prop, c, reginfo, NULL);
3351 RE_PV_QUOTED_DECL(quoted,utf8_target,PERL_DEBUG_PAD_ZERO(1),
3353 PerlIO_printf(Perl_debug_log,
3354 "Matching stclass %.*s against %s (%d bytes)\n",
3355 (int)SvCUR(prop), SvPVX_const(prop),
3356 quoted, (int)(strend - s));
3359 if (find_byclass(prog, c, s, strend, reginfo))
3361 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "Contradicts stclass... [regexec_flags]\n"));
3365 if (prog->float_substr != NULL || prog->float_utf8 != NULL) {
3373 if (! prog->float_utf8) {
3374 to_utf8_substr(prog);
3376 float_real = prog->float_utf8;
3379 if (! prog->float_substr) {
3380 if (! to_byte_substr(prog)) {
3381 NON_UTF8_TARGET_BUT_UTF8_REQUIRED(phooey);
3384 float_real = prog->float_substr;
3387 little = SvPV_const(float_real, len);
3388 if (SvTAIL(float_real)) {
3389 /* This means that float_real contains an artificial \n on
3390 * the end due to the presence of something like this:
3391 * /foo$/ where we can match both "foo" and "foo\n" at the
3392 * end of the string. So we have to compare the end of the
3393 * string first against the float_real without the \n and
3394 * then against the full float_real with the string. We
3395 * have to watch out for cases where the string might be
3396 * smaller than the float_real or the float_real without
3398 char *checkpos= strend - len;
3400 PerlIO_printf(Perl_debug_log,
3401 "%sChecking for float_real.%s\n",
3402 PL_colors[4], PL_colors[5]));
3403 if (checkpos + 1 < strbeg) {
3404 /* can't match, even if we remove the trailing \n
3405 * string is too short to match */
3407 PerlIO_printf(Perl_debug_log,
3408 "%sString shorter than required trailing substring, cannot match.%s\n",
3409 PL_colors[4], PL_colors[5]));
3411 } else if (memEQ(checkpos + 1, little, len - 1)) {
3412 /* can match, the end of the string matches without the
3414 last = checkpos + 1;
3415 } else if (checkpos < strbeg) {
3416 /* cant match, string is too short when the "\n" is
3419 PerlIO_printf(Perl_debug_log,
3420 "%sString does not contain required trailing substring, cannot match.%s\n",
3421 PL_colors[4], PL_colors[5]));
3423 } else if (!multiline) {
3424 /* non multiline match, so compare with the "\n" at the
3425 * end of the string */
3426 if (memEQ(checkpos, little, len)) {
3430 PerlIO_printf(Perl_debug_log,
3431 "%sString does not contain required trailing substring, cannot match.%s\n",
3432 PL_colors[4], PL_colors[5]));
3436 /* multiline match, so we have to search for a place
3437 * where the full string is located */
3443 last = rninstr(s, strend, little, little + len);
3445 last = strend; /* matching "$" */
3448 /* at one point this block contained a comment which was
3449 * probably incorrect, which said that this was a "should not
3450 * happen" case. Even if it was true when it was written I am
3451 * pretty sure it is not anymore, so I have removed the comment
3452 * and replaced it with this one. Yves */
3454 PerlIO_printf(Perl_debug_log,
3455 "%sString does not contain required substring, cannot match.%s\n",
3456 PL_colors[4], PL_colors[5]
3460 dontbother = strend - last + prog->float_min_offset;
3462 if (minlen && (dontbother < minlen))
3463 dontbother = minlen - 1;
3464 strend -= dontbother; /* this one's always in bytes! */
3465 /* We don't know much -- general case. */
3468 if (regtry(reginfo, &s))
3477 if (regtry(reginfo, &s))
3479 } while (s++ < strend);
3487 /* s/// doesn't like it if $& is earlier than where we asked it to
3488 * start searching (which can happen on something like /.\G/) */
3489 if ( (flags & REXEC_FAIL_ON_UNDERFLOW)
3490 && (prog->offs[0].start < stringarg - strbeg))
3492 /* this should only be possible under \G */
3493 assert(prog->intflags & PREGf_GPOS_SEEN);
3494 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
3495 "matched, but failing for REXEC_FAIL_ON_UNDERFLOW\n"));
3501 PerlIO_printf(Perl_debug_log,
3502 "rex=0x%"UVxf" freeing offs: 0x%"UVxf"\n",
3509 /* clean up; this will trigger destructors that will free all slabs
3510 * above the current one, and cleanup the regmatch_info_aux
3511 * and regmatch_info_aux_eval sructs */
3513 LEAVE_SCOPE(oldsave);
3515 if (RXp_PAREN_NAMES(prog))
3516 (void)hv_iterinit(RXp_PAREN_NAMES(prog));
3518 /* make sure $`, $&, $', and $digit will work later */
3519 if ( !(flags & REXEC_NOT_FIRST) )
3520 S_reg_set_capture_string(aTHX_ rx,
3521 strbeg, reginfo->strend,
3522 sv, flags, utf8_target);
3527 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch failed%s\n",
3528 PL_colors[4], PL_colors[5]));
3530 /* clean up; this will trigger destructors that will free all slabs
3531 * above the current one, and cleanup the regmatch_info_aux
3532 * and regmatch_info_aux_eval sructs */
3534 LEAVE_SCOPE(oldsave);
3537 /* we failed :-( roll it back */
3538 DEBUG_BUFFERS_r(PerlIO_printf(Perl_debug_log,
3539 "rex=0x%"UVxf" rolling back offs: freeing=0x%"UVxf" restoring=0x%"UVxf"\n",
3544 Safefree(prog->offs);
3551 /* Set which rex is pointed to by PL_reg_curpm, handling ref counting.
3552 * Do inc before dec, in case old and new rex are the same */
3553 #define SET_reg_curpm(Re2) \
3554 if (reginfo->info_aux_eval) { \
3555 (void)ReREFCNT_inc(Re2); \
3556 ReREFCNT_dec(PM_GETRE(PL_reg_curpm)); \
3557 PM_SETRE((PL_reg_curpm), (Re2)); \
3562 - regtry - try match at specific point
3564 STATIC bool /* 0 failure, 1 success */
3565 S_regtry(pTHX_ regmatch_info *reginfo, char **startposp)
3568 REGEXP *const rx = reginfo->prog;
3569 regexp *const prog = ReANY(rx);
3571 RXi_GET_DECL(prog,progi);
3572 GET_RE_DEBUG_FLAGS_DECL;
3574 PERL_ARGS_ASSERT_REGTRY;
3576 reginfo->cutpoint=NULL;
3578 prog->offs[0].start = *startposp - reginfo->strbeg;
3579 prog->lastparen = 0;
3580 prog->lastcloseparen = 0;
3582 /* XXXX What this code is doing here?!!! There should be no need
3583 to do this again and again, prog->lastparen should take care of
3586 /* Tests pat.t#187 and split.t#{13,14} seem to depend on this code.
3587 * Actually, the code in regcppop() (which Ilya may be meaning by
3588 * prog->lastparen), is not needed at all by the test suite
3589 * (op/regexp, op/pat, op/split), but that code is needed otherwise
3590 * this erroneously leaves $1 defined: "1" =~ /^(?:(\d)x)?\d$/
3591 * Meanwhile, this code *is* needed for the
3592 * above-mentioned test suite tests to succeed. The common theme
3593 * on those tests seems to be returning null fields from matches.
3594 * --jhi updated by dapm */
3596 if (prog->nparens) {
3597 regexp_paren_pair *pp = prog->offs;
3599 for (i = prog->nparens; i > (I32)prog->lastparen; i--) {
3607 result = regmatch(reginfo, *startposp, progi->program + 1);
3609 prog->offs[0].end = result;
3612 if (reginfo->cutpoint)
3613 *startposp= reginfo->cutpoint;
3614 REGCP_UNWIND(lastcp);
3619 #define sayYES goto yes
3620 #define sayNO goto no
3621 #define sayNO_SILENT goto no_silent
3623 /* we dont use STMT_START/END here because it leads to
3624 "unreachable code" warnings, which are bogus, but distracting. */
3625 #define CACHEsayNO \
3626 if (ST.cache_mask) \
3627 reginfo->info_aux->poscache[ST.cache_offset] |= ST.cache_mask; \
3630 /* this is used to determine how far from the left messages like
3631 'failed...' are printed. It should be set such that messages
3632 are inline with the regop output that created them.
3634 #define REPORT_CODE_OFF 32
3637 #define CHRTEST_UNINIT -1001 /* c1/c2 haven't been calculated yet */
3638 #define CHRTEST_VOID -1000 /* the c1/c2 "next char" test should be skipped */
3639 #define CHRTEST_NOT_A_CP_1 -999
3640 #define CHRTEST_NOT_A_CP_2 -998
3642 /* grab a new slab and return the first slot in it */
3644 STATIC regmatch_state *
3647 #if PERL_VERSION < 9 && !defined(PERL_CORE)
3650 regmatch_slab *s = PL_regmatch_slab->next;
3652 Newx(s, 1, regmatch_slab);
3653 s->prev = PL_regmatch_slab;
3655 PL_regmatch_slab->next = s;
3657 PL_regmatch_slab = s;
3658 return SLAB_FIRST(s);
3662 /* push a new state then goto it */
3664 #define PUSH_STATE_GOTO(state, node, input) \
3665 pushinput = input; \
3667 st->resume_state = state; \
3670 /* push a new state with success backtracking, then goto it */
3672 #define PUSH_YES_STATE_GOTO(state, node, input) \
3673 pushinput = input; \
3675 st->resume_state = state; \
3676 goto push_yes_state;
3683 regmatch() - main matching routine
3685 This is basically one big switch statement in a loop. We execute an op,
3686 set 'next' to point the next op, and continue. If we come to a point which
3687 we may need to backtrack to on failure such as (A|B|C), we push a
3688 backtrack state onto the backtrack stack. On failure, we pop the top
3689 state, and re-enter the loop at the state indicated. If there are no more
3690 states to pop, we return failure.
3692 Sometimes we also need to backtrack on success; for example /A+/, where
3693 after successfully matching one A, we need to go back and try to
3694 match another one; similarly for lookahead assertions: if the assertion
3695 completes successfully, we backtrack to the state just before the assertion
3696 and then carry on. In these cases, the pushed state is marked as
3697 'backtrack on success too'. This marking is in fact done by a chain of
3698 pointers, each pointing to the previous 'yes' state. On success, we pop to
3699 the nearest yes state, discarding any intermediate failure-only states.
3700 Sometimes a yes state is pushed just to force some cleanup code to be
3701 called at the end of a successful match or submatch; e.g. (??{$re}) uses
3702 it to free the inner regex.
3704 Note that failure backtracking rewinds the cursor position, while
3705 success backtracking leaves it alone.
3707 A pattern is complete when the END op is executed, while a subpattern
3708 such as (?=foo) is complete when the SUCCESS op is executed. Both of these
3709 ops trigger the "pop to last yes state if any, otherwise return true"
3712 A common convention in this function is to use A and B to refer to the two
3713 subpatterns (or to the first nodes thereof) in patterns like /A*B/: so A is
3714 the subpattern to be matched possibly multiple times, while B is the entire
3715 rest of the pattern. Variable and state names reflect this convention.
3717 The states in the main switch are the union of ops and failure/success of
3718 substates associated with with that op. For example, IFMATCH is the op
3719 that does lookahead assertions /(?=A)B/ and so the IFMATCH state means
3720 'execute IFMATCH'; while IFMATCH_A is a state saying that we have just
3721 successfully matched A and IFMATCH_A_fail is a state saying that we have
3722 just failed to match A. Resume states always come in pairs. The backtrack
3723 state we push is marked as 'IFMATCH_A', but when that is popped, we resume
3724 at IFMATCH_A or IFMATCH_A_fail, depending on whether we are backtracking
3725 on success or failure.
3727 The struct that holds a backtracking state is actually a big union, with
3728 one variant for each major type of op. The variable st points to the
3729 top-most backtrack struct. To make the code clearer, within each
3730 block of code we #define ST to alias the relevant union.
3732 Here's a concrete example of a (vastly oversimplified) IFMATCH
3738 #define ST st->u.ifmatch
3740 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3741 ST.foo = ...; // some state we wish to save
3743 // push a yes backtrack state with a resume value of
3744 // IFMATCH_A/IFMATCH_A_fail, then continue execution at the
3746 PUSH_YES_STATE_GOTO(IFMATCH_A, A, newinput);
3749 case IFMATCH_A: // we have successfully executed A; now continue with B
3751 bar = ST.foo; // do something with the preserved value
3754 case IFMATCH_A_fail: // A failed, so the assertion failed
3755 ...; // do some housekeeping, then ...
3756 sayNO; // propagate the failure
3763 For any old-timers reading this who are familiar with the old recursive
3764 approach, the code above is equivalent to:
3766 case IFMATCH: // we are executing the IFMATCH op, (?=A)B
3775 ...; // do some housekeeping, then ...
3776 sayNO; // propagate the failure
3779 The topmost backtrack state, pointed to by st, is usually free. If you
3780 want to claim it, populate any ST.foo fields in it with values you wish to
3781 save, then do one of
3783 PUSH_STATE_GOTO(resume_state, node, newinput);
3784 PUSH_YES_STATE_GOTO(resume_state, node, newinput);
3786 which sets that backtrack state's resume value to 'resume_state', pushes a
3787 new free entry to the top of the backtrack stack, then goes to 'node'.
3788 On backtracking, the free slot is popped, and the saved state becomes the
3789 new free state. An ST.foo field in this new top state can be temporarily
3790 accessed to retrieve values, but once the main loop is re-entered, it
3791 becomes available for reuse.
3793 Note that the depth of the backtrack stack constantly increases during the
3794 left-to-right execution of the pattern, rather than going up and down with
3795 the pattern nesting. For example the stack is at its maximum at Z at the
3796 end of the pattern, rather than at X in the following:
3798 /(((X)+)+)+....(Y)+....Z/
3800 The only exceptions to this are lookahead/behind assertions and the cut,
3801 (?>A), which pop all the backtrack states associated with A before
3804 Backtrack state structs are allocated in slabs of about 4K in size.
3805 PL_regmatch_state and st always point to the currently active state,
3806 and PL_regmatch_slab points to the slab currently containing
3807 PL_regmatch_state. The first time regmatch() is called, the first slab is
3808 allocated, and is never freed until interpreter destruction. When the slab
3809 is full, a new one is allocated and chained to the end. At exit from
3810 regmatch(), slabs allocated since entry are freed.
3815 #define DEBUG_STATE_pp(pp) \
3817 DUMP_EXEC_POS(locinput, scan, utf8_target); \
3818 PerlIO_printf(Perl_debug_log, \
3819 " %*s"pp" %s%s%s%s%s\n", \
3821 PL_reg_name[st->resume_state], \
3822 ((st==yes_state||st==mark_state) ? "[" : ""), \
3823 ((st==yes_state) ? "Y" : ""), \
3824 ((st==mark_state) ? "M" : ""), \
3825 ((st==yes_state||st==mark_state) ? "]" : "") \
3830 #define REG_NODE_NUM(x) ((x) ? (int)((x)-prog) : -1)
3835 S_debug_start_match(pTHX_ const REGEXP *prog, const bool utf8_target,
3836 const char *start, const char *end, const char *blurb)
3838 const bool utf8_pat = RX_UTF8(prog) ? 1 : 0;
3840 PERL_ARGS_ASSERT_DEBUG_START_MATCH;
3845 RE_PV_QUOTED_DECL(s0, utf8_pat, PERL_DEBUG_PAD_ZERO(0),
3846 RX_PRECOMP_const(prog), RX_PRELEN(prog), 60);
3848 RE_PV_QUOTED_DECL(s1, utf8_target, PERL_DEBUG_PAD_ZERO(1),
3849 start, end - start, 60);
3851 PerlIO_printf(Perl_debug_log,
3852 "%s%s REx%s %s against %s\n",
3853 PL_colors[4], blurb, PL_colors[5], s0, s1);
3855 if (utf8_target||utf8_pat)
3856 PerlIO_printf(Perl_debug_log, "UTF-8 %s%s%s...\n",
3857 utf8_pat ? "pattern" : "",
3858 utf8_pat && utf8_target ? " and " : "",
3859 utf8_target ? "string" : ""
3865 S_dump_exec_pos(pTHX_ const char *locinput,
3866 const regnode *scan,
3867 const char *loc_regeol,
3868 const char *loc_bostr,
3869 const char *loc_reg_starttry,
3870 const bool utf8_target)
3872 const int docolor = *PL_colors[0] || *PL_colors[2] || *PL_colors[4];
3873 const int taill = (docolor ? 10 : 7); /* 3 chars for "> <" */
3874 int l = (loc_regeol - locinput) > taill ? taill : (loc_regeol - locinput);
3875 /* The part of the string before starttry has one color
3876 (pref0_len chars), between starttry and current
3877 position another one (pref_len - pref0_len chars),
3878 after the current position the third one.
3879 We assume that pref0_len <= pref_len, otherwise we
3880 decrease pref0_len. */
3881 int pref_len = (locinput - loc_bostr) > (5 + taill) - l
3882 ? (5 + taill) - l : locinput - loc_bostr;
3885 PERL_ARGS_ASSERT_DUMP_EXEC_POS;
3887 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput - pref_len)))
3889 pref0_len = pref_len - (locinput - loc_reg_starttry);
3890 if (l + pref_len < (5 + taill) && l < loc_regeol - locinput)
3891 l = ( loc_regeol - locinput > (5 + taill) - pref_len
3892 ? (5 + taill) - pref_len : loc_regeol - locinput);
3893 while (utf8_target && UTF8_IS_CONTINUATION(*(U8*)(locinput + l)))
3897 if (pref0_len > pref_len)
3898 pref0_len = pref_len;
3900 const int is_uni = utf8_target ? 1 : 0;
3902 RE_PV_COLOR_DECL(s0,len0,is_uni,PERL_DEBUG_PAD(0),
3903 (locinput - pref_len),pref0_len, 60, 4, 5);
3905 RE_PV_COLOR_DECL(s1,len1,is_uni,PERL_DEBUG_PAD(1),
3906 (locinput - pref_len + pref0_len),
3907 pref_len - pref0_len, 60, 2, 3);
3909 RE_PV_COLOR_DECL(s2,len2,is_uni,PERL_DEBUG_PAD(2),
3910 locinput, loc_regeol - locinput, 10, 0, 1);
3912 const STRLEN tlen=len0+len1+len2;
3913 PerlIO_printf(Perl_debug_log,
3914 "%4"IVdf" <%.*s%.*s%s%.*s>%*s|",
3915 (IV)(locinput - loc_bostr),
3918 (docolor ? "" : "> <"),
3920 (int)(tlen > 19 ? 0 : 19 - tlen),
3927 /* reg_check_named_buff_matched()
3928 * Checks to see if a named buffer has matched. The data array of
3929 * buffer numbers corresponding to the buffer is expected to reside
3930 * in the regexp->data->data array in the slot stored in the ARG() of
3931 * node involved. Note that this routine doesn't actually care about the
3932 * name, that information is not preserved from compilation to execution.
3933 * Returns the index of the leftmost defined buffer with the given name
3934 * or 0 if non of the buffers matched.
3937 S_reg_check_named_buff_matched(const regexp *rex, const regnode *scan)
3940 RXi_GET_DECL(rex,rexi);
3941 SV *sv_dat= MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
3942 I32 *nums=(I32*)SvPVX(sv_dat);
3944 PERL_ARGS_ASSERT_REG_CHECK_NAMED_BUFF_MATCHED;
3946 for ( n=0; n<SvIVX(sv_dat); n++ ) {
3947 if ((I32)rex->lastparen >= nums[n] &&
3948 rex->offs[nums[n]].end != -1)
3958 S_setup_EXACTISH_ST_c1_c2(pTHX_ const regnode * const text_node, int *c1p,
3959 U8* c1_utf8, int *c2p, U8* c2_utf8, regmatch_info *reginfo)
3961 /* This function determines if there are one or two characters that match
3962 * the first character of the passed-in EXACTish node <text_node>, and if
3963 * so, returns them in the passed-in pointers.
3965 * If it determines that no possible character in the target string can
3966 * match, it returns FALSE; otherwise TRUE. (The FALSE situation occurs if
3967 * the first character in <text_node> requires UTF-8 to represent, and the
3968 * target string isn't in UTF-8.)
3970 * If there are more than two characters that could match the beginning of
3971 * <text_node>, or if more context is required to determine a match or not,
3972 * it sets both *<c1p> and *<c2p> to CHRTEST_VOID.
3974 * The motiviation behind this function is to allow the caller to set up
3975 * tight loops for matching. If <text_node> is of type EXACT, there is
3976 * only one possible character that can match its first character, and so
3977 * the situation is quite simple. But things get much more complicated if
3978 * folding is involved. It may be that the first character of an EXACTFish
3979 * node doesn't participate in any possible fold, e.g., punctuation, so it
3980 * can be matched only by itself. The vast majority of characters that are
3981 * in folds match just two things, their lower and upper-case equivalents.
3982 * But not all are like that; some have multiple possible matches, or match
3983 * sequences of more than one character. This function sorts all that out.
3985 * Consider the patterns A*B or A*?B where A and B are arbitrary. In a
3986 * loop of trying to match A*, we know we can't exit where the thing
3987 * following it isn't a B. And something can't be a B unless it is the
3988 * beginning of B. By putting a quick test for that beginning in a tight
3989 * loop, we can rule out things that can't possibly be B without having to
3990 * break out of the loop, thus avoiding work. Similarly, if A is a single
3991 * character, we can make a tight loop matching A*, using the outputs of
3994 * If the target string to match isn't in UTF-8, and there aren't
3995 * complications which require CHRTEST_VOID, *<c1p> and *<c2p> are set to
3996 * the one or two possible octets (which are characters in this situation)
3997 * that can match. In all cases, if there is only one character that can
3998 * match, *<c1p> and *<c2p> will be identical.
4000 * If the target string is in UTF-8, the buffers pointed to by <c1_utf8>
4001 * and <c2_utf8> will contain the one or two UTF-8 sequences of bytes that
4002 * can match the beginning of <text_node>. They should be declared with at
4003 * least length UTF8_MAXBYTES+1. (If the target string isn't in UTF-8, it is
4004 * undefined what these contain.) If one or both of the buffers are
4005 * invariant under UTF-8, *<c1p>, and *<c2p> will also be set to the
4006 * corresponding invariant. If variant, the corresponding *<c1p> and/or
4007 * *<c2p> will be set to a negative number(s) that shouldn't match any code
4008 * point (unless inappropriately coerced to unsigned). *<c1p> will equal
4009 * *<c2p> if and only if <c1_utf8> and <c2_utf8> are the same. */
4011 const bool utf8_target = reginfo->is_utf8_target;
4013 UV c1 = (UV)CHRTEST_NOT_A_CP_1;
4014 UV c2 = (UV)CHRTEST_NOT_A_CP_2;
4015 bool use_chrtest_void = FALSE;
4016 const bool is_utf8_pat = reginfo->is_utf8_pat;
4018 /* Used when we have both utf8 input and utf8 output, to avoid converting
4019 * to/from code points */
4020 bool utf8_has_been_setup = FALSE;
4024 U8 *pat = (U8*)STRING(text_node);
4025 U8 folded[UTF8_MAX_FOLD_CHAR_EXPAND * UTF8_MAXBYTES_CASE + 1] = { '\0' };
4027 if (OP(text_node) == EXACT || OP(text_node) == EXACTL) {
4029 /* In an exact node, only one thing can be matched, that first
4030 * character. If both the pat and the target are UTF-8, we can just
4031 * copy the input to the output, avoiding finding the code point of
4036 else if (utf8_target) {
4037 Copy(pat, c1_utf8, UTF8SKIP(pat), U8);
4038 Copy(pat, c2_utf8, UTF8SKIP(pat), U8);
4039 utf8_has_been_setup = TRUE;
4042 c2 = c1 = valid_utf8_to_uvchr(pat, NULL);
4045 else { /* an EXACTFish node */
4046 U8 *pat_end = pat + STR_LEN(text_node);
4048 /* An EXACTFL node has at least some characters unfolded, because what
4049 * they match is not known until now. So, now is the time to fold
4050 * the first few of them, as many as are needed to determine 'c1' and
4051 * 'c2' later in the routine. If the pattern isn't UTF-8, we only need
4052 * to fold if in a UTF-8 locale, and then only the Sharp S; everything
4053 * else is 1-1 and isn't assumed to be folded. In a UTF-8 pattern, we
4054 * need to fold as many characters as a single character can fold to,
4055 * so that later we can check if the first ones are such a multi-char
4056 * fold. But, in such a pattern only locale-problematic characters
4057 * aren't folded, so we can skip this completely if the first character
4058 * in the node isn't one of the tricky ones */
4059 if (OP(text_node) == EXACTFL) {
4061 if (! is_utf8_pat) {
4062 if (IN_UTF8_CTYPE_LOCALE && *pat == LATIN_SMALL_LETTER_SHARP_S)
4064 folded[0] = folded[1] = 's';
4066 pat_end = folded + 2;
4069 else if (is_PROBLEMATIC_LOCALE_FOLDEDS_START_utf8(pat)) {
4074 for (i = 0; i < UTF8_MAX_FOLD_CHAR_EXPAND && s < pat_end; i++) {
4076 *(d++) = (U8) toFOLD_LC(*s);
4081 _to_utf8_fold_flags(s,
4084 FOLD_FLAGS_FULL | FOLD_FLAGS_LOCALE);
4095 if ((is_utf8_pat && is_MULTI_CHAR_FOLD_utf8_safe(pat, pat_end))
4096 || (!is_utf8_pat && is_MULTI_CHAR_FOLD_latin1_safe(pat, pat_end)))
4098 /* Multi-character folds require more context to sort out. Also
4099 * PL_utf8_foldclosures used below doesn't handle them, so have to
4100 * be handled outside this routine */
4101 use_chrtest_void = TRUE;
4103 else { /* an EXACTFish node which doesn't begin with a multi-char fold */
4104 c1 = is_utf8_pat ? valid_utf8_to_uvchr(pat, NULL) : *pat;
4106 /* Load the folds hash, if not already done */
4108 if (! PL_utf8_foldclosures) {
4109 _load_PL_utf8_foldclosures();
4112 /* The fold closures data structure is a hash with the keys
4113 * being the UTF-8 of every character that is folded to, like
4114 * 'k', and the values each an array of all code points that
4115 * fold to its key. e.g. [ 'k', 'K', KELVIN_SIGN ].
4116 * Multi-character folds are not included */
4117 if ((! (listp = hv_fetch(PL_utf8_foldclosures,
4122 /* Not found in the hash, therefore there are no folds
4123 * containing it, so there is only a single character that
4127 else { /* Does participate in folds */
4128 AV* list = (AV*) *listp;
4129 if (av_tindex(list) != 1) {
4131 /* If there aren't exactly two folds to this, it is
4132 * outside the scope of this function */
4133 use_chrtest_void = TRUE;
4135 else { /* There are two. Get them */
4136 SV** c_p = av_fetch(list, 0, FALSE);
4138 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
4142 c_p = av_fetch(list, 1, FALSE);
4144 Perl_croak(aTHX_ "panic: invalid PL_utf8_foldclosures structure");
4148 /* Folds that cross the 255/256 boundary are forbidden
4149 * if EXACTFL (and isnt a UTF8 locale), or EXACTFA and
4150 * one is ASCIII. Since the pattern character is above
4151 * 255, and its only other match is below 256, the only
4152 * legal match will be to itself. We have thrown away
4153 * the original, so have to compute which is the one
4155 if ((c1 < 256) != (c2 < 256)) {
4156 if ((OP(text_node) == EXACTFL
4157 && ! IN_UTF8_CTYPE_LOCALE)
4158 || ((OP(text_node) == EXACTFA
4159 || OP(text_node) == EXACTFA_NO_TRIE)
4160 && (isASCII(c1) || isASCII(c2))))
4173 else /* Here, c1 is <= 255 */
4175 && HAS_NONLATIN1_FOLD_CLOSURE(c1)
4176 && ( ! (OP(text_node) == EXACTFL && ! IN_UTF8_CTYPE_LOCALE))
4177 && ((OP(text_node) != EXACTFA
4178 && OP(text_node) != EXACTFA_NO_TRIE)
4181 /* Here, there could be something above Latin1 in the target
4182 * which folds to this character in the pattern. All such
4183 * cases except LATIN SMALL LETTER Y WITH DIAERESIS have more
4184 * than two characters involved in their folds, so are outside
4185 * the scope of this function */
4186 if (UNLIKELY(c1 == LATIN_SMALL_LETTER_Y_WITH_DIAERESIS)) {
4187 c2 = LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS;
4190 use_chrtest_void = TRUE;
4193 else { /* Here nothing above Latin1 can fold to the pattern
4195 switch (OP(text_node)) {
4197 case EXACTFL: /* /l rules */
4198 c2 = PL_fold_locale[c1];
4201 case EXACTF: /* This node only generated for non-utf8
4203 assert(! is_utf8_pat);
4204 if (! utf8_target) { /* /d rules */
4209 /* /u rules for all these. This happens to work for
4210 * EXACTFA as nothing in Latin1 folds to ASCII */
4211 case EXACTFA_NO_TRIE: /* This node only generated for
4212 non-utf8 patterns */
4213 assert(! is_utf8_pat);
4218 c2 = PL_fold_latin1[c1];
4222 Perl_croak(aTHX_ "panic: Unexpected op %u", OP(text_node));
4223 NOT_REACHED; /* NOTREACHED */
4229 /* Here have figured things out. Set up the returns */
4230 if (use_chrtest_void) {
4231 *c2p = *c1p = CHRTEST_VOID;
4233 else if (utf8_target) {
4234 if (! utf8_has_been_setup) { /* Don't have the utf8; must get it */
4235 uvchr_to_utf8(c1_utf8, c1);
4236 uvchr_to_utf8(c2_utf8, c2);
4239 /* Invariants are stored in both the utf8 and byte outputs; Use
4240 * negative numbers otherwise for the byte ones. Make sure that the
4241 * byte ones are the same iff the utf8 ones are the same */
4242 *c1p = (UTF8_IS_INVARIANT(*c1_utf8)) ? *c1_utf8 : CHRTEST_NOT_A_CP_1;
4243 *c2p = (UTF8_IS_INVARIANT(*c2_utf8))
4246 ? CHRTEST_NOT_A_CP_1
4247 : CHRTEST_NOT_A_CP_2;
4249 else if (c1 > 255) {
4250 if (c2 > 255) { /* both possibilities are above what a non-utf8 string
4255 *c1p = *c2p = c2; /* c2 is the only representable value */
4257 else { /* c1 is representable; see about c2 */
4259 *c2p = (c2 < 256) ? c2 : c1;
4265 PERL_STATIC_INLINE bool
4266 S_isGCB(const GCB_enum before, const GCB_enum after)
4268 /* returns a boolean indicating if there is a Grapheme Cluster Boundary
4269 * between the inputs. See http://www.unicode.org/reports/tr29/ */
4271 return GCB_table[before][after];
4274 /* Combining marks attach to most classes that precede them, but this defines
4275 * the exceptions (from TR14) */
4276 #define LB_CM_ATTACHES_TO(prev) ( ! ( prev == LB_EDGE \
4277 || prev == LB_Mandatory_Break \
4278 || prev == LB_Carriage_Return \
4279 || prev == LB_Line_Feed \
4280 || prev == LB_Next_Line \
4281 || prev == LB_Space \
4282 || prev == LB_ZWSpace))
4285 S_isLB(pTHX_ LB_enum before,
4287 const U8 * const strbeg,
4288 const U8 * const curpos,
4289 const U8 * const strend,
4290 const bool utf8_target)
4292 U8 * temp_pos = (U8 *) curpos;
4293 LB_enum prev = before;
4295 /* Is the boundary between 'before' and 'after' line-breakable?
4296 * Most of this is just a table lookup of a generated table from Unicode
4297 * rules. But some rules require context to decide, and so have to be
4298 * implemented in code */
4300 PERL_ARGS_ASSERT_ISLB;
4302 /* Rule numbers in the comments below are as of Unicode 8.0 */
4306 switch (LB_table[before][after]) {
4311 case LB_NOBREAK_EVEN_WITH_SP_BETWEEN:
4314 case LB_SP_foo + LB_BREAKABLE:
4315 case LB_SP_foo + LB_NOBREAK:
4316 case LB_SP_foo + LB_NOBREAK_EVEN_WITH_SP_BETWEEN:
4318 /* When we have something following a SP, we have to look at the
4319 * context in order to know what to do.
4321 * SP SP should not reach here because LB7: Do not break before
4322 * spaces. (For two spaces in a row there is nothing that
4323 * overrides that) */
4324 assert(after != LB_Space);
4326 /* Here we have a space followed by a non-space. Mostly this is a
4327 * case of LB18: "Break after spaces". But there are complications
4328 * as the handling of spaces is somewhat tricky. They are in a
4329 * number of rules, which have to be applied in priority order, but
4330 * something earlier in the string can cause a rule to be skipped
4331 * and a lower priority rule invoked. A prime example is LB7 which
4332 * says don't break before a space. But rule LB8 (lower priority)
4333 * says that the first break opportunity after a ZW is after any
4334 * span of spaces immediately after it. If a ZW comes before a SP
4335 * in the input, rule LB8 applies, and not LB7. Other such rules
4336 * involve combining marks which are rules 9 and 10, but they may
4337 * override higher priority rules if they come earlier in the
4338 * string. Since we're doing random access into the middle of the
4339 * string, we have to look for rules that should get applied based
4340 * on both string position and priority. Combining marks do not
4341 * attach to either ZW nor SP, so we don't have to consider them
4344 * To check for LB8, we have to find the first non-space character
4345 * before this span of spaces */
4347 prev = backup_one_LB(strbeg, &temp_pos, utf8_target);
4349 while (prev == LB_Space);
4351 /* LB8 Break before any character following a zero-width space,
4352 * even if one or more spaces intervene.
4354 * So if we have a ZW just before this span, and to get here this
4355 * is the final space in the span. */
4356 if (prev == LB_ZWSpace) {
4360 /* Here, not ZW SP+. There are several rules that have higher
4361 * priority than LB18 and can be resolved now, as they don't depend
4362 * on anything earlier in the string (except ZW, which we have
4363 * already handled). One of these rules is LB11 Do not break
4364 * before Word joiner, but we have specially encoded that in the
4365 * lookup table so it is caught by the single test below which
4366 * catches the other ones. */
4367 if (LB_table[LB_Space][after] - LB_SP_foo
4368 == LB_NOBREAK_EVEN_WITH_SP_BETWEEN)
4373 /* If we get here, we have to XXX consider combining marks. */
4374 if (prev == LB_Combining_Mark) {
4376 /* What happens with these depends on the character they
4379 prev = backup_one_LB(strbeg, &temp_pos, utf8_target);
4381 while (prev == LB_Combining_Mark);
4383 /* Most times these attach to and inherit the characteristics
4384 * of that character, but not always, and when not, they are to
4385 * be treated as AL by rule LB10. */
4386 if (! LB_CM_ATTACHES_TO(prev)) {
4387 prev = LB_Alphabetic;
4391 /* Here, we have the character preceding the span of spaces all set
4392 * up. We follow LB18: "Break after spaces" unless the table shows
4393 * that is overriden */
4394 return LB_table[prev][after] != LB_NOBREAK_EVEN_WITH_SP_BETWEEN;
4398 /* We don't know how to treat the CM except by looking at the first
4399 * non-CM character preceding it */
4401 prev = backup_one_LB(strbeg, &temp_pos, utf8_target);
4403 while (prev == LB_Combining_Mark);
4405 /* Here, 'prev' is that first earlier non-CM character. If the CM
4406 * attatches to it, then it inherits the behavior of 'prev'. If it
4407 * doesn't attach, it is to be treated as an AL */
4408 if (! LB_CM_ATTACHES_TO(prev)) {
4409 prev = LB_Alphabetic;
4414 case LB_HY_or_BA_then_foo + LB_BREAKABLE:
4415 case LB_HY_or_BA_then_foo + LB_NOBREAK:
4417 /* LB21a Don't break after Hebrew + Hyphen.
4418 * HL (HY | BA) × */
4420 if (backup_one_LB(strbeg, &temp_pos, utf8_target)
4421 == LB_Hebrew_Letter)
4426 return LB_table[prev][after] - LB_HY_or_BA_then_foo == LB_BREAKABLE;
4428 case LB_PR_or_PO_then_OP_or_HY + LB_BREAKABLE:
4429 case LB_PR_or_PO_then_OP_or_HY + LB_NOBREAK:
4431 /* LB25a (PR | PO) × ( OP | HY )? NU */
4432 if (advance_one_LB(&temp_pos, strend, utf8_target) == LB_Numeric) {
4436 return LB_table[prev][after] - LB_PR_or_PO_then_OP_or_HY
4439 case LB_SY_or_IS_then_various + LB_BREAKABLE:
4440 case LB_SY_or_IS_then_various + LB_NOBREAK:
4442 /* LB25d NU (SY | IS)* × (NU | SY | IS | CL | CP ) */
4444 LB_enum temp = prev;
4446 temp = backup_one_LB(strbeg, &temp_pos, utf8_target);
4448 while (temp == LB_Break_Symbols || temp == LB_Infix_Numeric);
4449 if (temp == LB_Numeric) {
4453 return LB_table[prev][after] - LB_SY_or_IS_then_various
4457 case LB_various_then_PO_or_PR + LB_BREAKABLE:
4458 case LB_various_then_PO_or_PR + LB_NOBREAK:
4460 /* LB25e NU (SY | IS)* (CL | CP)? × (PO | PR) */
4462 LB_enum temp = prev;
4463 if (temp == LB_Close_Punctuation || temp == LB_Close_Parenthesis)
4465 temp = backup_one_LB(strbeg, &temp_pos, utf8_target);
4467 while (temp == LB_Break_Symbols || temp == LB_Infix_Numeric) {
4468 temp = backup_one_LB(strbeg, &temp_pos, utf8_target);
4470 if (temp == LB_Numeric) {
4473 return LB_various_then_PO_or_PR;
4481 PerlIO_printf(Perl_error_log, "Unhandled LB pair: LB_table[%d, %d] = %d\n",
4482 before, after, LB_table[before][after]);
4489 S_advance_one_LB(pTHX_ U8 ** curpos, const U8 * const strend, const bool utf8_target)
4493 PERL_ARGS_ASSERT_ADVANCE_ONE_LB;
4495 if (*curpos >= strend) {
4500 *curpos += UTF8SKIP(*curpos);
4501 if (*curpos >= strend) {
4504 lb = getLB_VAL_UTF8(*curpos, strend);
4508 if (*curpos >= strend) {
4511 lb = getLB_VAL_CP(**curpos);
4518 S_backup_one_LB(pTHX_ const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
4522 PERL_ARGS_ASSERT_BACKUP_ONE_LB;
4524 if (*curpos < strbeg) {
4529 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
4530 U8 * prev_prev_char_pos;
4532 if (! prev_char_pos) {
4536 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos, -1, strbeg))) {
4537 lb = getLB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
4538 *curpos = prev_char_pos;
4539 prev_char_pos = prev_prev_char_pos;
4542 *curpos = (U8 *) strbeg;
4547 if (*curpos - 2 < strbeg) {
4548 *curpos = (U8 *) strbeg;
4552 lb = getLB_VAL_CP(*(*curpos - 1));
4559 S_isSB(pTHX_ SB_enum before,
4561 const U8 * const strbeg,
4562 const U8 * const curpos,
4563 const U8 * const strend,
4564 const bool utf8_target)
4566 /* returns a boolean indicating if there is a Sentence Boundary Break
4567 * between the inputs. See http://www.unicode.org/reports/tr29/ */
4569 U8 * lpos = (U8 *) curpos;
4570 bool has_para_sep = FALSE;
4571 bool has_sp = FALSE;
4573 PERL_ARGS_ASSERT_ISSB;
4575 /* Break at the start and end of text.
4578 But unstated in Unicode is don't break if the text is empty */
4579 if (before == SB_EDGE || after == SB_EDGE) {
4580 return before != after;
4583 /* SB 3: Do not break within CRLF. */
4584 if (before == SB_CR && after == SB_LF) {
4588 /* Break after paragraph separators. CR and LF are considered
4589 * so because Unicode views text as like word processing text where there
4590 * are no newlines except between paragraphs, and the word processor takes
4591 * care of wrapping without there being hard line-breaks in the text *./
4592 SB4. Sep | CR | LF ÷ */
4593 if (before == SB_Sep || before == SB_CR || before == SB_LF) {
4597 /* Ignore Format and Extend characters, except after sot, Sep, CR, or LF.
4598 * (See Section 6.2, Replacing Ignore Rules.)
4599 SB5. X (Extend | Format)* → X */
4600 if (after == SB_Extend || after == SB_Format) {
4602 /* Implied is that the these characters attach to everything
4603 * immediately prior to them except for those separator-type
4604 * characters. And the rules earlier have already handled the case
4605 * when one of those immediately precedes the extend char */
4609 if (before == SB_Extend || before == SB_Format) {
4610 U8 * temp_pos = lpos;
4611 const SB_enum backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4612 if ( backup != SB_EDGE
4621 /* Here, both 'before' and 'backup' are these types; implied is that we
4622 * don't break between them */
4623 if (backup == SB_Extend || backup == SB_Format) {
4628 /* Do not break after ambiguous terminators like period, if they are
4629 * immediately followed by a number or lowercase letter, if they are
4630 * between uppercase letters, if the first following letter (optionally
4631 * after certain punctuation) is lowercase, or if they are followed by
4632 * "continuation" punctuation such as comma, colon, or semicolon. For
4633 * example, a period may be an abbreviation or numeric period, and thus may
4634 * not mark the end of a sentence.
4636 * SB6. ATerm × Numeric */
4637 if (before == SB_ATerm && after == SB_Numeric) {
4641 /* SB7. (Upper | Lower) ATerm × Upper */
4642 if (before == SB_ATerm && after == SB_Upper) {
4643 U8 * temp_pos = lpos;
4644 SB_enum backup = backup_one_SB(strbeg, &temp_pos, utf8_target);
4645 if (backup == SB_Upper || backup == SB_Lower) {
4650 /* The remaining rules that aren't the final one, all require an STerm or
4651 * an ATerm after having backed up over some Close* Sp*, and in one case an
4652 * optional Paragraph separator, although one rule doesn't have any Sp's in it.
4653 * So do that backup now, setting flags if either Sp or a paragraph
4654 * separator are found */
4656 if (before == SB_Sep || before == SB_CR || before == SB_LF) {
4657 has_para_sep = TRUE;
4658 before = backup_one_SB(strbeg, &lpos, utf8_target);
4661 if (before == SB_Sp) {
4664 before = backup_one_SB(strbeg, &lpos, utf8_target);
4666 while (before == SB_Sp);
4669 while (before == SB_Close) {
4670 before = backup_one_SB(strbeg, &lpos, utf8_target);
4673 /* The next few rules apply only when the backed-up-to is an ATerm, and in
4674 * most cases an STerm */
4675 if (before == SB_STerm || before == SB_ATerm) {
4677 /* So, here the lhs matches
4678 * (STerm | ATerm) Close* Sp* (Sep | CR | LF)?
4679 * and we have set flags if we found an Sp, or the optional Sep,CR,LF.
4680 * The rules that apply here are:
4682 * SB8 ATerm Close* Sp* × ( ¬(OLetter | Upper | Lower | Sep | CR
4683 | LF | STerm | ATerm) )* Lower
4684 SB8a (STerm | ATerm) Close* Sp* × (SContinue | STerm | ATerm)
4685 SB9 (STerm | ATerm) Close* × (Close | Sp | Sep | CR | LF)
4686 SB10 (STerm | ATerm) Close* Sp* × (Sp | Sep | CR | LF)
4687 SB11 (STerm | ATerm) Close* Sp* (Sep | CR | LF)? ÷
4690 /* And all but SB11 forbid having seen a paragraph separator */
4691 if (! has_para_sep) {
4692 if (before == SB_ATerm) { /* SB8 */
4693 U8 * rpos = (U8 *) curpos;
4694 SB_enum later = after;
4696 while ( later != SB_OLetter
4697 && later != SB_Upper
4698 && later != SB_Lower
4702 && later != SB_STerm
4703 && later != SB_ATerm
4704 && later != SB_EDGE)
4706 later = advance_one_SB(&rpos, strend, utf8_target);
4708 if (later == SB_Lower) {
4713 if ( after == SB_SContinue /* SB8a */
4714 || after == SB_STerm
4715 || after == SB_ATerm)
4720 if (! has_sp) { /* SB9 applies only if there was no Sp* */
4721 if ( after == SB_Close
4731 /* SB10. This and SB9 could probably be combined some way, but khw
4732 * has decided to follow the Unicode rule book precisely for
4733 * simplified maintenance */
4747 /* Otherwise, do not break.
4754 S_advance_one_SB(pTHX_ U8 ** curpos, const U8 * const strend, const bool utf8_target)
4758 PERL_ARGS_ASSERT_ADVANCE_ONE_SB;
4760 if (*curpos >= strend) {
4766 *curpos += UTF8SKIP(*curpos);
4767 if (*curpos >= strend) {
4770 sb = getSB_VAL_UTF8(*curpos, strend);
4771 } while (sb == SB_Extend || sb == SB_Format);
4776 if (*curpos >= strend) {
4779 sb = getSB_VAL_CP(**curpos);
4780 } while (sb == SB_Extend || sb == SB_Format);
4787 S_backup_one_SB(pTHX_ const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
4791 PERL_ARGS_ASSERT_BACKUP_ONE_SB;
4793 if (*curpos < strbeg) {
4798 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
4799 if (! prev_char_pos) {
4803 /* Back up over Extend and Format. curpos is always just to the right
4804 * of the characater whose value we are getting */
4806 U8 * prev_prev_char_pos;
4807 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos, -1,
4810 sb = getSB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
4811 *curpos = prev_char_pos;
4812 prev_char_pos = prev_prev_char_pos;
4815 *curpos = (U8 *) strbeg;
4818 } while (sb == SB_Extend || sb == SB_Format);
4822 if (*curpos - 2 < strbeg) {
4823 *curpos = (U8 *) strbeg;
4827 sb = getSB_VAL_CP(*(*curpos - 1));
4828 } while (sb == SB_Extend || sb == SB_Format);
4835 S_isWB(pTHX_ WB_enum previous,
4838 const U8 * const strbeg,
4839 const U8 * const curpos,
4840 const U8 * const strend,
4841 const bool utf8_target)
4843 /* Return a boolean as to if the boundary between 'before' and 'after' is
4844 * a Unicode word break, using their published algorithm, but tailored for
4845 * Perl by treating spans of white space as one unit. Context may be
4846 * needed to make this determination. If the value for the character
4847 * before 'before' is known, it is passed as 'previous'; otherwise that
4848 * should be set to WB_UNKNOWN. The other input parameters give the
4849 * boundaries and current position in the matching of the string. That
4850 * is, 'curpos' marks the position where the character whose wb value is
4851 * 'after' begins. See http://www.unicode.org/reports/tr29/ */
4853 U8 * before_pos = (U8 *) curpos;
4854 U8 * after_pos = (U8 *) curpos;
4855 WB_enum prev = before;
4858 PERL_ARGS_ASSERT_ISWB;
4860 /* Rule numbers in the comments below are as of Unicode 8.0 */
4864 switch (WB_table[before][after]) {
4871 case WB_hs_then_hs: /* 2 horizontal spaces in a row */
4872 next = advance_one_WB(&after_pos, strend, utf8_target,
4873 FALSE /* Don't skip Extend nor Format */ );
4874 /* A space immediately preceeding an Extend or Format is attached
4875 * to by them, and hence gets separated from previous spaces.
4876 * Otherwise don't break between horizontal white space */
4877 return next == WB_Extend || next == WB_Format;
4879 /* WB4 Ignore Format and Extend characters, except when they appear at
4880 * the beginning of a region of text. This code currently isn't
4881 * general purpose, but it works as the rules are currently and likely
4882 * to be laid out. The reason it works is that when 'they appear at
4883 * the beginning of a region of text', the rule is to break before
4884 * them, just like any other character. Therefore, the default rule
4885 * applies and we don't have to look in more depth. Should this ever
4886 * change, we would have to have 2 'case' statements, like in the
4887 * rules below, and backup a single character (not spacing over the
4888 * extend ones) and then see if that is one of the region-end
4889 * characters and go from there */
4890 case WB_Ex_or_FO_then_foo:
4891 prev = backup_one_WB(&previous, strbeg, &before_pos, utf8_target);
4894 case WB_DQ_then_HL + WB_BREAKABLE:
4895 case WB_DQ_then_HL + WB_NOBREAK:
4897 /* WB7c Hebrew_Letter Double_Quote × Hebrew_Letter */
4899 if (backup_one_WB(&previous, strbeg, &before_pos, utf8_target)
4900 == WB_Hebrew_Letter)
4905 return WB_table[before][after] - WB_DQ_then_HL == WB_BREAKABLE;
4907 case WB_HL_then_DQ + WB_BREAKABLE:
4908 case WB_HL_then_DQ + WB_NOBREAK:
4910 /* WB7b Hebrew_Letter × Double_Quote Hebrew_Letter */
4912 if (advance_one_WB(&after_pos, strend, utf8_target,
4913 TRUE /* Do skip Extend and Format */ )
4914 == WB_Hebrew_Letter)
4919 return WB_table[before][after] - WB_HL_then_DQ == WB_BREAKABLE;
4921 case WB_LE_or_HL_then_MB_or_ML_or_SQ + WB_NOBREAK:
4922 case WB_LE_or_HL_then_MB_or_ML_or_SQ + WB_BREAKABLE:
4924 /* WB6 (ALetter | Hebrew_Letter) × (MidLetter | MidNumLet
4925 * | Single_Quote) (ALetter | Hebrew_Letter) */
4927 next = advance_one_WB(&after_pos, strend, utf8_target,
4928 TRUE /* Do skip Extend and Format */ );
4930 if (next == WB_ALetter || next == WB_Hebrew_Letter)
4935 return WB_table[before][after]
4936 - WB_LE_or_HL_then_MB_or_ML_or_SQ == WB_BREAKABLE;
4938 case WB_MB_or_ML_or_SQ_then_LE_or_HL + WB_NOBREAK:
4939 case WB_MB_or_ML_or_SQ_then_LE_or_HL + WB_BREAKABLE:
4941 /* WB7 (ALetter | Hebrew_Letter) (MidLetter | MidNumLet
4942 * | Single_Quote) × (ALetter | Hebrew_Letter) */
4944 prev = backup_one_WB(&previous, strbeg, &before_pos, utf8_target);
4945 if (prev == WB_ALetter || prev == WB_Hebrew_Letter)
4950 return WB_table[before][after]
4951 - WB_MB_or_ML_or_SQ_then_LE_or_HL == WB_BREAKABLE;
4953 case WB_MB_or_MN_or_SQ_then_NU + WB_NOBREAK:
4954 case WB_MB_or_MN_or_SQ_then_NU + WB_BREAKABLE:
4956 /* WB11 Numeric (MidNum | (MidNumLet | Single_Quote)) × Numeric
4959 if (backup_one_WB(&previous, strbeg, &before_pos, utf8_target)
4965 return WB_table[before][after]
4966 - WB_MB_or_MN_or_SQ_then_NU == WB_BREAKABLE;
4968 case WB_NU_then_MB_or_MN_or_SQ + WB_NOBREAK:
4969 case WB_NU_then_MB_or_MN_or_SQ + WB_BREAKABLE:
4971 /* WB12 Numeric × (MidNum | MidNumLet | Single_Quote) Numeric */
4973 if (advance_one_WB(&after_pos, strend, utf8_target,
4974 TRUE /* Do skip Extend and Format */ )
4980 return WB_table[before][after]
4981 - WB_NU_then_MB_or_MN_or_SQ == WB_BREAKABLE;
4988 PerlIO_printf(Perl_error_log, "Unhandled WB pair: WB_table[%d, %d] = %d\n",
4989 before, after, WB_table[before][after]);
4996 S_advance_one_WB(pTHX_ U8 ** curpos,
4997 const U8 * const strend,
4998 const bool utf8_target,
4999 const bool skip_Extend_Format)
5003 PERL_ARGS_ASSERT_ADVANCE_ONE_WB;
5005 if (*curpos >= strend) {
5011 /* Advance over Extend and Format */
5013 *curpos += UTF8SKIP(*curpos);
5014 if (*curpos >= strend) {
5017 wb = getWB_VAL_UTF8(*curpos, strend);
5018 } while ( skip_Extend_Format
5019 && (wb == WB_Extend || wb == WB_Format));
5024 if (*curpos >= strend) {
5027 wb = getWB_VAL_CP(**curpos);
5028 } while ( skip_Extend_Format
5029 && (wb == WB_Extend || wb == WB_Format));
5036 S_backup_one_WB(pTHX_ WB_enum * previous, const U8 * const strbeg, U8 ** curpos, const bool utf8_target)
5040 PERL_ARGS_ASSERT_BACKUP_ONE_WB;
5042 /* If we know what the previous character's break value is, don't have
5044 if (*previous != WB_UNKNOWN) {
5047 /* But we need to move backwards by one */
5049 *curpos = reghopmaybe3(*curpos, -1, strbeg);
5051 *previous = WB_EDGE;
5052 *curpos = (U8 *) strbeg;
5055 *previous = WB_UNKNOWN;
5060 *previous = (*curpos <= strbeg) ? WB_EDGE : WB_UNKNOWN;
5063 /* And we always back up over these two types */
5064 if (wb != WB_Extend && wb != WB_Format) {
5069 if (*curpos < strbeg) {
5074 U8 * prev_char_pos = reghopmaybe3(*curpos, -1, strbeg);
5075 if (! prev_char_pos) {
5079 /* Back up over Extend and Format. curpos is always just to the right
5080 * of the characater whose value we are getting */
5082 U8 * prev_prev_char_pos;
5083 if ((prev_prev_char_pos = reghopmaybe3((U8 *) prev_char_pos,
5087 wb = getWB_VAL_UTF8(prev_prev_char_pos, prev_char_pos);
5088 *curpos = prev_char_pos;
5089 prev_char_pos = prev_prev_char_pos;
5092 *curpos = (U8 *) strbeg;
5095 } while (wb == WB_Extend || wb == WB_Format);
5099 if (*curpos - 2 < strbeg) {
5100 *curpos = (U8 *) strbeg;
5104 wb = getWB_VAL_CP(*(*curpos - 1));
5105 } while (wb == WB_Extend || wb == WB_Format);
5111 /* returns -1 on failure, $+[0] on success */
5113 S_regmatch(pTHX_ regmatch_info *reginfo, char *startpos, regnode *prog)
5116 #if PERL_VERSION < 9 && !defined(PERL_CORE)
5120 const bool utf8_target = reginfo->is_utf8_target;
5121 const U32 uniflags = UTF8_ALLOW_DEFAULT;
5122 REGEXP *rex_sv = reginfo->prog;
5123 regexp *rex = ReANY(rex_sv);
5124 RXi_GET_DECL(rex,rexi);
5125 /* the current state. This is a cached copy of PL_regmatch_state */
5127 /* cache heavy used fields of st in registers */
5130 U32 n = 0; /* general value; init to avoid compiler warning */
5131 SSize_t ln = 0; /* len or last; init to avoid compiler warning */
5132 char *locinput = startpos;
5133 char *pushinput; /* where to continue after a PUSH */
5134 I32 nextchr; /* is always set to UCHARAT(locinput), or -1 at EOS */
5136 bool result = 0; /* return value of S_regmatch */
5137 int depth = 0; /* depth of backtrack stack */
5138 U32 nochange_depth = 0; /* depth of GOSUB recursion with nochange */
5139 const U32 max_nochange_depth =
5140 (3 * rex->nparens > MAX_RECURSE_EVAL_NOCHANGE_DEPTH) ?
5141 3 * rex->nparens : MAX_RECURSE_EVAL_NOCHANGE_DEPTH;
5142 regmatch_state *yes_state = NULL; /* state to pop to on success of
5144 /* mark_state piggy backs on the yes_state logic so that when we unwind
5145 the stack on success we can update the mark_state as we go */
5146 regmatch_state *mark_state = NULL; /* last mark state we have seen */
5147 regmatch_state *cur_eval = NULL; /* most recent EVAL_AB state */
5148 struct regmatch_state *cur_curlyx = NULL; /* most recent curlyx */
5150 bool no_final = 0; /* prevent failure from backtracking? */
5151 bool do_cutgroup = 0; /* no_final only until next branch/trie entry */
5152 char *startpoint = locinput;
5153 SV *popmark = NULL; /* are we looking for a mark? */
5154 SV *sv_commit = NULL; /* last mark name seen in failure */
5155 SV *sv_yes_mark = NULL; /* last mark name we have seen
5156 during a successful match */
5157 U32 lastopen = 0; /* last open we saw */
5158 bool has_cutgroup = RX_HAS_CUTGROUP(rex) ? 1 : 0;
5159 SV* const oreplsv = GvSVn(PL_replgv);
5160 /* these three flags are set by various ops to signal information to
5161 * the very next op. They have a useful lifetime of exactly one loop
5162 * iteration, and are not preserved or restored by state pushes/pops
5164 bool sw = 0; /* the condition value in (?(cond)a|b) */
5165 bool minmod = 0; /* the next "{n,m}" is a "{n,m}?" */
5166 int logical = 0; /* the following EVAL is:
5170 or the following IFMATCH/UNLESSM is:
5171 false: plain (?=foo)
5172 true: used as a condition: (?(?=foo))
5174 PAD* last_pad = NULL;
5176 U8 gimme = G_SCALAR;
5177 CV *caller_cv = NULL; /* who called us */
5178 CV *last_pushed_cv = NULL; /* most recently called (?{}) CV */
5179 CHECKPOINT runops_cp; /* savestack position before executing EVAL */
5180 U32 maxopenparen = 0; /* max '(' index seen so far */
5181 int to_complement; /* Invert the result? */
5182 _char_class_number classnum;
5183 bool is_utf8_pat = reginfo->is_utf8_pat;
5188 GET_RE_DEBUG_FLAGS_DECL;
5191 /* protect against undef(*^R) */
5192 SAVEFREESV(SvREFCNT_inc_simple_NN(oreplsv));
5194 /* shut up 'may be used uninitialized' compiler warnings for dMULTICALL */
5195 multicall_oldcatch = 0;
5196 PERL_UNUSED_VAR(multicall_cop);
5198 PERL_ARGS_ASSERT_REGMATCH;
5200 DEBUG_OPTIMISE_r( DEBUG_EXECUTE_r({
5201 PerlIO_printf(Perl_debug_log,"regmatch start\n");
5204 st = PL_regmatch_state;
5206 /* Note that nextchr is a byte even in UTF */
5209 while (scan != NULL) {
5212 SV * const prop = sv_newmortal();
5213 regnode *rnext=regnext(scan);
5214 DUMP_EXEC_POS( locinput, scan, utf8_target );
5215 regprop(rex, prop, scan, reginfo, NULL);
5217 PerlIO_printf(Perl_debug_log,
5218 "%3"IVdf":%*s%s(%"IVdf")\n",
5219 (IV)(scan - rexi->program), depth*2, "",
5221 (PL_regkind[OP(scan)] == END || !rnext) ?
5222 0 : (IV)(rnext - rexi->program));
5225 next = scan + NEXT_OFF(scan);
5228 state_num = OP(scan);
5234 assert(nextchr < 256 && (nextchr >= 0 || nextchr == NEXTCHR_EOS));
5236 switch (state_num) {
5237 case SBOL: /* /^../ and /\A../ */
5238 if (locinput == reginfo->strbeg)
5242 case MBOL: /* /^../m */
5243 if (locinput == reginfo->strbeg ||
5244 (!NEXTCHR_IS_EOS && locinput[-1] == '\n'))
5251 if (locinput == reginfo->ganch)
5255 case KEEPS: /* \K */
5256 /* update the startpoint */
5257 st->u.keeper.val = rex->offs[0].start;
5258 rex->offs[0].start = locinput - reginfo->strbeg;
5259 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;
5266 NOT_REACHED; /* NOTREACHED */
5268 case MEOL: /* /..$/m */
5269 if (!NEXTCHR_IS_EOS && nextchr != '\n')
5273 case SEOL: /* /..$/ */
5274 if (!NEXTCHR_IS_EOS && nextchr != '\n')
5276 if (reginfo->strend - locinput > 1)
5281 if (!NEXTCHR_IS_EOS)
5285 case SANY: /* /./s */
5288 goto increment_locinput;
5290 case REG_ANY: /* /./ */
5291 if ((NEXTCHR_IS_EOS) || nextchr == '\n')
5293 goto increment_locinput;
5297 #define ST st->u.trie
5298 case TRIEC: /* (ab|cd) with known charclass */
5299 /* In this case the charclass data is available inline so
5300 we can fail fast without a lot of extra overhead.
5302 if(!NEXTCHR_IS_EOS && !ANYOF_BITMAP_TEST(scan, nextchr)) {
5304 PerlIO_printf(Perl_debug_log,
5305 "%*s %sfailed to match trie start class...%s\n",
5306 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
5309 NOT_REACHED; /* NOTREACHED */
5312 case TRIE: /* (ab|cd) */
5313 /* the basic plan of execution of the trie is:
5314 * At the beginning, run though all the states, and
5315 * find the longest-matching word. Also remember the position
5316 * of the shortest matching word. For example, this pattern:
5319 * when matched against the string "abcde", will generate
5320 * accept states for all words except 3, with the longest
5321 * matching word being 4, and the shortest being 2 (with
5322 * the position being after char 1 of the string).
5324 * Then for each matching word, in word order (i.e. 1,2,4,5),
5325 * we run the remainder of the pattern; on each try setting
5326 * the current position to the character following the word,
5327 * returning to try the next word on failure.
5329 * We avoid having to build a list of words at runtime by
5330 * using a compile-time structure, wordinfo[].prev, which
5331 * gives, for each word, the previous accepting word (if any).
5332 * In the case above it would contain the mappings 1->2, 2->0,
5333 * 3->0, 4->5, 5->1. We can use this table to generate, from
5334 * the longest word (4 above), a list of all words, by
5335 * following the list of prev pointers; this gives us the
5336 * unordered list 4,5,1,2. Then given the current word we have
5337 * just tried, we can go through the list and find the
5338 * next-biggest word to try (so if we just failed on word 2,
5339 * the next in the list is 4).
5341 * Since at runtime we don't record the matching position in
5342 * the string for each word, we have to work that out for
5343 * each word we're about to process. The wordinfo table holds
5344 * the character length of each word; given that we recorded
5345 * at the start: the position of the shortest word and its
5346 * length in chars, we just need to move the pointer the
5347 * difference between the two char lengths. Depending on
5348 * Unicode status and folding, that's cheap or expensive.
5350 * This algorithm is optimised for the case where are only a
5351 * small number of accept states, i.e. 0,1, or maybe 2.
5352 * With lots of accepts states, and having to try all of them,
5353 * it becomes quadratic on number of accept states to find all
5358 /* what type of TRIE am I? (utf8 makes this contextual) */
5359 DECL_TRIE_TYPE(scan);
5361 /* what trie are we using right now */
5362 reg_trie_data * const trie
5363 = (reg_trie_data*)rexi->data->data[ ARG( scan ) ];
5364 HV * widecharmap = MUTABLE_HV(rexi->data->data[ ARG( scan ) + 1 ]);
5365 U32 state = trie->startstate;
5367 if (scan->flags == EXACTL || scan->flags == EXACTFLU8) {
5368 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5370 && UTF8_IS_ABOVE_LATIN1(nextchr)
5371 && scan->flags == EXACTL)
5373 /* We only output for EXACTL, as we let the folder
5374 * output this message for EXACTFLU8 to avoid
5376 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput,
5381 && (NEXTCHR_IS_EOS || !TRIE_BITMAP_TEST(trie, nextchr)))
5383 if (trie->states[ state ].wordnum) {
5385 PerlIO_printf(Perl_debug_log,
5386 "%*s %smatched empty string...%s\n",
5387 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
5393 PerlIO_printf(Perl_debug_log,
5394 "%*s %sfailed to match trie start class...%s\n",
5395 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5])
5402 U8 *uc = ( U8* )locinput;
5406 U8 *uscan = (U8*)NULL;
5407 U8 foldbuf[ UTF8_MAXBYTES_CASE + 1 ];
5408 U32 charcount = 0; /* how many input chars we have matched */
5409 U32 accepted = 0; /* have we seen any accepting states? */
5411 ST.jump = trie->jump;
5414 ST.longfold = FALSE; /* char longer if folded => it's harder */
5417 /* fully traverse the TRIE; note the position of the
5418 shortest accept state and the wordnum of the longest
5421 while ( state && uc <= (U8*)(reginfo->strend) ) {
5422 U32 base = trie->states[ state ].trans.base;
5426 wordnum = trie->states[ state ].wordnum;
5428 if (wordnum) { /* it's an accept state */
5431 /* record first match position */
5433 ST.firstpos = (U8*)locinput;
5438 ST.firstchars = charcount;
5441 if (!ST.nextword || wordnum < ST.nextword)
5442 ST.nextword = wordnum;
5443 ST.topword = wordnum;
5446 DEBUG_TRIE_EXECUTE_r({
5447 DUMP_EXEC_POS( (char *)uc, scan, utf8_target );
5448 PerlIO_printf( Perl_debug_log,
5449 "%*s %sState: %4"UVxf" Accepted: %c ",
5450 2+depth * 2, "", PL_colors[4],
5451 (UV)state, (accepted ? 'Y' : 'N'));
5454 /* read a char and goto next state */
5455 if ( base && (foldlen || uc < (U8*)(reginfo->strend))) {
5457 REXEC_TRIE_READ_CHAR(trie_type, trie, widecharmap, uc,
5458 uscan, len, uvc, charid, foldlen,
5465 base + charid - 1 - trie->uniquecharcount)) >= 0)
5467 && ((U32)offset < trie->lasttrans)
5468 && trie->trans[offset].check == state)
5470 state = trie->trans[offset].next;
5481 DEBUG_TRIE_EXECUTE_r(
5482 PerlIO_printf( Perl_debug_log,
5483 "Charid:%3x CP:%4"UVxf" After State: %4"UVxf"%s\n",
5484 charid, uvc, (UV)state, PL_colors[5] );
5490 /* calculate total number of accept states */
5495 w = trie->wordinfo[w].prev;
5498 ST.accepted = accepted;
5502 PerlIO_printf( Perl_debug_log,
5503 "%*s %sgot %"IVdf" possible matches%s\n",
5504 REPORT_CODE_OFF + depth * 2, "",
5505 PL_colors[4], (IV)ST.accepted, PL_colors[5] );
5507 goto trie_first_try; /* jump into the fail handler */
5509 NOT_REACHED; /* NOTREACHED */
5511 case TRIE_next_fail: /* we failed - try next alternative */
5515 REGCP_UNWIND(ST.cp);
5516 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
5518 if (!--ST.accepted) {
5520 PerlIO_printf( Perl_debug_log,
5521 "%*s %sTRIE failed...%s\n",
5522 REPORT_CODE_OFF+depth*2, "",
5529 /* Find next-highest word to process. Note that this code
5530 * is O(N^2) per trie run (O(N) per branch), so keep tight */
5533 U16 const nextword = ST.nextword;
5534 reg_trie_wordinfo * const wordinfo
5535 = ((reg_trie_data*)rexi->data->data[ARG(ST.me)])->wordinfo;
5536 for (word=ST.topword; word; word=wordinfo[word].prev) {
5537 if (word > nextword && (!min || word < min))
5550 ST.lastparen = rex->lastparen;
5551 ST.lastcloseparen = rex->lastcloseparen;
5555 /* find start char of end of current word */
5557 U32 chars; /* how many chars to skip */
5558 reg_trie_data * const trie
5559 = (reg_trie_data*)rexi->data->data[ARG(ST.me)];
5561 assert((trie->wordinfo[ST.nextword].len - trie->prefixlen)
5563 chars = (trie->wordinfo[ST.nextword].len - trie->prefixlen)
5568 /* the hard option - fold each char in turn and find
5569 * its folded length (which may be different */
5570 U8 foldbuf[UTF8_MAXBYTES_CASE + 1];
5578 uvc = utf8n_to_uvchr((U8*)uc, UTF8_MAXLEN, &len,
5586 uvc = to_uni_fold(uvc, foldbuf, &foldlen);
5591 uvc = utf8n_to_uvchr(uscan, UTF8_MAXLEN, &len,
5607 scan = ST.me + ((ST.jump && ST.jump[ST.nextword])
5608 ? ST.jump[ST.nextword]
5612 PerlIO_printf( Perl_debug_log,
5613 "%*s %sTRIE matched word #%d, continuing%s\n",
5614 REPORT_CODE_OFF+depth*2, "",
5621 if (ST.accepted > 1 || has_cutgroup) {
5622 PUSH_STATE_GOTO(TRIE_next, scan, (char*)uc);
5623 NOT_REACHED; /* NOTREACHED */
5625 /* only one choice left - just continue */
5627 AV *const trie_words
5628 = MUTABLE_AV(rexi->data->data[ARG(ST.me)+TRIE_WORDS_OFFSET]);
5629 SV ** const tmp = trie_words
5630 ? av_fetch(trie_words, ST.nextword - 1, 0) : NULL;
5631 SV *sv= tmp ? sv_newmortal() : NULL;
5633 PerlIO_printf( Perl_debug_log,
5634 "%*s %sonly one match left, short-circuiting: #%d <%s>%s\n",
5635 REPORT_CODE_OFF+depth*2, "", PL_colors[4],
5637 tmp ? pv_pretty(sv, SvPV_nolen_const(*tmp), SvCUR(*tmp), 0,
5638 PL_colors[0], PL_colors[1],
5639 (SvUTF8(*tmp) ? PERL_PV_ESCAPE_UNI : 0)|PERL_PV_ESCAPE_NONASCII
5641 : "not compiled under -Dr",
5645 locinput = (char*)uc;
5646 continue; /* execute rest of RE */
5651 case EXACTL: /* /abc/l */
5652 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5654 /* Complete checking would involve going through every character
5655 * matched by the string to see if any is above latin1. But the
5656 * comparision otherwise might very well be a fast assembly
5657 * language routine, and I (khw) don't think slowing things down
5658 * just to check for this warning is worth it. So this just checks
5659 * the first character */
5660 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*locinput)) {
5661 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput, reginfo->strend);
5664 case EXACT: { /* /abc/ */
5665 char *s = STRING(scan);
5667 if (utf8_target != is_utf8_pat) {
5668 /* The target and the pattern have differing utf8ness. */
5670 const char * const e = s + ln;
5673 /* The target is utf8, the pattern is not utf8.
5674 * Above-Latin1 code points can't match the pattern;
5675 * invariants match exactly, and the other Latin1 ones need
5676 * to be downgraded to a single byte in order to do the
5677 * comparison. (If we could be confident that the target
5678 * is not malformed, this could be refactored to have fewer
5679 * tests by just assuming that if the first bytes match, it
5680 * is an invariant, but there are tests in the test suite
5681 * dealing with (??{...}) which violate this) */
5683 if (l >= reginfo->strend
5684 || UTF8_IS_ABOVE_LATIN1(* (U8*) l))
5688 if (UTF8_IS_INVARIANT(*(U8*)l)) {
5695 if (EIGHT_BIT_UTF8_TO_NATIVE(*l, *(l+1)) != * (U8*) s)
5705 /* The target is not utf8, the pattern is utf8. */
5707 if (l >= reginfo->strend
5708 || UTF8_IS_ABOVE_LATIN1(* (U8*) s))
5712 if (UTF8_IS_INVARIANT(*(U8*)s)) {
5719 if (EIGHT_BIT_UTF8_TO_NATIVE(*s, *(s+1)) != * (U8*) l)
5731 /* The target and the pattern have the same utf8ness. */
5732 /* Inline the first character, for speed. */
5733 if (reginfo->strend - locinput < ln
5734 || UCHARAT(s) != nextchr
5735 || (ln > 1 && memNE(s, locinput, ln)))
5744 case EXACTFL: { /* /abc/il */
5746 const U8 * fold_array;
5748 U32 fold_utf8_flags;
5750 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5751 folder = foldEQ_locale;
5752 fold_array = PL_fold_locale;
5753 fold_utf8_flags = FOLDEQ_LOCALE;
5756 case EXACTFLU8: /* /abc/il; but all 'abc' are above 255, so
5757 is effectively /u; hence to match, target
5759 if (! utf8_target) {
5762 fold_utf8_flags = FOLDEQ_LOCALE | FOLDEQ_S1_ALREADY_FOLDED
5763 | FOLDEQ_S1_FOLDS_SANE;
5764 folder = foldEQ_latin1;
5765 fold_array = PL_fold_latin1;
5768 case EXACTFU_SS: /* /\x{df}/iu */
5769 case EXACTFU: /* /abc/iu */
5770 folder = foldEQ_latin1;
5771 fold_array = PL_fold_latin1;
5772 fold_utf8_flags = is_utf8_pat ? FOLDEQ_S1_ALREADY_FOLDED : 0;
5775 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8
5777 assert(! is_utf8_pat);
5779 case EXACTFA: /* /abc/iaa */
5780 folder = foldEQ_latin1;
5781 fold_array = PL_fold_latin1;
5782 fold_utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
5785 case EXACTF: /* /abc/i This node only generated for
5786 non-utf8 patterns */
5787 assert(! is_utf8_pat);
5789 fold_array = PL_fold;
5790 fold_utf8_flags = 0;
5798 || state_num == EXACTFU_SS
5799 || (state_num == EXACTFL && IN_UTF8_CTYPE_LOCALE))
5801 /* Either target or the pattern are utf8, or has the issue where
5802 * the fold lengths may differ. */
5803 const char * const l = locinput;
5804 char *e = reginfo->strend;
5806 if (! foldEQ_utf8_flags(s, 0, ln, is_utf8_pat,
5807 l, &e, 0, utf8_target, fold_utf8_flags))
5815 /* Neither the target nor the pattern are utf8 */
5816 if (UCHARAT(s) != nextchr
5818 && UCHARAT(s) != fold_array[nextchr])
5822 if (reginfo->strend - locinput < ln)
5824 if (ln > 1 && ! folder(s, locinput, ln))
5830 case NBOUNDL: /* /\B/l */
5834 case BOUNDL: /* /\b/l */
5837 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
5839 if (FLAGS(scan) != TRADITIONAL_BOUND) {
5840 if (! IN_UTF8_CTYPE_LOCALE) {
5841 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
5842 B_ON_NON_UTF8_LOCALE_IS_WRONG);
5848 if (locinput == reginfo->strbeg)
5849 b1 = isWORDCHAR_LC('\n');
5851 b1 = isWORDCHAR_LC_utf8(reghop3((U8*)locinput, -1,
5852 (U8*)(reginfo->strbeg)));
5854 b2 = (NEXTCHR_IS_EOS)
5855 ? isWORDCHAR_LC('\n')
5856 : isWORDCHAR_LC_utf8((U8*)locinput);
5858 else { /* Here the string isn't utf8 */
5859 b1 = (locinput == reginfo->strbeg)
5860 ? isWORDCHAR_LC('\n')
5861 : isWORDCHAR_LC(UCHARAT(locinput - 1));
5862 b2 = (NEXTCHR_IS_EOS)
5863 ? isWORDCHAR_LC('\n')
5864 : isWORDCHAR_LC(nextchr);
5866 if (to_complement ^ (b1 == b2)) {
5872 case NBOUND: /* /\B/ */
5876 case BOUND: /* /\b/ */
5880 goto bound_ascii_match_only;
5882 case NBOUNDA: /* /\B/a */
5886 case BOUNDA: /* /\b/a */
5890 bound_ascii_match_only:
5891 /* Here the string isn't utf8, or is utf8 and only ascii characters
5892 * are to match \w. In the latter case looking at the byte just
5893 * prior to the current one may be just the final byte of a
5894 * multi-byte character. This is ok. There are two cases:
5895 * 1) it is a single byte character, and then the test is doing
5896 * just what it's supposed to.
5897 * 2) it is a multi-byte character, in which case the final byte is
5898 * never mistakable for ASCII, and so the test will say it is
5899 * not a word character, which is the correct answer. */
5900 b1 = (locinput == reginfo->strbeg)
5901 ? isWORDCHAR_A('\n')
5902 : isWORDCHAR_A(UCHARAT(locinput - 1));
5903 b2 = (NEXTCHR_IS_EOS)
5904 ? isWORDCHAR_A('\n')
5905 : isWORDCHAR_A(nextchr);
5906 if (to_complement ^ (b1 == b2)) {
5912 case NBOUNDU: /* /\B/u */
5916 case BOUNDU: /* /\b/u */
5919 if (UNLIKELY(reginfo->strbeg >= reginfo->strend)) {
5922 else if (utf8_target) {
5924 switch((bound_type) FLAGS(scan)) {
5925 case TRADITIONAL_BOUND:
5928 b1 = (locinput == reginfo->strbeg)
5929 ? 0 /* isWORDCHAR_L1('\n') */
5930 : isWORDCHAR_utf8(reghop3((U8*)locinput, -1,
5931 (U8*)(reginfo->strbeg)));
5932 b2 = (NEXTCHR_IS_EOS)
5933 ? 0 /* isWORDCHAR_L1('\n') */
5934 : isWORDCHAR_utf8((U8*)locinput);
5935 match = cBOOL(b1 != b2);
5939 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
5940 match = TRUE; /* GCB always matches at begin and
5944 /* Find the gcb values of previous and current
5945 * chars, then see if is a break point */
5946 match = isGCB(getGCB_VAL_UTF8(
5947 reghop3((U8*)locinput,
5949 (U8*)(reginfo->strbeg)),
5950 (U8*) reginfo->strend),
5951 getGCB_VAL_UTF8((U8*) locinput,
5952 (U8*) reginfo->strend));
5957 if (locinput == reginfo->strbeg) {
5960 else if (NEXTCHR_IS_EOS) {
5964 match = isLB(getLB_VAL_UTF8(
5965 reghop3((U8*)locinput,
5967 (U8*)(reginfo->strbeg)),
5968 (U8*) reginfo->strend),
5969 getLB_VAL_UTF8((U8*) locinput,
5970 (U8*) reginfo->strend),
5971 (U8*) reginfo->strbeg,
5973 (U8*) reginfo->strend,
5978 case SB_BOUND: /* Always matches at begin and end */
5979 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
5983 match = isSB(getSB_VAL_UTF8(
5984 reghop3((U8*)locinput,
5986 (U8*)(reginfo->strbeg)),
5987 (U8*) reginfo->strend),
5988 getSB_VAL_UTF8((U8*) locinput,
5989 (U8*) reginfo->strend),
5990 (U8*) reginfo->strbeg,
5992 (U8*) reginfo->strend,
5998 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6002 match = isWB(WB_UNKNOWN,
6004 reghop3((U8*)locinput,
6006 (U8*)(reginfo->strbeg)),
6007 (U8*) reginfo->strend),
6008 getWB_VAL_UTF8((U8*) locinput,
6009 (U8*) reginfo->strend),
6010 (U8*) reginfo->strbeg,
6012 (U8*) reginfo->strend,
6018 else { /* Not utf8 target */
6019 switch((bound_type) FLAGS(scan)) {
6020 case TRADITIONAL_BOUND:
6023 b1 = (locinput == reginfo->strbeg)
6024 ? 0 /* isWORDCHAR_L1('\n') */
6025 : isWORDCHAR_L1(UCHARAT(locinput - 1));
6026 b2 = (NEXTCHR_IS_EOS)
6027 ? 0 /* isWORDCHAR_L1('\n') */
6028 : isWORDCHAR_L1(nextchr);
6029 match = cBOOL(b1 != b2);
6034 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6035 match = TRUE; /* GCB always matches at begin and
6038 else { /* Only CR-LF combo isn't a GCB in 0-255
6040 match = UCHARAT(locinput - 1) != '\r'
6041 || UCHARAT(locinput) != '\n';
6046 if (locinput == reginfo->strbeg) {
6049 else if (NEXTCHR_IS_EOS) {
6053 match = isLB(getLB_VAL_CP(UCHARAT(locinput -1)),
6054 getLB_VAL_CP(UCHARAT(locinput)),
6055 (U8*) reginfo->strbeg,
6057 (U8*) reginfo->strend,
6062 case SB_BOUND: /* Always matches at begin and end */
6063 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6067 match = isSB(getSB_VAL_CP(UCHARAT(locinput -1)),
6068 getSB_VAL_CP(UCHARAT(locinput)),
6069 (U8*) reginfo->strbeg,
6071 (U8*) reginfo->strend,
6077 if (locinput == reginfo->strbeg || NEXTCHR_IS_EOS) {
6081 match = isWB(WB_UNKNOWN,
6082 getWB_VAL_CP(UCHARAT(locinput -1)),
6083 getWB_VAL_CP(UCHARAT(locinput)),
6084 (U8*) reginfo->strbeg,
6086 (U8*) reginfo->strend,
6093 if (to_complement ^ ! match) {
6098 case ANYOFL: /* /[abc]/l */
6099 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6101 if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(scan)) && ! IN_UTF8_CTYPE_LOCALE)
6103 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
6106 case ANYOFD: /* /[abc]/d */
6107 case ANYOF: /* /[abc]/ */
6110 if (utf8_target && ! UTF8_IS_INVARIANT(*locinput)) {
6111 if (!reginclass(rex, scan, (U8*)locinput, (U8*)reginfo->strend,
6114 locinput += UTF8SKIP(locinput);
6117 if (!REGINCLASS(rex, scan, (U8*)locinput, utf8_target))
6123 /* The argument (FLAGS) to all the POSIX node types is the class number
6126 case NPOSIXL: /* \W or [:^punct:] etc. under /l */
6130 case POSIXL: /* \w or [:punct:] etc. under /l */
6131 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6135 /* Use isFOO_lc() for characters within Latin1. (Note that
6136 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
6137 * wouldn't be invariant) */
6138 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
6139 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan), (U8) nextchr)))) {
6143 else if (UTF8_IS_DOWNGRADEABLE_START(nextchr)) {
6144 if (! (to_complement ^ cBOOL(isFOO_lc(FLAGS(scan),
6145 EIGHT_BIT_UTF8_TO_NATIVE(nextchr,
6146 *(locinput + 1))))))
6151 else { /* Here, must be an above Latin-1 code point */
6152 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(locinput, reginfo->strend);
6153 goto utf8_posix_above_latin1;
6156 /* Here, must be utf8 */
6157 locinput += UTF8SKIP(locinput);
6160 case NPOSIXD: /* \W or [:^punct:] etc. under /d */
6164 case POSIXD: /* \w or [:punct:] etc. under /d */
6170 case NPOSIXA: /* \W or [:^punct:] etc. under /a */
6172 if (NEXTCHR_IS_EOS) {
6176 /* All UTF-8 variants match */
6177 if (! UTF8_IS_INVARIANT(nextchr)) {
6178 goto increment_locinput;
6184 case POSIXA: /* \w or [:punct:] etc. under /a */
6187 /* We get here through POSIXD, NPOSIXD, and NPOSIXA when not in
6188 * UTF-8, and also from NPOSIXA even in UTF-8 when the current
6189 * character is a single byte */
6191 if (NEXTCHR_IS_EOS) {
6197 if (! (to_complement ^ cBOOL(_generic_isCC_A(nextchr,
6203 /* Here we are either not in utf8, or we matched a utf8-invariant,
6204 * so the next char is the next byte */
6208 case NPOSIXU: /* \W or [:^punct:] etc. under /u */
6212 case POSIXU: /* \w or [:punct:] etc. under /u */
6214 if (NEXTCHR_IS_EOS) {
6218 /* Use _generic_isCC() for characters within Latin1. (Note that
6219 * UTF8_IS_INVARIANT works even on non-UTF-8 strings, or else
6220 * wouldn't be invariant) */
6221 if (UTF8_IS_INVARIANT(nextchr) || ! utf8_target) {
6222 if (! (to_complement ^ cBOOL(_generic_isCC(nextchr,
6229 else if (UTF8_IS_DOWNGRADEABLE_START(nextchr)) {
6230 if (! (to_complement
6231 ^ cBOOL(_generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(nextchr,
6239 else { /* Handle above Latin-1 code points */
6240 utf8_posix_above_latin1:
6241 classnum = (_char_class_number) FLAGS(scan);
6242 if (classnum < _FIRST_NON_SWASH_CC) {
6244 /* Here, uses a swash to find such code points. Load if if
6245 * not done already */
6246 if (! PL_utf8_swash_ptrs[classnum]) {
6247 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
6248 PL_utf8_swash_ptrs[classnum]
6249 = _core_swash_init("utf8",
6252 PL_XPosix_ptrs[classnum], &flags);
6254 if (! (to_complement
6255 ^ cBOOL(swash_fetch(PL_utf8_swash_ptrs[classnum],
6256 (U8 *) locinput, TRUE))))
6261 else { /* Here, uses macros to find above Latin-1 code points */
6263 case _CC_ENUM_SPACE:
6264 if (! (to_complement
6265 ^ cBOOL(is_XPERLSPACE_high(locinput))))
6270 case _CC_ENUM_BLANK:
6271 if (! (to_complement
6272 ^ cBOOL(is_HORIZWS_high(locinput))))
6277 case _CC_ENUM_XDIGIT:
6278 if (! (to_complement
6279 ^ cBOOL(is_XDIGIT_high(locinput))))
6284 case _CC_ENUM_VERTSPACE:
6285 if (! (to_complement
6286 ^ cBOOL(is_VERTWS_high(locinput))))
6291 default: /* The rest, e.g. [:cntrl:], can't match
6293 if (! to_complement) {
6299 locinput += UTF8SKIP(locinput);
6303 case CLUMP: /* Match \X: logical Unicode character. This is defined as
6304 a Unicode extended Grapheme Cluster */
6307 if (! utf8_target) {
6309 /* Match either CR LF or '.', as all the other possibilities
6311 locinput++; /* Match the . or CR */
6312 if (nextchr == '\r' /* And if it was CR, and the next is LF,
6314 && locinput < reginfo->strend
6315 && UCHARAT(locinput) == '\n')
6322 /* Get the gcb type for the current character */
6323 GCB_enum prev_gcb = getGCB_VAL_UTF8((U8*) locinput,
6324 (U8*) reginfo->strend);
6326 /* Then scan through the input until we get to the first
6327 * character whose type is supposed to be a gcb with the
6328 * current character. (There is always a break at the
6330 locinput += UTF8SKIP(locinput);
6331 while (locinput < reginfo->strend) {
6332 GCB_enum cur_gcb = getGCB_VAL_UTF8((U8*) locinput,
6333 (U8*) reginfo->strend);
6334 if (isGCB(prev_gcb, cur_gcb)) {
6339 locinput += UTF8SKIP(locinput);
6346 case NREFFL: /* /\g{name}/il */
6347 { /* The capture buffer cases. The ones beginning with N for the
6348 named buffers just convert to the equivalent numbered and
6349 pretend they were called as the corresponding numbered buffer
6351 /* don't initialize these in the declaration, it makes C++
6356 const U8 *fold_array;
6359 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6360 folder = foldEQ_locale;
6361 fold_array = PL_fold_locale;
6363 utf8_fold_flags = FOLDEQ_LOCALE;
6366 case NREFFA: /* /\g{name}/iaa */
6367 folder = foldEQ_latin1;
6368 fold_array = PL_fold_latin1;
6370 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
6373 case NREFFU: /* /\g{name}/iu */
6374 folder = foldEQ_latin1;
6375 fold_array = PL_fold_latin1;
6377 utf8_fold_flags = 0;
6380 case NREFF: /* /\g{name}/i */
6382 fold_array = PL_fold;
6384 utf8_fold_flags = 0;
6387 case NREF: /* /\g{name}/ */
6391 utf8_fold_flags = 0;
6394 /* For the named back references, find the corresponding buffer
6396 n = reg_check_named_buff_matched(rex,scan);
6401 goto do_nref_ref_common;
6403 case REFFL: /* /\1/il */
6404 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
6405 folder = foldEQ_locale;
6406 fold_array = PL_fold_locale;
6407 utf8_fold_flags = FOLDEQ_LOCALE;
6410 case REFFA: /* /\1/iaa */
6411 folder = foldEQ_latin1;
6412 fold_array = PL_fold_latin1;
6413 utf8_fold_flags = FOLDEQ_UTF8_NOMIX_ASCII;
6416 case REFFU: /* /\1/iu */
6417 folder = foldEQ_latin1;
6418 fold_array = PL_fold_latin1;
6419 utf8_fold_flags = 0;
6422 case REFF: /* /\1/i */
6424 fold_array = PL_fold;
6425 utf8_fold_flags = 0;
6428 case REF: /* /\1/ */
6431 utf8_fold_flags = 0;
6435 n = ARG(scan); /* which paren pair */
6438 ln = rex->offs[n].start;
6439 reginfo->poscache_iter = reginfo->poscache_maxiter; /* Void cache */
6440 if (rex->lastparen < n || ln == -1)
6441 sayNO; /* Do not match unless seen CLOSEn. */
6442 if (ln == rex->offs[n].end)
6445 s = reginfo->strbeg + ln;
6446 if (type != REF /* REF can do byte comparison */
6447 && (utf8_target || type == REFFU || type == REFFL))
6449 char * limit = reginfo->strend;
6451 /* This call case insensitively compares the entire buffer
6452 * at s, with the current input starting at locinput, but
6453 * not going off the end given by reginfo->strend, and
6454 * returns in <limit> upon success, how much of the
6455 * current input was matched */
6456 if (! foldEQ_utf8_flags(s, NULL, rex->offs[n].end - ln, utf8_target,
6457 locinput, &limit, 0, utf8_target, utf8_fold_flags))
6465 /* Not utf8: Inline the first character, for speed. */
6466 if (!NEXTCHR_IS_EOS &&
6467 UCHARAT(s) != nextchr &&
6469 UCHARAT(s) != fold_array[nextchr]))
6471 ln = rex->offs[n].end - ln;
6472 if (locinput + ln > reginfo->strend)
6474 if (ln > 1 && (type == REF
6475 ? memNE(s, locinput, ln)
6476 : ! folder(s, locinput, ln)))
6482 case NOTHING: /* null op; e.g. the 'nothing' following
6483 * the '*' in m{(a+|b)*}' */
6485 case TAIL: /* placeholder while compiling (A|B|C) */
6489 #define ST st->u.eval
6494 regexp_internal *rei;
6495 regnode *startpoint;
6497 case GOSTART: /* (?R) */
6498 case GOSUB: /* /(...(?1))/ /(...(?&foo))/ */
6499 if (cur_eval && cur_eval->locinput==locinput) {
6500 if (cur_eval->u.eval.close_paren == (U32)ARG(scan))
6501 Perl_croak(aTHX_ "Infinite recursion in regex");
6502 if ( ++nochange_depth > max_nochange_depth )
6504 "Pattern subroutine nesting without pos change"
6505 " exceeded limit in regex");
6512 if (OP(scan)==GOSUB) {
6513 startpoint = scan + ARG2L(scan);
6514 ST.close_paren = ARG(scan);
6516 startpoint = rei->program+1;
6520 /* Save all the positions seen so far. */
6521 ST.cp = regcppush(rex, 0, maxopenparen);
6522 REGCP_SET(ST.lastcp);
6524 /* and then jump to the code we share with EVAL */
6525 goto eval_recurse_doit;
6528 case EVAL: /* /(?{A})B/ /(??{A})B/ and /(?(?{A})X|Y)B/ */
6529 if (cur_eval && cur_eval->locinput==locinput) {
6530 if ( ++nochange_depth > max_nochange_depth )
6531 Perl_croak(aTHX_ "EVAL without pos change exceeded limit in regex");
6536 /* execute the code in the {...} */
6540 OP * const oop = PL_op;
6541 COP * const ocurcop = PL_curcop;
6545 /* save *all* paren positions */
6546 regcppush(rex, 0, maxopenparen);
6547 REGCP_SET(runops_cp);
6550 caller_cv = find_runcv(NULL);
6554 if (rexi->data->what[n] == 'r') { /* code from an external qr */
6556 (REGEXP*)(rexi->data->data[n])
6559 nop = (OP*)rexi->data->data[n+1];
6561 else if (rexi->data->what[n] == 'l') { /* literal code */
6563 nop = (OP*)rexi->data->data[n];
6564 assert(CvDEPTH(newcv));
6567 /* literal with own CV */
6568 assert(rexi->data->what[n] == 'L');
6569 newcv = rex->qr_anoncv;
6570 nop = (OP*)rexi->data->data[n];
6573 /* normally if we're about to execute code from the same
6574 * CV that we used previously, we just use the existing
6575 * CX stack entry. However, its possible that in the
6576 * meantime we may have backtracked, popped from the save
6577 * stack, and undone the SAVECOMPPAD(s) associated with
6578 * PUSH_MULTICALL; in which case PL_comppad no longer
6579 * points to newcv's pad. */
6580 if (newcv != last_pushed_cv || PL_comppad != last_pad)
6582 U8 flags = (CXp_SUB_RE |
6583 ((newcv == caller_cv) ? CXp_SUB_RE_FAKE : 0));
6584 if (last_pushed_cv) {
6585 /* PUSH/POP_MULTICALL save and restore the
6586 * caller's PL_comppad; if we call multiple subs
6587 * using the same CX block, we have to save and
6588 * unwind the varying PL_comppad's ourselves,
6589 * especially restoring the right PL_comppad on
6590 * backtrack - so save it on the save stack */
6592 CHANGE_MULTICALL_FLAGS(newcv, flags);
6595 PUSH_MULTICALL_FLAGS(newcv, flags);
6597 last_pushed_cv = newcv;
6600 /* these assignments are just to silence compiler
6602 multicall_cop = NULL;
6604 last_pad = PL_comppad;
6606 /* the initial nextstate you would normally execute
6607 * at the start of an eval (which would cause error
6608 * messages to come from the eval), may be optimised
6609 * away from the execution path in the regex code blocks;
6610 * so manually set PL_curcop to it initially */
6612 OP *o = cUNOPx(nop)->op_first;
6613 assert(o->op_type == OP_NULL);
6614 if (o->op_targ == OP_SCOPE) {
6615 o = cUNOPo->op_first;
6618 assert(o->op_targ == OP_LEAVE);
6619 o = cUNOPo->op_first;
6620 assert(o->op_type == OP_ENTER);
6624 if (o->op_type != OP_STUB) {
6625 assert( o->op_type == OP_NEXTSTATE
6626 || o->op_type == OP_DBSTATE
6627 || (o->op_type == OP_NULL
6628 && ( o->op_targ == OP_NEXTSTATE
6629 || o->op_targ == OP_DBSTATE
6633 PL_curcop = (COP*)o;
6638 DEBUG_STATE_r( PerlIO_printf(Perl_debug_log,
6639 " re EVAL PL_op=0x%"UVxf"\n", PTR2UV(nop)) );
6641 rex->offs[0].end = locinput - reginfo->strbeg;
6642 if (reginfo->info_aux_eval->pos_magic)
6643 MgBYTEPOS_set(reginfo->info_aux_eval->pos_magic,
6644 reginfo->sv, reginfo->strbeg,
6645 locinput - reginfo->strbeg);
6648 SV *sv_mrk = get_sv("REGMARK", 1);
6649 sv_setsv(sv_mrk, sv_yes_mark);
6652 /* we don't use MULTICALL here as we want to call the
6653 * first op of the block of interest, rather than the
6654 * first op of the sub. Also, we don't want to free
6655 * the savestack frame */
6656 before = (IV)(SP-PL_stack_base);
6658 CALLRUNOPS(aTHX); /* Scalar context. */
6660 if ((IV)(SP-PL_stack_base) == before)
6661 ret = &PL_sv_undef; /* protect against empty (?{}) blocks. */
6667 /* before restoring everything, evaluate the returned
6668 * value, so that 'uninit' warnings don't use the wrong
6669 * PL_op or pad. Also need to process any magic vars
6670 * (e.g. $1) *before* parentheses are restored */
6675 if (logical == 0) /* (?{})/ */
6676 sv_setsv(save_scalar(PL_replgv), ret); /* $^R */
6677 else if (logical == 1) { /* /(?(?{...})X|Y)/ */
6678 sw = cBOOL(SvTRUE(ret));
6681 else { /* /(??{}) */
6682 /* if its overloaded, let the regex compiler handle
6683 * it; otherwise extract regex, or stringify */
6684 if (SvGMAGICAL(ret))
6685 ret = sv_mortalcopy(ret);
6686 if (!SvAMAGIC(ret)) {
6690 if (SvTYPE(sv) == SVt_REGEXP)
6691 re_sv = (REGEXP*) sv;
6692 else if (SvSMAGICAL(ret)) {
6693 MAGIC *mg = mg_find(ret, PERL_MAGIC_qr);
6695 re_sv = (REGEXP *) mg->mg_obj;
6698 /* force any undef warnings here */
6699 if (!re_sv && !SvPOK(ret) && !SvNIOK(ret)) {
6700 ret = sv_mortalcopy(ret);
6701 (void) SvPV_force_nolen(ret);
6707 /* *** Note that at this point we don't restore
6708 * PL_comppad, (or pop the CxSUB) on the assumption it may
6709 * be used again soon. This is safe as long as nothing
6710 * in the regexp code uses the pad ! */
6712 PL_curcop = ocurcop;
6713 S_regcp_restore(aTHX_ rex, runops_cp, &maxopenparen);
6714 PL_curpm = PL_reg_curpm;
6720 /* only /(??{})/ from now on */
6723 /* extract RE object from returned value; compiling if
6727 re_sv = reg_temp_copy(NULL, re_sv);
6732 if (SvUTF8(ret) && IN_BYTES) {
6733 /* In use 'bytes': make a copy of the octet
6734 * sequence, but without the flag on */
6736 const char *const p = SvPV(ret, len);
6737 ret = newSVpvn_flags(p, len, SVs_TEMP);
6739 if (rex->intflags & PREGf_USE_RE_EVAL)
6740 pm_flags |= PMf_USE_RE_EVAL;
6742 /* if we got here, it should be an engine which
6743 * supports compiling code blocks and stuff */
6744 assert(rex->engine && rex->engine->op_comp);
6745 assert(!(scan->flags & ~RXf_PMf_COMPILETIME));
6746 re_sv = rex->engine->op_comp(aTHX_ &ret, 1, NULL,
6747 rex->engine, NULL, NULL,
6748 /* copy /msixn etc to inner pattern */
6753 & (SVs_TEMP | SVs_GMG | SVf_ROK))
6754 && (!SvPADTMP(ret) || SvREADONLY(ret))) {
6755 /* This isn't a first class regexp. Instead, it's
6756 caching a regexp onto an existing, Perl visible
6758 sv_magic(ret, MUTABLE_SV(re_sv), PERL_MAGIC_qr, 0, 0);
6764 RXp_MATCH_COPIED_off(re);
6765 re->subbeg = rex->subbeg;
6766 re->sublen = rex->sublen;
6767 re->suboffset = rex->suboffset;
6768 re->subcoffset = rex->subcoffset;
6770 re->lastcloseparen = 0;
6773 debug_start_match(re_sv, utf8_target, locinput,
6774 reginfo->strend, "Matching embedded");
6776 startpoint = rei->program + 1;
6777 ST.close_paren = 0; /* only used for GOSUB */
6778 /* Save all the seen positions so far. */
6779 ST.cp = regcppush(rex, 0, maxopenparen);
6780 REGCP_SET(ST.lastcp);
6781 /* and set maxopenparen to 0, since we are starting a "fresh" match */
6783 /* run the pattern returned from (??{...}) */
6785 eval_recurse_doit: /* Share code with GOSUB below this line
6786 * At this point we expect the stack context to be
6787 * set up correctly */
6789 /* invalidate the S-L poscache. We're now executing a
6790 * different set of WHILEM ops (and their associated
6791 * indexes) against the same string, so the bits in the
6792 * cache are meaningless. Setting maxiter to zero forces
6793 * the cache to be invalidated and zeroed before reuse.
6794 * XXX This is too dramatic a measure. Ideally we should
6795 * save the old cache and restore when running the outer
6797 reginfo->poscache_maxiter = 0;
6799 /* the new regexp might have a different is_utf8_pat than we do */
6800 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(re_sv));
6802 ST.prev_rex = rex_sv;
6803 ST.prev_curlyx = cur_curlyx;
6805 SET_reg_curpm(rex_sv);
6810 ST.prev_eval = cur_eval;
6812 /* now continue from first node in postoned RE */
6813 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);
7075 NOT_REACHED; /* NOTREACHED */
7078 case CURLYX_end: /* just finished matching all of A*B */
7079 cur_curlyx = ST.prev_curlyx;
7081 NOT_REACHED; /* NOTREACHED */
7083 case CURLYX_end_fail: /* just failed to match all of A*B */
7085 cur_curlyx = ST.prev_curlyx;
7087 NOT_REACHED; /* NOTREACHED */
7091 #define ST st->u.whilem
7093 case WHILEM: /* just matched an A in /A*B/ (for complex A) */
7095 /* see the discussion above about CURLYX/WHILEM */
7100 assert(cur_curlyx); /* keep Coverity happy */
7102 min = ARG1(cur_curlyx->u.curlyx.me);
7103 max = ARG2(cur_curlyx->u.curlyx.me);
7104 A = NEXTOPER(cur_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS;
7105 n = ++cur_curlyx->u.curlyx.count; /* how many A's matched */
7106 ST.save_lastloc = cur_curlyx->u.curlyx.lastloc;
7107 ST.cache_offset = 0;
7111 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
7112 "%*s whilem: matched %ld out of %d..%d\n",
7113 REPORT_CODE_OFF+depth*2, "", (long)n, min, max)
7116 /* First just match a string of min A's. */
7119 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
7121 cur_curlyx->u.curlyx.lastloc = locinput;
7122 REGCP_SET(ST.lastcp);
7124 PUSH_STATE_GOTO(WHILEM_A_pre, A, locinput);
7125 NOT_REACHED; /* NOTREACHED */
7128 /* If degenerate A matches "", assume A done. */
7130 if (locinput == cur_curlyx->u.curlyx.lastloc) {
7131 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
7132 "%*s whilem: empty match detected, trying continuation...\n",
7133 REPORT_CODE_OFF+depth*2, "")
7135 goto do_whilem_B_max;
7138 /* super-linear cache processing.
7140 * The idea here is that for certain types of CURLYX/WHILEM -
7141 * principally those whose upper bound is infinity (and
7142 * excluding regexes that have things like \1 and other very
7143 * non-regular expresssiony things), then if a pattern like
7144 * /....A*.../ fails and we backtrack to the WHILEM, then we
7145 * make a note that this particular WHILEM op was at string
7146 * position 47 (say) when the rest of pattern failed. Then, if
7147 * we ever find ourselves back at that WHILEM, and at string
7148 * position 47 again, we can just fail immediately rather than
7149 * running the rest of the pattern again.
7151 * This is very handy when patterns start to go
7152 * 'super-linear', like in (a+)*(a+)*(a+)*, where you end up
7153 * with a combinatorial explosion of backtracking.
7155 * The cache is implemented as a bit array, with one bit per
7156 * string byte position per WHILEM op (up to 16) - so its
7157 * between 0.25 and 2x the string size.
7159 * To avoid allocating a poscache buffer every time, we do an
7160 * initially countdown; only after we have executed a WHILEM
7161 * op (string-length x #WHILEMs) times do we allocate the
7164 * The top 4 bits of scan->flags byte say how many different
7165 * relevant CURLLYX/WHILEM op pairs there are, while the
7166 * bottom 4-bits is the identifying index number of this
7172 if (!reginfo->poscache_maxiter) {
7173 /* start the countdown: Postpone detection until we
7174 * know the match is not *that* much linear. */
7175 reginfo->poscache_maxiter
7176 = (reginfo->strend - reginfo->strbeg + 1)
7178 /* possible overflow for long strings and many CURLYX's */
7179 if (reginfo->poscache_maxiter < 0)
7180 reginfo->poscache_maxiter = I32_MAX;
7181 reginfo->poscache_iter = reginfo->poscache_maxiter;
7184 if (reginfo->poscache_iter-- == 0) {
7185 /* initialise cache */
7186 const SSize_t size = (reginfo->poscache_maxiter + 7)/8;
7187 regmatch_info_aux *const aux = reginfo->info_aux;
7188 if (aux->poscache) {
7189 if ((SSize_t)reginfo->poscache_size < size) {
7190 Renew(aux->poscache, size, char);
7191 reginfo->poscache_size = size;
7193 Zero(aux->poscache, size, char);
7196 reginfo->poscache_size = size;
7197 Newxz(aux->poscache, size, char);
7199 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
7200 "%swhilem: Detected a super-linear match, switching on caching%s...\n",
7201 PL_colors[4], PL_colors[5])
7205 if (reginfo->poscache_iter < 0) {
7206 /* have we already failed at this position? */
7207 SSize_t offset, mask;
7209 reginfo->poscache_iter = -1; /* stop eventual underflow */
7210 offset = (scan->flags & 0xf) - 1
7211 + (locinput - reginfo->strbeg)
7213 mask = 1 << (offset % 8);
7215 if (reginfo->info_aux->poscache[offset] & mask) {
7216 DEBUG_EXECUTE_r( PerlIO_printf(Perl_debug_log,
7217 "%*s whilem: (cache) already tried at this position...\n",
7218 REPORT_CODE_OFF+depth*2, "")
7220 sayNO; /* cache records failure */
7222 ST.cache_offset = offset;
7223 ST.cache_mask = mask;
7227 /* Prefer B over A for minimal matching. */
7229 if (cur_curlyx->u.curlyx.minmod) {
7230 ST.save_curlyx = cur_curlyx;
7231 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
7232 ST.cp = regcppush(rex, ST.save_curlyx->u.curlyx.parenfloor,
7234 REGCP_SET(ST.lastcp);
7235 PUSH_YES_STATE_GOTO(WHILEM_B_min, ST.save_curlyx->u.curlyx.B,
7237 NOT_REACHED; /* NOTREACHED */
7240 /* Prefer A over B for maximal matching. */
7242 if (n < max) { /* More greed allowed? */
7243 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
7245 cur_curlyx->u.curlyx.lastloc = locinput;
7246 REGCP_SET(ST.lastcp);
7247 PUSH_STATE_GOTO(WHILEM_A_max, A, locinput);
7248 NOT_REACHED; /* NOTREACHED */
7250 goto do_whilem_B_max;
7252 NOT_REACHED; /* NOTREACHED */
7254 case WHILEM_B_min: /* just matched B in a minimal match */
7255 case WHILEM_B_max: /* just matched B in a maximal match */
7256 cur_curlyx = ST.save_curlyx;
7258 NOT_REACHED; /* NOTREACHED */
7260 case WHILEM_B_max_fail: /* just failed to match B in a maximal match */
7261 cur_curlyx = ST.save_curlyx;
7262 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
7263 cur_curlyx->u.curlyx.count--;
7265 NOT_REACHED; /* NOTREACHED */
7267 case WHILEM_A_min_fail: /* just failed to match A in a minimal match */
7269 case WHILEM_A_pre_fail: /* just failed to match even minimal A */
7270 REGCP_UNWIND(ST.lastcp);
7271 regcppop(rex, &maxopenparen);
7272 cur_curlyx->u.curlyx.lastloc = ST.save_lastloc;
7273 cur_curlyx->u.curlyx.count--;
7275 NOT_REACHED; /* NOTREACHED */
7277 case WHILEM_A_max_fail: /* just failed to match A in a maximal match */
7278 REGCP_UNWIND(ST.lastcp);
7279 regcppop(rex, &maxopenparen); /* Restore some previous $<digit>s? */
7280 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
7281 "%*s whilem: failed, trying continuation...\n",
7282 REPORT_CODE_OFF+depth*2, "")
7285 if (cur_curlyx->u.curlyx.count >= REG_INFTY
7286 && ckWARN(WARN_REGEXP)
7287 && !reginfo->warned)
7289 reginfo->warned = TRUE;
7290 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
7291 "Complex regular subexpression recursion limit (%d) "
7297 ST.save_curlyx = cur_curlyx;
7298 cur_curlyx = cur_curlyx->u.curlyx.prev_curlyx;
7299 PUSH_YES_STATE_GOTO(WHILEM_B_max, ST.save_curlyx->u.curlyx.B,
7301 NOT_REACHED; /* NOTREACHED */
7303 case WHILEM_B_min_fail: /* just failed to match B in a minimal match */
7304 cur_curlyx = ST.save_curlyx;
7305 REGCP_UNWIND(ST.lastcp);
7306 regcppop(rex, &maxopenparen);
7308 if (cur_curlyx->u.curlyx.count >= /*max*/ARG2(cur_curlyx->u.curlyx.me)) {
7309 /* Maximum greed exceeded */
7310 if (cur_curlyx->u.curlyx.count >= REG_INFTY
7311 && ckWARN(WARN_REGEXP)
7312 && !reginfo->warned)
7314 reginfo->warned = TRUE;
7315 Perl_warner(aTHX_ packWARN(WARN_REGEXP),
7316 "Complex regular subexpression recursion "
7317 "limit (%d) exceeded",
7320 cur_curlyx->u.curlyx.count--;
7324 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
7325 "%*s trying longer...\n", REPORT_CODE_OFF+depth*2, "")
7327 /* Try grabbing another A and see if it helps. */
7328 cur_curlyx->u.curlyx.lastloc = locinput;
7329 ST.cp = regcppush(rex, cur_curlyx->u.curlyx.parenfloor,
7331 REGCP_SET(ST.lastcp);
7332 PUSH_STATE_GOTO(WHILEM_A_min,
7333 /*A*/ NEXTOPER(ST.save_curlyx->u.curlyx.me) + EXTRA_STEP_2ARGS,
7335 NOT_REACHED; /* NOTREACHED */
7338 #define ST st->u.branch
7340 case BRANCHJ: /* /(...|A|...)/ with long next pointer */
7341 next = scan + ARG(scan);
7344 scan = NEXTOPER(scan);
7347 case BRANCH: /* /(...|A|...)/ */
7348 scan = NEXTOPER(scan); /* scan now points to inner node */
7349 ST.lastparen = rex->lastparen;
7350 ST.lastcloseparen = rex->lastcloseparen;
7351 ST.next_branch = next;
7354 /* Now go into the branch */
7356 PUSH_YES_STATE_GOTO(BRANCH_next, scan, locinput);
7358 PUSH_STATE_GOTO(BRANCH_next, scan, locinput);
7360 NOT_REACHED; /* NOTREACHED */
7362 case CUTGROUP: /* /(*THEN)/ */
7363 sv_yes_mark = st->u.mark.mark_name = scan->flags
7364 ? MUTABLE_SV(rexi->data->data[ ARG( scan ) ])
7366 PUSH_STATE_GOTO(CUTGROUP_next, next, locinput);
7367 NOT_REACHED; /* NOTREACHED */
7369 case CUTGROUP_next_fail:
7372 if (st->u.mark.mark_name)
7373 sv_commit = st->u.mark.mark_name;
7375 NOT_REACHED; /* NOTREACHED */
7379 NOT_REACHED; /* NOTREACHED */
7381 case BRANCH_next_fail: /* that branch failed; try the next, if any */
7386 REGCP_UNWIND(ST.cp);
7387 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7388 scan = ST.next_branch;
7389 /* no more branches? */
7390 if (!scan || (OP(scan) != BRANCH && OP(scan) != BRANCHJ)) {
7392 PerlIO_printf( Perl_debug_log,
7393 "%*s %sBRANCH failed...%s\n",
7394 REPORT_CODE_OFF+depth*2, "",
7400 continue; /* execute next BRANCH[J] op */
7403 case MINMOD: /* next op will be non-greedy, e.g. A*? */
7408 #define ST st->u.curlym
7410 case CURLYM: /* /A{m,n}B/ where A is fixed-length */
7412 /* This is an optimisation of CURLYX that enables us to push
7413 * only a single backtracking state, no matter how many matches
7414 * there are in {m,n}. It relies on the pattern being constant
7415 * length, with no parens to influence future backrefs
7419 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
7421 ST.lastparen = rex->lastparen;
7422 ST.lastcloseparen = rex->lastcloseparen;
7424 /* if paren positive, emulate an OPEN/CLOSE around A */
7426 U32 paren = ST.me->flags;
7427 if (paren > maxopenparen)
7428 maxopenparen = paren;
7429 scan += NEXT_OFF(scan); /* Skip former OPEN. */
7437 ST.c1 = CHRTEST_UNINIT;
7440 if (!(ST.minmod ? ARG1(ST.me) : ARG2(ST.me))) /* min/max */
7443 curlym_do_A: /* execute the A in /A{m,n}B/ */
7444 PUSH_YES_STATE_GOTO(CURLYM_A, ST.A, locinput); /* match A */
7445 NOT_REACHED; /* NOTREACHED */
7447 case CURLYM_A: /* we've just matched an A */
7449 /* after first match, determine A's length: u.curlym.alen */
7450 if (ST.count == 1) {
7451 if (reginfo->is_utf8_target) {
7452 char *s = st->locinput;
7453 while (s < locinput) {
7459 ST.alen = locinput - st->locinput;
7462 ST.count = ST.minmod ? ARG1(ST.me) : ARG2(ST.me);
7465 PerlIO_printf(Perl_debug_log,
7466 "%*s CURLYM now matched %"IVdf" times, len=%"IVdf"...\n",
7467 (int)(REPORT_CODE_OFF+(depth*2)), "",
7468 (IV) ST.count, (IV)ST.alen)
7471 if (cur_eval && cur_eval->u.eval.close_paren &&
7472 cur_eval->u.eval.close_paren == (U32)ST.me->flags)
7476 I32 max = (ST.minmod ? ARG1(ST.me) : ARG2(ST.me));
7477 if ( max == REG_INFTY || ST.count < max )
7478 goto curlym_do_A; /* try to match another A */
7480 goto curlym_do_B; /* try to match B */
7482 case CURLYM_A_fail: /* just failed to match an A */
7483 REGCP_UNWIND(ST.cp);
7485 if (ST.minmod || ST.count < ARG1(ST.me) /* min*/
7486 || (cur_eval && cur_eval->u.eval.close_paren &&
7487 cur_eval->u.eval.close_paren == (U32)ST.me->flags))
7490 curlym_do_B: /* execute the B in /A{m,n}B/ */
7491 if (ST.c1 == CHRTEST_UNINIT) {
7492 /* calculate c1 and c2 for possible match of 1st char
7493 * following curly */
7494 ST.c1 = ST.c2 = CHRTEST_VOID;
7496 if (HAS_TEXT(ST.B) || JUMPABLE(ST.B)) {
7497 regnode *text_node = ST.B;
7498 if (! HAS_TEXT(text_node))
7499 FIND_NEXT_IMPT(text_node);
7502 (HAS_TEXT(text_node) && PL_regkind[OP(text_node)] == EXACT)
7504 But the former is redundant in light of the latter.
7506 if this changes back then the macro for
7507 IS_TEXT and friends need to change.
7509 if (PL_regkind[OP(text_node)] == EXACT) {
7510 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
7511 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
7521 PerlIO_printf(Perl_debug_log,
7522 "%*s CURLYM trying tail with matches=%"IVdf"...\n",
7523 (int)(REPORT_CODE_OFF+(depth*2)),
7526 if (! NEXTCHR_IS_EOS && ST.c1 != CHRTEST_VOID) {
7527 if (! UTF8_IS_INVARIANT(nextchr) && utf8_target) {
7528 if (memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
7529 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
7531 /* simulate B failing */
7533 PerlIO_printf(Perl_debug_log,
7534 "%*s CURLYM Fast bail next target=0x%"UVXf" c1=0x%"UVXf" c2=0x%"UVXf"\n",
7535 (int)(REPORT_CODE_OFF+(depth*2)),"",
7536 valid_utf8_to_uvchr((U8 *) locinput, NULL),
7537 valid_utf8_to_uvchr(ST.c1_utf8, NULL),
7538 valid_utf8_to_uvchr(ST.c2_utf8, NULL))
7540 state_num = CURLYM_B_fail;
7541 goto reenter_switch;
7544 else if (nextchr != ST.c1 && nextchr != ST.c2) {
7545 /* simulate B failing */
7547 PerlIO_printf(Perl_debug_log,
7548 "%*s CURLYM Fast bail next target=0x%X c1=0x%X c2=0x%X\n",
7549 (int)(REPORT_CODE_OFF+(depth*2)),"",
7550 (int) nextchr, ST.c1, ST.c2)
7552 state_num = CURLYM_B_fail;
7553 goto reenter_switch;
7558 /* emulate CLOSE: mark current A as captured */
7559 I32 paren = ST.me->flags;
7561 rex->offs[paren].start
7562 = HOPc(locinput, -ST.alen) - reginfo->strbeg;
7563 rex->offs[paren].end = locinput - reginfo->strbeg;
7564 if ((U32)paren > rex->lastparen)
7565 rex->lastparen = paren;
7566 rex->lastcloseparen = paren;
7569 rex->offs[paren].end = -1;
7570 if (cur_eval && cur_eval->u.eval.close_paren &&
7571 cur_eval->u.eval.close_paren == (U32)ST.me->flags)
7580 PUSH_STATE_GOTO(CURLYM_B, ST.B, locinput); /* match B */
7581 NOT_REACHED; /* NOTREACHED */
7583 case CURLYM_B_fail: /* just failed to match a B */
7584 REGCP_UNWIND(ST.cp);
7585 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7587 I32 max = ARG2(ST.me);
7588 if (max != REG_INFTY && ST.count == max)
7590 goto curlym_do_A; /* try to match a further A */
7592 /* backtrack one A */
7593 if (ST.count == ARG1(ST.me) /* min */)
7596 SET_locinput(HOPc(locinput, -ST.alen));
7597 goto curlym_do_B; /* try to match B */
7600 #define ST st->u.curly
7602 #define CURLY_SETPAREN(paren, success) \
7605 rex->offs[paren].start = HOPc(locinput, -1) - reginfo->strbeg; \
7606 rex->offs[paren].end = locinput - reginfo->strbeg; \
7607 if (paren > rex->lastparen) \
7608 rex->lastparen = paren; \
7609 rex->lastcloseparen = paren; \
7612 rex->offs[paren].end = -1; \
7613 rex->lastparen = ST.lastparen; \
7614 rex->lastcloseparen = ST.lastcloseparen; \
7618 case STAR: /* /A*B/ where A is width 1 char */
7622 scan = NEXTOPER(scan);
7625 case PLUS: /* /A+B/ where A is width 1 char */
7629 scan = NEXTOPER(scan);
7632 case CURLYN: /* /(A){m,n}B/ where A is width 1 char */
7633 ST.paren = scan->flags; /* Which paren to set */
7634 ST.lastparen = rex->lastparen;
7635 ST.lastcloseparen = rex->lastcloseparen;
7636 if (ST.paren > maxopenparen)
7637 maxopenparen = ST.paren;
7638 ST.min = ARG1(scan); /* min to match */
7639 ST.max = ARG2(scan); /* max to match */
7640 if (cur_eval && cur_eval->u.eval.close_paren &&
7641 cur_eval->u.eval.close_paren == (U32)ST.paren) {
7645 scan = regnext(NEXTOPER(scan) + NODE_STEP_REGNODE);
7648 case CURLY: /* /A{m,n}B/ where A is width 1 char */
7650 ST.min = ARG1(scan); /* min to match */
7651 ST.max = ARG2(scan); /* max to match */
7652 scan = NEXTOPER(scan) + NODE_STEP_REGNODE;
7655 * Lookahead to avoid useless match attempts
7656 * when we know what character comes next.
7658 * Used to only do .*x and .*?x, but now it allows
7659 * for )'s, ('s and (?{ ... })'s to be in the way
7660 * of the quantifier and the EXACT-like node. -- japhy
7663 assert(ST.min <= ST.max);
7664 if (! HAS_TEXT(next) && ! JUMPABLE(next)) {
7665 ST.c1 = ST.c2 = CHRTEST_VOID;
7668 regnode *text_node = next;
7670 if (! HAS_TEXT(text_node))
7671 FIND_NEXT_IMPT(text_node);
7673 if (! HAS_TEXT(text_node))
7674 ST.c1 = ST.c2 = CHRTEST_VOID;
7676 if ( PL_regkind[OP(text_node)] != EXACT ) {
7677 ST.c1 = ST.c2 = CHRTEST_VOID;
7681 /* Currently we only get here when
7683 PL_rekind[OP(text_node)] == EXACT
7685 if this changes back then the macro for IS_TEXT and
7686 friends need to change. */
7687 if (! S_setup_EXACTISH_ST_c1_c2(aTHX_
7688 text_node, &ST.c1, ST.c1_utf8, &ST.c2, ST.c2_utf8,
7700 char *li = locinput;
7703 regrepeat(rex, &li, ST.A, reginfo, ST.min, depth)
7709 if (ST.c1 == CHRTEST_VOID)
7710 goto curly_try_B_min;
7712 ST.oldloc = locinput;
7714 /* set ST.maxpos to the furthest point along the
7715 * string that could possibly match */
7716 if (ST.max == REG_INFTY) {
7717 ST.maxpos = reginfo->strend - 1;
7719 while (UTF8_IS_CONTINUATION(*(U8*)ST.maxpos))
7722 else if (utf8_target) {
7723 int m = ST.max - ST.min;
7724 for (ST.maxpos = locinput;
7725 m >0 && ST.maxpos < reginfo->strend; m--)
7726 ST.maxpos += UTF8SKIP(ST.maxpos);
7729 ST.maxpos = locinput + ST.max - ST.min;
7730 if (ST.maxpos >= reginfo->strend)
7731 ST.maxpos = reginfo->strend - 1;
7733 goto curly_try_B_min_known;
7737 /* avoid taking address of locinput, so it can remain
7739 char *li = locinput;
7740 ST.count = regrepeat(rex, &li, ST.A, reginfo, ST.max, depth);
7741 if (ST.count < ST.min)
7744 if ((ST.count > ST.min)
7745 && (PL_regkind[OP(ST.B)] == EOL) && (OP(ST.B) != MEOL))
7747 /* A{m,n} must come at the end of the string, there's
7748 * no point in backing off ... */
7750 /* ...except that $ and \Z can match before *and* after
7751 newline at the end. Consider "\n\n" =~ /\n+\Z\n/.
7752 We may back off by one in this case. */
7753 if (UCHARAT(locinput - 1) == '\n' && OP(ST.B) != EOS)
7757 goto curly_try_B_max;
7759 NOT_REACHED; /* NOTREACHED */
7761 case CURLY_B_min_known_fail:
7762 /* failed to find B in a non-greedy match where c1,c2 valid */
7764 REGCP_UNWIND(ST.cp);
7766 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7768 /* Couldn't or didn't -- move forward. */
7769 ST.oldloc = locinput;
7771 locinput += UTF8SKIP(locinput);
7775 curly_try_B_min_known:
7776 /* find the next place where 'B' could work, then call B */
7780 n = (ST.oldloc == locinput) ? 0 : 1;
7781 if (ST.c1 == ST.c2) {
7782 /* set n to utf8_distance(oldloc, locinput) */
7783 while (locinput <= ST.maxpos
7784 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput)))
7786 locinput += UTF8SKIP(locinput);
7791 /* set n to utf8_distance(oldloc, locinput) */
7792 while (locinput <= ST.maxpos
7793 && memNE(locinput, ST.c1_utf8, UTF8SKIP(locinput))
7794 && memNE(locinput, ST.c2_utf8, UTF8SKIP(locinput)))
7796 locinput += UTF8SKIP(locinput);
7801 else { /* Not utf8_target */
7802 if (ST.c1 == ST.c2) {
7803 while (locinput <= ST.maxpos &&
7804 UCHARAT(locinput) != ST.c1)
7808 while (locinput <= ST.maxpos
7809 && UCHARAT(locinput) != ST.c1
7810 && UCHARAT(locinput) != ST.c2)
7813 n = locinput - ST.oldloc;
7815 if (locinput > ST.maxpos)
7818 /* In /a{m,n}b/, ST.oldloc is at "a" x m, locinput is
7819 * at b; check that everything between oldloc and
7820 * locinput matches */
7821 char *li = ST.oldloc;
7823 if (regrepeat(rex, &li, ST.A, reginfo, n, depth) < n)
7825 assert(n == REG_INFTY || locinput == li);
7827 CURLY_SETPAREN(ST.paren, ST.count);
7828 if (cur_eval && cur_eval->u.eval.close_paren &&
7829 cur_eval->u.eval.close_paren == (U32)ST.paren) {
7832 PUSH_STATE_GOTO(CURLY_B_min_known, ST.B, locinput);
7834 NOT_REACHED; /* NOTREACHED */
7836 case CURLY_B_min_fail:
7837 /* failed to find B in a non-greedy match where c1,c2 invalid */
7839 REGCP_UNWIND(ST.cp);
7841 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7843 /* failed -- move forward one */
7845 char *li = locinput;
7846 if (!regrepeat(rex, &li, ST.A, reginfo, 1, depth)) {
7853 if (ST.count <= ST.max || (ST.max == REG_INFTY &&
7854 ST.count > 0)) /* count overflow ? */
7857 CURLY_SETPAREN(ST.paren, ST.count);
7858 if (cur_eval && cur_eval->u.eval.close_paren &&
7859 cur_eval->u.eval.close_paren == (U32)ST.paren) {
7862 PUSH_STATE_GOTO(CURLY_B_min, ST.B, locinput);
7866 NOT_REACHED; /* NOTREACHED */
7869 /* a successful greedy match: now try to match B */
7870 if (cur_eval && cur_eval->u.eval.close_paren &&
7871 cur_eval->u.eval.close_paren == (U32)ST.paren) {
7875 bool could_match = locinput < reginfo->strend;
7877 /* If it could work, try it. */
7878 if (ST.c1 != CHRTEST_VOID && could_match) {
7879 if (! UTF8_IS_INVARIANT(UCHARAT(locinput)) && utf8_target)
7881 could_match = memEQ(locinput,
7886 UTF8SKIP(locinput));
7889 could_match = UCHARAT(locinput) == ST.c1
7890 || UCHARAT(locinput) == ST.c2;
7893 if (ST.c1 == CHRTEST_VOID || could_match) {
7894 CURLY_SETPAREN(ST.paren, ST.count);
7895 PUSH_STATE_GOTO(CURLY_B_max, ST.B, locinput);
7896 NOT_REACHED; /* NOTREACHED */
7901 case CURLY_B_max_fail:
7902 /* failed to find B in a greedy match */
7904 REGCP_UNWIND(ST.cp);
7906 UNWIND_PAREN(ST.lastparen, ST.lastcloseparen);
7909 if (--ST.count < ST.min)
7911 locinput = HOPc(locinput, -1);
7912 goto curly_try_B_max;
7916 case END: /* last op of main pattern */
7919 /* we've just finished A in /(??{A})B/; now continue with B */
7921 st->u.eval.prev_rex = rex_sv; /* inner */
7923 /* Save *all* the positions. */
7924 st->u.eval.cp = regcppush(rex, 0, maxopenparen);
7925 rex_sv = cur_eval->u.eval.prev_rex;
7926 is_utf8_pat = reginfo->is_utf8_pat = cBOOL(RX_UTF8(rex_sv));
7927 SET_reg_curpm(rex_sv);
7928 rex = ReANY(rex_sv);
7929 rexi = RXi_GET(rex);
7930 cur_curlyx = cur_eval->u.eval.prev_curlyx;
7932 REGCP_SET(st->u.eval.lastcp);
7934 /* Restore parens of the outer rex without popping the
7936 S_regcp_restore(aTHX_ rex, cur_eval->u.eval.lastcp,
7939 st->u.eval.prev_eval = cur_eval;
7940 cur_eval = cur_eval->u.eval.prev_eval;
7942 PerlIO_printf(Perl_debug_log, "%*s EVAL trying tail ... %"UVxf"\n",
7943 REPORT_CODE_OFF+depth*2, "",PTR2UV(cur_eval)););
7944 if ( nochange_depth )
7947 PUSH_YES_STATE_GOTO(EVAL_AB, st->u.eval.prev_eval->u.eval.B,
7948 locinput); /* match B */
7951 if (locinput < reginfo->till) {
7952 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log,
7953 "%sMatch possible, but length=%ld is smaller than requested=%ld, failing!%s\n",
7955 (long)(locinput - startpos),
7956 (long)(reginfo->till - startpos),
7959 sayNO_SILENT; /* Cannot match: too short. */
7961 sayYES; /* Success! */
7963 case SUCCEED: /* successful SUSPEND/UNLESSM/IFMATCH/CURLYM */
7965 PerlIO_printf(Perl_debug_log,
7966 "%*s %ssubpattern success...%s\n",
7967 REPORT_CODE_OFF+depth*2, "", PL_colors[4], PL_colors[5]));
7968 sayYES; /* Success! */
7971 #define ST st->u.ifmatch
7976 case SUSPEND: /* (?>A) */
7978 newstart = locinput;
7981 case UNLESSM: /* -ve lookaround: (?!A), or with flags, (?<!A) */
7983 goto ifmatch_trivial_fail_test;
7985 case IFMATCH: /* +ve lookaround: (?=A), or with flags, (?<=A) */
7987 ifmatch_trivial_fail_test:
7989 char * const s = HOPBACKc(locinput, scan->flags);
7994 sw = 1 - cBOOL(ST.wanted);
7998 next = scan + ARG(scan);
8006 newstart = locinput;
8010 ST.logical = logical;
8011 logical = 0; /* XXX: reset state of logical once it has been saved into ST */
8013 /* execute body of (?...A) */
8014 PUSH_YES_STATE_GOTO(IFMATCH_A, NEXTOPER(NEXTOPER(scan)), newstart);
8015 NOT_REACHED; /* NOTREACHED */
8018 case IFMATCH_A_fail: /* body of (?...A) failed */
8019 ST.wanted = !ST.wanted;
8022 case IFMATCH_A: /* body of (?...A) succeeded */
8024 sw = cBOOL(ST.wanted);
8026 else if (!ST.wanted)
8029 if (OP(ST.me) != SUSPEND) {
8030 /* restore old position except for (?>...) */
8031 locinput = st->locinput;
8033 scan = ST.me + ARG(ST.me);
8036 continue; /* execute B */
8040 case LONGJMP: /* alternative with many branches compiles to
8041 * (BRANCHJ; EXACT ...; LONGJMP ) x N */
8042 next = scan + ARG(scan);
8047 case COMMIT: /* (*COMMIT) */
8048 reginfo->cutpoint = reginfo->strend;
8051 case PRUNE: /* (*PRUNE) */
8053 sv_yes_mark = sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8054 PUSH_STATE_GOTO(COMMIT_next, next, locinput);
8055 NOT_REACHED; /* NOTREACHED */
8057 case COMMIT_next_fail:
8061 NOT_REACHED; /* NOTREACHED */
8063 case OPFAIL: /* (*FAIL) */
8065 sv_commit = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8067 /* deal with (?(?!)X|Y) properly,
8068 * make sure we trigger the no branch
8069 * of the trailing IFTHEN structure*/
8075 NOT_REACHED; /* NOTREACHED */
8077 #define ST st->u.mark
8078 case MARKPOINT: /* (*MARK:foo) */
8079 ST.prev_mark = mark_state;
8080 ST.mark_name = sv_commit = sv_yes_mark
8081 = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8083 ST.mark_loc = locinput;
8084 PUSH_YES_STATE_GOTO(MARKPOINT_next, next, locinput);
8085 NOT_REACHED; /* NOTREACHED */
8087 case MARKPOINT_next:
8088 mark_state = ST.prev_mark;
8090 NOT_REACHED; /* NOTREACHED */
8092 case MARKPOINT_next_fail:
8093 if (popmark && sv_eq(ST.mark_name,popmark))
8095 if (ST.mark_loc > startpoint)
8096 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
8097 popmark = NULL; /* we found our mark */
8098 sv_commit = ST.mark_name;
8101 PerlIO_printf(Perl_debug_log,
8102 "%*s %ssetting cutpoint to mark:%"SVf"...%s\n",
8103 REPORT_CODE_OFF+depth*2, "",
8104 PL_colors[4], SVfARG(sv_commit), PL_colors[5]);
8107 mark_state = ST.prev_mark;
8108 sv_yes_mark = mark_state ?
8109 mark_state->u.mark.mark_name : NULL;
8111 NOT_REACHED; /* NOTREACHED */
8113 case SKIP: /* (*SKIP) */
8115 /* (*SKIP) : if we fail we cut here*/
8116 ST.mark_name = NULL;
8117 ST.mark_loc = locinput;
8118 PUSH_STATE_GOTO(SKIP_next,next, locinput);
8120 /* (*SKIP:NAME) : if there is a (*MARK:NAME) fail where it was,
8121 otherwise do nothing. Meaning we need to scan
8123 regmatch_state *cur = mark_state;
8124 SV *find = MUTABLE_SV(rexi->data->data[ ARG( scan ) ]);
8127 if ( sv_eq( cur->u.mark.mark_name,
8130 ST.mark_name = find;
8131 PUSH_STATE_GOTO( SKIP_next, next, locinput);
8133 cur = cur->u.mark.prev_mark;
8136 /* Didn't find our (*MARK:NAME) so ignore this (*SKIP:NAME) */
8139 case SKIP_next_fail:
8141 /* (*CUT:NAME) - Set up to search for the name as we
8142 collapse the stack*/
8143 popmark = ST.mark_name;
8145 /* (*CUT) - No name, we cut here.*/
8146 if (ST.mark_loc > startpoint)
8147 reginfo->cutpoint = HOPBACKc(ST.mark_loc, 1);
8148 /* but we set sv_commit to latest mark_name if there
8149 is one so they can test to see how things lead to this
8152 sv_commit=mark_state->u.mark.mark_name;
8156 NOT_REACHED; /* NOTREACHED */
8159 case LNBREAK: /* \R */
8160 if ((n=is_LNBREAK_safe(locinput, reginfo->strend, utf8_target))) {
8167 PerlIO_printf(Perl_error_log, "%"UVxf" %d\n",
8168 PTR2UV(scan), OP(scan));
8169 Perl_croak(aTHX_ "regexp memory corruption");
8171 /* this is a point to jump to in order to increment
8172 * locinput by one character */
8174 assert(!NEXTCHR_IS_EOS);
8176 locinput += PL_utf8skip[nextchr];
8177 /* locinput is allowed to go 1 char off the end, but not 2+ */
8178 if (locinput > reginfo->strend)
8187 /* switch break jumps here */
8188 scan = next; /* prepare to execute the next op and ... */
8189 continue; /* ... jump back to the top, reusing st */
8193 /* push a state that backtracks on success */
8194 st->u.yes.prev_yes_state = yes_state;
8198 /* push a new regex state, then continue at scan */
8200 regmatch_state *newst;
8203 regmatch_state *cur = st;
8204 regmatch_state *curyes = yes_state;
8206 regmatch_slab *slab = PL_regmatch_slab;
8207 for (;curd > -1;cur--,curd--) {
8208 if (cur < SLAB_FIRST(slab)) {
8210 cur = SLAB_LAST(slab);
8212 PerlIO_printf(Perl_error_log, "%*s#%-3d %-10s %s\n",
8213 REPORT_CODE_OFF + 2 + depth * 2,"",
8214 curd, PL_reg_name[cur->resume_state],
8215 (curyes == cur) ? "yes" : ""
8218 curyes = cur->u.yes.prev_yes_state;
8221 DEBUG_STATE_pp("push")
8224 st->locinput = locinput;
8226 if (newst > SLAB_LAST(PL_regmatch_slab))
8227 newst = S_push_slab(aTHX);
8228 PL_regmatch_state = newst;
8230 locinput = pushinput;
8238 * We get here only if there's trouble -- normally "case END" is
8239 * the terminating point.
8241 Perl_croak(aTHX_ "corrupted regexp pointers");
8242 NOT_REACHED; /* NOTREACHED */
8246 /* we have successfully completed a subexpression, but we must now
8247 * pop to the state marked by yes_state and continue from there */
8248 assert(st != yes_state);
8250 while (st != yes_state) {
8252 if (st < SLAB_FIRST(PL_regmatch_slab)) {
8253 PL_regmatch_slab = PL_regmatch_slab->prev;
8254 st = SLAB_LAST(PL_regmatch_slab);
8258 DEBUG_STATE_pp("pop (no final)");
8260 DEBUG_STATE_pp("pop (yes)");
8266 while (yes_state < SLAB_FIRST(PL_regmatch_slab)
8267 || yes_state > SLAB_LAST(PL_regmatch_slab))
8269 /* not in this slab, pop slab */
8270 depth -= (st - SLAB_FIRST(PL_regmatch_slab) + 1);
8271 PL_regmatch_slab = PL_regmatch_slab->prev;
8272 st = SLAB_LAST(PL_regmatch_slab);
8274 depth -= (st - yes_state);
8277 yes_state = st->u.yes.prev_yes_state;
8278 PL_regmatch_state = st;
8281 locinput= st->locinput;
8282 state_num = st->resume_state + no_final;
8283 goto reenter_switch;
8286 DEBUG_EXECUTE_r(PerlIO_printf(Perl_debug_log, "%sMatch successful!%s\n",
8287 PL_colors[4], PL_colors[5]));
8289 if (reginfo->info_aux_eval) {
8290 /* each successfully executed (?{...}) block does the equivalent of
8291 * local $^R = do {...}
8292 * When popping the save stack, all these locals would be undone;
8293 * bypass this by setting the outermost saved $^R to the latest
8295 /* I dont know if this is needed or works properly now.
8296 * see code related to PL_replgv elsewhere in this file.
8299 if (oreplsv != GvSV(PL_replgv))
8300 sv_setsv(oreplsv, GvSV(PL_replgv));
8307 PerlIO_printf(Perl_debug_log,
8308 "%*s %sfailed...%s\n",
8309 REPORT_CODE_OFF+depth*2, "",
8310 PL_colors[4], PL_colors[5])
8322 /* there's a previous state to backtrack to */
8324 if (st < SLAB_FIRST(PL_regmatch_slab)) {
8325 PL_regmatch_slab = PL_regmatch_slab->prev;
8326 st = SLAB_LAST(PL_regmatch_slab);
8328 PL_regmatch_state = st;
8329 locinput= st->locinput;
8331 DEBUG_STATE_pp("pop");
8333 if (yes_state == st)
8334 yes_state = st->u.yes.prev_yes_state;
8336 state_num = st->resume_state + 1; /* failure = success + 1 */
8337 goto reenter_switch;
8342 if (rex->intflags & PREGf_VERBARG_SEEN) {
8343 SV *sv_err = get_sv("REGERROR", 1);
8344 SV *sv_mrk = get_sv("REGMARK", 1);
8346 sv_commit = &PL_sv_no;
8348 sv_yes_mark = &PL_sv_yes;
8351 sv_commit = &PL_sv_yes;
8352 sv_yes_mark = &PL_sv_no;
8356 sv_setsv(sv_err, sv_commit);
8357 sv_setsv(sv_mrk, sv_yes_mark);
8361 if (last_pushed_cv) {
8364 PERL_UNUSED_VAR(SP);
8367 assert(!result || locinput - reginfo->strbeg >= 0);
8368 return result ? locinput - reginfo->strbeg : -1;
8372 - regrepeat - repeatedly match something simple, report how many
8374 * What 'simple' means is a node which can be the operand of a quantifier like
8377 * startposp - pointer a pointer to the start position. This is updated
8378 * to point to the byte following the highest successful
8380 * p - the regnode to be repeatedly matched against.
8381 * reginfo - struct holding match state, such as strend
8382 * max - maximum number of things to match.
8383 * depth - (for debugging) backtracking depth.
8386 S_regrepeat(pTHX_ regexp *prog, char **startposp, const regnode *p,
8387 regmatch_info *const reginfo, I32 max, int depth)
8389 char *scan; /* Pointer to current position in target string */
8391 char *loceol = reginfo->strend; /* local version */
8392 I32 hardcount = 0; /* How many matches so far */
8393 bool utf8_target = reginfo->is_utf8_target;
8394 unsigned int to_complement = 0; /* Invert the result? */
8396 _char_class_number classnum;
8398 PERL_UNUSED_ARG(depth);
8401 PERL_ARGS_ASSERT_REGREPEAT;
8404 if (max == REG_INFTY)
8406 else if (! utf8_target && loceol - scan > max)
8407 loceol = scan + max;
8409 /* Here, for the case of a non-UTF-8 target we have adjusted <loceol> down
8410 * to the maximum of how far we should go in it (leaving it set to the real
8411 * end, if the maximum permissible would take us beyond that). This allows
8412 * us to make the loop exit condition that we haven't gone past <loceol> to
8413 * also mean that we haven't exceeded the max permissible count, saving a
8414 * test each time through the loop. But it assumes that the OP matches a
8415 * single byte, which is true for most of the OPs below when applied to a
8416 * non-UTF-8 target. Those relatively few OPs that don't have this
8417 * characteristic will have to compensate.
8419 * There is no adjustment for UTF-8 targets, as the number of bytes per
8420 * character varies. OPs will have to test both that the count is less
8421 * than the max permissible (using <hardcount> to keep track), and that we
8422 * are still within the bounds of the string (using <loceol>. A few OPs
8423 * match a single byte no matter what the encoding. They can omit the max
8424 * test if, for the UTF-8 case, they do the adjustment that was skipped
8427 * Thus, the code above sets things up for the common case; and exceptional
8428 * cases need extra work; the common case is to make sure <scan> doesn't
8429 * go past <loceol>, and for UTF-8 to also use <hardcount> to make sure the
8430 * count doesn't exceed the maximum permissible */
8435 while (scan < loceol && hardcount < max && *scan != '\n') {
8436 scan += UTF8SKIP(scan);
8440 while (scan < loceol && *scan != '\n')
8446 while (scan < loceol && hardcount < max) {
8447 scan += UTF8SKIP(scan);
8455 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8456 if (utf8_target && UTF8_IS_ABOVE_LATIN1(*scan)) {
8457 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(scan, loceol);
8461 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
8465 /* Can use a simple loop if the pattern char to match on is invariant
8466 * under UTF-8, or both target and pattern aren't UTF-8. Note that we
8467 * can use UTF8_IS_INVARIANT() even if the pattern isn't UTF-8, as it's
8468 * true iff it doesn't matter if the argument is in UTF-8 or not */
8469 if (UTF8_IS_INVARIANT(c) || (! utf8_target && ! reginfo->is_utf8_pat)) {
8470 if (utf8_target && loceol - scan > max) {
8471 /* We didn't adjust <loceol> because is UTF-8, but ok to do so,
8472 * since here, to match at all, 1 char == 1 byte */
8473 loceol = scan + max;
8475 while (scan < loceol && UCHARAT(scan) == c) {
8479 else if (reginfo->is_utf8_pat) {
8481 STRLEN scan_char_len;
8483 /* When both target and pattern are UTF-8, we have to do
8485 while (hardcount < max
8487 && (scan_char_len = UTF8SKIP(scan)) <= STR_LEN(p)
8488 && memEQ(scan, STRING(p), scan_char_len))
8490 scan += scan_char_len;
8494 else if (! UTF8_IS_ABOVE_LATIN1(c)) {
8496 /* Target isn't utf8; convert the character in the UTF-8
8497 * pattern to non-UTF8, and do a simple loop */
8498 c = EIGHT_BIT_UTF8_TO_NATIVE(c, *(STRING(p) + 1));
8499 while (scan < loceol && UCHARAT(scan) == c) {
8502 } /* else pattern char is above Latin1, can't possibly match the
8507 /* Here, the string must be utf8; pattern isn't, and <c> is
8508 * different in utf8 than not, so can't compare them directly.
8509 * Outside the loop, find the two utf8 bytes that represent c, and
8510 * then look for those in sequence in the utf8 string */
8511 U8 high = UTF8_TWO_BYTE_HI(c);
8512 U8 low = UTF8_TWO_BYTE_LO(c);
8514 while (hardcount < max
8515 && scan + 1 < loceol
8516 && UCHARAT(scan) == high
8517 && UCHARAT(scan + 1) == low)
8525 case EXACTFA_NO_TRIE: /* This node only generated for non-utf8 patterns */
8526 assert(! reginfo->is_utf8_pat);
8529 utf8_flags = FOLDEQ_UTF8_NOMIX_ASCII;
8533 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8534 utf8_flags = FOLDEQ_LOCALE;
8537 case EXACTF: /* This node only generated for non-utf8 patterns */
8538 assert(! reginfo->is_utf8_pat);
8543 if (! utf8_target) {
8546 utf8_flags = FOLDEQ_LOCALE | FOLDEQ_S2_ALREADY_FOLDED
8547 | FOLDEQ_S2_FOLDS_SANE;
8552 utf8_flags = reginfo->is_utf8_pat ? FOLDEQ_S2_ALREADY_FOLDED : 0;
8556 U8 c1_utf8[UTF8_MAXBYTES+1], c2_utf8[UTF8_MAXBYTES+1];
8558 assert(STR_LEN(p) == reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1);
8560 if (S_setup_EXACTISH_ST_c1_c2(aTHX_ p, &c1, c1_utf8, &c2, c2_utf8,
8563 if (c1 == CHRTEST_VOID) {
8564 /* Use full Unicode fold matching */
8565 char *tmpeol = reginfo->strend;
8566 STRLEN pat_len = reginfo->is_utf8_pat ? UTF8SKIP(STRING(p)) : 1;
8567 while (hardcount < max
8568 && foldEQ_utf8_flags(scan, &tmpeol, 0, utf8_target,
8569 STRING(p), NULL, pat_len,
8570 reginfo->is_utf8_pat, utf8_flags))
8573 tmpeol = reginfo->strend;
8577 else if (utf8_target) {
8579 while (scan < loceol
8581 && memEQ(scan, c1_utf8, UTF8SKIP(scan)))
8583 scan += UTF8SKIP(scan);
8588 while (scan < loceol
8590 && (memEQ(scan, c1_utf8, UTF8SKIP(scan))
8591 || memEQ(scan, c2_utf8, UTF8SKIP(scan))))
8593 scan += UTF8SKIP(scan);
8598 else if (c1 == c2) {
8599 while (scan < loceol && UCHARAT(scan) == c1) {
8604 while (scan < loceol &&
8605 (UCHARAT(scan) == c1 || UCHARAT(scan) == c2))
8614 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8616 if (ANYOFL_UTF8_LOCALE_REQD(FLAGS(p)) && ! IN_UTF8_CTYPE_LOCALE) {
8617 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE), utf8_locale_required);
8623 while (hardcount < max
8625 && reginclass(prog, p, (U8*)scan, (U8*) loceol, utf8_target))
8627 scan += UTF8SKIP(scan);
8631 while (scan < loceol && REGINCLASS(prog, p, (U8*)scan, 0))
8636 /* The argument (FLAGS) to all the POSIX node types is the class number */
8643 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8644 if (! utf8_target) {
8645 while (scan < loceol && to_complement ^ cBOOL(isFOO_lc(FLAGS(p),
8651 while (hardcount < max && scan < loceol
8652 && to_complement ^ cBOOL(isFOO_utf8_lc(FLAGS(p),
8655 scan += UTF8SKIP(scan);
8668 if (utf8_target && loceol - scan > max) {
8670 /* We didn't adjust <loceol> at the beginning of this routine
8671 * because is UTF-8, but it is actually ok to do so, since here, to
8672 * match, 1 char == 1 byte. */
8673 loceol = scan + max;
8675 while (scan < loceol && _generic_isCC_A((U8) *scan, FLAGS(p))) {
8688 if (! utf8_target) {
8689 while (scan < loceol && ! _generic_isCC_A((U8) *scan, FLAGS(p))) {
8695 /* The complement of something that matches only ASCII matches all
8696 * non-ASCII, plus everything in ASCII that isn't in the class. */
8697 while (hardcount < max && scan < loceol
8698 && (! isASCII_utf8(scan)
8699 || ! _generic_isCC_A((U8) *scan, FLAGS(p))))
8701 scan += UTF8SKIP(scan);
8712 if (! utf8_target) {
8713 while (scan < loceol && to_complement
8714 ^ cBOOL(_generic_isCC((U8) *scan, FLAGS(p))))
8721 classnum = (_char_class_number) FLAGS(p);
8722 if (classnum < _FIRST_NON_SWASH_CC) {
8724 /* Here, a swash is needed for above-Latin1 code points.
8725 * Process as many Latin1 code points using the built-in rules.
8726 * Go to another loop to finish processing upon encountering
8727 * the first Latin1 code point. We could do that in this loop
8728 * as well, but the other way saves having to test if the swash
8729 * has been loaded every time through the loop: extra space to
8731 while (hardcount < max && scan < loceol) {
8732 if (UTF8_IS_INVARIANT(*scan)) {
8733 if (! (to_complement ^ cBOOL(_generic_isCC((U8) *scan,
8740 else if (UTF8_IS_DOWNGRADEABLE_START(*scan)) {
8741 if (! (to_complement
8742 ^ cBOOL(_generic_isCC(EIGHT_BIT_UTF8_TO_NATIVE(*scan,
8751 goto found_above_latin1;
8758 /* For these character classes, the knowledge of how to handle
8759 * every code point is compiled in to Perl via a macro. This
8760 * code is written for making the loops as tight as possible.
8761 * It could be refactored to save space instead */
8763 case _CC_ENUM_SPACE:
8764 while (hardcount < max
8766 && (to_complement ^ cBOOL(isSPACE_utf8(scan))))
8768 scan += UTF8SKIP(scan);
8772 case _CC_ENUM_BLANK:
8773 while (hardcount < max
8775 && (to_complement ^ cBOOL(isBLANK_utf8(scan))))
8777 scan += UTF8SKIP(scan);
8781 case _CC_ENUM_XDIGIT:
8782 while (hardcount < max
8784 && (to_complement ^ cBOOL(isXDIGIT_utf8(scan))))
8786 scan += UTF8SKIP(scan);
8790 case _CC_ENUM_VERTSPACE:
8791 while (hardcount < max
8793 && (to_complement ^ cBOOL(isVERTWS_utf8(scan))))
8795 scan += UTF8SKIP(scan);
8799 case _CC_ENUM_CNTRL:
8800 while (hardcount < max
8802 && (to_complement ^ cBOOL(isCNTRL_utf8(scan))))
8804 scan += UTF8SKIP(scan);
8809 Perl_croak(aTHX_ "panic: regrepeat() node %d='%s' has an unexpected character class '%d'", OP(p), PL_reg_name[OP(p)], classnum);
8815 found_above_latin1: /* Continuation of POSIXU and NPOSIXU */
8817 /* Load the swash if not already present */
8818 if (! PL_utf8_swash_ptrs[classnum]) {
8819 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
8820 PL_utf8_swash_ptrs[classnum] = _core_swash_init(
8824 PL_XPosix_ptrs[classnum], &flags);
8827 while (hardcount < max && scan < loceol
8828 && to_complement ^ cBOOL(_generic_utf8(
8831 swash_fetch(PL_utf8_swash_ptrs[classnum],
8835 scan += UTF8SKIP(scan);
8842 while (hardcount < max && scan < loceol &&
8843 (c=is_LNBREAK_utf8_safe(scan, loceol))) {
8848 /* LNBREAK can match one or two latin chars, which is ok, but we
8849 * have to use hardcount in this situation, and throw away the
8850 * adjustment to <loceol> done before the switch statement */
8851 loceol = reginfo->strend;
8852 while (scan < loceol && (c=is_LNBREAK_latin1_safe(scan, loceol))) {
8861 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
8875 /* These are all 0 width, so match right here or not at all. */
8879 Perl_croak(aTHX_ "panic: regrepeat() called with unrecognized node type %d='%s'", OP(p), PL_reg_name[OP(p)]);
8880 NOT_REACHED; /* NOTREACHED */
8887 c = scan - *startposp;
8891 GET_RE_DEBUG_FLAGS_DECL;
8893 SV * const prop = sv_newmortal();
8894 regprop(prog, prop, p, reginfo, NULL);
8895 PerlIO_printf(Perl_debug_log,
8896 "%*s %s can match %"IVdf" times out of %"IVdf"...\n",
8897 REPORT_CODE_OFF + depth*2, "", SvPVX_const(prop),(IV)c,(IV)max);
8905 #if !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION)
8907 - regclass_swash - prepare the utf8 swash. Wraps the shared core version to
8908 create a copy so that changes the caller makes won't change the shared one.
8909 If <altsvp> is non-null, will return NULL in it, for back-compat.
8912 Perl_regclass_swash(pTHX_ const regexp *prog, const regnode* node, bool doinit, SV** listsvp, SV **altsvp)
8914 PERL_ARGS_ASSERT_REGCLASS_SWASH;
8920 return newSVsv(_get_regclass_nonbitmap_data(prog, node, doinit, listsvp, NULL, NULL));
8923 #endif /* !defined(PERL_IN_XSUB_RE) || defined(PLUGGABLE_RE_EXTENSION) */
8926 - reginclass - determine if a character falls into a character class
8928 n is the ANYOF-type regnode
8929 p is the target string
8930 p_end points to one byte beyond the end of the target string
8931 utf8_target tells whether p is in UTF-8.
8933 Returns true if matched; false otherwise.
8935 Note that this can be a synthetic start class, a combination of various
8936 nodes, so things you think might be mutually exclusive, such as locale,
8937 aren't. It can match both locale and non-locale
8942 S_reginclass(pTHX_ regexp * const prog, const regnode * const n, const U8* const p, const U8* const p_end, const bool utf8_target)
8945 const char flags = ANYOF_FLAGS(n);
8949 PERL_ARGS_ASSERT_REGINCLASS;
8951 /* If c is not already the code point, get it. Note that
8952 * UTF8_IS_INVARIANT() works even if not in UTF-8 */
8953 if (! UTF8_IS_INVARIANT(c) && utf8_target) {
8955 c = utf8n_to_uvchr(p, p_end - p, &c_len,
8956 (UTF8_ALLOW_DEFAULT & UTF8_ALLOW_ANYUV)
8957 | UTF8_ALLOW_FFFF | UTF8_CHECK_ONLY);
8958 /* see [perl #37836] for UTF8_ALLOW_ANYUV; [perl #38293] for
8959 * UTF8_ALLOW_FFFF */
8960 if (c_len == (STRLEN)-1)
8961 Perl_croak(aTHX_ "Malformed UTF-8 character (fatal)");
8962 if (c > 255 && OP(n) == ANYOFL && ! ANYOFL_UTF8_LOCALE_REQD(flags)) {
8963 _CHECK_AND_OUTPUT_WIDE_LOCALE_CP_MSG(c);
8967 /* If this character is potentially in the bitmap, check it */
8968 if (c < NUM_ANYOF_CODE_POINTS) {
8969 if (ANYOF_BITMAP_TEST(n, c))
8972 & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
8979 else if (flags & ANYOF_LOCALE_FLAGS) {
8980 if ((flags & ANYOFL_FOLD)
8982 && ANYOF_BITMAP_TEST(n, PL_fold_locale[c]))
8986 else if (ANYOF_POSIXL_TEST_ANY_SET(n)
8990 /* The data structure is arranged so bits 0, 2, 4, ... are set
8991 * if the class includes the Posix character class given by
8992 * bit/2; and 1, 3, 5, ... are set if the class includes the
8993 * complemented Posix class given by int(bit/2). So we loop
8994 * through the bits, each time changing whether we complement
8995 * the result or not. Suppose for the sake of illustration
8996 * that bits 0-3 mean respectively, \w, \W, \s, \S. If bit 0
8997 * is set, it means there is a match for this ANYOF node if the
8998 * character is in the class given by the expression (0 / 2 = 0
8999 * = \w). If it is in that class, isFOO_lc() will return 1,
9000 * and since 'to_complement' is 0, the result will stay TRUE,
9001 * and we exit the loop. Suppose instead that bit 0 is 0, but
9002 * bit 1 is 1. That means there is a match if the character
9003 * matches \W. We won't bother to call isFOO_lc() on bit 0,
9004 * but will on bit 1. On the second iteration 'to_complement'
9005 * will be 1, so the exclusive or will reverse things, so we
9006 * are testing for \W. On the third iteration, 'to_complement'
9007 * will be 0, and we would be testing for \s; the fourth
9008 * iteration would test for \S, etc.
9010 * Note that this code assumes that all the classes are closed
9011 * under folding. For example, if a character matches \w, then
9012 * its fold does too; and vice versa. This should be true for
9013 * any well-behaved locale for all the currently defined Posix
9014 * classes, except for :lower: and :upper:, which are handled
9015 * by the pseudo-class :cased: which matches if either of the
9016 * other two does. To get rid of this assumption, an outer
9017 * loop could be used below to iterate over both the source
9018 * character, and its fold (if different) */
9021 int to_complement = 0;
9023 while (count < ANYOF_MAX) {
9024 if (ANYOF_POSIXL_TEST(n, count)
9025 && to_complement ^ cBOOL(isFOO_lc(count/2, (U8) c)))
9038 /* If the bitmap didn't (or couldn't) match, and something outside the
9039 * bitmap could match, try that. */
9041 if (c >= NUM_ANYOF_CODE_POINTS
9042 && (flags & ANYOF_MATCHES_ALL_ABOVE_BITMAP))
9044 match = TRUE; /* Everything above the bitmap matches */
9046 /* Here doesn't match everything above the bitmap. If there is
9047 * some information available beyond the bitmap, we may find a
9048 * match in it. If so, this is most likely because the code point
9049 * is outside the bitmap range. But rarely, it could be because of
9050 * some other reason. If so, various flags are set to indicate
9051 * this possibility. On ANYOFD nodes, there may be matches that
9052 * happen only when the target string is UTF-8; or for other node
9053 * types, because runtime lookup is needed, regardless of the
9054 * UTF-8ness of the target string. Finally, under /il, there may
9055 * be some matches only possible if the locale is a UTF-8 one. */
9056 else if ( ARG(n) != ANYOF_ONLY_HAS_BITMAP
9057 && ( c >= NUM_ANYOF_CODE_POINTS
9058 || ( (flags & ANYOF_SHARED_d_UPPER_LATIN1_UTF8_STRING_MATCHES_non_d_RUNTIME_USER_PROP)
9059 && ( UNLIKELY(OP(n) != ANYOFD)
9060 || (utf8_target && ! isASCII_uni(c)
9061 # if NUM_ANYOF_CODE_POINTS > 256
9065 || ( ANYOFL_SOME_FOLDS_ONLY_IN_UTF8_LOCALE(flags)
9066 && IN_UTF8_CTYPE_LOCALE)))
9068 SV* only_utf8_locale = NULL;
9069 SV * const sw = _get_regclass_nonbitmap_data(prog, n, TRUE, 0,
9070 &only_utf8_locale, NULL);
9076 } else { /* Convert to utf8 */
9077 utf8_p = utf8_buffer;
9078 append_utf8_from_native_byte(*p, &utf8_p);
9079 utf8_p = utf8_buffer;
9082 if (swash_fetch(sw, utf8_p, TRUE)) {
9086 if (! match && only_utf8_locale && IN_UTF8_CTYPE_LOCALE) {
9087 match = _invlist_contains_cp(only_utf8_locale, c);
9091 if (UNICODE_IS_SUPER(c)
9093 & ANYOF_SHARED_d_MATCHES_ALL_NON_UTF8_NON_ASCII_non_d_WARN_SUPER)
9095 && ckWARN_d(WARN_NON_UNICODE))
9097 Perl_warner(aTHX_ packWARN(WARN_NON_UNICODE),
9098 "Matched non-Unicode code point 0x%04"UVXf" against Unicode property; may not be portable", c);
9102 #if ANYOF_INVERT != 1
9103 /* Depending on compiler optimization cBOOL takes time, so if don't have to
9105 # error ANYOF_INVERT needs to be set to 1, or guarded with cBOOL below,
9108 /* The xor complements the return if to invert: 1^1 = 0, 1^0 = 1 */
9109 return (flags & ANYOF_INVERT) ^ match;
9113 S_reghop3(U8 *s, SSize_t off, const U8* lim)
9115 /* return the position 'off' UTF-8 characters away from 's', forward if
9116 * 'off' >= 0, backwards if negative. But don't go outside of position
9117 * 'lim', which better be < s if off < 0 */
9119 PERL_ARGS_ASSERT_REGHOP3;
9122 while (off-- && s < lim) {
9123 /* XXX could check well-formedness here */
9128 while (off++ && s > lim) {
9130 if (UTF8_IS_CONTINUED(*s)) {
9131 while (s > lim && UTF8_IS_CONTINUATION(*s))
9133 if (! UTF8_IS_START(*s)) {
9134 Perl_croak_nocontext("Malformed UTF-8 character (fatal)");
9137 /* XXX could check well-formedness here */
9144 S_reghop4(U8 *s, SSize_t off, const U8* llim, const U8* rlim)
9146 PERL_ARGS_ASSERT_REGHOP4;
9149 while (off-- && s < rlim) {
9150 /* XXX could check well-formedness here */
9155 while (off++ && s > llim) {
9157 if (UTF8_IS_CONTINUED(*s)) {
9158 while (s > llim && UTF8_IS_CONTINUATION(*s))
9160 if (! UTF8_IS_START(*s)) {
9161 Perl_croak_nocontext("Malformed UTF-8 character (fatal)");
9164 /* XXX could check well-formedness here */
9170 /* like reghop3, but returns NULL on overrun, rather than returning last
9174 S_reghopmaybe3(U8* s, SSize_t off, const U8* lim)
9176 PERL_ARGS_ASSERT_REGHOPMAYBE3;
9179 while (off-- && s < lim) {
9180 /* XXX could check well-formedness here */
9187 while (off++ && s > lim) {
9189 if (UTF8_IS_CONTINUED(*s)) {
9190 while (s > lim && 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 */
9205 /* when executing a regex that may have (?{}), extra stuff needs setting
9206 up that will be visible to the called code, even before the current
9207 match has finished. In particular:
9209 * $_ is localised to the SV currently being matched;
9210 * pos($_) is created if necessary, ready to be updated on each call-out
9212 * a fake PMOP is created that can be set to PL_curpm (normally PL_curpm
9213 isn't set until the current pattern is successfully finished), so that
9214 $1 etc of the match-so-far can be seen;
9215 * save the old values of subbeg etc of the current regex, and set then
9216 to the current string (again, this is normally only done at the end
9221 S_setup_eval_state(pTHX_ regmatch_info *const reginfo)
9224 regexp *const rex = ReANY(reginfo->prog);
9225 regmatch_info_aux_eval *eval_state = reginfo->info_aux_eval;
9227 eval_state->rex = rex;
9230 /* Make $_ available to executed code. */
9231 if (reginfo->sv != DEFSV) {
9233 DEFSV_set(reginfo->sv);
9236 if (!(mg = mg_find_mglob(reginfo->sv))) {
9237 /* prepare for quick setting of pos */
9238 mg = sv_magicext_mglob(reginfo->sv);
9241 eval_state->pos_magic = mg;
9242 eval_state->pos = mg->mg_len;
9243 eval_state->pos_flags = mg->mg_flags;
9246 eval_state->pos_magic = NULL;
9248 if (!PL_reg_curpm) {
9249 /* PL_reg_curpm is a fake PMOP that we can attach the current
9250 * regex to and point PL_curpm at, so that $1 et al are visible
9251 * within a /(?{})/. It's just allocated once per interpreter the
9252 * first time its needed */
9253 Newxz(PL_reg_curpm, 1, PMOP);
9256 SV* const repointer = &PL_sv_undef;
9257 /* this regexp is also owned by the new PL_reg_curpm, which
9258 will try to free it. */
9259 av_push(PL_regex_padav, repointer);
9260 PL_reg_curpm->op_pmoffset = av_tindex(PL_regex_padav);
9261 PL_regex_pad = AvARRAY(PL_regex_padav);
9265 SET_reg_curpm(reginfo->prog);
9266 eval_state->curpm = PL_curpm;
9267 PL_curpm = PL_reg_curpm;
9268 if (RXp_MATCH_COPIED(rex)) {
9269 /* Here is a serious problem: we cannot rewrite subbeg,
9270 since it may be needed if this match fails. Thus
9271 $` inside (?{}) could fail... */
9272 eval_state->subbeg = rex->subbeg;
9273 eval_state->sublen = rex->sublen;
9274 eval_state->suboffset = rex->suboffset;
9275 eval_state->subcoffset = rex->subcoffset;
9277 eval_state->saved_copy = rex->saved_copy;
9279 RXp_MATCH_COPIED_off(rex);
9282 eval_state->subbeg = NULL;
9283 rex->subbeg = (char *)reginfo->strbeg;
9285 rex->subcoffset = 0;
9286 rex->sublen = reginfo->strend - reginfo->strbeg;
9290 /* destructor to clear up regmatch_info_aux and regmatch_info_aux_eval */
9293 S_cleanup_regmatch_info_aux(pTHX_ void *arg)
9295 regmatch_info_aux *aux = (regmatch_info_aux *) arg;
9296 regmatch_info_aux_eval *eval_state = aux->info_aux_eval;
9299 Safefree(aux->poscache);
9303 /* undo the effects of S_setup_eval_state() */
9305 if (eval_state->subbeg) {
9306 regexp * const rex = eval_state->rex;
9307 rex->subbeg = eval_state->subbeg;
9308 rex->sublen = eval_state->sublen;
9309 rex->suboffset = eval_state->suboffset;
9310 rex->subcoffset = eval_state->subcoffset;
9312 rex->saved_copy = eval_state->saved_copy;
9314 RXp_MATCH_COPIED_on(rex);
9316 if (eval_state->pos_magic)
9318 eval_state->pos_magic->mg_len = eval_state->pos;
9319 eval_state->pos_magic->mg_flags =
9320 (eval_state->pos_magic->mg_flags & ~MGf_BYTES)
9321 | (eval_state->pos_flags & MGf_BYTES);
9324 PL_curpm = eval_state->curpm;
9327 PL_regmatch_state = aux->old_regmatch_state;
9328 PL_regmatch_slab = aux->old_regmatch_slab;
9330 /* free all slabs above current one - this must be the last action
9331 * of this function, as aux and eval_state are allocated within
9332 * slabs and may be freed here */
9334 s = PL_regmatch_slab->next;
9336 PL_regmatch_slab->next = NULL;
9338 regmatch_slab * const osl = s;
9347 S_to_utf8_substr(pTHX_ regexp *prog)
9349 /* Converts substr fields in prog from bytes to UTF-8, calling fbm_compile
9350 * on the converted value */
9354 PERL_ARGS_ASSERT_TO_UTF8_SUBSTR;
9357 if (prog->substrs->data[i].substr
9358 && !prog->substrs->data[i].utf8_substr) {
9359 SV* const sv = newSVsv(prog->substrs->data[i].substr);
9360 prog->substrs->data[i].utf8_substr = sv;
9361 sv_utf8_upgrade(sv);
9362 if (SvVALID(prog->substrs->data[i].substr)) {
9363 if (SvTAIL(prog->substrs->data[i].substr)) {
9364 /* Trim the trailing \n that fbm_compile added last
9366 SvCUR_set(sv, SvCUR(sv) - 1);
9367 /* Whilst this makes the SV technically "invalid" (as its
9368 buffer is no longer followed by "\0") when fbm_compile()
9369 adds the "\n" back, a "\0" is restored. */
9370 fbm_compile(sv, FBMcf_TAIL);
9374 if (prog->substrs->data[i].substr == prog->check_substr)
9375 prog->check_utf8 = sv;
9381 S_to_byte_substr(pTHX_ regexp *prog)
9383 /* Converts substr fields in prog from UTF-8 to bytes, calling fbm_compile
9384 * on the converted value; returns FALSE if can't be converted. */
9388 PERL_ARGS_ASSERT_TO_BYTE_SUBSTR;
9391 if (prog->substrs->data[i].utf8_substr
9392 && !prog->substrs->data[i].substr) {
9393 SV* sv = newSVsv(prog->substrs->data[i].utf8_substr);
9394 if (! sv_utf8_downgrade(sv, TRUE)) {
9397 if (SvVALID(prog->substrs->data[i].utf8_substr)) {
9398 if (SvTAIL(prog->substrs->data[i].utf8_substr)) {
9399 /* Trim the trailing \n that fbm_compile added last
9401 SvCUR_set(sv, SvCUR(sv) - 1);
9402 fbm_compile(sv, FBMcf_TAIL);
9406 prog->substrs->data[i].substr = sv;
9407 if (prog->substrs->data[i].utf8_substr == prog->check_utf8)
9408 prog->check_substr = sv;
9416 * ex: set ts=8 sts=4 sw=4 et: